Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): harden environment switching failures
DavidShen3768fecc9b7a
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex a61ebb7908..ab7b83e359 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -379,8 +379,14 @@ function RootLayout() {'{reason}',endpointGate.reason ?? 'unknown',)}- actionLabel={loginText('retry')}- onAction={endpointGate.retry}+ actionLabel={loginText(+ endpointGate.canResetToDev ? 'endpointGateResetToDev' : 'retry',+ )}+ onAction={+ endpointGate.canResetToDev+ ? endpointGate.resetToDev+ : endpointGate.retry+ }/></MobileLoginHandoffStage>);@@ -429,7 +435,7 @@ function RootLayout() {* 品牌视觉由 MobileLoginHandoffStage 宿主拥有,本层背景透明、内容沉到下半屏* (避开品牌三要素),仅承载标题/说明/唯一动作。端点闸门与强更闸门共用本层* ——阻断语义一致:没有"跳过 / 稍后再说",只有一个出口。端点错误屏的文案 key 化- * 契约不变(endpointGateTitle / endpointGateSubtitle{reason} / retry)。+ * Release 覆盖失败时唯一动作改为返回 Dev;其它失败仍为 retry。*/function StartupGateBlockedContent({title,diff --git a/apps/mobile/scripts/build-ios.mjs b/apps/mobile/scripts/build-ios.mjsindex 8009ee5555..b22ba02872 100644--- a/apps/mobile/scripts/build-ios.mjs+++ b/apps/mobile/scripts/build-ios.mjs@@ -73,6 +73,47 @@ const NPX = process.platform === 'win32' ? 'npx.cmd' : 'npx';function log(msg) { console.error(msg); }+const IOS_BUILD_FAILURE_STAGE = Object.freeze({+ arguments: 'arguments',+ regionConfig: 'region-config',+ buildPlan: 'build-plan',+ preflight: 'preflight',+ toolchain: 'toolchain',+ artifactValidation: 'artifact-validation',+ output: 'output',+});++let iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.arguments;++// 只按脚本控制的阶段输出固定诊断,不打印异常消息或环境变量值。+function reportIosBuildFailure() {+ switch (iosBuildFailureStage) {+ case IOS_BUILD_FAILURE_STAGE.arguments:+ console.error('iOS 构建失败(参数检查):请确认已传 --region cn|global|dev,且其它参数合法。');+ break;+ case IOS_BUILD_FAILURE_STAGE.regionConfig:+ console.error('iOS 构建失败(区域配置):请检查 apps/mobile/scripts/self-host-regions.json 及对应 endpoint 配置是否存在且有效。');+ break;+ case IOS_BUILD_FAILURE_STAGE.buildPlan:+ console.error('iOS 构建失败(构建计划):请检查 apps/mobile/app.json 与区域产物配置。');+ break;+ case IOS_BUILD_FAILURE_STAGE.preflight:+ console.error('iOS 构建失败(构建前检查):请检查 Git 门禁、签名描述符、macOS/Xcode 与必需的 EXPO_PUBLIC_* 配置。');+ break;+ case IOS_BUILD_FAILURE_STAGE.toolchain:+ console.error('iOS 构建失败(工具链):请查看上方 Expo/CocoaPods/Xcode 输出;若无输出,请检查 npx、CocoaPods、Xcode 与本机签名材料。');+ break;+ case IOS_BUILD_FAILURE_STAGE.artifactValidation:+ console.error('iOS 构建失败(产物校验):请检查 IPA 路径与内嵌 runtimeVersion。');+ break;+ case IOS_BUILD_FAILURE_STAGE.output:+ console.error('iOS 构建失败(复制产物):请检查 --out 目录权限与磁盘空间。');+ break;+ default:+ console.error('iOS 构建失败;未能确定失败阶段。');+ }+}+// self-host 变体的构建环境(与原发布线同源:prebuild/fingerprint 与安装包一致)。function selfhostEnv(region, desktopVersion) {const env = {@@ -175,6 +216,7 @@ function buildIpa(env, region) {}async function main() {+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.arguments;const args = parseArgs(process.argv.slice(2));// --region 必填(cn|global|dev):选出本次出包身份 + 签名描述符(见 lib/self-host-region.mjs)。// 不走 resolveSelfHostRegion:它对 dev 强校验发布专用的 npkgExpectBundle,与纯构建@@ -188,10 +230,12 @@ async function main() {if (!SELF_HOST_REGIONS.includes(rawRegion)) {throw new Error(`--region 只能是 ${SELF_HOST_REGIONS.join(' 或 ')},收到: ${rawRegion}`);}+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.regionConfig;const region = loadSelfHostRegions({ mode: 'local' })[rawRegion];if (!region.iosBundleId?.trim()) {throw new Error(`self-host-regions.json 的 ${region.authRegion}.iosBundleId 未填(构建必需)`);}+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.buildPlan;const desktopVersion = typeof args.desktopVersion === 'string' ? args.desktopVersion : '';const env = selfhostEnv(region, desktopVersion);const appJson = readAppJson();@@ -204,6 +248,7 @@ async function main() {// git 闸门只管真构建:dry-run 纯本地(不做 origin/main 远端比对,分支/离线可跑)。if (args.execute) {+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.preflight;if (!args.skipGitGate) assertProductionGitGate();else log(' warn: --skip-git-gate,跳过 main/clean/HEAD 校验(仅本地迭代用)');if (missingBake.length) {@@ -239,20 +284,24 @@ async function main() {return;}+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.preflight;if (process.platform !== 'darwin') throw new Error('--execute 需在 macOS 上运行(xcodebuild)');// region / endpoint manifest 自举基址必须齐全(读仓内 config/endpoint*.json,离线可用)。assertPublicEnv(env, { variant: 'production', requiredKeys: SELF_HOST_PUBLIC_ENV_KEYS });+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.toolchain;const ipaPath = buildIpa(env, region);log(` ✓ ipa: ${ipaPath}`);+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.artifactValidation;// 权威 runtimeVersion = 真正烤进 .ipa 的 EXUpdates.bundle/fingerprint(仅报告,供发布侧比对)。const runtimeVersion = readEmbeddedRuntimeVersionFromIpa(ipaPath);log(` ✓ runtimeVersion(读自 .ipa 内嵌 fingerprint): ${runtimeVersion}`);let finalPath = ipaPath;if (typeof args.out === 'string' && args.out) {+ iosBuildFailureStage = IOS_BUILD_FAILURE_STAGE.output;const outDir = resolve(String(args.out));if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true });finalPath = join(outDir, basename(ipaPath));@@ -269,7 +318,6 @@ async function main() {}main().catch(() => {- // 子进程已继承 stdout/stderr;这里只输出固定提示,避免异常消息夹带签名/证书 env 值。- console.error('iOS 构建失败;详细原因请查看上方构建工具输出。');+ reportIosBuildFailure();process.exit(1);});diff --git a/apps/mobile/src/__tests__/devServerEnvironment.test.ts b/apps/mobile/src/__tests__/devServerEnvironment.test.tsindex 061be90ddd..5cf3297651 100644--- a/apps/mobile/src/__tests__/devServerEnvironment.test.ts+++ b/apps/mobile/src/__tests__/devServerEnvironment.test.ts@@ -128,6 +128,34 @@ describe('CindyDev server environment preference', () => {).rejects.toBe(reloadError);expect(calls).toEqual(['persist:release', 'reload', 'persist:dev']);});++ it('restores in-memory state and preserves the reload error when persistence rollback also fails', async () => {+ const environment = await freshModule();+ const reloadError = new Error('reload unavailable');+ storage.removeItem.mockRejectedValueOnce(+ new Error('rollback storage unavailable'),+ );++ await expect(+ environment.switchDevServerEnvironmentAndReload({+ current: 'dev',+ next: 'release',+ reload: async () => {+ throw reloadError;+ },+ setEnvironment: environment.setDevServerEnvironment,+ }),+ ).rejects.toBe(reloadError);++ expect(storage.setItem).toHaveBeenCalledWith(+ environment.__testing.storageKey,+ 'release',+ );+ expect(storage.removeItem).toHaveBeenCalledWith(+ environment.__testing.storageKey,+ );+ expect(environment.getDevServerEnvironment()).toBe('dev');+ });});describe('CindyDev startup endpoint steps', () => {@@ -210,4 +238,51 @@ describe('CindyDev startup endpoint steps', () => {},]);});++ it('allows returning to Dev only when the Release overlay step fails', async () => {+ const environment = await freshModule();+ const steps = environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: true,+ environment: 'release',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: true,+ });++ const outcome = await environment.runDevServerEndpointStartupSteps(+ steps,+ async (step) =>+ step.preserveBuildReleaseMetadata+ ? { ok: false as const, reason: 'fetch-failed' }+ : { ok: true as const },+ );++ expect(outcome).toEqual({+ ok: false,+ reason: 'fetch-failed',+ canResetToDev: true,+ });+ });++ it('keeps the ordinary retry path when the packaged Dev manifest fails', async () => {+ const environment = await freshModule();+ const steps = environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: true,+ environment: 'release',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: true,+ });++ await expect(+ environment.runDevServerEndpointStartupSteps(steps, async () => ({+ ok: false as const,+ reason: 'invalid-json',+ })),+ ).resolves.toEqual({+ ok: false,+ reason: 'invalid-json',+ canResetToDev: false,+ });+ });});diff --git a/apps/mobile/src/__tests__/loginSkinVisual.test.ts b/apps/mobile/src/__tests__/loginSkinVisual.test.tsindex def945815b..97a7477a08 100644--- a/apps/mobile/src/__tests__/loginSkinVisual.test.ts+++ b/apps/mobile/src/__tests__/loginSkinVisual.test.ts@@ -44,7 +44,7 @@ describe('loginSkin 白底体系视觉(源码接线 + token 参数)', () => {expect(layoutSource).toContain('StartupGateBlockedContent');// 文案 key 化契约保持(startupGateCopy 闸门同源)expect(layoutSource).toContain("loginText('endpointGateTitle')");- expect(layoutSource).toContain("loginText('retry')");+ expect(layoutSource).toContain("'endpointGateResetToDev' : 'retry'");});it('login-panel-border:面板 1px panelBorder 描边 + panelBg r36(368:1383)', () => {diff --git a/apps/mobile/src/__tests__/startupGateCopy.test.ts b/apps/mobile/src/__tests__/startupGateCopy.test.tsindex 3946d9dd45..5ab895d64f 100644--- a/apps/mobile/src/__tests__/startupGateCopy.test.ts+++ b/apps/mobile/src/__tests__/startupGateCopy.test.ts@@ -31,10 +31,11 @@ const loginSource = readFileSync();describe("endpoint 闸门失败屏(_layout.tsx)文案 key 化", () => {- it("error 态三段文案全部走 loginMessages key", () => {+ it("error 态文案与动态动作全部走 loginMessages key", () => {expect(layoutSource).toContain("loginText('endpointGateTitle')");expect(layoutSource).toContain("loginText('endpointGateSubtitle')");- expect(layoutSource).toContain("loginText('retry')");+ expect(layoutSource).toContain("'endpointGateResetToDev' : 'retry'");+ expect(layoutSource).toContain('endpointGate.resetToDev');// {reason} 占位符在渲染点替换,保留闸门失败原因透出expect(layoutSource).toContain("'{reason}'");expect(layoutSource).toContain("endpointGate.reason ?? 'unknown'");@@ -51,6 +52,7 @@ describe("endpoint 闸门失败屏(_layout.tsx)文案 key 化", () => {const catalog = loginMessages[locale];expect(catalog.endpointGateTitle.trim(), locale).not.toBe("");expect(catalog.endpointGateSubtitle, locale).toContain("{reason}");+ expect(catalog.endpointGateResetToDev.trim(), locale).not.toBe("");expect(catalog.retry.trim(), locale).not.toBe("");}});diff --git a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts b/apps/mobile/src/auth/__tests__/loginHandoffState.test.tsindex a189b157b3..041416559d 100644--- a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts+++ b/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts@@ -220,7 +220,8 @@ describe('loginHandoff 接线(Provider/reporter 拓扑 + 清理,读源码断言)expect(layoutSource).toContain('<MobileLoginHandoffStage>');// 内容层的动作 prop 已从 retry 专用改为通用 action(端点重试 / 强更去更新共用同一层),// 端点错误屏的接线与文案 key 化契约不变。- expect(layoutSource).toContain('onAction={endpointGate.retry}');+ expect(layoutSource).toContain('? endpointGate.resetToDev');+ expect(layoutSource).toContain(': endpointGate.retry');expect(layoutSource).toContain("loginText('endpointGateTitle')");});diff --git a/apps/mobile/src/auth/loginMessages.ts b/apps/mobile/src/auth/loginMessages.tsindex 988c15aa77..8820541903 100644--- a/apps/mobile/src/auth/loginMessages.ts+++ b/apps/mobile/src/auth/loginMessages.ts@@ -125,6 +125,7 @@ const messages = {errorFallback: "登入未完成,請重試。",endpointGateTitle: "無法取得伺服器設定",endpointGateSubtitle: "請檢查網路連線後重試({reason})",+ endpointGateResetToDev: "返回 Dev",retry: "重試",configIssueAuthBaseUrl: "登入服務地址必須是 http(s) URL。",},@@ -239,6 +240,7 @@ const messages = {errorFallback: "登录未完成,请重试。",endpointGateTitle: "无法获取服务器配置",endpointGateSubtitle: "请检查网络连接后重试({reason})",+ endpointGateResetToDev: "返回 Dev",retry: "重试",configIssueAuthBaseUrl: "登录服务地址必须是 http(s) URL。",},@@ -366,6 +368,7 @@ const messages = {endpointGateTitle: "Unable to load server configuration",endpointGateSubtitle:"Check your network connection and try again ({reason})",+ endpointGateResetToDev: "Return to Dev",retry: "Retry",configIssueAuthBaseUrl:"The sign-in service address must be an http(s) URL.",@@ -493,6 +496,7 @@ const messages = {endpointGateTitle: "サーバー設定を取得できません",endpointGateSubtitle:"ネットワーク接続を確認してから再試行してください({reason})",+ endpointGateResetToDev: "Dev に戻る",retry: "再試行",configIssueAuthBaseUrl:"ログインサービスのアドレスは http(s) URL である必要があります。",@@ -617,6 +621,7 @@ const messages = {endpointGateTitle: "서버 설정을 가져올 수 없습니다",endpointGateSubtitle:"네트워크 연결을 확인한 후 다시 시도해 주세요({reason})",+ endpointGateResetToDev: "Dev로 돌아가기",retry: "다시 시도",configIssueAuthBaseUrl: "로그인 서비스 주소는 http(s) URL이어야 합니다.",},diff --git a/apps/mobile/src/config/devServerEnvironment.ts b/apps/mobile/src/config/devServerEnvironment.tsindex a7eef276d7..460fe0a818 100644--- a/apps/mobile/src/config/devServerEnvironment.ts+++ b/apps/mobile/src/config/devServerEnvironment.ts@@ -21,6 +21,10 @@ export interface DevServerEnvironmentReloadSwitch {setEnvironment: (environment: DevServerEnvironment) => Promise<void>;}+export type DevServerEndpointStartupRunOutcome =+ | { ok: true }+ | { ok: false; reason: string; canResetToDev: boolean };+export const DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED =process.env.EXPO_PUBLIC_CINDY_AUTH_REGION === 'dev';@@ -43,6 +47,12 @@ function notifyListeners(): void {}}+function restoreActiveEnvironment(environment: DevServerEnvironment): void {+ activeEnvironment = environment;+ hydrated = true;+ notifyListeners();+}+export function hydrateDevServerEnvironment(): Promise<DevServerEnvironment> {if (!DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED) {hydrated = true;@@ -110,6 +120,25 @@ export function buildDevServerEndpointStartupSteps(input: {return steps;}+/** 执行启动步骤,并标记失败是否发生在可撤销的 Release 业务端点覆盖阶段。 */+export async function runDevServerEndpointStartupSteps(+ steps: readonly DevServerEndpointStartupStep[],+ runStep: (+ step: DevServerEndpointStartupStep,+ ) => Promise<{ ok: true } | { ok: false; reason: string }>,+): Promise<DevServerEndpointStartupRunOutcome> {+ for (const step of steps) {+ const outcome = await runStep(step);+ if (!outcome.ok) {+ return {+ ...outcome,+ canResetToDev: step.preserveBuildReleaseMetadata,+ };+ }+ }+ return { ok: true };+}+/** 重载失败时恢复旧选择,避免当前进程端点与持久化环境不一致。 */export async function switchDevServerEnvironmentAndReload(input: DevServerEnvironmentReloadSwitch,@@ -118,7 +147,13 @@ export async function switchDevServerEnvironmentAndReload(try {await input.reload();} catch (error) {- await input.setEnvironment(input.current);+ try {+ await input.setEnvironment(input.current);+ } catch {+ // 持久化层不可用时仍须让当前 JS 进程与实际未重载的旧端点保持一致。+ // 最终继续抛出原始 reload 错误,避免回滚错误掩盖首要故障。+ restoreActiveEnvironment(input.current);+ }throw error;}}diff --git a/apps/mobile/src/config/useStartupEndpointGate.ts b/apps/mobile/src/config/useStartupEndpointGate.tsindex 099835eab2..254a327971 100644--- a/apps/mobile/src/config/useStartupEndpointGate.ts+++ b/apps/mobile/src/config/useStartupEndpointGate.ts@@ -21,6 +21,8 @@ import {DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED,buildDevServerEndpointStartupSteps,hydrateDevServerEnvironment,+ runDevServerEndpointStartupSteps,+ setDevServerEnvironment,} from './devServerEnvironment';export type StartupEndpointGateStatus = 'pending' | 'ready' | 'error';@@ -29,6 +31,10 @@ export interface StartupEndpointGate {status: StartupEndpointGateStatus;/** status === 'error' 时的失败原因(fetch-failed / invalid-json / ...)。 */reason: string | null;+ /** Release 业务端点覆盖失败时,唯一动作可将 CindyDev 恢复到 Dev。 */+ canResetToDev: boolean;+ /** 清除 Release 选择后重新执行启动闸门。 */+ resetToDev: () => void;/** 错误屏「重试」:回到 pending 并重新拉取。 */retry: () => void;}@@ -42,6 +48,7 @@ export function useStartupEndpointGate(): StartupEndpointGate {enabled ? 'pending' : 'ready',);const [reason, setReason] = useState<string | null>(null);+ const [canResetToDev, setCanResetToDev] = useState(false);const [attempt, setAttempt] = useState(0);const running = useRef(false);@@ -61,22 +68,23 @@ export function useStartupEndpointGate(): StartupEndpointGate {releaseManifestBaseUrl: DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,switchEnabled: DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED,});- for (const step of steps) {- const outcome = await runStartupEndpointResolve({+ return runDevServerEndpointStartupSteps(steps, (step) =>+ runStartupEndpointResolve({expectedRegion: BUILD_AUTH_REGION,manifestBaseUrl: step.manifestBaseUrl,preserveBuildReleaseMetadata: step.preserveBuildReleaseMetadata,resolveIsTestFlight: isTestFlightBuild,- });- if (!outcome.ok) return outcome;- }- return { ok: true as const, source: 'cdn' as const };+ }),+ );})().then((outcome) => {running.current = false;if (cancelled) return;- if (outcome.ok) setStatus('ready');- else {+ if (outcome.ok) {+ setCanResetToDev(false);+ setStatus('ready');+ } else {setReason(outcome.reason);+ setCanResetToDev(outcome.canResetToDev);setStatus('error');}});@@ -87,9 +95,29 @@ export function useStartupEndpointGate(): StartupEndpointGate {const retry = useCallback(() => {setReason(null);+ setCanResetToDev(false);setStatus('pending');setAttempt((n) => n + 1);}, []);- return { status, reason, retry };+ const resetToDev = useCallback(() => {+ if (running.current) return;+ running.current = true;+ setReason(null);+ setCanResetToDev(false);+ setStatus('pending');+ void setDevServerEnvironment('dev')+ .then(() => {+ running.current = false;+ setAttempt((n) => n + 1);+ })+ .catch(() => {+ running.current = false;+ setReason('environment-reset-failed');+ setCanResetToDev(true);+ setStatus('error');+ });+ }, []);++ return { status, reason, canResetToDev, resetToDev, retry };}diff --git a/scripts/__tests__/client-endpoint-build-env.test.mjs b/scripts/__tests__/client-endpoint-build-env.test.mjsindex 19ec8bd94e..299932159e 100644--- a/scripts/__tests__/client-endpoint-build-env.test.mjs+++ b/scripts/__tests__/client-endpoint-build-env.test.mjs@@ -131,6 +131,27 @@ test('Android 构建在子进程启动前失败时输出安全且可执行的诊assert.doesNotMatch(result.stderr, /详细原因请查看上方构建工具输出/);});+test('iOS 构建在子进程启动前失败时输出安全且可执行的诊断', () => {+ const fakeSecret = 'fake-ios-signing-secret-that-must-not-leak';+ const result = spawnSync(+ process.execPath,+ [path.resolve('apps/mobile/scripts/build-ios.mjs'), '--region', 'invalid'],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ XDT_IOS_SIGNING_SECRET_DEV: fakeSecret,+ },+ },+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /iOS 构建失败(参数检查)/);+ assert.match(result.stderr, /--region cn\|global\|dev/);+ assert.doesNotMatch(result.stderr, new RegExp(fakeSecret));+ assert.doesNotMatch(result.stderr, /详细原因请查看上方构建工具输出/);+});+test('端点清单自举基址缺失、非法协议或携带凭据时 fail closed', () => {const repoRoot = writeRepoFixtures();const cnPath = path.join(repoRoot, 'config', 'endpoint.json');