Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): add CindyDev server environment switch
DavidShen280c946e0823
diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.jsindex 856efb56dc..1a09be2aeb 100644--- a/apps/mobile/app.config.js+++ b/apps/mobile/app.config.js@@ -113,11 +113,10 @@ function resolveMobileBuildEnv() {return loadMobileClientBuildEnv();}-function resolvePeerManifestBaseUrl(region) {+function resolveManifestBaseUrl(region) {const previousRegion = process.env.EXPO_PUBLIC_CINDY_AUTH_REGION;try {- process.env.EXPO_PUBLIC_CINDY_AUTH_REGION =- region === 'global' ? 'cn' : 'global';+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = region;const peerBuildEnv = loadMobileClientBuildEnv();return peerBuildEnv.EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL;} finally {@@ -129,6 +128,10 @@ function resolvePeerManifestBaseUrl(region) {}}+function resolvePeerManifestBaseUrl(region) {+ return resolveManifestBaseUrl(region === 'global' ? 'cn' : 'global');+}+const REGION_CONFIG = {cn: {scheme: 'cindycn',@@ -206,6 +209,14 @@ module.exports = (context = {}) => {...mobileBuildEnv,EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL:resolvePeerManifestBaseUrl(region),+ // CindyDev 的业务服务器切换只需把 CN Release 的可信清单基址内联进 JS。+ // 不写入 extra / resolved ExpoConfig,避免让纯 JS 开发功能改变 runtime fingerprint。+ ...(region === 'dev'+ ? {+ EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL:+ resolveManifestBaseUrl('cn'),+ }+ : {}),};for (const [key, value] of Object.entries(mobileBundleEnv)) {if (!process.env[key]?.trim()) process.env[key] = value;diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex 26e24734e7..623d64d681 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -6,6 +6,7 @@ import { useRouter } from 'expo-router';import { Children, Fragment, isValidElement, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import {Alert,+ DevSettings,FlatList,Image,Linking,@@ -53,6 +54,11 @@ import {IS_TESTFLIGHT_BUILD,REVIEW_MODE,} from '@/config/env';+import {+ DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED,+ type DevServerEnvironment,+} from '@/config/devServerEnvironment';+import { useDevServerEnvironment } from '@/config/useDevServerEnvironment';import { LEGAL_LINKS } from '@/config/legalLinks';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { buildMobileDeviceName } from '@/device-link/mobileDeviceIdentity';@@ -148,6 +154,13 @@ export default function SettingsScreen() {const { enabled: betaEnabled, ready: betaReady, setEnabled: setBetaEnabled } = useBetaChannel();const [betaBusy, setBetaBusy] = useState(false);const showBetaBadge = betaReady && betaEnabled;+ const {+ environment: devServerEnvironment,+ ready: devServerEnvironmentReady,+ setEnvironment: setDevServerEnvironment,+ } = useDevServerEnvironment();+ const [devServerEnvironmentBusy, setDevServerEnvironmentBusy] =+ useState(false);const updateCheckInFlightRef = useRef(false);// 语音词典:手机只读展示被控桌面的词典快照(正本在桌面,手机不参与合并)。const [dictionaryScreenOpen, setDictionaryScreenOpen] = useState(false);@@ -539,6 +552,86 @@ export default function SettingsScreen() {}}, [auth, loggingOut, router]);+ const switchDevServerEnvironment = useCallback(+ async (next: DevServerEnvironment) => {+ if (+ !DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED ||+ devServerEnvironmentBusy ||+ !devServerEnvironmentReady ||+ next === devServerEnvironment+ ) {+ return;+ }+ setDevServerEnvironmentBusy(true);+ try {+ // 旧环境的 push 注销、token 与账号缓存必须先在旧端点仍生效时清理。+ await auth.logout();+ await setDevServerEnvironment(next);+ if (__DEV__) {+ DevSettings.reload();+ return;+ }+ if (Updates.isEnabled) {+ await Updates.reloadAsync();+ return;+ }+ router.replace('/login');+ Alert.alert(+ t('settings.devServerEnvironment.title'),+ t('settings.devServerEnvironment.restartRequired'),+ );+ } catch {+ Alert.alert(+ t('settings.devServerEnvironment.title'),+ t('settings.devServerEnvironment.switchFailed'),+ );+ } finally {+ setDevServerEnvironmentBusy(false);+ }+ },+ [+ auth,+ devServerEnvironment,+ devServerEnvironmentBusy,+ devServerEnvironmentReady,+ router,+ setDevServerEnvironment,+ t,+ ],+ );++ const confirmDevServerEnvironmentSwitch = useCallback(() => {+ if (+ !DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED ||+ devServerEnvironmentBusy ||+ !devServerEnvironmentReady+ ) {+ return;+ }+ const next: DevServerEnvironment =+ devServerEnvironment === 'dev' ? 'release' : 'dev';+ Alert.alert(+ t('settings.devServerEnvironment.confirmTitle', {+ environment: t(`settings.devServerEnvironment.options.${next}`),+ }),+ t('settings.devServerEnvironment.confirmBody'),+ [+ { text: t('settings.devServerEnvironment.cancel'), style: 'cancel' },+ {+ text: t('settings.devServerEnvironment.switchAction'),+ style: 'destructive',+ onPress: () => void switchDevServerEnvironment(next),+ },+ ],+ );+ }, [+ devServerEnvironment,+ devServerEnvironmentBusy,+ devServerEnvironmentReady,+ switchDevServerEnvironment,+ t,+ ]);+const openAccountDeletion = useCallback(() => {router.push('/account-deletion');}, [router]);@@ -1007,6 +1100,25 @@ export default function SettingsScreen() {>{debugExpanded? [+ ...(DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED+ ? [+ <ActionInfoRow+ accessibilityLabel={t('settings.devServerEnvironment.accessibility')}+ detail={t('settings.devServerEnvironment.description')}+ key="dev-server-environment"+ label={t('settings.devServerEnvironment.title')}+ onPress={confirmDevServerEnvironmentSwitch}+ testID="settings.devServerEnvironment"+ value={+ devServerEnvironmentBusy+ ? t('settings.devServerEnvironment.switching')+ : t(+ `settings.devServerEnvironment.options.${devServerEnvironment}`,+ )+ }+ />,+ ]+ : []),...debugSection.rows.map((row) => (row.copyValue ? (<CopyRow copied={copiedRowId === row.id} key={row.id} onCopy={copyRow} row={row} />diff --git a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts b/apps/mobile/src/__tests__/clientEndpointStartup.test.tsindex 85261cd5a2..53b593d2f5 100644--- a/apps/mobile/src/__tests__/clientEndpointStartup.test.ts+++ b/apps/mobile/src/__tests__/clientEndpointStartup.test.ts@@ -97,6 +97,95 @@ describe('runStartupEndpointResolve(CDN 解析)', () => {).resolves.toEqual({ ok: true, source: 'cdn' });});+ it('可从指定的第二个可信清单基址拉取端点', async () => {+ const { startup } = await freshModules();+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ text: async () => FULL_MANIFEST,+ } as Response);+ try {+ await expect(+ startup.runStartupEndpointResolve({+ autoRetryDelaysMs: [],+ manifestBaseUrl: 'https://release-manifest.example/app',+ }),+ ).resolves.toEqual({ ok: true, source: 'cdn' });+ expect(fetchSpy).toHaveBeenCalledWith(+ expect.stringMatching(+ /^https:\/\/release-manifest\.example\/app\/endpoint\.json\?t=\d+$/,+ ),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ } finally {+ fetchSpy.mockRestore();+ }+ });++ it('第二份清单按显式目标区域校验,不受安装包默认区域限制', async () => {+ const { startup } = await freshModules();+ const apply = vi.fn();++ await expect(+ startup.runStartupEndpointResolve({+ apply,+ expectedRegion: 'global',+ fetchManifest: okFetch(+ JSON.stringify({ ...FULL_MANIFEST_OBJECT, region: 'global' }),+ ),+ }),+ ).resolves.toEqual({ ok: true, source: 'cdn' });+ expect(apply).toHaveBeenCalledTimes(1);+ });++ it('切换业务服务器时保留 CindyDev 的 OTA 与审核元数据', async () => {+ process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST = '1';+ vi.resetModules();+ vi.doMock('expo-constants', () => ({+ default: { expoConfig: { version: '9.9.9' } },+ }));+ try {+ const env = await import('@/config/env');+ const startup = await import('@/config/clientEndpointStartup');+ const buildManifest = JSON.stringify({+ ...FULL_MANIFEST_OBJECT,+ authApiBaseUrl: 'https://auth.dev.example.com',+ mobileUpdateBaseUrl: 'https://updates.dev.example.com',+ review: '9.9.9',+ });+ await startup.runStartupEndpointResolve({+ fetchManifest: okFetch(buildManifest),+ });+ expect(env.AUTH_API_BASE_URL).toBe('https://auth.dev.example.com');+ expect(env.OTA_SERVER_BASE_URL).toBe('https://updates.dev.example.com');+ expect(env.REVIEW_MODE).toBe(true);+ expect(env.IS_TESTFLIGHT_BUILD).toBe(false);++ const releaseManifest = JSON.stringify({+ ...FULL_MANIFEST_OBJECT,+ authApiBaseUrl: 'https://auth.release.example.com',+ mobileUpdateBaseUrl: 'https://updates.release.example.com',+ review: '0.0.0',+ });+ await startup.runStartupEndpointResolve({+ fetchManifest: okFetch(releaseManifest),+ preserveBuildReleaseMetadata: true,+ resolveIsTestFlight: async () => true,+ });++ expect(env.AUTH_API_BASE_URL).toBe('https://auth.release.example.com');+ expect(env.OTA_SERVER_BASE_URL).toBe('https://updates.dev.example.com');+ expect(env.REVIEW_MODE).toBe(true);+ expect(env.IS_TESTFLIGHT_BUILD).toBe(false);+ expect(+ env.getMobileEndpointForRealm(env.BUILD_AUTH_REGION, 'authApiBaseUrl'),+ ).toBe('https://auth.release.example.com');+ } finally {+ delete process.env.EXPO_PUBLIC_XDT_OTA_SELFHOST;+ vi.doUnmock('expo-constants');+ vi.resetModules();+ }+ });+it('二进制版本优先读原生 0.1.2,不被 OTA manifest 的 0.1.0 覆盖', async () => {vi.resetModules();vi.doMock('expo-application', () => ({diff --git a/apps/mobile/src/__tests__/devServerEnvironment.test.ts b/apps/mobile/src/__tests__/devServerEnvironment.test.tsnew file mode 100644index 0000000000..aeef6010a1--- /dev/null+++ b/apps/mobile/src/__tests__/devServerEnvironment.test.ts@@ -0,0 +1,192 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const storage = vi.hoisted(() => ({+ getItem: vi.fn<() => Promise<string | null>>(),+ removeItem: vi.fn<() => Promise<void>>(),+ setItem: vi.fn<() => Promise<void>>(),+}));++vi.mock('@react-native-async-storage/async-storage', () => ({+ default: storage,+}));++const originalAuthRegion = process.env.EXPO_PUBLIC_CINDY_AUTH_REGION;++async function freshModule(region: 'cn' | 'dev' = 'dev') {+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = region;+ vi.resetModules();+ return import('@/config/devServerEnvironment');+}++beforeEach(() => {+ vi.clearAllMocks();+ storage.getItem.mockResolvedValue(null);+ storage.removeItem.mockResolvedValue(undefined);+ storage.setItem.mockResolvedValue(undefined);+});++afterEach(() => {+ if (originalAuthRegion === undefined) {+ delete process.env.EXPO_PUBLIC_CINDY_AUTH_REGION;+ } else {+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = originalAuthRegion;+ }+ vi.resetModules();+});++describe('CindyDev server environment preference', () => {+ it('is unavailable to release builds and never touches their storage', async () => {+ const environment = await freshModule('cn');++ expect(environment.DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED).toBe(false);+ await expect(environment.hydrateDevServerEnvironment()).resolves.toBe(+ 'dev',+ );+ await expect(+ environment.setDevServerEnvironment('release'),+ ).rejects.toThrow('dev-server-environment-switch-unavailable');+ expect(storage.getItem).not.toHaveBeenCalled();+ expect(storage.setItem).not.toHaveBeenCalled();+ });++ it('defaults CindyDev to Dev when no override is stored', async () => {+ const environment = await freshModule();++ await expect(environment.hydrateDevServerEnvironment()).resolves.toBe(+ 'dev',+ );+ expect(environment.getDevServerEnvironment()).toBe('dev');+ expect(storage.getItem).toHaveBeenCalledWith(+ environment.__testing.storageKey,+ );+ });++ it('hydrates an explicit Release override', async () => {+ storage.getItem.mockResolvedValue('release');+ const environment = await freshModule();++ await expect(environment.hydrateDevServerEnvironment()).resolves.toBe(+ 'release',+ );+ expect(environment.getDevServerEnvironment()).toBe('release');+ });++ it('stores only the Release override and removes it when switching to Dev', async () => {+ const environment = await freshModule();++ await environment.setDevServerEnvironment('release');+ expect(storage.setItem).toHaveBeenCalledWith(+ environment.__testing.storageKey,+ 'release',+ );+ expect(environment.getDevServerEnvironment()).toBe('release');++ await environment.setDevServerEnvironment('dev');+ expect(storage.removeItem).toHaveBeenCalledWith(+ environment.__testing.storageKey,+ );+ expect(environment.getDevServerEnvironment()).toBe('dev');+ });++ it('fails safe to Dev when reading the preference fails', async () => {+ storage.getItem.mockRejectedValue(new Error('storage unavailable'));+ const environment = await freshModule();++ await expect(environment.hydrateDevServerEnvironment()).resolves.toBe(+ 'dev',+ );+ expect(environment.getDevServerEnvironment()).toBe('dev');+ });++ it('keeps the active environment unchanged when persistence fails', async () => {+ storage.setItem.mockRejectedValue(new Error('storage unavailable'));+ const environment = await freshModule();++ await expect(+ environment.setDevServerEnvironment('release'),+ ).rejects.toThrow('storage unavailable');+ expect(environment.getDevServerEnvironment()).toBe('dev');+ });+});++describe('CindyDev startup endpoint steps', () => {+ it('keeps the existing single-manifest path outside CindyDev', async () => {+ const environment = await freshModule('cn');++ expect(+ environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: true,+ environment: 'dev',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: false,+ }),+ ).toEqual([+ {+ manifestBaseUrl: 'https://dev.example',+ preserveBuildReleaseMetadata: false,+ },+ ]);+ });++ it('uses only the packaged CindyDev manifest while Dev is selected', async () => {+ const environment = await freshModule();++ expect(+ environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: true,+ environment: 'dev',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: true,+ }),+ ).toEqual([+ {+ manifestBaseUrl: 'https://dev.example',+ preserveBuildReleaseMetadata: false,+ },+ ]);+ });++ it('loads CindyDev metadata first and Release business endpoints second', async () => {+ const environment = await freshModule();++ expect(+ environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: true,+ environment: 'release',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: true,+ }),+ ).toEqual([+ {+ manifestBaseUrl: 'https://dev.example',+ preserveBuildReleaseMetadata: false,+ },+ {+ manifestBaseUrl: 'https://release.example',+ preserveBuildReleaseMetadata: true,+ },+ ]);+ });++ it('uses only the Release manifest in local Metro when Release is selected', async () => {+ const environment = await freshModule();++ expect(+ environment.buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: 'https://dev.example',+ defaultEndpointGateEnabled: false,+ environment: 'release',+ releaseManifestBaseUrl: 'https://release.example',+ switchEnabled: true,+ }),+ ).toEqual([+ {+ manifestBaseUrl: 'https://release.example',+ preserveBuildReleaseMetadata: true,+ },+ ]);+ });+});diff --git a/apps/mobile/src/__tests__/mobileSettings.test.ts b/apps/mobile/src/__tests__/mobileSettings.test.tsindex 677d7c6c42..65b4047d7d 100644--- a/apps/mobile/src/__tests__/mobileSettings.test.ts+++ b/apps/mobile/src/__tests__/mobileSettings.test.ts@@ -24,6 +24,47 @@ describe('mobile settings overview', () => {expect(source).not.toContain('LanguageOptionRow');});+ it('shows the server switch only in CindyDev and clears the old session before reloading', () => {+ const settingsSource = readTextLf(+ resolve(process.cwd(), 'app/settings.tsx'),+ 'utf8',+ );+ const environmentSource = readTextLf(+ resolve(process.cwd(), 'src/config/devServerEnvironment.ts'),+ 'utf8',+ );+ const switchStart = settingsSource.indexOf(+ 'const switchDevServerEnvironment = useCallback(',+ );+ const logoutIndex = settingsSource.indexOf(+ 'await auth.logout();',+ switchStart,+ );+ const persistIndex = settingsSource.indexOf(+ 'await setDevServerEnvironment(next);',+ switchStart,+ );+ const reloadIndex = settingsSource.indexOf(+ 'DevSettings.reload();',+ switchStart,+ );++ expect(settingsSource).toContain(+ '...(DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED',+ );+ expect(settingsSource).toContain(+ 'testID="settings.devServerEnvironment"',+ );+ expect(environmentSource).toContain(+ "process.env.EXPO_PUBLIC_CINDY_AUTH_REGION === 'dev'",+ );+ expect(environmentSource).not.toContain('TextInput');+ expect(switchStart).toBeGreaterThan(-1);+ expect(logoutIndex).toBeGreaterThan(switchStart);+ expect(persistIndex).toBeGreaterThan(logoutIndex);+ expect(reloadIndex).toBeGreaterThan(persistIndex);+ });+it('keeps the device-link hello name and settings device name on one source', () => {expect(buildMobileDeviceName({ constantsDeviceName: ' Carol iPhone ', platform: 'ios' })).toBe('Carol iPhone');expect(buildMobileDeviceName({ constantsDeviceName: ' ', platform: 'android' })).toBe('Cindy android');diff --git a/apps/mobile/src/__tests__/nativeAppConfig.test.ts b/apps/mobile/src/__tests__/nativeAppConfig.test.tsindex 738706b758..f9ea53bfaf 100644--- a/apps/mobile/src/__tests__/nativeAppConfig.test.ts+++ b/apps/mobile/src/__tests__/nativeAppConfig.test.ts@@ -14,6 +14,7 @@ const managedEnvKeys = ['EXPO_PUBLIC_APP_VARIANT','EXPO_PUBLIC_BETA_DEV','EXPO_PUBLIC_CINDY_AUTH_REGION',+ 'EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL','EXPO_PUBLIC_ENDPOINT_MANIFEST_BASE_URL','EXPO_PUBLIC_ENDPOINT_MANIFEST_PEER_BASE_URL','EXPO_PUBLIC_XDT_OTA_SELFHOST',@@ -99,6 +100,44 @@ describe('mobile native app config', () => {);});+ it('keeps the CN Release manifest injection CindyDev-only and outside Expo config', () => {+ const appJson = JSON.parse(+ readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),+ );+ const buildConfig = require(resolve(process.cwd(), 'app.config.js'));+ const appConfigSource = readFileSync(+ resolve(process.cwd(), 'app.config.js'),+ 'utf8',+ );++ expect(appConfigSource).toContain("...(region === 'dev'");+ expect(appConfigSource).toContain(+ 'EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL:',+ );+ expect(appConfigSource).toContain("resolveManifestBaseUrl('cn')");+ expect(appConfigSource).not.toContain(+ 'xdtProductionEnv: mobileBundleEnv',+ );++ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'cn';+ const cn = buildConfig({ config: appJson.expo });+ expect(+ process.env.EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,+ ).toBeUndefined();+ expect(JSON.stringify(cn)).not.toContain(+ 'EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL',+ );++ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION = 'global';+ const global = buildConfig({ config: appJson.expo });+ expect(+ process.env.EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,+ ).toBeUndefined();+ expect(JSON.stringify(global)).not.toContain(+ 'EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL',+ );+ });+it('injects EAS owner / projectId / updates from env and omits them when unset', () => {const appJson = JSON.parse(readFileSync(resolve(process.cwd(), 'app.json'), 'utf8'),diff --git a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts b/apps/mobile/src/__tests__/pushNotificationsRealm.test.tsindex bb62038f77..395bf9d28c 100644--- a/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts+++ b/apps/mobile/src/__tests__/pushNotificationsRealm.test.ts@@ -9,6 +9,9 @@ const envState = vi.hoisted(() => ({global: 'https://relay.global.example',},}));+const devEnvironmentState = vi.hoisted(() => ({+ active: 'dev' as 'dev' | 'release',+}));const mocks = vi.hoisted(() => ({asyncGetItem: vi.fn(async (key: string) => store.get(key) ?? null),loadMobileEndpointsForRealm: vi.fn(async (_realm: 'cn' | 'global') => ({})),@@ -51,6 +54,10 @@ vi.mock('@/config/env', () => ({envState.endpointByRealm[realm],}));+vi.mock('@/config/devServerEnvironment', () => ({+ getDevServerEnvironment: () => devEnvironmentState.active,+}));+import {retryPendingUnregister,syncPushRegistration,@@ -59,6 +66,8 @@ import {const REGISTERED_KEY = 'cindy.push.registered';const PENDING_KEY = 'cindy.push.pendingUnregister';+const DEV_REGISTERED_KEY = `${REGISTERED_KEY}.dev`;+const RELEASE_REGISTERED_KEY = `${REGISTERED_KEY}.release`;function setStoredRealms(key: string, realms: Array<'cn' | 'global'>): void {store.set(key, JSON.stringify({ version: 1, realms }));@@ -77,6 +86,7 @@ describe('push notification realm routing', () => {store.clear();envState.activeRealm = 'cn';envState.buildRegion = 'cn';+ devEnvironmentState.active = 'dev';mocks.getPermissionsAsync.mockResolvedValue({status: 'granted',canAskAgain: false,@@ -135,6 +145,44 @@ describe('push notification realm routing', () => {}),}),);+ expect(readStoredRealms(DEV_REGISTERED_KEY)).toEqual(['cn']);+ expect(store.has(REGISTERED_KEY)).toBe(false);+ });++ it('CindyDev 的 Dev 与 Release 推送状态互相隔离', async () => {+ envState.buildRegion = 'dev';+ const apiFetch = vi.fn().mockResolvedValue({ registered: true });++ await syncPushRegistration({ enabled: true, apiFetch });+ devEnvironmentState.active = 'release';+ await syncPushRegistration({ enabled: true, apiFetch });++ expect(readStoredRealms(DEV_REGISTERED_KEY)).toEqual(['cn']);+ expect(readStoredRealms(RELEASE_REGISTERED_KEY)).toEqual(['cn']);+ expect(apiFetch).toHaveBeenCalledTimes(2);+ });++ it('Release 环境不读取旧 CindyDev 的无后缀状态', async () => {+ envState.buildRegion = 'dev';+ devEnvironmentState.active = 'release';+ setStoredRealms(REGISTERED_KEY, ['global']);+ const apiFetch = vi.fn().mockResolvedValue({ registered: true });++ await syncPushRegistration({ enabled: true, apiFetch });++ expect(readStoredRealms(RELEASE_REGISTERED_KEY)).toEqual(['cn']);+ expect(readStoredRealms(REGISTERED_KEY)).toEqual(['global']);+ });++ it('Dev 环境把旧 CindyDev 的无后缀状态迁移到环境专属 key', async () => {+ envState.buildRegion = 'dev';+ setStoredRealms(REGISTERED_KEY, ['global']);+ const apiFetch = vi.fn().mockResolvedValue({ registered: true });++ await syncPushRegistration({ enabled: true, apiFetch });++ expect(readStoredRealms(DEV_REGISTERED_KEY)).toEqual(['cn', 'global']);+ expect(store.has(REGISTERED_KEY)).toBe(false);});it('切换区域前用旧 token 向显式冻结的旧区域撤销', async () => {diff --git a/apps/mobile/src/config/clientEndpointStartup.ts b/apps/mobile/src/config/clientEndpointStartup.tsindex 437b9266f9..e5abede807 100644--- a/apps/mobile/src/config/clientEndpointStartup.ts+++ b/apps/mobile/src/config/clientEndpointStartup.ts@@ -21,6 +21,7 @@import {resolveClientEndpointsStrict,type ClientEndpointMap,+ type ClientEndpointRegion,} from '@cindy/maker-shared/client-endpoints';import {@@ -70,9 +71,12 @@ function defaultSleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}-async function fetchManifestViaCdn(timeoutMs: number): Promise<ManifestFetchResult> {+async function fetchManifestViaCdn(+ timeoutMs: number,+ manifestBaseUrl: string = ENDPOINT_MANIFEST_BASE_URL,+): Promise<ManifestFetchResult> {// 构建缺自举基址属打包配置事故:CDN 级不可用,交给启动闸门阻断。- if (!ENDPOINT_MANIFEST_BASE_URL) return { ok: false, detail: 'missing-manifest-base-url' };+ if (!manifestBaseUrl) return { ok: false, detail: 'missing-manifest-base-url' };const controller = new AbortController();let timedOut = false;const timer = setTimeout(() => {@@ -81,7 +85,7 @@ async function fetchManifestViaCdn(timeoutMs: number): Promise<ManifestFetchResu}, timeoutMs);try {const response = await fetch(- `${ENDPOINT_MANIFEST_BASE_URL}${MANIFEST_RELATIVE_PATH}?t=${Date.now()}`,+ `${manifestBaseUrl}${MANIFEST_RELATIVE_PATH}?t=${Date.now()}`,{ signal: controller.signal },);if (!response.ok) return { ok: false, detail: `http-${response.status}` };@@ -104,6 +108,12 @@ export interface StartupEndpointResolveDeps {isTestFlight: boolean;region: 'cn' | 'global' | null;}) => void;+ /** CindyDev 切换 Release 时传入第二个受信任清单基址。 */+ manifestBaseUrl?: string;+ /** 目标清单必须匹配的 auth 物理区域;默认仍为安装包构建区域。 */+ expectedRegion?: ClientEndpointRegion;+ /** 只切业务端点,保留 CindyDev 构建清单决定的 OTA / 审核元数据。 */+ preserveBuildReleaseMetadata?: boolean;timeoutMs?: number;/** 自动重试节奏,默认 AUTO_RETRY_DELAYS_MS;传 `[]` 关闭(单次尝试)。 */autoRetryDelaysMs?: readonly number[];@@ -159,8 +169,20 @@ export async function runStartupEndpointResolve(deps: StartupEndpointResolveDeps = {},): Promise<StartupEndpointResolveOutcome> {try {- const fetchManifest = deps.fetchManifest ?? fetchManifestViaCdn;- const apply = deps.apply ?? applyResolvedClientEndpoints;+ const fetchManifest =+ deps.fetchManifest ??+ ((requestTimeoutMs: number) =>+ fetchManifestViaCdn(+ requestTimeoutMs,+ deps.manifestBaseUrl ?? ENDPOINT_MANIFEST_BASE_URL,+ ));+ const apply =+ deps.apply ??+ ((resolved) =>+ applyResolvedClientEndpoints(resolved, {+ preserveBuildReleaseMetadata:+ deps.preserveBuildReleaseMetadata === true,+ }));const timeoutMs = deps.timeoutMs ?? ATTEMPT_TIMEOUT_MS;const retryDelays = deps.autoRetryDelaysMs ?? AUTO_RETRY_DELAYS_MS;const sleep = deps.sleep ?? defaultSleep;@@ -177,10 +199,11 @@ export async function runStartupEndpointResolve(const result = resolveClientEndpointsStrict(fetched.text);if (!result.ok) return { ok: false, reason: result.reason };// 老清单缺 region 时保持兼容;一旦自报 region,就必须与安装包构建区域一致。- if (result.region !== null && result.region !== BUILD_AUTH_REGION) {+ const expectedRegion = deps.expectedRegion ?? BUILD_AUTH_REGION;+ if (result.region !== null && result.region !== expectedRegion) {return {ok: false,- reason: `region-mismatch:${BUILD_AUTH_REGION}:${result.region}`,+ reason: `region-mismatch:${expectedRegion}:${result.region}`,};}diff --git a/apps/mobile/src/config/devServerEnvironment.ts b/apps/mobile/src/config/devServerEnvironment.tsnew file mode 100644index 0000000000..cca1dfcdc1--- /dev/null+++ b/apps/mobile/src/config/devServerEnvironment.ts@@ -0,0 +1,133 @@+/**+ * CindyDev 专属的业务服务器环境选择。+ *+ * `dev` 是系统默认值;仅把用户显式选择的 `release` 作为 override 落盘。+ * CN / Global 正式包不读取、不写入该配置,始终返回 `dev` 占位值,调用方还需用+ * `DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED` 控制入口与行为。+ */+import AsyncStorage from '@react-native-async-storage/async-storage';++export type DevServerEnvironment = 'dev' | 'release';++export interface DevServerEndpointStartupStep {+ manifestBaseUrl: string;+ preserveBuildReleaseMetadata: boolean;+}++export const DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED =+ process.env.EXPO_PUBLIC_CINDY_AUTH_REGION === 'dev';++const STORAGE_KEY = 'cindy.mobile.devServerEnvironment.release.v1';+const DEFAULT_ENVIRONMENT: DevServerEnvironment = 'dev';++let activeEnvironment: DevServerEnvironment = DEFAULT_ENVIRONMENT;+let hydrated = false;+let hydratePromise: Promise<DevServerEnvironment> | null = null;+let mutationTail: Promise<void> = Promise.resolve();+const listeners = new Set<() => void>();++function notifyListeners(): void {+ for (const listener of [...listeners]) {+ try {+ listener();+ } catch {+ // A broken view subscriber must not break the persisted environment state.+ }+ }+}++export function hydrateDevServerEnvironment(): Promise<DevServerEnvironment> {+ if (!DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED) {+ hydrated = true;+ activeEnvironment = DEFAULT_ENVIRONMENT;+ return Promise.resolve(activeEnvironment);+ }+ if (hydrated) return Promise.resolve(activeEnvironment);+ if (hydratePromise) return hydratePromise;+ hydratePromise = AsyncStorage.getItem(STORAGE_KEY)+ .then((raw) => {+ activeEnvironment = raw === 'release' ? 'release' : DEFAULT_ENVIRONMENT;+ hydrated = true;+ notifyListeners();+ return activeEnvironment;+ })+ .catch(() => {+ // Fail safe to the CindyDev build's own environment. A storage failure must+ // never silently route an internal build to Release.+ activeEnvironment = DEFAULT_ENVIRONMENT;+ hydrated = true;+ notifyListeners();+ return activeEnvironment;+ })+ .finally(() => {+ hydratePromise = null;+ });+ return hydratePromise;+}++/** 启动 gate hydrate 后可同步读取;未 hydrate 时同样 fail safe 到 Dev。 */+export function getDevServerEnvironment(): DevServerEnvironment {+ return activeEnvironment;+}++export function subscribeDevServerEnvironment(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++/**+ * 正式 CindyDev 包先加载自己的清单来固定 OTA / 审核元数据;选择 Release 时再+ * 用第二份清单只覆写业务端点。Metro 本地开发默认直接消费包内 Dev 清单,因此+ * 仅在选择 Release 时需要联网。+ */+export function buildDevServerEndpointStartupSteps(input: {+ buildManifestBaseUrl: string;+ defaultEndpointGateEnabled: boolean;+ environment: DevServerEnvironment;+ releaseManifestBaseUrl: string;+ switchEnabled: boolean;+}): DevServerEndpointStartupStep[] {+ const steps: DevServerEndpointStartupStep[] = [];+ if (input.defaultEndpointGateEnabled) {+ steps.push({+ manifestBaseUrl: input.buildManifestBaseUrl,+ preserveBuildReleaseMetadata: false,+ });+ }+ if (input.switchEnabled && input.environment === 'release') {+ steps.push({+ manifestBaseUrl: input.releaseManifestBaseUrl,+ preserveBuildReleaseMetadata: true,+ });+ }+ return steps;+}++export async function setDevServerEnvironment(+ next: DevServerEnvironment,+): Promise<void> {+ if (!DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED) {+ throw new Error('dev-server-environment-switch-unavailable');+ }+ await hydrateDevServerEnvironment();+ const run = mutationTail.then(async () => {+ if (next === 'release') await AsyncStorage.setItem(STORAGE_KEY, 'release');+ else await AsyncStorage.removeItem(STORAGE_KEY);+ activeEnvironment = next;+ notifyListeners();+ });+ mutationTail = run.catch(() => undefined);+ return run;+}++export const __testing = {+ storageKey: STORAGE_KEY,+ async resetMemory(): Promise<void> {+ await mutationTail.catch(() => undefined);+ activeEnvironment = DEFAULT_ENVIRONMENT;+ hydrated = false;+ hydratePromise = null;+ mutationTail = Promise.resolve();+ listeners.clear();+ },+};diff --git a/apps/mobile/src/config/env.ts b/apps/mobile/src/config/env.tsindex 66fc23d8b1..c47e26e80e 100644--- a/apps/mobile/src/config/env.ts+++ b/apps/mobile/src/config/env.ts@@ -372,6 +372,18 @@ export const ENDPOINT_MANIFEST_PEER_BASE_URL = ('').replace(/\/+$/, '');+/**+ * CindyDev 内部包切换到 CN Release 时使用的第二个可信自举地址。+ * 只经 Metro 环境变量进入 JS,不属于 ExpoConfig / 原生包身份;正式包恒为空串。+ */+export const DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL =+ AUTH_REGION === 'dev'+ ? (+ process.env+ .EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL?.trim() || ''+ ).replace(/\/+$/, '')+ : '';+function trustedMobileRealmManifestBaseUrls(): RealmManifestBaseUrls {return BUILD_AUTH_REGION === 'global'? {@@ -390,18 +402,21 @@ function trustedMobileRealmManifestBaseUrls(): RealmManifestBaseUrls {* 构建区域默认值;跨区域组织会话由 activateMobileSessionRealm 整体切换* token 消费端点。*/-export function applyResolvedClientEndpoints(resolved: {- authApiBaseUrl?: string;- oauthBrokerApiBaseUrl?: string;- deviceLinkApiBaseUrl?: string;- voiceApiBaseUrl?: string;- mobileUpdateBaseUrl?: string;- /** 审核模式送审版本号(parser 产出,null = 清单未填;undefined = 不改动)。 */- reviewVersion?: string | null;- /** iOS StoreKit 分发环境;TestFlight 保留 OTA、禁用整包外跳。 */- isTestFlight?: boolean;- region?: ClientEndpointRegion | null;-}): void {+export function applyResolvedClientEndpoints(+ resolved: {+ authApiBaseUrl?: string;+ oauthBrokerApiBaseUrl?: string;+ deviceLinkApiBaseUrl?: string;+ voiceApiBaseUrl?: string;+ mobileUpdateBaseUrl?: string;+ /** 审核模式送审版本号(parser 产出,null = 清单未填;undefined = 不改动)。 */+ reviewVersion?: string | null;+ /** iOS StoreKit 分发环境;TestFlight 保留 OTA、禁用整包外跳。 */+ isTestFlight?: boolean;+ region?: ClientEndpointRegion | null;+ },+ options: { preserveBuildReleaseMetadata?: boolean } = {},+): void {if (resolved.authApiBaseUrl !== undefined) {AUTH_API_BASE_URL = normalizeBaseUrlWithDefault(resolved.authApiBaseUrl,@@ -425,18 +440,29 @@ export function applyResolvedClientEndpoints(resolved: {syncBuildTokenEndpointCache();// 仅自建变体吃清单覆写,保住「非自建 ⇒ OTA_SERVER_BASE_URL 恒空串」不变量// (调用点虽都有 IS_OTA_SELFHOST 门控,这里再挡一层,变体身份始终由烧包决定)。- if (resolved.mobileUpdateBaseUrl !== undefined && IS_OTA_SELFHOST) {+ if (+ !options.preserveBuildReleaseMetadata &&+ resolved.mobileUpdateBaseUrl !== undefined &&+ IS_OTA_SELFHOST+ ) {OTA_SERVER_BASE_URL = resolved.mobileUpdateBaseUrl.replace(/\/+$/, '');}- if (resolved.reviewVersion !== undefined) {+ if (+ !options.preserveBuildReleaseMetadata &&+ resolved.reviewVersion !== undefined+ ) {resolvedReviewVersion = resolved.reviewVersion;}- if (resolved.isTestFlight !== undefined) {+ if (+ !options.preserveBuildReleaseMetadata &&+ resolved.isTestFlight !== undefined+ ) {IS_TESTFLIGHT_BUILD = resolved.isTestFlight;}if (- resolved.reviewVersion !== undefined ||- resolved.isTestFlight !== undefined+ !options.preserveBuildReleaseMetadata &&+ (resolved.reviewVersion !== undefined ||+ resolved.isTestFlight !== undefined)) {REVIEW_MODE = isReviewModeActive(resolvedReviewVersion,diff --git a/apps/mobile/src/config/useDevServerEnvironment.ts b/apps/mobile/src/config/useDevServerEnvironment.tsnew file mode 100644index 0000000000..05c3126562--- /dev/null+++ b/apps/mobile/src/config/useDevServerEnvironment.ts@@ -0,0 +1,43 @@+import { useCallback, useEffect, useState } from 'react';++import {+ getDevServerEnvironment,+ hydrateDevServerEnvironment,+ setDevServerEnvironment,+ subscribeDevServerEnvironment,+ type DevServerEnvironment,+} from './devServerEnvironment';++export function useDevServerEnvironment(): {+ environment: DevServerEnvironment;+ ready: boolean;+ setEnvironment: (next: DevServerEnvironment) => Promise<void>;+} {+ const [environment, setEnvironmentState] = useState(getDevServerEnvironment);+ const [ready, setReady] = useState(false);++ useEffect(() => {+ let cancelled = false;+ const sync = () => {+ if (!cancelled) setEnvironmentState(getDevServerEnvironment());+ };+ const unsubscribe = subscribeDevServerEnvironment(sync);+ void hydrateDevServerEnvironment().then(() => {+ if (!cancelled) {+ sync();+ setReady(true);+ }+ });+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);++ const setEnvironment = useCallback(async (next: DevServerEnvironment) => {+ await setDevServerEnvironment(next);+ setEnvironmentState(next);+ }, []);++ return { environment, ready, setEnvironment };+}diff --git a/apps/mobile/src/config/useStartupEndpointGate.ts b/apps/mobile/src/config/useStartupEndpointGate.tsindex 2b6b585fd6..099835eab2 100644--- a/apps/mobile/src/config/useStartupEndpointGate.ts+++ b/apps/mobile/src/config/useStartupEndpointGate.ts@@ -11,7 +11,17 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { isTestFlightBuild } from '@/platform/appDistribution';import { runStartupEndpointResolve } from './clientEndpointStartup';-import { resolveEnvFlag } from './env';+import {+ BUILD_AUTH_REGION,+ DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,+ ENDPOINT_MANIFEST_BASE_URL,+ resolveEnvFlag,+} from './env';+import {+ DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED,+ buildDevServerEndpointStartupSteps,+ hydrateDevServerEnvironment,+} from './devServerEnvironment';export type StartupEndpointGateStatus = 'pending' | 'ready' | 'error';@@ -24,8 +34,13 @@ export interface StartupEndpointGate {}export function useStartupEndpointGate(): StartupEndpointGate {- const enabled = !__DEV__ || resolveEnvFlag(process.env.EXPO_PUBLIC_ENDPOINTS_CDN);- const [status, setStatus] = useState<StartupEndpointGateStatus>(enabled ? 'pending' : 'ready');+ const defaultEndpointGateEnabled =+ !__DEV__ || resolveEnvFlag(process.env.EXPO_PUBLIC_ENDPOINTS_CDN);+ const enabled =+ defaultEndpointGateEnabled || DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED;+ const [status, setStatus] = useState<StartupEndpointGateStatus>(+ enabled ? 'pending' : 'ready',+ );const [reason, setReason] = useState<string | null>(null);const [attempt, setAttempt] = useState(0);const running = useRef(false);@@ -35,12 +50,32 @@ export function useStartupEndpointGate(): StartupEndpointGate {if (status === 'error') return; // 等用户点重试running.current = true;let cancelled = false;- void runStartupEndpointResolve({ resolveIsTestFlight: isTestFlightBuild }).then((outcome) => {+ void (async () => {+ const environment = DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED+ ? await hydrateDevServerEnvironment()+ : 'dev';+ const steps = buildDevServerEndpointStartupSteps({+ buildManifestBaseUrl: ENDPOINT_MANIFEST_BASE_URL,+ defaultEndpointGateEnabled,+ environment,+ releaseManifestBaseUrl: DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,+ switchEnabled: DEV_SERVER_ENVIRONMENT_SWITCH_ENABLED,+ });+ for (const step of steps) {+ const outcome = await 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) setStatus('ready');+ else {setReason(outcome.reason);setStatus('error');}@@ -48,7 +83,7 @@ export function useStartupEndpointGate(): StartupEndpointGate {return () => {cancelled = true;};- }, [enabled, status, attempt]);+ }, [defaultEndpointGateEnabled, enabled, status, attempt]);const retry = useCallback(() => {setReason(null);diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.jsonindex baa2911103..71b8be5249 100644--- a/apps/mobile/src/i18n/locales/en/settings.json+++ b/apps/mobile/src/i18n/locales/en/settings.json@@ -85,6 +85,22 @@"authServer": "Auth Server","authRegion": "Sign-in Region"},+ "devServerEnvironment": {+ "title": "Server Environment",+ "description": "Only affects the backend CindyDev connects to",+ "accessibility": "Switch server environment",+ "options": {+ "dev": "Dev",+ "release": "Release"+ },+ "confirmTitle": "Switch to {{environment}}?",+ "confirmBody": "Switching signs you out and restarts the app.",+ "cancel": "Cancel",+ "switchAction": "Switch",+ "switching": "Switching",+ "restartRequired": "The server environment has changed. Fully quit and reopen the app.",+ "switchFailed": "Could not switch the server environment. Try again."+ },"updateInfo": {"embedded": "With app package","embeddedFallback": "With app package (OTA not applied)",diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.jsonindex b626ff3028..5582ac553f 100644--- a/apps/mobile/src/i18n/locales/ja/settings.json+++ b/apps/mobile/src/i18n/locales/ja/settings.json@@ -85,6 +85,22 @@"authServer": "Auth Server","authRegion": "ログインリージョン"},+ "devServerEnvironment": {+ "title": "サーバー環境",+ "description": "CindyDev が接続する業務サーバーにのみ影響します",+ "accessibility": "サーバー環境を切り替える",+ "options": {+ "dev": "Dev",+ "release": "Release"+ },+ "confirmTitle": "{{environment}} に切り替えますか?",+ "confirmBody": "切り替えると現在のアカウントからログアウトし、App を再起動します。",+ "cancel": "キャンセル",+ "switchAction": "切り替える",+ "switching": "切り替え中",+ "restartRequired": "サーバー環境を切り替えました。App を完全に終了してから再度開いてください。",+ "switchFailed": "サーバー環境を切り替えられませんでした。もう一度お試しください。"+ },"updateInfo": {"embedded": "アプリ本体と同梱","embeddedFallback": "アプリ本体と同梱(OTA 未適用)",diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.jsonindex c61fc48637..0f52ff3023 100644--- a/apps/mobile/src/i18n/locales/ko/settings.json+++ b/apps/mobile/src/i18n/locales/ko/settings.json@@ -85,6 +85,22 @@"authServer": "Auth Server","authRegion": "로그인 지역"},+ "devServerEnvironment": {+ "title": "서버 환경",+ "description": "CindyDev가 연결하는 업무 서버에만 영향을 줍니다",+ "accessibility": "서버 환경 전환",+ "options": {+ "dev": "Dev",+ "release": "Release"+ },+ "confirmTitle": "{{environment}} 환경으로 전환할까요?",+ "confirmBody": "전환하면 현재 계정에서 로그아웃되고 App이 다시 시작됩니다.",+ "cancel": "취소",+ "switchAction": "전환",+ "switching": "전환 중",+ "restartRequired": "서버 환경을 전환했습니다. App을 완전히 종료한 후 다시 열어 주세요.",+ "switchFailed": "서버 환경을 전환하지 못했습니다. 다시 시도해 주세요."+ },"updateInfo": {"embedded": "앱 패키지 포함","embeddedFallback": "앱 패키지 포함 (OTA 미적용)",diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.jsonindex 7a8b89c66c..b4a95a970e 100644--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json@@ -85,6 +85,22 @@"authServer": "Auth Server","authRegion": "登录区域"},+ "devServerEnvironment": {+ "title": "服务器环境",+ "description": "仅影响 CindyDev 连接的业务服务器",+ "accessibility": "切换服务器环境",+ "options": {+ "dev": "Dev",+ "release": "Release"+ },+ "confirmTitle": "切换到 {{environment}}?",+ "confirmBody": "切换会退出当前账号并重启 App。",+ "cancel": "取消",+ "switchAction": "切换",+ "switching": "切换中",+ "restartRequired": "服务器环境已切换。请完全退出 App 后重新打开。",+ "switchFailed": "切换服务器环境失败,请重试。"+ },"updateInfo": {"embedded": "随整包","embeddedFallback": "随整包(热更未生效)",diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.jsonindex 10654f28f8..e14da59a7a 100644--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json@@ -85,6 +85,22 @@"authServer": "Auth Server","authRegion": "登入區域"},+ "devServerEnvironment": {+ "title": "伺服器環境",+ "description": "僅影響 CindyDev 連線的業務伺服器",+ "accessibility": "切換伺服器環境",+ "options": {+ "dev": "Dev",+ "release": "Release"+ },+ "confirmTitle": "切換至 {{environment}}?",+ "confirmBody": "切換會登出目前帳號並重新啟動 App。",+ "cancel": "取消",+ "switchAction": "切換",+ "switching": "切換中",+ "restartRequired": "伺服器環境已切換。請完全結束 App 後重新開啟。",+ "switchFailed": "切換伺服器環境失敗,請再試一次。"+ },"updateInfo": {"embedded": "隨整包","embeddedFallback": "隨整包(熱更未生效)",diff --git a/apps/mobile/src/notifications/pushNotifications.ts b/apps/mobile/src/notifications/pushNotifications.tsindex 880cb7a712..10374d78ff 100644--- a/apps/mobile/src/notifications/pushNotifications.ts+++ b/apps/mobile/src/notifications/pushNotifications.ts@@ -9,6 +9,7 @@ import {getMobileEndpointForRealm,loadMobileEndpointsForRealm,} from '@/config/env';+import { getDevServerEnvironment } from '@/config/devServerEnvironment';import Notifications from './nativeNotifications';import { buildPushTokenRegistrationBody } from './pushRegistrationModel';@@ -42,6 +43,22 @@ interface PushRealmState {realms: ClientEndpointRegion[];}+function pushStateStorageKeys(baseKey: string): {+ primary: string;+ migrationFallback: string | null;+} {+ if (AUTH_REGION !== 'dev') {+ return { primary: baseKey, migrationFallback: null };+ }+ const environment = getDevServerEnvironment();+ return {+ primary: `${baseKey}.${environment}`,+ // 旧 CindyDev 只连接 Dev;无环境后缀的存量状态只能归到 Dev,绝不能+ // 在首次切到 Release 时误迁移过去。+ migrationFallback: environment === 'dev' ? baseKey : null,+ };+}+/** React effects / token listener / 设置页可能同时触发,串行化避免注册与撤销倒序。 */let pushMutationTail: Promise<void> = Promise.resolve();/**@@ -72,7 +89,13 @@ async function readPushRealms(legacyRealm: ClientEndpointRegion = BUILD_AUTH_REGION,): Promise<Set<ClientEndpointRegion>> {try {- const raw = await AsyncStorage.getItem(key);+ const storageKeys = pushStateStorageKeys(key);+ const primaryRaw = await AsyncStorage.getItem(storageKeys.primary);+ const raw =+ primaryRaw ??+ (storageKeys.migrationFallback+ ? await AsyncStorage.getItem(storageKeys.migrationFallback)+ : null);if (!raw || raw === '0') return new Set();if (raw === '1') return new Set([legacyRealm]);const parsed: unknown = JSON.parse(raw);@@ -96,15 +119,26 @@ async function writePushRealms(key: string,realms: ReadonlySet<ClientEndpointRegion>,): Promise<void> {+ const storageKeys = pushStateStorageKeys(key);if (realms.size === 0) {- await AsyncStorage.removeItem(key);+ await AsyncStorage.removeItem(storageKeys.primary);+ if (storageKeys.migrationFallback) {+ await AsyncStorage.removeItem(storageKeys.migrationFallback).catch(+ () => undefined,+ );+ }return;}const state: PushRealmState = {version: PUSH_REALM_STATE_VERSION,realms: (['cn', 'global'] as const).filter((realm) => realms.has(realm)),};- await AsyncStorage.setItem(key, JSON.stringify(state));+ await AsyncStorage.setItem(storageKeys.primary, JSON.stringify(state));+ if (storageKeys.migrationFallback) {+ await AsyncStorage.removeItem(storageKeys.migrationFallback).catch(+ () => undefined,+ );+ }}async function addPushRealm(diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 029eaf7dc5..566d2b81c2 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -203,6 +203,10 @@ Cindy 在 X 上发出的那条公开回复。zh-CN 取「回帖」以强调它应用异常终止。此前只出现在内部日志里, 随日志上报进入用户可见文案, 因此登记。ko 取音译「크래시」而非「충돌」——后者在韩语里更常指冲突/碰撞(如合并冲突), 会与 merge conflict 语境混读。proposed。+### Release++CindyDev 内部设置中的正式业务服务器环境标签,五语固定保留英文 Release。它表示 App 当前连接哪套服务,不代表安装包发行版本、OTA 通道或 cn / global 区域;因 release 也是普通英文单词,关闭全局大小写扫描,具体 UI key 由 Mobile 定向测试约束。+### Devicedevice-link 里「可以选择在哪台机器上运行」这一维度,两端统一叫「设备」。desktop 的 machineSwitcher 本来就是 This device / このデバイス / 이 기기,mobile 原先用 computer 系(选择电脑 / パソコンを選択 / 컴퓨터 선택),2026-07 裁决为向 device 系对齐,与既有 device-code(设备码 / デバイスコード / 기기 코드)同口径。alsoAllowed 保留「电脑」系:指代桌面端物理机的文案(安装、导出、等待确认)换成「设备」反而不通中文,那是 desktop/PC 的意思,不是这里的目标维度。@@ -311,7 +315,7 @@ OS 进程语境(资源用量面板、浏览器 guest 进程、终端)。注意### Dev-dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值、不翻译,理由同 region-code-cn。与 CN 不同的是 dev 还是个普通技术词:豁免的两条文案里“Always on in dev mode.”“dev builds may be authorized…”“dev 模式下始终开启”指的是开发模式而非本区域标签,小写本就正确(四语同 key 一并覆盖)。用 exempt 精确豁免这两条、而不是整条关掉 checkCase,是为了保住徽标值本身的大小写约束——这正是本条存在的意义。2026-07-28 起同一代号也用于 submit_github_issue 的提交确认卡片与 issue 正文(`issueAgent.confirm.regionCodeDev`)与侧栏用户卡片版本行(`sidebar.user.regionCodeDev`),口径与徽标完全一致:global 不标;「哪些区域要标」的唯一事实源是 `apps/desktop/src/shared/regionCode.ts`。+dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值、不翻译,理由同 region-code-cn。与 CN 不同的是 dev 还是个普通技术词:豁免的两条文案里“Always on in dev mode.”“dev builds may be authorized…”“dev 模式下始终开启”指的是开发模式而非本区域标签,小写本就正确(四语同 key 一并覆盖)。用 exempt 精确豁免这两条、而不是整条关掉 checkCase,是为了保住徽标值本身的大小写约束——这正是本条存在的意义。2026-07-28 起同一代号也用于 submit_github_issue 的提交确认卡片与 issue 正文(`issueAgent.confirm.regionCodeDev`)与侧栏用户卡片版本行(`sidebar.user.regionCodeDev`),口径与徽标完全一致:global 不标;「哪些区域要标」的唯一事实源是 `apps/desktop/src/shared/regionCode.ts`。2026-08-26 起 CindyDev 内部的业务服务器环境切换也沿用 Dev 标签;这里只表示所连接的服务环境,不能据此改变安装包区域或身份。已确定禁用:`开发版(仅当英文含 Dev)`(zh-CN)、`開発版(仅当英文含 Dev)`(ja)、`개발판(仅当英文含 Dev)`(ko)diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex d3eded8994..f78315564d 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -288,6 +288,7 @@"en": "Dev","translations": {"zh-CN": "Dev",+ "zh-TW": "Dev","ja": "Dev","ko": "Dev"},@@ -315,7 +316,20 @@"desktop:settings.about.debugLogDescription","desktop:settings.voiceInput.permissions.inputMonitoring.tooltip"],- "note": "dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值、不翻译,理由同 region-code-cn。与 CN 不同的是 dev 还是个普通技术词:豁免的两条文案里“Always on in dev mode.”“dev builds may be authorized…”“dev 模式下始终开启”指的是开发模式而非本区域标签,小写本就正确(四语同 key 一并覆盖)。用 exempt 精确豁免这两条、而不是整条关掉 checkCase,是为了保住徽标值本身的大小写约束——这正是本条存在的意义。2026-07-28 起同一代号也用于 submit_github_issue 的提交确认卡片与 issue 正文(`issueAgent.confirm.regionCodeDev`)与侧栏用户卡片版本行(`sidebar.user.regionCodeDev`),口径与徽标完全一致:global 不标;「哪些区域要标」的唯一事实源是 `apps/desktop/src/shared/regionCode.ts`。"+ "note": "dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值、不翻译,理由同 region-code-cn。与 CN 不同的是 dev 还是个普通技术词:豁免的两条文案里“Always on in dev mode.”“dev builds may be authorized…”“dev 模式下始终开启”指的是开发模式而非本区域标签,小写本就正确(四语同 key 一并覆盖)。用 exempt 精确豁免这两条、而不是整条关掉 checkCase,是为了保住徽标值本身的大小写约束——这正是本条存在的意义。2026-07-28 起同一代号也用于 submit_github_issue 的提交确认卡片与 issue 正文(`issueAgent.confirm.regionCodeDev`)与侧栏用户卡片版本行(`sidebar.user.regionCodeDev`),口径与徽标完全一致:global 不标;「哪些区域要标」的唯一事实源是 `apps/desktop/src/shared/regionCode.ts`。2026-08-26 起 CindyDev 内部的业务服务器环境切换也沿用 Dev 标签;这里只表示所连接的服务环境,不能据此改变安装包区域或身份。"+ },+ {+ "id": "dev-server-environment-release",+ "status": "proposed",+ "en": "Release",+ "translations": {+ "zh-CN": "Release",+ "zh-TW": "Release",+ "ja": "Release",+ "ko": "Release"+ },+ "checkCase": false,+ "note": "CindyDev 内部设置中的正式业务服务器环境标签,五语固定保留英文 Release。它表示 App 当前连接哪套服务,不代表安装包发行版本、OTA 通道或 cn / global 区域;因 release 也是普通英文单词,关闭全局大小写扫描,具体 UI key 由 Mobile 定向测试约束。"},{"id": "agent",