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。

feat(mobile): 支持详细本地 Debug 日志与手动上传摘要 (#4092)

Dash66adfb5d7b4a
diff --git a/apps/mobile/.env.example b/apps/mobile/.env.example
index 7c18456ed9..4d5c73a9b7 100644
--- a/apps/mobile/.env.example
+++ b/apps/mobile/.env.example
@@ -5,6 +5,11 @@
# - 下面几个 base URL 仅在连本地 / staging 时显式覆写,不要复述生产域名。
# 清单自举基址由 ensure-mobile-env 从对应 region 的 config/endpoint*.json.cdnBaseUrl 补写。
EXPO_PUBLIC_CINDY_AUTH_REGION=global
+# Optional personal diagnostics default; normal builds leave this unset/0.
+# A saved setting always wins. Logs remain local until the user exports/uploads.
+EXPO_PUBLIC_CINDY_DIAGNOSTICS=0
+# Upload target is injected by Metro from private config/log-upload.json, not hand-filled here.
+# Release producers set CINDY_REQUIRE_LOG_UPLOAD_CONFIG=1 to require that config.
EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL=
EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL=
EXPO_PUBLIC_CINDY_AUTH_BASE_URL=
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index fe1e8106db..4129b93679 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -1,3 +1,4 @@
+import { startLocalDiagnostics } from '@/debug/localDiagnostics';
import {
DarkTheme as NavigationDarkTheme,
DefaultTheme as NavigationLightTheme,
@@ -350,6 +351,7 @@ function RootAfterEndpoints() {
}
function RootLayout() {
+ useEffect(() => startLocalDiagnostics(), []);
// Dev-only:注册开发者菜单的"清缓存 + reload"项(内部 __DEV__ gate,生产为 no-op)。
useEffect(() => {
registerDevCacheMenu();
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 83dd046d48..82b27d9e3e 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,4 +1,5 @@
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { isInFlightDeviceLinkError } from '@cindy/device-link';
import { takeRefinementContextTail, truncateRefinementReply } from '@cindy/voice-input-core';
import {
@@ -2040,6 +2041,7 @@ export default function SessionScreen() {
useEffect(() => {
if (contentRecoveryState === 'syncing') recoveryStartedAtRef.current = Date.now();
else console.debug('[device-link] content recovered', { elapsedMs: Date.now() - recoveryStartedAtRef.current });
+ mobileDebugLog('debug', 'recovery', 'content recovery state', { state: contentRecoveryState, elapsedMs: Date.now() - recoveryStartedAtRef.current });
}, [contentRecoveryState]);
const showConnectionBanner = useShowConnectionBanner(
status,
@@ -3174,6 +3176,7 @@ export default function SessionScreen() {
// 落一条 debug:区分不了「瞬时离线可自愈」与「sessionId 非法 / 协议不匹配」等永久性
// 错误,后者会让镜像长期过期到下次重连才补读——留痕便于排查 device-link 兼容回归。
console.debug('[agent-switch] getSessionAgentSwitchIntent 读回失败,保留现有镜像', err);
+ mobileDebugLog('debug', 'recovery', 'agent switch intent read failed; retaining snapshot', err);
});
return () => {
cancelled = true;
@@ -3399,6 +3402,7 @@ export default function SessionScreen() {
if (contentKeyAtStart !== null && contentRecoveryKeyRef.current === contentKeyAtStart) {
syncRun.satisfy('subscription-acked');
console.debug('[device-link] recovery snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });
+ mobileDebugLog('debug', 'recovery', 'snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });
}
// 已读回执门槛:本会话在当前连接代完成过整窗同步。sessionId / epoch / 门槛代号
// 都取 sync 开始时的快照——原地切 session、重连、attention 上升沿之后,启动更早
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsx
index 2313c1b381..2ac4bf8a1c 100644
--- a/apps/mobile/app/settings.tsx
+++ b/apps/mobile/app/settings.tsx
@@ -1,3 +1,5 @@
+import { diagnosticUploadConfigured, uploadMobileDiagnostics } from '@/debug/mobileDiagnosticUpload';
+import { clearDiagnostics, diagnosticsEnabled, exportDiagnostics, hydrateDiagnostics, setDiagnosticsEnabled } from '@/debug/localDiagnostics';
import Constants from 'expo-constants';
import * as Clipboard from 'expo-clipboard';
import * as Updates from 'expo-updates';
@@ -19,7 +21,7 @@ import {
} from 'react-native';
import { Text, TextInput } from '@/components/AppText';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
-import { ChevronDown, ChevronRight, X } from 'lucide-react-native';
+import { ChevronDown, ChevronRight, Ellipsis, X } from 'lucide-react-native';
import { useTranslation } from 'react-i18next';
import type { DeviceView } from '@cindy/device-link';
import { useAuth } from '@/auth/AuthContext';
@@ -139,6 +141,48 @@ export default function SettingsScreen() {
const { lastPresenceSnapshot, status, invoke } = useDeviceLink();
const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
const [loggingOut, setLoggingOut] = useState(false);
+ const [localLogsEnabled, setLocalLogsEnabled] = useState(false);
+ const [localLogsReady, setLocalLogsReady] = useState(false);
+ const [localLogsBusy, setLocalLogsBusy] = useState(false);
+ const [localLogsConsent, setLocalLogsConsent] = useState(false);
+ const [localLogUploadMessage, setLocalLogUploadMessage] = useState<string | null>(null);
+ const localLogsLock = useRef(false);
+ useEffect(() => {
+ let mounted = true;
+ void hydrateDiagnostics().then(() => {
+ if (mounted) {
+ setLocalLogsEnabled(diagnosticsEnabled());
+ setLocalLogsReady(true);
+ }
+ });
+ return () => {
+ mounted = false;
+ };
+ }, []);
+ const runLocalLogAction = async (action: () => Promise<void>) => {
+ if (localLogsLock.current) return;
+ localLogsLock.current = true;
+ setLocalLogsBusy(true);
+ try {
+ await action();
+ } catch {
+ Alert.alert(
+ t('settings.localLogs.title'),
+ t('settings.localLogs.failed'),
+ );
+ } finally {
+ setLocalLogsEnabled(diagnosticsEnabled());
+ setLocalLogsBusy(false);
+ localLogsLock.current = false;
+ }
+ };
+ const handleLocalLogOption = (id: string) => {
+ if (!localLogsReady || localLogsBusy) return;
+ if (id === 'clear') Alert.alert(t('settings.localLogs.clear'), t('settings.localLogs.clearHint'), [
+ { text: t('settings.localLogs.cancel'), style: 'cancel' },
+ { text: t('settings.localLogs.clear'), style: 'destructive', onPress: () => void runLocalLogAction(clearDiagnostics) },
+ ]);
+ };
const [accountDeletionAvailable, setAccountDeletionAvailable] =
useState(false);
const [debugExpanded, setDebugExpanded] = useState(false);
@@ -673,6 +717,7 @@ export default function SettingsScreen() {
const sync = () => {
if (cancelled) return;
const snapshot = getAnalyticsConsentState();
+ setLocalLogsConsent(snapshot.consent);
setAnalyticsEnabledState(snapshot.enabled);
setAnalyticsCustomized(snapshot.enabledCustomized);
};
@@ -1128,6 +1173,82 @@ export default function SettingsScreen() {
>
{debugExpanded
? [
+ <View
+ key="local-logs-toggle"
+ style={styles.switchRow}
+ testID="settings.localLogs"
+ >
+ <View style={styles.switchTexts}>
+ <Text style={styles.rowLabel}>
+ {t('settings.localLogs.title')}
+ </Text>
+ <Text style={styles.hint}>
+ {t('settings.localLogs.hint')}
+ </Text>
+ </View>
+ <NativeSwitch
+ accessibilityLabel={t('settings.localLogs.record')}
+ disabled={!localLogsReady || localLogsBusy}
+ value={localLogsEnabled}
+ seedColor={colors.inputCaret}
+ onValueChange={(value) =>
+ void runLocalLogAction(() =>
+ setDiagnosticsEnabled(value),
+ )
+ }
+ />
+ <NativePullDownMenu
+ actions={[
+ { id: 'clear', title: t('settings.localLogs.clear'), destructive: true, disabled: !localLogsReady || localLogsBusy },
+ ]}
+ onAction={handleLocalLogOption}
+ >
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={t('settings.localLogs.options')}
+ disabled={!localLogsReady || localLogsBusy}
+ style={styles.localLogOptions}
+ onPress={usesNativePullDownMenu() ? undefined : () => Alert.alert(t('settings.localLogs.options'), undefined, [
+ { text: t('settings.localLogs.clear'), style: 'destructive', onPress: () => handleLocalLogOption('clear') },
+ { text: t('settings.localLogs.cancel'), style: 'cancel' },
+ ])}
+ >
+ <Ellipsis color={colors.textTertiary} size={iconSize.lg} strokeWidth={iconStroke.regular} />
+ </Pressable>
+ </NativePullDownMenu>
+ </View>,
+ <ActionInfoRow
+ key="local-logs-export"
+ accessibilityLabel={t('settings.localLogs.export')}
+ label={t('settings.localLogs.export')}
+ detail={t('settings.localLogs.exportHint')}
+ disabled={!localLogsReady || localLogsBusy}
+ value={localLogsBusy ? t('settings.localLogs.busy') : ''}
+ onPress={() => void runLocalLogAction(exportDiagnostics)}
+ />,
+ <ActionInfoRow
+ key="local-logs-upload"
+ accessibilityLabel={t('settings.localLogs.upload')}
+ label={t('settings.localLogs.upload')}
+ disabled={!localLogsReady || localLogsBusy || !diagnosticUploadConfigured() || !localLogsConsent}
+ detail={!diagnosticUploadConfigured()
+ ? t('settings.localLogs.uploadResult.unavailable')
+ : !localLogsConsent ? t('settings.localLogs.uploadResult.consentRequired')
+ : localLogUploadMessage ?? t('settings.localLogs.uploadHint')}
+ value={
+ localLogsBusy ? t('settings.localLogs.busy') : ''
+ }
+ onPress={() =>
+ void runLocalLogAction(async () => {
+ const result = await uploadMobileDiagnostics();
+ if (result.kind === 'uploaded') {
+ let copied = false;
+ try { await Clipboard.setStringAsync(result.uploadCode); copied = true; } catch { /* upload already succeeded */ }
+ setLocalLogUploadMessage(t(copied ? 'settings.localLogs.uploadCopied' : 'settings.localLogs.uploadSucceeded', { code: result.uploadCode }));
+ } else setLocalLogUploadMessage(t(`settings.localLogs.uploadResult.${result.kind}`));
+ })
+ }
+ />,
...(DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED
? [
<ActionInfoRow
@@ -1425,6 +1546,7 @@ function ActionInfoRow({
accessibilityLabel,
accessibilityRole = 'button',
detail,
+ disabled = false,
label,
onPress,
testID,
@@ -1433,6 +1555,7 @@ function ActionInfoRow({
accessibilityLabel: string;
accessibilityRole?: 'button' | 'link';
detail?: string;
+ disabled?: boolean;
label: string;
onPress(): void;
testID?: string;
@@ -1444,8 +1567,10 @@ function ActionInfoRow({
<Pressable
accessibilityLabel={accessibilityLabel}
accessibilityRole={accessibilityRole}
+ accessibilityState={{ disabled }}
+ disabled={disabled}
onPress={onPress}
- style={({ pressed }) => [styles.row, pressed && styles.pressed]}
+ style={({ pressed }) => [styles.row, (pressed || disabled) && styles.pressed]}
testID={testID}
>
<View style={styles.rowLine}>
@@ -1747,6 +1872,7 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
rowLabel: { color: colors.textSecondary, flexShrink: 0, fontSize: typeScale.code },
rowValue: { color: colors.textPrimary, flex: 1, fontSize: typeScale.code, textAlign: 'right' },
rowDetail: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption },
+ localLogOptions: { minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' },
switchRow: {
alignItems: 'center',
flexDirection: 'row',
diff --git a/apps/mobile/docs/simulator-debugging.md b/apps/mobile/docs/simulator-debugging.md
index 493b57596a..c9d3d0cbb3 100644
--- a/apps/mobile/docs/simulator-debugging.md
+++ b/apps/mobile/docs/simulator-debugging.md
@@ -265,8 +265,41 @@ For device-link network symptoms, collect:
## Render Storm Forensics And Regression Measurement
-背景:2026-07 会话白屏/卡死排查确立的取证与回归测量体系(手机端无落盘日志,
-这套是唯一的量化通道)。触碰 `remoteSessionStore` 订阅链、首页/详情页列表派生
+Release 也可在设置 → 调试 / 开发者打开 Debug 日志,复现后导出。默认关闭;开启后记录
+手机连接恢复、网络变化、错误与堆栈、滚动与键盘几何、渲染计数/解析耗时、JS 停摆。
+不记录聊天正文、完整请求或凭证,不复制被控端任务日志,不捕捉任意 console 或原生日志。
+详细日志最多保留 7 天、8 MiB;每 2 秒及前后台切换时落盘,突然杀进程可能丢失最后一批。
+配置日志服务的构建还可手动上传筛选后的运行摘要(最近 7 天最多 500 条),成功自动复制编号。
+上传摘要不包含详细 Debug 文件,需要详细现场时用导出或开发设备容器读取。
+
+### 从开发版 iPhone 读取历史 Debug 文件
+
+手机与 Mac 配对、开启 Developer Mode 后,可通过 Xcode 设备管理窗口
+(Devices and Simulators)选择对应开发版 App,使用 Download Container。
+在下载的 `.xcappdata` 中查看 `AppData/Documents/cindy-debug/mobile-debug-*.ndjson`。
+记录时不需要连着 Xcode;配对设备通过同网 Wi-Fi 可用时,也可以无线读取。
+这不是任意互联网远程访问,实际权限取决于设备连接、开发签名与系统授权。
+
+也可只拷出日志目录(bundle ID 必须取当前安装的开发版,不猜区域或包名):
+
+```sh
+xcrun devicectl device copy from \
+ --device '<paired-device-id>' \
+ --domain-type appDataContainer \
+ --domain-identifier '<installed-development-bundle-id>' \
+ --source Documents/cindy-debug \
+ --destination /tmp/cindy-mobile-debug
+```
+
+历史文件不会自动出现在 Xcode 实时 Console;该文件日志不是 Apple Unified Logging。
+日志随 App 容器保存(可能进入系统备份),卸载会删除。尚未开启记录或尚未落盘时目录可能不存在。
+Apple 参考:[配对设备](https://developer.apple.com/documentation/xcode/pairing-your-devices-with-your-mac)、
+[下载容器](https://developer.apple.com/documentation/metal/creating-binary-archives-from-device-built-pipeline-state-objects)。
+
+### 进一步测量
+
+背景:2026-07 会话白屏/卡死排查确立的取证与回归测量体系。
+触碰 `remoteSessionStore` 订阅链、首页/详情页列表派生
(索引 useMemo、sections、行 memo)、或做相关重构时,改动前后各测一轮对比。
三层信号,从粗到细:
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index 6dba9a54ce..e5dbd505e2 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -3,6 +3,14 @@ const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
const workspaceRoot = path.resolve(__dirname, '../..');
+// Keep upload routing build-time-only, with the desktop validator as the single configuration source.
+// Missing config is allowed for local/open-source builds; malformed or cross-region config is not.
+const { mobileLogUploadBuildEnv, mobileLogUploadConfigRequired } = require('../../scripts/shared/log-upload-build-env.mjs');
+Object.assign(process.env, mobileLogUploadBuildEnv({
+ repoRoot: workspaceRoot,
+ authRegion: process.env.EXPO_PUBLIC_CINDY_AUTH_REGION || 'global',
+ allowMissing: !mobileLogUploadConfigRequired(),
+}));
const workspaceNodeModules = path.join(workspaceRoot, 'node_modules');
const appNodeModules = path.join(__dirname, 'node_modules');
const sharedArrayBufferPolyfill = path.join(__dirname, 'src/polyfills/sharedArrayBuffer.js');
diff --git a/apps/mobile/src/__tests__/messageFollowGesture.test.ts b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
index 87b68b9855..acb96580e4 100644
--- a/apps/mobile/src/__tests__/messageFollowGesture.test.ts
+++ b/apps/mobile/src/__tests__/messageFollowGesture.test.ts
@@ -4,6 +4,7 @@ import ts from 'typescript';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as scrollModel from '@/session/messageScroll';
import { createMobileTailFollower } from '@/session/messageTailFollower';
+import { mobileDebugEnabled, mobileDebugLog, setMobileDebugSink } from '@/debug/mobileDebugLog';
// Execute the production callbacks without mounting Markdown/media/native views. Unlike source
// assertions, this harness interleaves touch, native scroll, content-size, timers and frame delivery.
@@ -60,7 +61,7 @@ function harness() {
metrics.offsetY = metrics.contentHeight - metrics.viewportHeight;
});
const environment = {
- ...scrollModel, ...state, createMobileTailFollower,
+ ...scrollModel, ...state, createMobileTailFollower, mobileDebugEnabled, mobileDebugLog,
listRef: ref({
scrollToEnd: tailScroll,
scrollToIndex: vi.fn(),
@@ -99,9 +100,23 @@ beforeEach(() => {
vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 16));
vi.stubGlobal('cancelAnimationFrame', (timer: ReturnType<typeof setTimeout>) => clearTimeout(timer));
});
-afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+afterEach(() => { setMobileDebugSink(undefined); vi.useRealTimers(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
describe('streaming follow yields to the reader', () => {
+ it.each(['off', 'on', 'failed'])('preserves reader ownership with Debug recording %s', (recording) => {
+ const sink = vi.fn(() => { if (recording === 'failed') throw new Error('storage unavailable'); });
+ setMobileDebugSink(recording === 'off' ? undefined : sink);
+ const h = harness();
+ h.handleScrollBeginDrag(h.scrollEvent(1200));
+ h.handleScroll(h.scrollEvent(1180));
+ h.handleScrollEndDrag();
+ h.handleContentSize(400, 2500);
+ settle();
+ expect(h.state.nearBottomRef.current).toBe(false);
+ expect(h.tailScroll).not.toHaveBeenCalled();
+ expect(sink.mock.calls.length > 0).toBe(recording !== 'off');
+ });
+
it.each([1196, 1180].flatMap((offset) => ['missing', 'before-verify', 'after-verify'].map((end) => ({ offset, end }))))(
'releases a cancelled drag at $offset with end event $end', ({ offset, end }) => {
const h = harness();
diff --git a/apps/mobile/src/debug/diagnosticEvents.test.ts b/apps/mobile/src/debug/diagnosticEvents.test.ts
new file mode 100644
index 0000000000..4711fccff4
--- /dev/null
+++ b/apps/mobile/src/debug/diagnosticEvents.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+import { projectDiagnostic, restoreDiagnosticEvents } from "./diagnosticEvents";
+
+describe("local diagnostic privacy boundary", () => {
+ it("drops unknown messages and error contents", () => {
+ expect(projectDiagnostic(["secret chat content"])).toBeNull();
+ expect(
+ projectDiagnostic(
+ ["relay connection error", new Error("Bearer secret")],
+ 10,
+ ),
+ ).toEqual({ at: 10, event: "relay connection error", fields: {} });
+ });
+ it("keeps recovery enums and numbers without identities or nested payloads", () => {
+ expect(
+ projectDiagnostic(
+ [
+ "recovery phase",
+ {
+ elapsedMs: 123,
+ phase: "history",
+ outcome: "applied",
+ count: 2,
+ peer: "private-device",
+ connection: Infinity,
+ body: "secret",
+ url: "https://private",
+ },
+ ],
+ 20,
+ ),
+ ).toEqual({
+ at: 20,
+ event: "recovery phase",
+ fields: {
+ elapsedMs: 123,
+ phase: "history",
+ outcome: "applied",
+ count: 2,
+ },
+ });
+ });
+ it("never stores interpolated close reasons or request identifiers", () => {
+ const events = [
+ projectDiagnostic(
+ ["device-link disconnected (code=1001, reason=secret, onlineForMs=2)"],
+ 1,
+ ),
+ projectDiagnostic(
+ ["device-link request timeout private-id elapsed=12ms"],
+ 2,
+ ),
+ ];
+ expect(JSON.stringify(events)).not.toMatch(/secret|private-id/);
+ expect(
+ projectDiagnostic(["device-link online (protocol=v1, elapsedMs=200)"], 3)
+ ?.fields,
+ ).toEqual({ elapsedMs: 200 });
+ });
+ it("revalidates saved fields and bounds history", () => {
+ const events = restoreDiagnosticEvents(
+ Array.from({ length: 1000 }, (_, at) => ({
+ at,
+ event: "app started",
+ fields: { secret: "token" },
+ other: "password",
+ })),
+ );
+ expect(events).toHaveLength(500);
+ expect(events[0]).toEqual({ at: 500, event: "app started", fields: {} });
+ expect(
+ restoreDiagnosticEvents([null, { at: NaN, event: "app started" }]),
+ ).toEqual([]);
+ expect(JSON.stringify(events)).not.toMatch(/token|password/);
+ });
+});
diff --git a/apps/mobile/src/debug/diagnosticEvents.ts b/apps/mobile/src/debug/diagnosticEvents.ts
new file mode 100644
index 0000000000..c5c8d72039
--- /dev/null
+++ b/apps/mobile/src/debug/diagnosticEvents.ts
@@ -0,0 +1,125 @@
+/** Persist only known event names and bounded numbers/enums, never arbitrary log arguments. */
+export type DiagnosticEvent = {
+ at: number;
+ event: string;
+ fields: Record<string, number | string>;
+};
+export const MAX_DIAGNOSTIC_EVENTS = 500;
+const names = [
+ "app started",
+ "app active",
+ "app background",
+ "app inactive",
+ "js stall",
+ "recovery phase",
+ "getToken failed",
+ "createWebSocket failed",
+ "relay connection error",
+ "device-link inbound frame failed",
+ "device-link reliable frame failed",
+ "device-link control frame failed",
+ "device-link legacy frame failed",
+ "device-link online",
+ "device-link disconnected",
+ "device-link stopped by host",
+ "discarding live socket for reconnect",
+ "device-link request timeout",
+ "network probe timed out",
+] as const;
+const numericKeys = [
+ "generation",
+ "connection",
+ "peer",
+ "operation",
+ "elapsedMs",
+ "foregroundElapsedMs",
+ "count",
+];
+const phases = ["subscription", "history", "pending", "projection", "goal"];
+const outcomes = ["applied", "superseded", "failed"];
+function boundedNumber(value: unknown): value is number {
+ return (
+ typeof value === "number" &&
+ Number.isFinite(value) &&
+ value >= 0 &&
+ value <= 1e12
+ );
+}
+
+export function projectDiagnostic(
+ args: readonly unknown[],
+ at = Date.now(),
+): DiagnosticEvent | null {
+ const message = args[0];
+ if (
+ typeof message !== "string" ||
+ message.length > 4096 ||
+ !Number.isFinite(at)
+ )
+ return null;
+ const event = names.find(
+ (name) =>
+ message === name ||
+ message.startsWith(`${name} (`) ||
+ (name === "device-link request timeout" &&
+ message.startsWith(`${name} `)),
+ );
+ if (!event) return null;
+ const fields: DiagnosticEvent["fields"] = {};
+ // Do not serialize errors, stack traces, identifiers, endpoints, or even unknown nested fields.
+ if (event === "recovery phase" || event === "js stall") {
+ const data = args[1];
+ if (data && typeof data === "object") {
+ const record = data as Record<string, unknown>;
+ for (const key of numericKeys)
+ if (boundedNumber(record[key])) fields[key] = record[key];
+ if (event === "recovery phase") {
+ if (typeof record.phase === "string" && phases.includes(record.phase))
+ fields.phase = record.phase;
+ if (
+ typeof record.outcome === "string" &&
+ outcomes.includes(record.outcome)
+ )
+ fields.outcome = record.outcome;
+ }
+ }
+ }
+ // Extract only client-generated timing fields. Never retain the original interpolated message.
+ if (event === "device-link online" || event === "network probe timed out") {
+ const match = /elapsedMs=(\d+(?:\.\d+)?)/.exec(message);
+ if (match && boundedNumber(Number(match[1])))
+ fields.elapsedMs = Number(match[1]);
+ }
+ return { at, event, fields };
+}
+
+/** Re-project saved input too: an older/corrupt file must not bypass today's recording boundary. */
+export function restoreDiagnosticEvents(value: unknown): DiagnosticEvent[] {
+ if (!Array.isArray(value)) return [];
+ return value.slice(-MAX_DIAGNOSTIC_EVENTS).flatMap((row: unknown) => {
+ if (!row || typeof row !== "object") return [];
+ const record = row as Record<string, unknown>;
+ if (
+ typeof record.at !== "number" ||
+ !Number.isFinite(record.at) ||
+ record.at < 0
+ )
+ return [];
+ const projected = projectDiagnostic(
+ [record.event, record.fields],
+ record.at,
+ );
+ if (!projected) return [];
+ // The saved timing is separate from its canonical event label.
+ if (
+ (projected.event === "device-link online" ||
+ projected.event === "network probe timed out") &&
+ record.fields &&
+ typeof record.fields === "object"
+ ) {
+ const elapsedMs = (record.fields as Record<string, unknown>).elapsedMs;
+ if (boundedNumber(elapsedMs)) projected.fields.elapsedMs = elapsedMs;
+ }
+ return [projected];
+ });
+}
diff --git a/apps/mobile/src/debug/diagnosticUpload.test.ts b/apps/mobile/src/debug/diagnosticUpload.test.ts
new file mode 100644
index 0000000000..5eaf688bfc
--- /dev/null
+++ b/apps/mobile/src/debug/diagnosticUpload.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ parseDiagnosticUploadTarget,
+ uploadDiagnosticSnapshot,
+ type DiagnosticUploadDeps,
+} from "./diagnosticUpload";
+
+const target = {
+ region: "global",
+ project: "test-global",
+ logstore: "test-mobile",
+ endpointHost: "ap-southeast-1.log.aliyuncs.com",
+};
+function deps(): DiagnosticUploadDeps {
+ return {
+ rawTarget: JSON.stringify(target),
+ region: "global",
+ consent: vi.fn(async () => true),
+ snapshot: vi.fn(async () => [
+ { at: Date.now(), event: "app started", fields: { token: "secret" } },
+ ]),
+ randomBytes: () => new Uint8Array(16),
+ fetch: vi.fn(async () => new Response("", { status: 200 })),
+ appVersion: "测试",
+ platform: "ios",
+ osVersion: "27",
+ };
+}
+describe("manual mobile diagnostic upload", () => {
+ it("uses desktop wire format and byte counts without credentials or unknown fields", async () => {
+ const d = deps();
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({
+ kind: "uploaded",
+ uploadCode: "2222-2222",
+ count: 1,
+ });
+ const [url, init] = vi.mocked(d.fetch).mock.calls[0];
+ expect(url).toBe(
+ "https://test-global.ap-southeast-1.log.aliyuncs.com/logstores/test-mobile/track",
+ );
+ expect(init.headers).toMatchObject({
+ "x-log-apiversion": "0.6.0",
+ "x-log-bodyrawsize": String(
+ new TextEncoder().encode(String(init.body)).byteLength,
+ ),
+ });
+ expect(String(init.body)).not.toMatch(/secret|token|Authorization/);
+ expect(init.credentials).toBe("omit");
+ expect(init.redirect).toBe("error");
+ expect(JSON.parse(String(init.body)).__logs__[0].uploadCode).toBe(
+ "2222-2222",
+ );
+ });
+ it.each([
+ "",
+ JSON.stringify({ ...target, region: "cn" }),
+ JSON.stringify({ ...target, project: "evil.com" }),
+ JSON.stringify({ ...target, endpointHost: "evil.com" }),
+ ])(
+ "rejects absent or invalid routing before any collection: %s",
+ async (raw) => {
+ const d = { ...deps(), rawTarget: raw };
+ expect(parseDiagnosticUploadTarget(raw, "global")).toBeNull();
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({
+ kind: "unavailable",
+ });
+ expect(d.snapshot).not.toHaveBeenCalled();
+ expect(d.fetch).not.toHaveBeenCalled();
+ },
+ );
+ it("requires consent even when the user manually asks to upload", async () => {
+ const d = deps();
+ vi.mocked(d.consent).mockResolvedValue(false);
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({
+ kind: "consentRequired",
+ });
+ expect(d.snapshot).not.toHaveBeenCalled();
+ expect(d.fetch).not.toHaveBeenCalled();
+ });
+ it("rechecks consent after asynchronous collection", async () => {
+ const d = deps();
+ vi.mocked(d.consent).mockResolvedValueOnce(true).mockResolvedValue(false);
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({
+ kind: "consentRequired",
+ });
+ expect(d.fetch).not.toHaveBeenCalled();
+ });
+ it("does not upload empty or invalid records", async () => {
+ const d = deps();
+ vi.mocked(d.snapshot).mockResolvedValue([{ at: 1, event: "unknown body" }]);
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({ kind: "empty" });
+ expect(d.fetch).not.toHaveBeenCalled();
+ });
+ it("treats server errors as failure without retries", async () => {
+ const d = deps();
+ vi.mocked(d.fetch).mockResolvedValue(new Response("", { status: 503 }));
+ expect(await uploadDiagnosticSnapshot(d)).toEqual({ kind: "failed" });
+ expect(d.fetch).toHaveBeenCalledTimes(1);
+ });
+ it("cancels a stalled network request", async () => {
+ vi.useFakeTimers();
+ try {
+ const d = deps();
+ vi.mocked(d.fetch).mockImplementation(
+ (_url, init) =>
+ new Promise((_resolve, reject) => {
+ init.signal?.addEventListener("abort", () =>
+ reject(new Error("aborted")),
+ );
+ }),
+ );
+ const result = uploadDiagnosticSnapshot(d);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(await result).toEqual({ kind: "failed" });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/mobile/src/debug/diagnosticUpload.ts b/apps/mobile/src/debug/diagnosticUpload.ts
new file mode 100644
index 0000000000..7f60206a28
--- /dev/null
+++ b/apps/mobile/src/debug/diagnosticUpload.ts
@@ -0,0 +1,137 @@
+import { restoreDiagnosticEvents } from "./diagnosticEvents";
+
+/** Desktop SLS web-tracking wire contract, with mobile's narrower event projection. */
+export interface DiagnosticUploadTarget {
+ region: string;
+ project: string;
+ logstore: string;
+ endpointHost: string;
+}
+export function parseDiagnosticUploadTarget(
+ raw: string,
+ region: string,
+): DiagnosticUploadTarget | null {
+ try {
+ const value = JSON.parse(raw);
+ if (
+ !value ||
+ value.region !== region ||
+ !["cn", "global", "dev"].includes(region)
+ )
+ return null;
+ if (
+ typeof value.project !== "string" ||
+ !/^[a-z0-9][a-z0-9-]*$/.test(value.project)
+ )
+ return null;
+ if (
+ typeof value.logstore !== "string" ||
+ !/^[a-z0-9][a-z0-9-]*$/.test(value.logstore)
+ )
+ return null;
+ if (
+ typeof value.endpointHost !== "string" ||
+ !/^[a-z0-9][a-z0-9-]*\.log\.aliyuncs\.com$/.test(value.endpointHost)
+ )
+ return null;
+ return {
+ region,
+ project: value.project,
+ logstore: value.logstore,
+ endpointHost: value.endpointHost,
+ };
+ } catch {
+ return null;
+ }
+}
+
+export type DiagnosticUploadResult =
+ | { kind: "uploaded"; uploadCode: string; count: number }
+ | { kind: "unavailable" | "consentRequired" | "empty" | "failed" };
+
+/** Dependencies keep tests offline and keep native/auth modules out of the wire contract. */
+export interface DiagnosticUploadDeps {
+ rawTarget: string;
+ region: string;
+ consent(): Promise<boolean>;
+ snapshot(): Promise<unknown>;
+ randomBytes(size: number): Uint8Array;
+ fetch(input: string, init: RequestInit): Promise<Response>;
+ appVersion: string;
+ platform: string;
+ osVersion: string;
+}
+
+export async function uploadDiagnosticSnapshot(
+ deps: DiagnosticUploadDeps,
+): Promise<DiagnosticUploadResult> {
+ const target = parseDiagnosticUploadTarget(deps.rawTarget, deps.region);
+ if (!target) return { kind: "unavailable" };
+ try {
+ if (!(await deps.consent())) return { kind: "consentRequired" };
+ const events = restoreDiagnosticEvents(await deps.snapshot());
+ if (!events.length) return { kind: "empty" };
+ // Same readable alphabet and XXXX-XXXX format as desktop; rejection sampling avoids bias.
+ const alphabet = "23456789ABCDEFGHJKMNPQRSTVWXYZ";
+ const limit = Math.floor(256 / alphabet.length) * alphabet.length;
+ let code = "";
+ for (let attempt = 0; code.length < 8 && attempt < 32; attempt++) {
+ for (const byte of deps.randomBytes(16)) {
+ if (byte < limit) code += alphabet[byte % alphabet.length];
+ if (code.length === 8) break;
+ }
+ }
+ if (code.length !== 8) return { kind: "failed" };
+ const uploadCode = `${code.slice(0, 4)}-${code.slice(4)}`;
+ const body = JSON.stringify({
+ __topic__: "cindy-client-log",
+ __source__: "mobile",
+ __tags__: {
+ uploadCode,
+ region: target.region,
+ reason: "manual",
+ appVersion: deps.appVersion.slice(0, 80),
+ platform: deps.platform === "ios" ? "ios" : "android",
+ osVersion: deps.osVersion.slice(0, 80),
+ },
+ __logs__: events.map((event) => ({
+ ts: new Date(event.at).toISOString(),
+ level: "info",
+ src: "mobile",
+ scope: "mobile-diagnostics",
+ msg: JSON.stringify({ event: event.event, ...event.fields }),
+ uploadCode,
+ })),
+ });
+ const size = new TextEncoder().encode(body).byteLength;
+ // 500 bounded events fit in one desktop-sized batch. Refuse, never silently truncate a payload.
+ if (size > 1024 * 1024) return { kind: "failed" };
+ if (!(await deps.consent())) return { kind: "consentRequired" };
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 20_000);
+ try {
+ const response = await deps.fetch(
+ `https://${target.project}.${target.endpointHost}/logstores/${target.logstore}/track`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "x-log-apiversion": "0.6.0",
+ "x-log-bodyrawsize": String(size),
+ },
+ body,
+ signal: controller.signal,
+ credentials: "omit",
+ redirect: "error",
+ },
+ );
+ return response.status >= 200 && response.status < 300
+ ? { kind: "uploaded", uploadCode, count: events.length }
+ : { kind: "failed" };
+ } finally {
+ clearTimeout(timer);
+ }
+ } catch {
+ return { kind: "failed" };
+ }
+}
diff --git a/apps/mobile/src/debug/localDiagnostics.test.ts b/apps/mobile/src/debug/localDiagnostics.test.ts
new file mode 100644
index 0000000000..9edf6b3f76
--- /dev/null
+++ b/apps/mobile/src/debug/localDiagnostics.test.ts
@@ -0,0 +1,346 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const storage = vi.hoisted(() => ({ getItem: vi.fn(), setItem: vi.fn() }));
+const files = vi.hoisted(() => ({
+ write: vi.fn(),
+ remove: vi.fn(),
+ share: vi.fn(),
+ available: vi.fn(),
+ append: vi.fn(),
+ clear: vi.fn(),
+ copy: vi.fn(),
+ prune: vi.fn(),
+}));
+const lifecycle = vi.hoisted(() => ({ listen: vi.fn() }));
+vi.mock("./mobileDebugFiles", () => ({
+ appendMobileDebugFile: files.append,
+ clearMobileDebugFiles: files.clear,
+ copyMobileDebugFiles: files.copy,
+ pruneMobileDebugFiles: files.prune,
+}));
+vi.mock("@react-native-async-storage/async-storage", () => ({
+ default: storage,
+}));
+vi.mock("expo-file-system", () => ({
+ File: class {
+ uri = "file:///cache/cindy-diagnostics.json";
+ exists = true;
+ write = files.write;
+ delete = files.remove;
+ },
+ Paths: { cache: "file:///cache" },
+}));
+vi.mock("expo-sharing", () => ({
+ isAvailableAsync: files.available,
+ shareAsync: files.share,
+}));
+vi.mock("react-native", () => ({
+ AppState: {
+ currentState: "active",
+ addEventListener: lifecycle.listen,
+ },
+}));
+afterEach(() => vi.useRealTimers());
+beforeEach(() => {
+ vi.resetModules();
+ vi.stubEnv("EXPO_PUBLIC_CINDY_DIAGNOSTICS", "1");
+ storage.getItem.mockReset().mockResolvedValue(null);
+ storage.setItem.mockReset().mockResolvedValue(undefined);
+ files.write.mockReset();
+ files.append.mockReset();
+ files.clear.mockReset();
+ files.copy.mockReset();
+ files.prune.mockReset();
+ lifecycle.listen.mockReset().mockReturnValue({ remove() {} });
+ files.remove.mockReset();
+ files.share.mockReset().mockResolvedValue(undefined);
+ files.available.mockReset().mockResolvedValue(true);
+});
+describe("local journal persistence", () => {
+ it.each([false, true])(
+ "stops collection throughout a delayed opt-out (save fails: %s)",
+ async (fails) => {
+ vi.useFakeTimers();
+ const log = await import("./localDiagnostics");
+ const debug = await import("./mobileDebugLog");
+ const stop = log.startLocalDiagnostics();
+ await log.hydrateDiagnostics();
+ await log.flushDiagnostics();
+ const before = await log.diagnosticSnapshot();
+ let resolve!: () => void;
+ let reject!: (error: Error) => void;
+ storage.setItem.mockImplementationOnce(
+ () =>
+ new Promise<void>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ }),
+ );
+ const pending = log.setDiagnosticsEnabled(false);
+ const outcome = pending.catch(() => {});
+ expect(debug.mobileDebugEnabled()).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.advanceTimersByTimeAsync(4000);
+ debug.mobileDebugLog("debug", "recovery", "after opt-out");
+ log.recordDiagnostic("relay connection error");
+ if (fails) reject(new Error("save failed"));
+ else resolve();
+ await outcome;
+ expect(log.diagnosticsEnabled()).toBe(fails);
+ await log.flushDiagnostics();
+ expect(
+ files.append.mock.calls.map(([batch]) => batch).join(""),
+ ).not.toContain("after opt-out");
+ expect(await log.diagnosticSnapshot()).toEqual(before);
+ expect(vi.getTimerCount()).toBe(fails ? 1 : 0);
+ stop();
+ },
+ );
+ it("prunes on disabled startup and foreground without recording or starting a probe", async () => {
+ vi.useFakeTimers();
+ storage.getItem.mockResolvedValue(
+ JSON.stringify({ enabled: false, events: [] }),
+ );
+ files.prune.mockImplementationOnce(() => {
+ throw new Error("storage unavailable");
+ });
+ const log = await import("./localDiagnostics");
+ const stop = log.startLocalDiagnostics();
+ await log.hydrateDiagnostics();
+ await log.flushDiagnostics();
+ expect(files.prune).toHaveBeenCalledTimes(1);
+ const change = lifecycle.listen.mock.calls[0][1];
+ change("background");
+ change("active");
+ await log.flushDiagnostics();
+ expect(files.prune).toHaveBeenCalledTimes(2);
+ expect(files.append).not.toHaveBeenCalled();
+ expect(storage.setItem).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ stop();
+ });
+ it.each([false, true])(
+ "keeps the previous preference when saving %s fails",
+ async (next) => {
+ storage.getItem.mockResolvedValue(
+ JSON.stringify({ enabled: !next, events: [] }),
+ );
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ storage.setItem.mockRejectedValueOnce(new Error("storage unavailable"));
+ await expect(log.setDiagnosticsEnabled(next)).rejects.toThrow(
+ "storage unavailable",
+ );
+ expect(log.diagnosticsEnabled()).toBe(!next);
+ await log.flushDiagnostics();
+ expect(JSON.parse(storage.setItem.mock.calls.at(-1)![1]).enabled).toBe(
+ !next,
+ );
+ },
+ );
+ it("runs no probe while off and stops it immediately after a durable opt-out", async () => {
+ vi.useFakeTimers();
+ vi.stubEnv("EXPO_PUBLIC_CINDY_DIAGNOSTICS", "0");
+ const log = await import("./localDiagnostics");
+ const stop = log.startLocalDiagnostics();
+ await log.hydrateDiagnostics();
+ expect(vi.getTimerCount()).toBe(0);
+ await log.setDiagnosticsEnabled(true);
+ expect(vi.getTimerCount()).toBe(1);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(
+ files.append.mock.calls.some(([batch]) =>
+ batch.includes("render metrics"),
+ ),
+ ).toBe(true);
+ await log.setDiagnosticsEnabled(false);
+ expect(vi.getTimerCount()).toBe(0);
+ stop();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it("persists detailed local errors but exposes only the whitelist to upload", async () => {
+ const log = await import("./localDiagnostics");
+ const debug = await import("./mobileDebugLog");
+ await log.hydrateDiagnostics();
+ debug.mobileDebugLog(
+ "error",
+ "device-link",
+ "relay connection error",
+ new Error("socket timed out Bearer hidden-secret"),
+ );
+ debug.mobileDebugLog("debug", "recovery", "snapshot applied", {
+ elapsedMs: 456,
+ count: 12,
+ });
+ await log.flushDiagnostics();
+ const batch = files.append.mock.calls[0][0];
+ expect(batch).toContain("socket timed out");
+ expect(batch).toContain("snapshot applied");
+ expect(batch).not.toContain("hidden-secret");
+ expect(await log.diagnosticSnapshot()).toEqual([
+ { at: expect.any(Number), event: "relay connection error", fields: {} },
+ ]);
+ await log.setDiagnosticsEnabled(false);
+ files.append.mockClear();
+ debug.mobileDebugLog("debug", "scroll", "disabled event");
+ await log.flushDiagnostics();
+ expect(files.append).not.toHaveBeenCalled();
+ });
+ it("bounds detailed buffers while disk is slow and records the overflow", async () => {
+ const log = await import("./localDiagnostics");
+ const { mobileDebugLog } = await import("./mobileDebugLog");
+ await log.hydrateDiagnostics();
+ let release!: () => void;
+ storage.setItem.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ mobileDebugLog("debug", "recovery", "start");
+ const first = log.flushDiagnostics();
+ await Promise.resolve();
+ for (let i = 0; i < 180; i++)
+ mobileDebugLog("debug", "recovery", "x".repeat(4000));
+ const later = log.flushDiagnostics();
+ expect(files.append).toHaveBeenCalledTimes(1);
+ release();
+ await Promise.all([first, later]);
+ expect(files.append).toHaveBeenCalledTimes(2);
+ expect(files.append.mock.calls[1][0].length).toBeLessThan(513 * 1024);
+ expect(files.append.mock.calls[1][0]).toContain("debug records lost");
+ });
+ it("recovers after file failure and reports a gap without blocking the opt-out", async () => {
+ const log = await import("./localDiagnostics");
+ const { mobileDebugLog } = await import("./mobileDebugLog");
+ await log.hydrateDiagnostics();
+ mobileDebugLog("debug", "recovery", "failed batch");
+ files.append.mockImplementationOnce(() => {
+ throw new Error("disk full");
+ });
+ await expect(log.setDiagnosticsEnabled(false)).rejects.toThrow("disk full");
+ expect(JSON.parse(storage.setItem.mock.calls.at(-1)![1]).enabled).toBe(
+ false,
+ );
+ await log.flushDiagnostics();
+ expect(files.append.mock.calls.at(-1)![0]).toContain("debug records lost");
+ });
+ it("turns recording off without clearing retained logs", async () => {
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ log.recordDiagnostic("app active");
+ await log.setDiagnosticsEnabled(false);
+ expect(log.diagnosticsEnabled()).toBe(false);
+ const saved = JSON.parse(storage.setItem.mock.calls.at(-1)![1]);
+ expect(saved.enabled).toBe(false);
+ expect(saved.events).toHaveLength(1);
+ });
+ it.each([false, true])(
+ "cleans the export cache after sharing (failure=%s)",
+ async (fails) => {
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ log.recordDiagnostic(
+ "relay connection error",
+ new Error("private token"),
+ );
+ if (fails) files.share.mockRejectedValueOnce(new Error("share failed"));
+ if (fails)
+ await expect(log.exportDiagnostics()).rejects.toThrow("share failed");
+ else await log.exportDiagnostics();
+ expect(files.remove).toHaveBeenCalledOnce();
+ expect(files.copy).toHaveBeenCalledOnce();
+ await log.exportDiagnostics();
+ expect(files.share).toHaveBeenCalledTimes(2);
+ },
+ );
+ it("is off by default in normal builds", async () => {
+ vi.stubEnv("EXPO_PUBLIC_CINDY_DIAGNOSTICS", "");
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ expect(log.diagnosticsEnabled()).toBe(false);
+ });
+ it("prunes expired and future records before persisting and exporting", async () => {
+ const now = Date.now();
+ storage.getItem.mockResolvedValue(
+ JSON.stringify({
+ events: [
+ { at: now - 8 * 86400_000, event: "app started" },
+ { at: now + 86400_000, event: "app started" },
+ { at: now, event: "app active" },
+ ],
+ }),
+ );
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ expect(await log.diagnosticSnapshot()).toEqual([
+ { at: now, event: "app active", fields: {} },
+ ]);
+ await log.flushDiagnostics();
+ expect(
+ JSON.parse(storage.setItem.mock.calls.at(-1)![1]).events,
+ ).toHaveLength(1);
+ });
+ it("does not enable a corrupt opt-out record", async () => {
+ storage.getItem.mockResolvedValue('{"enabled":"false"}');
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ expect(log.diagnosticsEnabled()).toBe(false);
+ });
+ it("does not record before hydration and bounds persisted events", async () => {
+ const log = await import("./localDiagnostics");
+ log.recordDiagnostic("relay connection error", "private");
+ await log.hydrateDiagnostics();
+ for (let i = 0; i < 700; i++) log.recordDiagnostic("app active");
+ await log.flushDiagnostics();
+ const saved = JSON.parse(storage.setItem.mock.calls.at(-1)![1]);
+ expect(saved.events).toHaveLength(500);
+ expect(saved.enabled).toBeUndefined();
+ expect(JSON.stringify(saved)).not.toContain("private");
+ });
+ it("retains an explicit opt-out across launches", async () => {
+ storage.getItem.mockResolvedValue(
+ JSON.stringify({ enabled: false, events: [] }),
+ );
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ log.recordDiagnostic("app started");
+ await log.flushDiagnostics();
+ expect(log.diagnosticsEnabled()).toBe(false);
+ expect(storage.setItem).not.toHaveBeenCalled();
+ });
+ it("fails closed on an unreadable store", async () => {
+ storage.getItem.mockRejectedValue(new Error("unavailable"));
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ expect(log.diagnosticsEnabled()).toBe(false);
+ });
+ it("orders clear after an older in-flight save", async () => {
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ let release!: () => void;
+ storage.setItem.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+ log.recordDiagnostic("app started");
+ const first = log.flushDiagnostics();
+ await Promise.resolve();
+ const cleared = log.clearDiagnostics();
+ release();
+ await Promise.all([first, cleared]);
+ expect(JSON.parse(storage.setItem.mock.calls.at(-1)![1]).events).toEqual(
+ [],
+ );
+ });
+ it("reports failed writes and retries on the next flush", async () => {
+ const log = await import("./localDiagnostics");
+ await log.hydrateDiagnostics();
+ storage.setItem.mockRejectedValueOnce(new Error("disk full"));
+ log.recordDiagnostic("app started");
+ await expect(log.flushDiagnostics()).rejects.toThrow("disk full");
+ await log.flushDiagnostics();
+ expect(storage.setItem).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/mobile/src/debug/localDiagnostics.ts b/apps/mobile/src/debug/localDiagnostics.ts
new file mode 100644
index 0000000000..805b299546
--- /dev/null
+++ b/apps/mobile/src/debug/localDiagnostics.ts
@@ -0,0 +1,284 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import { File, Paths } from "expo-file-system";
+import * as Sharing from "expo-sharing";
+import { AppState } from "react-native";
+import { mobileDebugLog, setMobileDebugSink } from "./mobileDebugLog";
+import { serializeMobileDebugRecord } from "./mobileDebugRecord";
+import {
+ appendMobileDebugFile,
+ clearMobileDebugFiles,
+ copyMobileDebugFiles,
+ pruneMobileDebugFiles,
+} from "./mobileDebugFiles";
+import { getMobileMarkdownRenderMetrics } from "../session/mobileMarkdownRenderMetrics";
+import { getMobileMessageWebViewMetrics } from "../session/mobileMessageWebViewMetrics";
+import {
+ MAX_DIAGNOSTIC_EVENTS,
+ projectDiagnostic,
+ restoreDiagnosticEvents,
+ type DiagnosticEvent,
+} from "./diagnosticEvents";
+
+const KEY = "cindy.mobile.localDiagnostics.v1";
+const DEFAULT_ENABLED = process.env.EXPO_PUBLIC_CINDY_DIAGNOSTICS === "1";
+let enabled = false;
+let override: boolean | undefined;
+let persistedOverride: boolean | undefined;
+const recordingListeners = new Set<() => void>();
+let events: DiagnosticEvent[] = [];
+let hydration: Promise<void> | undefined;
+let ready = false;
+let dirty = false;
+let writes = Promise.resolve();
+let flushing = false;
+let sharing = false;
+let debugBatch = "";
+let debugBytes = 0;
+let dropped = 0;
+const MAX_PENDING_BYTES = 512 * 1024;
+
+function updateDebugSink(): void {
+ setMobileDebugSink(
+ enabled
+ ? (level, scope, args) => {
+ if (scope === "device-link" || scope === "lifecycle")
+ recordDiagnostic(...args);
+ const line = serializeMobileDebugRecord(level, scope, args);
+ const bytes = new TextEncoder().encode(line).byteLength;
+ if (debugBytes + bytes > MAX_PENDING_BYTES) {
+ dropped++;
+ return;
+ }
+ debugBatch += line;
+ debugBytes += bytes;
+ }
+ : undefined,
+ );
+ for (const listener of recordingListeners) listener();
+}
+
+function retainedEvents(value: unknown): DiagnosticEvent[] {
+ const now = Date.now();
+ return restoreDiagnosticEvents(value).filter(
+ (event) => event.at >= now - 7 * 24 * 60 * 60 * 1000 && event.at <= now,
+ );
+}
+
+/** Explicitly hydrated, bounded local journal. No upload and no global console interception. */
+export function hydrateDiagnostics(): Promise<void> {
+ return (hydration ??= (async () => {
+ try {
+ const raw = await AsyncStorage.getItem(KEY);
+ if (raw !== null) {
+ if (raw.length > 256_000) throw new Error("oversized diagnostics");
+ const saved = JSON.parse(raw);
+ if (
+ !saved ||
+ typeof saved !== "object" ||
+ Array.isArray(saved) ||
+ (saved.enabled !== undefined && typeof saved.enabled !== "boolean")
+ )
+ throw new Error("invalid diagnostics");
+ override =
+ typeof saved.enabled === "boolean" ? saved.enabled : undefined;
+ events = retainedEvents(saved.events);
+ dirty =
+ Array.isArray(saved.events) && saved.events.length !== events.length;
+ }
+ enabled = override ?? DEFAULT_ENABLED;
+ } catch {
+ // Read failures cannot silently turn an existing opt-out back on.
+ enabled = false;
+ override = false;
+ }
+ ready = true;
+ persistedOverride = override;
+ updateDebugSink();
+ })());
+}
+
+export function diagnosticsEnabled(): boolean {
+ return enabled;
+}
+
+/** Revalidate before either export or upload; never return mutable journal state. */
+export async function diagnosticSnapshot(): Promise<DiagnosticEvent[]> {
+ await hydrateDiagnostics();
+ return retainedEvents(events);
+}
+
+export function recordDiagnostic(...args: unknown[]): void {
+ if (!ready || !enabled) return;
+ const event = projectDiagnostic(args);
+ if (!event) return;
+ events.push(event);
+ if (events.length > MAX_DIAGNOSTIC_EVENTS)
+ events.splice(0, events.length - MAX_DIAGNOSTIC_EVENTS);
+ dirty = true;
+}
+
+export function flushDiagnostics(): Promise<void> {
+ // Keep only the bounded live buffer while a disk write is pending, not a queue of large snapshots.
+ if (flushing) return writes.then(flushDiagnostics);
+ const retained = retainedEvents(events);
+ if (retained.length !== events.length) {
+ events = retained;
+ dirty = true;
+ }
+ if (!ready || (!dirty && !debugBatch && !dropped)) return writes;
+ dirty = false;
+ flushing = true;
+ const batch =
+ debugBatch +
+ (dropped
+ ? serializeMobileDebugRecord("warn", "performance", [
+ "debug records lost (buffer or storage)",
+ { dropped },
+ ])
+ : "");
+ debugBatch = "";
+ debugBytes = 0;
+ dropped = 0;
+ // Snapshot before enqueueing; sequential writes prevent an older flush resurrecting cleared logs.
+ const snapshotOverride = override;
+ const snapshot = JSON.stringify({ enabled: snapshotOverride, events });
+ const pending = writes.then(async () => {
+ // File failure must not discard the pending settings/summary write.
+ try {
+ appendMobileDebugFile(batch);
+ } catch (error) {
+ // Count records in the failed batch; a settings-only failure did not lose the file contents.
+ if (batch) dropped += batch.split("\n").length - 1;
+ throw error;
+ } finally {
+ await AsyncStorage.setItem(KEY, snapshot);
+ persistedOverride = snapshotOverride;
+ }
+ });
+ writes = pending
+ .catch(() => {
+ dirty = true;
+ // Do not grow an unbounded retry queue when storage is unavailable.
+ // A later successful flush explicitly records the gap.
+ })
+ .finally(() => {
+ flushing = false;
+ });
+ return pending;
+}
+
+export async function setDiagnosticsEnabled(value: boolean): Promise<void> {
+ if (!ready) await hydrateDiagnostics();
+ // Opt-out stops collection before any storage await; a failed save restores the durable state.
+ if (!value) {
+ enabled = false;
+ updateDebugSink();
+ }
+ override = value;
+ dirty = true;
+ try {
+ await flushDiagnostics();
+ } finally {
+ // The switch and probe reflect the last durable preference, including failed opt-outs.
+ override = persistedOverride;
+ enabled = override ?? DEFAULT_ENABLED;
+ updateDebugSink();
+ }
+ if (value)
+ mobileDebugLog("info", "lifecycle", "debug recording enabled", {
+ appState: AppState.currentState,
+ });
+}
+
+export async function clearDiagnostics(): Promise<void> {
+ await hydrateDiagnostics();
+ events = [];
+ debugBatch = "";
+ debugBytes = 0;
+ dropped = 0;
+ dirty = true;
+ const cleared = writes.then(clearMobileDebugFiles);
+ writes = cleared.catch(() => {});
+ await cleared;
+ await flushDiagnostics();
+}
+
+export async function exportDiagnostics(): Promise<void> {
+ if (sharing) return;
+ sharing = true;
+ let file: File | undefined;
+ try {
+ await hydrateDiagnostics();
+ await flushDiagnostics();
+ if (!(await Sharing.isAvailableAsync()))
+ throw new Error("sharing unavailable");
+ file = new File(Paths.cache, `cindy-mobile-debug-${Date.now()}.ndjson`);
+ copyMobileDebugFiles(file);
+ await Sharing.shareAsync(file.uri, {
+ mimeType: "text/plain",
+ UTI: "public.plain-text",
+ });
+ } finally {
+ try {
+ if (file?.exists) file.delete();
+ } finally {
+ sharing = false;
+ }
+ }
+}
+
+/** Lifecycle flush plus a low-frequency foreground-only stall probe; no Metro dependency. */
+export function startLocalDiagnostics(): () => void {
+ // Retention is independent of recording. Reuse the write queue and lifecycle, not a timer.
+ const prune = () => {
+ writes = writes.then(pruneMobileDebugFiles).catch(() => {});
+ };
+ prune();
+ let stopped = false;
+ let state = AppState.currentState;
+ let lastTick = performance.now();
+ void hydrateDiagnostics().then(() => {
+ if (!stopped)
+ mobileDebugLog("info", "lifecycle", "app started", { appState: state });
+ });
+ const listener = AppState.addEventListener("change", (next) => {
+ if (next === "active") prune();
+ state = next;
+ lastTick = performance.now();
+ mobileDebugLog("info", "lifecycle", `app ${next}`);
+ void flushDiagnostics().catch(() => {});
+ });
+ let timer: ReturnType<typeof setInterval> | undefined;
+ const tick = () => {
+ const now = performance.now();
+ if (state === "active" && now - lastTick > 3000)
+ mobileDebugLog("warn", "lifecycle", "js stall", {
+ elapsedMs: now - lastTick - 2000,
+ });
+ lastTick = now;
+ if (enabled)
+ mobileDebugLog("debug", "performance", "render metrics", {
+ markdown: getMobileMarkdownRenderMetrics(),
+ webViews: getMobileMessageWebViewMetrics(),
+ });
+ void flushDiagnostics().catch(() => {});
+ };
+ const syncProbe = () => {
+ if (!enabled || stopped) {
+ if (timer !== undefined) clearInterval(timer);
+ timer = undefined;
+ } else if (timer === undefined) {
+ lastTick = performance.now();
+ timer = setInterval(tick, 2000);
+ }
+ };
+ recordingListeners.add(syncProbe);
+ syncProbe();
+ return () => {
+ stopped = true;
+ listener.remove();
+ recordingListeners.delete(syncProbe);
+ syncProbe();
+ void flushDiagnostics().catch(() => {});
+ };
+}
diff --git a/apps/mobile/src/debug/mobileDebugFiles.test.ts b/apps/mobile/src/debug/mobileDebugFiles.test.ts
new file mode 100644
index 0000000000..c4cdda0038
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDebugFiles.test.ts
@@ -0,0 +1,136 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+const disk = vi.hoisted(() => ({
+ files: new Map<string, string>(),
+ dirs: new Set<string>(),
+ closed: vi.fn(),
+}));
+vi.mock("expo-file-system", () => {
+ const uri = (parts: (string | { uri: string })[]) =>
+ parts.map((part) => (typeof part === "string" ? part : part.uri)).join("/");
+ class File {
+ uri: string;
+ constructor(...parts: (string | { uri: string })[]) {
+ this.uri = uri(parts);
+ }
+ get name() {
+ return this.uri.split("/").at(-1)!;
+ }
+ get exists() {
+ return disk.files.has(this.uri);
+ }
+ get size() {
+ return new TextEncoder().encode(disk.files.get(this.uri) ?? "").length;
+ }
+ create() {
+ if (this.exists) throw new Error("exists");
+ disk.files.set(this.uri, "");
+ }
+ write(value: string | Uint8Array, options?: { append: boolean }) {
+ const text =
+ typeof value === "string" ? value : new TextDecoder().decode(value);
+ disk.files.set(
+ this.uri,
+ (options?.append ? (disk.files.get(this.uri) ?? "") : "") + text,
+ );
+ }
+ delete() {
+ disk.files.delete(this.uri);
+ }
+ open() {
+ const bytes = new TextEncoder().encode(disk.files.get(this.uri)!);
+ return {
+ offset: 0,
+ size: bytes.length,
+ close: disk.closed,
+ readBytes(length: number) {
+ const chunk = bytes.slice(this.offset, this.offset + length);
+ this.offset += chunk.length;
+ return chunk;
+ },
+ };
+ }
+ }
+ class Directory {
+ uri: string;
+ constructor(...parts: (string | { uri: string })[]) {
+ this.uri = uri(parts);
+ }
+ get exists() {
+ return disk.dirs.has(this.uri);
+ }
+ create() {
+ disk.dirs.add(this.uri);
+ }
+ list() {
+ return [...disk.files.keys()]
+ .filter((path) => path.startsWith(this.uri + "/"))
+ .map((path) => new File(path));
+ }
+ }
+ return {
+ File,
+ Directory,
+ Paths: { document: "file:///documents", cache: "file:///cache" },
+ };
+});
+import { File } from "expo-file-system";
+import {
+ appendMobileDebugFile,
+ clearMobileDebugFiles,
+ copyMobileDebugFiles,
+ pruneMobileDebugFiles,
+ DEBUG_FILE_BYTES,
+} from "./mobileDebugFiles";
+
+beforeEach(() => {
+ disk.files.clear();
+ disk.dirs.clear();
+ disk.closed.mockClear();
+});
+describe("bounded debug files readable from the app container", () => {
+ it("does not create storage when pruning a never-enabled journal", () => {
+ pruneMobileDebugFiles();
+ expect(disk.dirs.size).toBe(0);
+ expect(disk.files.size).toBe(0);
+ });
+ it("appends valid detailed lines and exports all chunks, closing input handles", () => {
+ appendMobileDebugFile('{"level":"debug"}\n');
+ appendMobileDebugFile('{"level":"error"}\n');
+ expect(disk.files.size).toBe(1);
+ expect([...disk.files.keys()][0]).toMatch(
+ /documents\/cindy-debug\/mobile-debug-.*\.ndjson/,
+ );
+ const out = new File("file:///cache/export.ndjson");
+ copyMobileDebugFiles(out);
+ expect(disk.files.get(out.uri)).toBe(
+ '{"level":"debug"}\n{"level":"error"}\n',
+ );
+ expect(disk.closed).toHaveBeenCalledOnce();
+ });
+ it("rotates at byte boundaries and retains at most eight files", () => {
+ for (let i = 0; i < 12; i++)
+ appendMobileDebugFile(String(i % 10).repeat(DEBUG_FILE_BYTES));
+ expect(disk.files.size).toBe(8);
+ expect(
+ [...disk.files.values()].every(
+ (value) => value.length <= DEBUG_FILE_BYTES,
+ ),
+ ).toBe(true);
+ expect(() => appendMobileDebugFile("中".repeat(DEBUG_FILE_BYTES))).toThrow(
+ "too large",
+ );
+ });
+ it("prunes expired files, preserves unrelated files and clears only its owned logs", () => {
+ appendMobileDebugFile("recent\n");
+ const old = `file:///documents/cindy-debug/mobile-debug-${Date.now() - 8 * 86400_000}-0.ndjson`;
+ disk.files.set(old, "expired\n");
+ disk.files.set("file:///documents/cindy-debug/unrelated.txt", "keep");
+ pruneMobileDebugFiles();
+ expect(disk.files.has(old)).toBe(false);
+ expect([...disk.files.values()]).toContain("recent\n");
+ clearMobileDebugFiles();
+ expect([...disk.files.entries()]).toEqual([
+ ["file:///documents/cindy-debug/unrelated.txt", "keep"],
+ ]);
+ });
+});
diff --git a/apps/mobile/src/debug/mobileDebugFiles.ts b/apps/mobile/src/debug/mobileDebugFiles.ts
new file mode 100644
index 0000000000..9f1396f9c7
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDebugFiles.ts
@@ -0,0 +1,85 @@
+import { Directory, File, Paths } from "expo-file-system";
+
+export const DEBUG_FILE_BYTES = 1024 * 1024;
+export const DEBUG_FILE_COUNT = 8;
+const RETENTION_MS = 7 * 86400_000;
+const FILE_NAME = /^mobile-debug-(\d{13})-(\d+)\.ndjson$/;
+let sequence = 0;
+
+function directory(): Directory {
+ return new Directory(Paths.document, "cindy-debug");
+}
+
+function retainedFiles(now = Date.now()): File[] {
+ const dir = directory();
+ if (!dir.exists) return [];
+ const files = dir
+ .list()
+ .filter(
+ (file): file is File => file instanceof File && FILE_NAME.test(file.name),
+ )
+ .sort((a, b) => {
+ const aa = FILE_NAME.exec(a.name)!;
+ const bb = FILE_NAME.exec(b.name)!;
+ return Number(aa[1]) - Number(bb[1]) || Number(aa[2]) - Number(bb[2]);
+ });
+ return files.filter((file, index) => {
+ const created = Number(FILE_NAME.exec(file.name)![1]);
+ if (
+ created < now - RETENTION_MS ||
+ created > now ||
+ file.size > DEBUG_FILE_BYTES ||
+ index < files.length - DEBUG_FILE_COUNT
+ ) {
+ file.delete();
+ return false;
+ }
+ return true;
+ });
+}
+
+export function pruneMobileDebugFiles(): void {
+ retainedFiles();
+}
+
+/** Batch append, bounded rotation. No disk access at import time; caller serializes flush/clear/export. */
+export function appendMobileDebugFile(batch: string): void {
+ const files = retainedFiles();
+ if (!batch) return;
+ const bytes = new TextEncoder().encode(batch).byteLength;
+ if (bytes > DEBUG_FILE_BYTES) throw new Error("debug batch too large");
+ const dir = directory();
+ dir.create({ intermediates: true, idempotent: true });
+ let file = files.at(-1);
+ if (!file || file.size + bytes > DEBUG_FILE_BYTES) {
+ do {
+ file = new File(dir, `mobile-debug-${Date.now()}-${sequence++}.ndjson`);
+ } while (file.exists);
+ file.create();
+ // Enforce the total cap before appending another file.
+ if (files.length >= DEBUG_FILE_COUNT) files[0].delete();
+ }
+ file.write(batch, { append: true });
+}
+
+export function clearMobileDebugFiles(): void {
+ const dir = directory();
+ if (!dir.exists) return;
+ for (const file of dir.list())
+ if (file instanceof File && FILE_NAME.test(file.name)) file.delete();
+}
+
+/** Copy bounded chunks, not the whole journal into JS memory. Export is the detailed local log. */
+export function copyMobileDebugFiles(destination: File): void {
+ destination.create();
+ for (const file of retainedFiles()) {
+ const handle = file.open();
+ try {
+ while ((handle.offset ?? 0) < (handle.size ?? 0)) {
+ destination.write(handle.readBytes(64 * 1024), { append: true });
+ }
+ } finally {
+ handle.close();
+ }
+ }
+}
diff --git a/apps/mobile/src/debug/mobileDebugLog.ts b/apps/mobile/src/debug/mobileDebugLog.ts
new file mode 100644
index 0000000000..29c80d4444
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDebugLog.ts
@@ -0,0 +1,35 @@
+/** Phone-local instrumentation only. Never pass session bodies, request payloads or credentials. */
+export type MobileDebugScope =
+ | "device-link"
+ | "recovery"
+ | "lifecycle"
+ | "performance"
+ | "scroll"
+ | "keyboard";
+export type MobileDebugLevel = "debug" | "info" | "warn" | "error";
+type Sink = (
+ level: MobileDebugLevel,
+ scope: MobileDebugScope,
+ args: unknown[],
+) => void;
+let sink: Sink | undefined;
+
+export function setMobileDebugSink(next: Sink | undefined): void {
+ sink = next;
+}
+export function mobileDebugEnabled(): boolean {
+ return sink !== undefined;
+}
+
+/** Disabled recording does no serialization or native I/O. Diagnostics must never break the app. */
+export function mobileDebugLog(
+ level: MobileDebugLevel,
+ scope: MobileDebugScope,
+ ...args: unknown[]
+): void {
+ try {
+ sink?.(level, scope, args);
+ } catch {
+ /* best-effort instrumentation */
+ }
+}
diff --git a/apps/mobile/src/debug/mobileDebugRecord.test.ts b/apps/mobile/src/debug/mobileDebugRecord.test.ts
new file mode 100644
index 0000000000..9ed08321cb
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDebugRecord.test.ts
@@ -0,0 +1,129 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ mobileDebugEnabled,
+ mobileDebugLog,
+ setMobileDebugSink,
+} from "./mobileDebugLog";
+import { serializeMobileDebugRecord } from "./mobileDebugRecord";
+
+afterEach(() => setMobileDebugSink(undefined));
+describe("detailed phone debug records", () => {
+ it.each([
+ "Cookie: session=fixtureA; csrf=fixtureB",
+ "Set-Cookie: session=fixtureA; HttpOnly; other=fixtureB",
+ 'Authorization: Digest username="fixtureA", response="fixtureB"',
+ "Proxy-Authorization: Custom fixtureA, fixtureB",
+ "cOoKiE: session=fixtureA;\r\n csrf=fixtureB",
+ JSON.stringify({
+ Authorization: 'Digest username="fixtureA", response="fixtureB"',
+ }),
+ ])(
+ "removes whole multipart credential headers across every text entry: %s",
+ (text) => {
+ const error = new Error(text, { cause: new Error(text) });
+ const result = JSON.parse(
+ serializeMobileDebugRecord("error", "device-link", [
+ text,
+ error,
+ { diagnostic: text },
+ { elapsedMs: 12 },
+ ]),
+ );
+ expect(JSON.stringify(result)).not.toMatch(/fixtureA|fixtureB/);
+ expect(result.args[0]).toBe("[redacted credential header]");
+ expect(result.args[1].message).toBe("[redacted credential header]");
+ expect(result.args[1].stack).toBe("[redacted credential header]");
+ expect(result.args[1].cause.message).toBe("[redacted credential header]");
+ expect(result.args[3].elapsedMs).toBe(12);
+ },
+ );
+ it.each([0, 1, 2, 3])(
+ "redacts credentials in JSON encoded %s times, including errors and causes",
+ (depth) => {
+ let text = JSON.stringify({
+ token: 'fixture-value with "quotes" and spaces',
+ });
+ for (let i = 0; i < depth; i++) text = JSON.stringify(text);
+ const error = new Error(text, { cause: new Error(text) });
+ const line = serializeMobileDebugRecord("error", "device-link", [
+ text,
+ error,
+ ]);
+ expect(line).not.toMatch(/fixture-value|quotes|and spaces/);
+ expect(JSON.parse(line).args[1].message).toContain("redacted");
+ },
+ );
+ it("redacts escaped credential values even when their key is not escaped", () => {
+ const line = serializeMobileDebugRecord("error", "device-link", [
+ String.raw`password=\"fixture-value with spaces\"`,
+ ]);
+ expect(line).not.toContain("fixture-value");
+ });
+ it("does no work while disabled and never propagates sink failures", () => {
+ const sink = vi.fn(() => {
+ throw new Error("disk full");
+ });
+ expect(mobileDebugEnabled()).toBe(false);
+ mobileDebugLog("debug", "scroll", "position", { offsetY: 12 });
+ expect(sink).not.toHaveBeenCalled();
+ setMobileDebugSink(sink);
+ expect(() => mobileDebugLog("debug", "scroll", "position")).not.toThrow();
+ expect(sink).toHaveBeenCalledOnce();
+ });
+ it("retains request timing, error message, stack and cause without credentials or bodies", () => {
+ const cause = new Error("socket timed out");
+ const error = new Error("connection failed Bearer very-secret", { cause });
+ Object.assign(error, {
+ code: "ETIMEDOUT",
+ headers: { Authorization: "hidden" },
+ body: "private conversation",
+ });
+ const line = serializeMobileDebugRecord(
+ "error",
+ "device-link",
+ ["request failed elapsed=120ms", error],
+ 123,
+ );
+ const result = JSON.parse(line);
+ expect(result).toMatchObject({
+ at: 123,
+ level: "error",
+ scope: "device-link",
+ });
+ expect(result.args[1]).toMatchObject({
+ code: "ETIMEDOUT",
+ message: "connection failed Bearer [redacted]",
+ cause: { message: "socket timed out" },
+ });
+ expect(result.args[1].stack).toContain("connection failed");
+ expect(line).not.toMatch(/very-secret|hidden|private conversation/);
+ });
+ it("filters nested content, string credentials and URL paths; escapes forged record boundaries", () => {
+ const line = serializeMobileDebugRecord("debug", "recovery", [
+ 'stage\n{"level":"error"}',
+ {
+ nested: { token: "secret1", prompt: "secret2", message: "secret3" },
+ error:
+ 'https://user:[email protected]/private?token=secret4 bearer secret5 x-api-key="secret6"',
+ elapsedMs: 123,
+ },
+ ]);
+ expect(line.trim().split("\n")).toHaveLength(1);
+ expect(line).not.toMatch(/secret[1-6]|user:pass|\/private/);
+ expect(JSON.parse(line).args[1].elapsedMs).toBe(123);
+ });
+ it("bounds cyclic data and avoids getters/toJSON", () => {
+ const getter = vi.fn(() => "private");
+ const value: Record<string, unknown> = { toJSON: getter };
+ Object.defineProperty(value, "hostile", { get: getter, enumerable: true });
+ value.self = value;
+ value.items = Array.from({ length: 100 }, () => "x".repeat(10_000));
+ const line = serializeMobileDebugRecord("debug", "performance", [
+ "snapshot",
+ value,
+ ]);
+ expect(line.length).toBeLessThanOrEqual(16_001);
+ expect(() => JSON.parse(line)).not.toThrow();
+ expect(getter).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/debug/mobileDebugRecord.ts b/apps/mobile/src/debug/mobileDebugRecord.ts
new file mode 100644
index 0000000000..6261f00465
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDebugRecord.ts
@@ -0,0 +1,118 @@
+import type { MobileDebugLevel, MobileDebugScope } from "./mobileDebugLog";
+
+// Defense in depth for explicitly instrumented local events, not a license to capture arbitrary console.
+const privateKey =
+ /authorization|cookie|password|secret|token|api.?key|credential|^(body|payload|prompt|messages?|content|text|transcript|headers|args|input|output|data)$/i;
+const MAX_STRING = 4000;
+export function redactMobileDebugText(value: string): string {
+ // Header values can span quoted fields, separators and folded lines. Never guess their end.
+ if (
+ /\b(?:[\w-]*authorization|[\w-]*cookie)["']?\s*[:=]/i.test(
+ value.slice(0, MAX_STRING).replace(/\\+["']/g, '"'),
+ )
+ )
+ return "[redacted credential header]";
+ // Escaped JSON may contain quoted delimiters inside the secret itself. Drop that text
+ // rather than partially matching a value and leaking its suffix (also handles nested encoding).
+ if (
+ /\\+["']/.test(value.slice(0, MAX_STRING)) &&
+ /\b[\w-]{0,40}(?:token|password|secret|api[-_]?key|authorization|cookie)[\w-]{0,40}["']?\s*[:=]/i.test(
+ value.slice(0, MAX_STRING).replace(/\\+["']/g, '"'),
+ )
+ )
+ return "[redacted escaped credential]";
+ return value
+ .slice(0, MAX_STRING)
+ .replace(/\b(Bearer|Basic)\s+[^\s,;'"}]+/gi, "$1 [redacted]")
+ .replace(
+ /(\b[\w-]{0,40}(?:token|password|secret|api[-_]?key|authorization|cookie)[\w-]{0,40}["']?\s*[:=]\s*)(?:"[^"\n]*"|'[^'\n]*'|[^\s,;}]+)/gi,
+ "$1[redacted]",
+ )
+ .replace(/\b(?:sk-|gh[pousr]_|github_pat_)[a-zA-Z0-9_-]{8,}/g, "[redacted]")
+ .replace(
+ /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,
+ "[redacted]",
+ )
+ .replace(/(?:https?|wss?):\/\/[^\s<>"')]+/gi, (url) => {
+ try {
+ const parsed = new URL(url);
+ return `${parsed.protocol}//${parsed.host}/[redacted-path]`;
+ } catch {
+ return "[redacted-url]";
+ }
+ })
+ .replace(/\b[\w.+-]{1,128}@[\w.-]{1,128}\.[a-z]{2,}/gi, "[redacted-email]")
+ .replace(/(?:\/Users\/|\/home\/)[^\s/]+/g, "/[home]")
+ .slice(0, MAX_STRING);
+}
+
+/** Keep error causes/stacks, enums and timings; no arbitrary getters/toJSON (Error.stack may be lazy). */
+export function serializeMobileDebugRecord(
+ level: MobileDebugLevel,
+ scope: MobileDebugScope,
+ args: unknown[],
+ at = Date.now(),
+): string {
+ const seen = new WeakSet<object>();
+ let remaining = 120;
+ function safe(value: unknown, depth = 0): unknown {
+ if (--remaining < 0 || depth > 5) return "[truncated]";
+ if (typeof value === "string") return redactMobileDebugText(value);
+ if (typeof value === "number")
+ return Number.isFinite(value) ? value : String(value);
+ if (value === null || typeof value === "boolean") return value;
+ if (typeof value === "function") return "[function]";
+ if (typeof value !== "object") return String(value);
+ if (seen.has(value)) return "[circular]";
+ seen.add(value);
+ if (Array.isArray(value))
+ return value.slice(0, 30).map((item) => safe(item, depth + 1));
+ const out: Record<string, unknown> = Object.create(null);
+ const descriptors = Object.getOwnPropertyDescriptors(value);
+ if (
+ value instanceof Error &&
+ descriptors.stack &&
+ !("value" in descriptors.stack)
+ ) {
+ try {
+ out.stack = safe(value.stack, depth + 1);
+ } catch {
+ out.stack = "[unavailable]";
+ }
+ }
+ for (const [key, descriptor] of Object.entries(descriptors).slice(0, 40)) {
+ if (key === "stack" && "stack" in out) continue;
+ out[redactMobileDebugText(key)] =
+ privateKey.test(key) && !(value instanceof Error && key === "message")
+ ? "[redacted]"
+ : "value" in descriptor
+ ? safe(descriptor.value, depth + 1)
+ : "[accessor]";
+ }
+ if (value instanceof Error && !("name" in out)) out.name = "Error";
+ return out;
+ }
+ const record = {
+ at,
+ level,
+ scope,
+ args: args.slice(0, 12).map((arg) => safe(arg)),
+ };
+ const json = JSON.stringify(record);
+ // Preserve valid NDJSON even when one error object is unusually large.
+ return (
+ (json.length <= 16_000
+ ? json
+ : JSON.stringify({
+ at,
+ level,
+ scope,
+ args: [
+ typeof args[0] === "string"
+ ? redactMobileDebugText(args[0])
+ : "[record]",
+ "[record truncated]",
+ ],
+ })) + "\n"
+ );
+}
diff --git a/apps/mobile/src/debug/mobileDiagnosticUpload.ts b/apps/mobile/src/debug/mobileDiagnosticUpload.ts
new file mode 100644
index 0000000000..a5460808dc
--- /dev/null
+++ b/apps/mobile/src/debug/mobileDiagnosticUpload.ts
@@ -0,0 +1,40 @@
+import Constants from "expo-constants";
+import * as Crypto from "expo-crypto";
+import { fetch } from "expo/fetch";
+import { Platform } from "react-native";
+import { AUTH_REGION } from "@/config/env";
+import { hydratePrivacyConsent } from "@/update/updateConsentGate";
+import { diagnosticSnapshot } from "./localDiagnostics";
+import {
+ parseDiagnosticUploadTarget,
+ uploadDiagnosticSnapshot,
+ type DiagnosticUploadResult,
+} from "./diagnosticUpload";
+
+const rawTarget = process.env.EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET ?? "";
+let uploading = false;
+export function diagnosticUploadConfigured(): boolean {
+ return parseDiagnosticUploadTarget(rawTarget, AUTH_REGION) !== null;
+}
+
+/** Only called by the settings action; no background upload or persistent retry queue. */
+export async function uploadMobileDiagnostics(): Promise<DiagnosticUploadResult> {
+ if (uploading) return { kind: "failed" };
+ uploading = true;
+ try {
+ return await uploadDiagnosticSnapshot({
+ rawTarget,
+ region: AUTH_REGION,
+ consent: hydratePrivacyConsent,
+ snapshot: diagnosticSnapshot,
+ randomBytes: Crypto.getRandomBytes,
+ fetch,
+ appVersion:
+ Constants.nativeAppVersion ?? Constants.expoConfig?.version ?? "",
+ platform: Platform.OS,
+ osVersion: String(Platform.Version),
+ });
+ } finally {
+ uploading = false;
+ }
+}
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 0b659c40fc..b8df60a8d2 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -3,6 +3,7 @@ import { createBackgroundConnection } from './backgroundConnection';
import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase } from './recoveryDiagnostics';
import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';
import { AppState, Platform } from 'react-native';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
import {
DeviceLinkClient,
DeviceLinkError,
@@ -451,6 +452,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const held = markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend);
noteSessionLiveStreamsAcked(held);
if (held.length > 0) record?.('subscription', 'applied', held.length);
+ mobileDebugLog('debug', 'recovery', 'subscription acknowledged', { topicCount: held.length });
},
});
}, []);
@@ -1154,6 +1156,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
void import('expo-network').then(({ addNetworkStateListener }) => {
if (disposed) return;
networkSubscription = addNetworkStateListener((network) => {
+ mobileDebugLog('debug', 'device-link', 'network changed', { type: network.type, connected: network.isConnected, reachable: network.isInternetReachable, appState: AppState.currentState });
if (AppState.currentState !== 'active' || network.isConnected === false) return;
client.notifyNetworkChanged();
});
@@ -1899,6 +1902,7 @@ const mobileDeviceLinkLogger = {
};
function logMobileDeviceLink(level: MobileDeviceLinkLogLevel, args: unknown[]): void {
+ mobileDebugLog(level, 'device-link', ...args);
if (!__DEV__ && level === 'debug') return;
if (level === 'error') {
console.error('[device-link]', ...args);
diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.json
index 7873fb750b..d6eff90aa3 100644
--- a/apps/mobile/src/i18n/locales/en/settings.json
+++ b/apps/mobile/src/i18n/locales/en/settings.json
@@ -1,4 +1,27 @@
{
+ "localLogs": {
+ "upload": "Upload logs",
+ "uploadHint": "Send only filtered run records and app/system versions. Export for detailed debug logs.",
+ "uploadResult": {
+ "unavailable": "Log upload is unavailable in this build.",
+ "consentRequired": "Accept the Privacy Policy before uploading logs.",
+ "empty": "No recent logs. Enable recording and reproduce the problem first.",
+ "failed": "Upload failed. Logs are still saved on this phone."
+ },
+ "title": "Debug logs",
+ "record": "Record debug logs",
+ "hint": "Record phone connection, recovery, scrolling, keyboard and performance details. Off by default; keeps up to 7 days and 8 MB. Never uploaded automatically.",
+ "export": "Export debug logs",
+ "clear": "Clear logs",
+ "busy": "Working…",
+ "failed": "Unable to save or share logs. Please try again.",
+ "clearHint": "Delete the saved diagnostic logs?",
+ "cancel": "Cancel",
+ "exportHint": "Share detailed local logs for troubleshooting. No conversation content or credentials.",
+ "options": "Log options",
+ "uploadCopied": "Uploaded. Code {{code}} copied.",
+ "uploadSucceeded": "Uploaded. Code {{code}}."
+ },
"title": "Settings",
"language": {
"title": "Language",
diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.json
index 8f7b431c66..f51d309d76 100644
--- a/apps/mobile/src/i18n/locales/ja/settings.json
+++ b/apps/mobile/src/i18n/locales/ja/settings.json
@@ -1,4 +1,27 @@
{
+ "localLogs": {
+ "upload": "ログを送信",
+ "uploadHint": "選別した実行記録とアプリ・OSのバージョンのみ送信します。詳細ログは書き出してください。",
+ "uploadResult": {
+ "unavailable": "このビルドではログ送信が設定されていません。",
+ "consentRequired": "ログ送信前にプライバシーポリシーに同意してください。",
+ "empty": "最近のログがありません。記録を有効にして問題を再現してください。",
+ "failed": "送信に失敗しました。ログは端末に保存されています。"
+ },
+ "title": "デバッグログ",
+ "record": "デバッグログを記録",
+ "hint": "スマートフォンの接続、復旧、スクロール、キーボード、性能の詳細を記録します。初期設定はオフ。最大7日間・8 MB保存し、自動送信しません。",
+ "export": "デバッグログを書き出す",
+ "clear": "ログを消去",
+ "busy": "処理中…",
+ "failed": "ログの保存または共有ができません。再試行してください。",
+ "clearHint": "保存済みの診断ログを削除しますか?",
+ "cancel": "キャンセル",
+ "exportHint": "詳細なローカルログを共有して問題を調査します。会話の本文や認証情報は含みません。",
+ "options": "ログのオプション",
+ "uploadCopied": "送信しました。番号 {{code}} をコピーしました。",
+ "uploadSucceeded": "送信しました。番号 {{code}}。"
+ },
"title": "設定",
"language": {
"title": "言語",
diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.json
index e61053560c..af70dacbbf 100644
--- a/apps/mobile/src/i18n/locales/ko/settings.json
+++ b/apps/mobile/src/i18n/locales/ko/settings.json
@@ -1,4 +1,27 @@
{
+ "localLogs": {
+ "upload": "로그 업로드",
+ "uploadHint": "선별된 실행 기록과 앱 및 OS 버전만 전송합니다. 상세 로그는 내보내기를 사용하세요.",
+ "uploadResult": {
+ "unavailable": "이 빌드에는 로그 업로드가 설정되지 않았습니다.",
+ "consentRequired": "로그를 업로드하기 전에 개인정보 처리방침에 동의해 주세요.",
+ "empty": "최근 로그가 없습니다. 기록을 켜고 문제를 재현해 주세요.",
+ "failed": "업로드하지 못했습니다. 로그는 휴대폰에 보관되어 있습니다."
+ },
+ "title": "디버그 로그",
+ "record": "디버그 로그 기록",
+ "hint": "휴대폰 연결, 복구, 스크롤, 키보드 및 성능 세부 정보를 기록합니다. 기본 꺼짐이며 최대 7일, 8 MB를 보관합니다. 자동 업로드하지 않습니다.",
+ "export": "디버그 로그 내보내기",
+ "clear": "로그 지우기",
+ "busy": "처리 중…",
+ "failed": "로그를 저장하거나 공유할 수 없습니다. 다시 시도해 주세요.",
+ "clearHint": "저장된 진단 로그를 삭제할까요?",
+ "cancel": "취소",
+ "exportHint": "문제 해결을 위해 상세 로컬 로그를 공유합니다. 대화 내용이나 인증 정보는 포함하지 않습니다.",
+ "options": "로그 옵션",
+ "uploadCopied": "업로드했습니다. 번호 {{code}}를 복사했습니다.",
+ "uploadSucceeded": "업로드했습니다. 번호 {{code}}."
+ },
"title": "설정",
"language": {
"title": "언어",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.json
index fdac779c89..742c119a6a 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json
@@ -1,4 +1,27 @@
{
+ "localLogs": {
+ "upload": "上传日志",
+ "uploadHint": "仅发送筛选后的运行记录及应用、系统版本。详细 Debug 日志请使用导出。",
+ "uploadResult": {
+ "unavailable": "当前版本未配置日志上传。",
+ "consentRequired": "上传日志前需同意隐私政策。",
+ "empty": "暂无近期日志,请先开启记录并复现问题。",
+ "failed": "上传失败,日志仍保留在手机上。"
+ },
+ "title": "Debug 日志",
+ "record": "记录 Debug 日志",
+ "hint": "记录手机上的连接、恢复、滚动、键盘与性能细节。默认关闭,最多保留 7 天、8 MB,不会自动上传。",
+ "export": "导出 Debug 日志",
+ "clear": "清空日志",
+ "busy": "处理中…",
+ "failed": "无法保存或分享日志,请重试。",
+ "clearHint": "删除已保存的诊断日志?",
+ "cancel": "取消",
+ "exportHint": "分享详细本地日志供排障使用;不包含对话正文或凭证。",
+ "options": "日志选项",
+ "uploadCopied": "上传成功,编号 {{code}} 已复制。",
+ "uploadSucceeded": "上传成功,编号 {{code}}。"
+ },
"title": "设置",
"language": {
"title": "语言",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.json
index 3babe9a8d1..b1f9981f06 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json
@@ -1,4 +1,27 @@
{
+ "localLogs": {
+ "upload": "上傳日誌",
+ "uploadHint": "僅傳送篩選後的執行記錄及應用程式、系統版本。詳細 Debug 日誌請使用匯出。",
+ "uploadResult": {
+ "unavailable": "目前版本未設定日誌上傳。",
+ "consentRequired": "上傳日誌前需同意隱私政策。",
+ "empty": "暫無近期日誌,請先開啟記錄並重現問題。",
+ "failed": "上傳失敗,日誌仍保留在手機上。"
+ },
+ "title": "Debug 日誌",
+ "record": "記錄 Debug 日誌",
+ "hint": "記錄手機上的連線、恢復、捲動、鍵盤與效能細節。預設關閉,最多保留 7 天、8 MB,不會自動上傳。",
+ "export": "匯出 Debug 日誌",
+ "clear": "清空日誌",
+ "busy": "處理中…",
+ "failed": "無法儲存或分享日誌,請重試。",
+ "clearHint": "刪除已儲存的診斷日誌?",
+ "cancel": "取消",
+ "exportHint": "分享詳細本機日誌供疑難排解;不含任務內文或憑證。",
+ "options": "日誌選項",
+ "uploadCopied": "上傳成功,編號 {{code}} 已複製。",
+ "uploadSucceeded": "上傳成功,編號 {{code}}。"
+ },
"title": "設定",
"language": {
"title": "語言",
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b5606d7a2f..aa1ef67854 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -1,4 +1,5 @@
import { CompanionMessageCard } from '@/session/CompanionMessageCard';
+import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Image as ExpoImage } from 'expo-image';
@@ -2004,6 +2005,10 @@ export function MessageRenderer({
};
const previousOffsetY = scrollMetricsRef.current.offsetY;
scrollMetricsRef.current = metrics;
+ if (mobileDebugEnabled()) mobileDebugLog('debug', 'scroll', 'list scroll', {
+ ...metrics, dragging: isDragSample, momentum: isMomentumScrollingRef.current,
+ readingOlder: readingOlderRef.current, nearBottom: nearBottomRef.current,
+ });
if (readingOlderRef.current) {
if (
isDragSample
@@ -2407,7 +2412,7 @@ export function MessageRenderer({
}, [requestLoadEarlier]);
const renderMessageItem = useCallback(({ item }: { item: MobileMessageRenderItem }) => {
- if (__DEV__) recordMobileMessageRenderItem();
+ if (__DEV__ || mobileDebugEnabled()) recordMobileMessageRenderItem();
return (
<RenderListItemView
actions={actions}
@@ -4915,7 +4920,11 @@ function MarkdownBody({
}, [text]);
useLayoutEffect(() => {
markdownParseRef.current = markdownParse.result;
- if (__DEV__) recordMobileMarkdownParse(markdownParse.result, markdownParse.durationMs);
+ if (__DEV__ || mobileDebugEnabled()) recordMobileMarkdownParse(markdownParse.result, markdownParse.durationMs);
+ if (mobileDebugEnabled()) mobileDebugLog('debug', 'performance', 'markdown parsed', {
+ durationMs: markdownParse.durationMs, incremental: markdownParse.result.incremental,
+ reusedBlockCount: markdownParse.result.reusedBlockCount, parsedSourceUtf16Length: markdownParse.result.parsedSourceUtf16Length,
+ });
}, [markdownParse]);
const blocks = markdownParse.result.blocks;
// Android 的 selectable Text 内嵌 View(直连内联图)行为未定义,含这类 inline 的块不开选中。
diff --git a/apps/mobile/src/session/useMobileKeyboardState.ts b/apps/mobile/src/session/useMobileKeyboardState.ts
index c865e9e6f5..8201f2d8c2 100644
--- a/apps/mobile/src/session/useMobileKeyboardState.ts
+++ b/apps/mobile/src/session/useMobileKeyboardState.ts
@@ -11,6 +11,7 @@ import {
import type { LoginKeyboardRect } from '@/auth/loginKeyboardAvoidance';
import { isDockedKeyboard } from '@/auth/loginKeyboardAvoidance';
import { getCachedReduceMotionEnabled } from '@/hooks/useReduceMotion';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
export interface MobileKeyboardState {
/** 窗口底部实际被遮挡的高度,交互式收起时不等于键盘自身高度。 */
@@ -64,6 +65,7 @@ export function useMobileKeyboardState(): MobileKeyboardState {
setState(next);
};
const update = (event: KeyboardEvent) => {
+ mobileDebugLog('debug', 'keyboard', 'frame received', { shown, durationMs: event.duration, easing: event.easing, frame: event.endCoordinates });
latestEvent = event;
if (Platform.OS === 'ios' && shown && event.endCoordinates.screenY === 0) {
// 保留 RN KAV 的系统交叉淡化兼容:此时 screenY=0 不是全屏遮挡。
diff --git a/docs/dev-rules/log-upload-and-redaction.md b/docs/dev-rules/log-upload-and-redaction.md
index 4b317579f7..ba6ebe5583 100644
--- a/docs/dev-rules/log-upload-and-redaction.md
+++ b/docs/dev-rules/log-upload-and-redaction.md
@@ -257,7 +257,33 @@ main/log-upload/logUploadTarget.ts ← 解析 + 区域交叉校验;不
补不出来,重试无益;只要崩溃邻域已有归属它的记录进上报就清标记,避免对同一份不可读文件无限重传。
- **全链路失败静默**:任何异常收敛成一个 outcome,不弹错误、不影响业务。
-## 6. Review 清单
+## 6. Mobile 手动诊断日志
+
+Mobile 的设置 → 调试 / 开发者提供 Debug 开关、导出与手动上传;清空收在日志选项菜单,不提供恢复默认记录设置。普通构建默认不记录;
+个人排障构建可用 `EXPO_PUBLIC_CINDY_DIAGNOSTICS=1` 设置默认值,用户保存的开关优先。
+
+- 本地详细 Debug 与上传摘要分别保存。`mobileDebugLog.ts` 只接手机自身的显式记录点:连接与网络变化、
+ 恢复阶段、生命周期、JS 停摆、渲染计数与解析耗时、滚动几何和键盘状态。保留级别、错误原因与堆栈,
+ `mobileDebugRecord.ts` 在落盘前过滤敏感字段、凭证、地址参数等;禁止传入消息正文、请求体或完整鉴权信息,
+ 不接管全局 console,不重复保存被控端任务记录。
+- 详细日志在 `Paths.document/cindy-debug/`,NDJSON 文件每份最多 1 MiB、最多 8 份、保留最近 7 天。
+ 每 2 秒及前后台切换时批量落盘;内存待写最多 512 KiB,溢出或写失败在后续记录中标明丢失,不能无限重试堆积。
+ 突然杀进程可能丢失尚未落盘的最后一批,JS 停摆只能在恢复后测得。Documents 属 App 持久容器,可能随系统备份。
+ 导出分享详细日志的唯一缓存副本,分享成功、失败或取消后清理;关闭记录不清空历史。
+ 无论开关是否开启,启动及回到前台都会清理过期文件;App 未运行时无法执行清理,下次启动时补做。
+- `diagnosticEvents.ts` 继续作为上传摘要的写入与读取白名单:只重建固定事件名、有限数值和枚举,
+ 不保留错误正文、堆栈、地址、凭证、消息正文或设备/账号标识。摘要仍在 AsyncStorage,最多 500 条、最近 7 天。
+ 上传不得读取详细 Debug 文件;上传前再次投影。
+- 手动上传检查隐私政策同意,不依赖使用统计偏好;复用 §4 的构建目标校验器与 Desktop SLS
+ web-tracking 协议、上传编号格式。附带的元数据仅有区域、版本、平台、系统版本与本次上传编号。
+ 不增加自动上传、崩溃标记、后台重试或新的服务端接口;20 秒超时,失败保留本地日志。
+- Metro 从 `config/log-upload.json` 只注入当前构建区域的 `EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET`。
+ 本地/开源缺少文件时禁用上传并解释原因;EAS 商店 profiles 自动要求该配置,缺失即失败。
+ 仓外正式发布流程仍须设置 `CINDY_REQUIRE_LOG_UPLOAD_CONFIG=1`;普通本地原生构建不等同于发布。
+ 损坏配置或区域交叉配置始终硬失败。
+ 真实目标与密钥不得提交到仓库,运行期不从远程端点清单选择目标。
+
+## 7. Review 清单
1. 改了 `logger.ts` 的行格式或 `mainLogRecordFormat.ts` 吗?读侧与写侧是否同时确认?哨兵判定
是否仍然只认**第 0 字节**(放宽成「文件里出现过哨兵」即隐私逃逸)?
diff --git a/scripts/__tests__/log-upload-build-env.test.mjs b/scripts/__tests__/log-upload-build-env.test.mjs
index cb8ea1855c..8356d95a5b 100644
--- a/scripts/__tests__/log-upload-build-env.test.mjs
+++ b/scripts/__tests__/log-upload-build-env.test.mjs
@@ -15,6 +15,8 @@ import { afterEach, test } from 'node:test';
import {
LOG_UPLOAD_TARGET_ENV,
desktopLogUploadBuildEnv,
+ mobileLogUploadBuildEnv,
+ mobileLogUploadConfigRequired,
loadLogUploadTargets,
slsEndpointHost,
} from '../shared/log-upload-build-env.mjs';
@@ -26,6 +28,34 @@ const VALID = {
dev: null,
};
+test('mobile store profiles require upload config while local builds may omit it', () => {
+ const missing = path.join(makeTempDir('cindy-mobile-upload-'), 'missing.json');
+ for (const profile of ['production', 'testflight', 'production-global', 'testflight-global', 'store-cn-base', 'store-global-base']) {
+ const allowMissing = !mobileLogUploadConfigRequired({ EAS_BUILD_PROFILE: profile, CINDY_REQUIRE_LOG_UPLOAD_CONFIG: '0' });
+ assert.equal(allowMissing, false);
+ assert.throws(() => mobileLogUploadBuildEnv({ authRegion: 'global', configPath: missing, allowMissing }), /缺少日志上报配置/);
+ }
+ assert.equal(mobileLogUploadConfigRequired({ CINDY_REQUIRE_LOG_UPLOAD_CONFIG: '1' }), true);
+ for (const env of [{}, { NODE_ENV: 'production' }, { EXPO_PUBLIC_XDT_OTA_SELFHOST: '1' }, { EAS_BUILD_PROFILE: 'adhoc' }]) {
+ assert.equal(mobileLogUploadConfigRequired(env), false);
+ assert.equal(mobileLogUploadBuildEnv({ configPath: missing, allowMissing: !mobileLogUploadConfigRequired(env) }).EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET, '');
+ }
+});
+
+test('mobile build env shares desktop validation and injects only the selected region', () => {
+ const configPath = writeConfig(VALID);
+ for (const authRegion of ['cn', 'global', 'dev']) {
+ const mobile = mobileLogUploadBuildEnv({ authRegion, configPath });
+ assert.deepEqual(Object.keys(mobile), ['EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET']);
+ assert.equal(mobile.EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET,
+ desktopLogUploadBuildEnv({ authRegion, configPath })[LOG_UPLOAD_TARGET_ENV]);
+ }
+ const missing = path.join(makeTempDir('cindy-mobile-upload-'), 'missing.json');
+ assert.throws(() => mobileLogUploadBuildEnv({ authRegion: 'global', configPath: missing }), /缺少日志上报配置/);
+ assert.equal(mobileLogUploadBuildEnv({ authRegion: 'global', configPath: missing, allowMissing: true }).EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET, '');
+ assert.throws(() => mobileLogUploadBuildEnv({ authRegion: 'global', configPath: writeConfig('{bad'), allowMissing: true }), /不是合法 JSON/);
+});
+
/**
* 本文件建过的临时目录。用 `afterEach` 统一回收,与 `client-endpoint-build-env.test.mjs`
* 同款——不用在测试执行期调 `test.after()` 注册根级钩子(那依赖 node:test 的导出形态与
diff --git a/scripts/shared/log-upload-build-env.mjs b/scripts/shared/log-upload-build-env.mjs
index d473c58cd6..f67238b2b1 100644
--- a/scripts/shared/log-upload-build-env.mjs
+++ b/scripts/shared/log-upload-build-env.mjs
@@ -199,3 +199,14 @@ export function desktopLogUploadBuildEnv({ authRegion, repoRoot, configPath, all
}
export const __testing = { OPTIONAL_REGIONS, normalizeRegionTarget, assertRegionsIsolated };
+
+/** Mobile consumes the same validated single-region target, inlined into its JS bundle by Expo. */
+export function mobileLogUploadConfigRequired(env = process.env) {
+ return env.CINDY_REQUIRE_LOG_UPLOAD_CONFIG === '1'
+ || /^(?:production|testflight)(?:-global)?$|^store-(?:cn|global)-base$/.test(env.EAS_BUILD_PROFILE ?? '');
+}
+
+export function mobileLogUploadBuildEnv(options = {}) {
+ const env = desktopLogUploadBuildEnv(options);
+ return { EXPO_PUBLIC_CINDY_LOG_UPLOAD_TARGET: env[LOG_UPLOAD_TARGET_ENV] };
+}