Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(update): 新增 beta 测试渠道(beta 通道 manifest / OTA 切换) (#2666)
guyong-zapo02313eda0389
diff --git a/apps/desktop/src/main/manifestService.ts b/apps/desktop/src/main/manifestService.tsindex 5f077fb8f1..dd8ab88dd0 100644--- a/apps/desktop/src/main/manifestService.ts+++ b/apps/desktop/src/main/manifestService.ts@@ -17,8 +17,11 @@import { app, net } from 'electron';import * as canaryFlagStore from './canaryFlagStore';+import { resolveUpdateChannel } from '@cindy/maker-shared/update-channel';+import { createLogger } from './logger';import { getClientEndpoint } from './clientEndpointsService';+import { isBetaChannelEnabled } from './updateChannelStore';const log = createLogger('manifestService');@@ -98,6 +101,12 @@ const REQUEST_TIMEOUT_MS = 30_000;// ── State ──────────────────────────────────────────────────────────────────let cached: Manifest | null = null;+/**+ * manifest 代际:切渠道(clearCachedManifest)时 +1。fetchManifest 发起时快照,+ * 响应完成写 cached 前核对——若期间切了渠道,这次 in-flight 的旧渠道响应直接作废,+ * 不写缓存、返回 null,让调用方(agent prepare / 更新轮询)下次按新渠道重新 fetch。+ */+let manifestEpoch = 0;// ── Helpers ────────────────────────────────────────────────────────────────@@ -137,6 +146,10 @@ export function isDev(): boolean {* instead of the stable manifest. On failure we deliberately do NOT fall back* to stable — that would silently downgrade canary users to whatever stale* version is sitting on the stable channel.+ *+ * beta 渠道(2026-08):设备级开关(isBetaChannelEnabled)。发布通道按+ * resolveUpdateChannel 收敛为 canary > beta > release;release 无后缀,+ * canary/beta 分别拼 -canary / -beta 后缀。canary 命中时忽略 beta。*/export async function fetchManifest(timeoutMs?: number,@@ -145,11 +158,16 @@ export async function fetchManifest(if (isDev()) return null;if (signal?.aborted) return null;- const isCanary = canaryFlagStore.read();- const channelSuffix = isCanary ? '-canary' : '';+ const channel = resolveUpdateChannel(+ canaryFlagStore.read(),+ isBetaChannelEnabled(),+ );+ const channelSuffix = channel === 'release' ? '' : `-${channel}`;// Cache-bust: append timestamp to prevent Chromium / CDN serving stale manifestconst url = `${getBaseUrl()}/manifest-${getPlatformKey()}${channelSuffix}.json?t=${Date.now()}`;- log.info('Fetching (%s channel): %s', isCanary ? 'canary' : 'stable', url);+ // 快照发起时的代际:响应完成写 cached 前核对,期间切渠道则作废本次结果。+ const epochAtStart = manifestEpoch;+ log.info('Fetching (%s channel): %s', channel, url);return new Promise<Manifest | null>((resolve) => {try {@@ -185,6 +203,13 @@ export async function fetchManifest(if (settled) return;try {const json = JSON.parse(body) as Manifest;+ // 响应回来前切了渠道:这是旧渠道的 manifest,不作废会污染 cached,+ // 让后续 agent prepare 装旧渠道资产。返回 null 让调用方下次按新渠道重取。+ if (epochAtStart !== manifestEpoch) {+ log.info('manifest channel changed during fetch — discarding stale response');+ finish(null);+ return;+ }cached = json;log.info('Fetched OK: app.version=%s, hotfix=%s', json.app?.version, json.app?.hotfix?.file ?? 'none');finish(json);@@ -215,3 +240,63 @@ export async function fetchManifest(export function getCachedManifest(): Manifest | null {return cached;}++/**+ * 清掉内存里的 manifest 缓存。+ *+ * 切渠道(beta↔release)时调用:agent 二进制(Claude Code / Codex / ripgrep / pi)+ * 的 prepare 会先 getCachedManifest() 再 fetchManifest(),若缓存还停在旧渠道,+ * 同进程内切渠道后可能继续按旧渠道的版本号/下载地址安装资产。清掉后下一次+ * prepare/轮询会重新按新渠道 fetch。+ */+export function clearCachedManifest(): void {+ cached = null;+ manifestEpoch += 1;+}++/**+ * 探测 beta 渠道 manifest 是否可达(HTTP 200)。+ *+ * 供设置页在用户打开 beta 开关前预检:CDN 尚未部署 manifest-{platform}-beta.json+ * 时拒绝开启。beta 失败不回落 stable(与 canary 同口径),一旦开启却拉不到,+ * 不只应用热更失效,连 agent 二进制(Claude Code / Codex / ripgrep / pi)也会因+ * 拿不到 manifest 里的版本号而不可用(见 agent-binaries/factory.ts 的+ * 「manifest 之后才判 isInstalled」顺序)——所以「能不能开」必须提前探明,+ * 而不是等用户重启后才发现坏了。+ *+ * 只判 HTTP 200 可达,不解析正文、不写 cache、不改当前发布通道。dev 不联网,+ * 直接返回 true(dev 不消费远程 manifest,无需预检)。+ */+export function probeBetaManifest(timeoutMs = 8_000): Promise<boolean> {+ if (isDev()) return Promise.resolve(true);+ const url = `${getBaseUrl()}/manifest-${getPlatformKey()}-beta.json?t=${Date.now()}`;+ return new Promise<boolean>((resolve) => {+ try {+ const request = net.request(url);+ let settled = false;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ const finish = (value: boolean, abortRequest = false): void => {+ if (settled) return;+ settled = true;+ if (timeout) clearTimeout(timeout);+ if (abortRequest) request.abort();+ resolve(value);+ };+ timeout = setTimeout(() => finish(false, true), timeoutMs);+ request.on('response', (response) => {+ // 读完响应体以正确触发流结束、避免连接泄漏(内容不关心)。+ response.on('data', () => {});+ response.on('end', () => finish(response.statusCode === 200));+ response.on('error', () => finish(false));+ });+ request.on('error', () => finish(false));+ try {+ request.end();+ } catch {+ finish(false, true);+ }+ } catch {+ resolve(false);+ }+ });+}diff --git a/apps/desktop/src/main/updateChannelStore.ts b/apps/desktop/src/main/updateChannelStore.tsnew file mode 100644index 0000000000..4063929279--- /dev/null+++ b/apps/desktop/src/main/updateChannelStore.ts@@ -0,0 +1,81 @@+/**+ * updateChannelStore.ts+ * ---------------------------------------------------------------------------+ * beta 测试渠道的**设备级**本地开关。+ *+ * 与 canaryFlagStore 的关键区别:+ * - canary 是**账号级、服务端下发**的灰度标记(feature-flags → 本地持久化 →+ * 登出清),所以它的 flag 文件随账号生命周期走;+ * - beta 是**设备级、客户端本地设置**——设置页一个开关,登出/换号都不清。+ * 所以这里用 createOverrideSettingsFile(与 auto-update-settings 同一套+ * override 语义:默认值 + 用户 override、恢复默认只删 override),而不是仿+ * canaryFlagStore 的裸 JSON。+ *+ * 落盘:userData/update-channel-settings.json,字段 { enableBeta: boolean }。+ * 默认关闭。manifestService.fetchManifest() 用 resolveUpdateChannel 把本开关与+ * canaryFlagStore.read() 收敛成最终发布通道(优先级 canary > beta > release)。+ */++import { app } from 'electron';+import path from 'node:path';++import { desktopMakerLogger } from './maker-host/logger-adapter.js';+import {+ createOverrideSettingsFile,+ type OverrideSettingsState,+} from './maker-host/override-settings-file.js';++const log = desktopMakerLogger.child('update-channel-settings');++export interface UpdateChannelSettings {+ enableBeta: boolean;+}++const DEFAULTS: UpdateChannelSettings = {+ enableBeta: false,+};++function settingsFilePath(): string {+ return path.join(app.getPath('userData'), 'update-channel-settings.json');+}++function normalize(raw: unknown): UpdateChannelSettings {+ if (!raw || typeof raw !== 'object') return { ...DEFAULTS };+ const r = raw as Record<string, unknown>;+ return {+ enableBeta:+ typeof r.enableBeta === 'boolean' ? r.enableBeta : DEFAULTS.enableBeta,+ };+}++const store = createOverrideSettingsFile<UpdateChannelSettings>({+ filePath: settingsFilePath,+ defaults: DEFAULTS,+ normalize,+ log,+ label: 'update-channel',+});++export function readUpdateChannelSettings(): UpdateChannelSettings {+ return store.read();+}++export function readUpdateChannelSettingsState(): OverrideSettingsState<UpdateChannelSettings> {+ return store.readState();+}++export function writeEnableBeta(enableBeta: boolean): void {+ store.writePatch({ enableBeta });+ log.info('beta update channel setting written', { enableBeta });+}++export function resetUpdateChannelSettings(): UpdateChannelSettings {+ return store.reset();+}++/** manifestService 消费的单一读取入口:返回是否启用 beta(设备级)。 */+export function isBetaChannelEnabled(): boolean {+ return readUpdateChannelSettings().enableBeta;+}++export const __testing = { normalize };diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.tsindex c368410441..7eb1eba8b7 100644--- a/apps/desktop/src/main/updateService.ts+++ b/apps/desktop/src/main/updateService.ts@@ -28,7 +28,7 @@ import os from 'node:os';import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';-import { fetchManifest, getBaseUrl, isDev } from './manifestService';+import { fetchManifest, getBaseUrl, isDev, probeBetaManifest, clearCachedManifest } from './manifestService';import type { Manifest } from './manifestService';import { download, DownloadError } from './downloader/index';import { ProgressNormalizer } from './updateProgressNormalizer';@@ -40,6 +40,13 @@ import {resetAutoUpdateSettings,writeAutoRelaunchOnIdle,} from './auto-update-settings-store';+import {+ readUpdateChannelSettings,+ readUpdateChannelSettingsState,+ resetUpdateChannelSettings,+ writeEnableBeta,+} from './updateChannelStore';+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';import {AUTO_UPDATE_IDLE_THRESHOLD_SECONDS,getAutoRelaunchBlockReason,@@ -134,6 +141,12 @@ const STARTUP_MANIFEST_TIMEOUT_MS = 8_000;let currentStatus: UpdateStatus = 'idle';let readyVersion: string | undefined;let readyFilePath: string | undefined;+/**+ * 更新渠道代际计数:用户在下载进行中关掉 beta(clearStagedPatch)时 +1,+ * 让 in-flight 的 checkForUpdate 在写回 patch-info / 恢复旧 patch 前察觉+ * 「渠道已变」,放弃本次下载产物,避免 opt-out 后仍被装到 beta 版本。+ */+let updateChannelEpoch = 0;let pollTimer: ReturnType<typeof setInterval> | null = null;let autoRelaunchPollTimer: ReturnType<typeof setInterval> | null = null;let isRelaunching = false;@@ -545,6 +558,36 @@ function removePatchInfo(): void {try { fs.unlinkSync(path.join(getUpdatesDir(), PATCH_INFO_FILE)); } catch { /* ignore */ }}+/**+ * 清掉已 staged 的补丁(ready 态):删 zip + patch-info.json,状态回 idle。+ * 只在「用户关掉 beta 开关」时调用——opt-out 后不能仍让 staged 的 beta patch+ * 在下一次启动/后台轮询里被装上去(切渠道不等于切版本,必须把旧渠道的补丁作废)。+ */+function clearStagedPatch(): void {+ if (readyFilePath) {+ try { fs.unlinkSync(readyFilePath); } catch { /* ignore */ }+ }+ readyVersion = undefined;+ readyFilePath = undefined;+ removePatchInfo();+ // 递增代际:任何 in-flight 的 checkForUpdate 在写回 patch 前都会看到代际变化,+ // 从而放弃本次(基于旧渠道的)下载产物,不把 beta patch 重新落盘。+ updateChannelEpoch += 1;+ // 切渠道后旧渠道的 manifest 缓存作废:否则 agent 二进制 prepare 先+ // getCachedManifest() 会继续按旧渠道的版本号/下载地址安装资产。+ clearCachedManifest();+ // downloading 也要重置:opt-out 若发生在「首次 beta 下载进行中」,status 仍是+ // downloading;不 reset 的话,in-flight 下载完成后 discard 分支只是 `return 'idle'`+ // 而不 setStatus,update-get-status / update-check-now 会永远卡在 downloading。+ if (+ currentStatus === 'ready' ||+ currentStatus === 'superseding' ||+ currentStatus === 'downloading'+ ) {+ setStatus('idle');+ }+}+function incrementApplyAttempts(): void {const infoPath = path.join(getUpdatesDir(), PATCH_INFO_FILE);try {@@ -677,6 +720,9 @@ export function isVersionlessAppVersion(version: string): boolean {async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<CheckForUpdateResult> {log.info('checkForUpdate() called, currentStatus=%s', currentStatus);+ // 快照发起时的渠道代际;下载期间若用户 opt-out(clearStagedPatch 递增),+ // 成功/失败写回前都据此作废本次产物。+ const channelEpochAtStart = updateChannelEpoch;if (isVersionlessAppVersion(app.getVersion())) {log.info('Versionless build (placeholder %s) — in-app update disabled', app.getVersion());@@ -842,6 +888,18 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<ChecleanOldFiles(fileName);}+ // 下载期间用户切渠道(渠道代际已变):放弃这次下载的产物,不写 patch-info。+ // 否则会重新落盘一份旧渠道 patch,用户切渠道后仍被呈现旧版本更新。+ if (channelEpochAtStart !== updateChannelEpoch) {+ log.info('update channel changed during download — discarding patch v%s', latestVersion);+ try { fs.unlinkSync(destPath); } catch { /* ignore */ }+ // 必须 setStatus:切渠道可能发生在请求仍在 checking 阶段时(clearStagedPatch+ // 不覆盖 checking),本分支之前已被 setStatus('downloading'),不归位的话+ // update-check-now 会一直 short-circuit 返回 downloading。+ setStatus('idle');+ return 'idle';+ }+const requireRelogin = manifest.app.requireRelogin === true;writePatchInfo({version: latestVersion,@@ -875,6 +933,12 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che// readyFilePath 全都没动过,直接重新广播 ready 让 banner 按钮从 loading 恢复成可点。// 下一次 30min 轮询会再次尝试 b。if (wasReady) {+ // 下载期间用户切渠道:旧 patch 已被 clearStagedPatch 清掉,不能恢复。+ if (channelEpochAtStart !== updateChannelEpoch) {+ log.info('update channel changed during superseding download — not restoring stale patch');+ setStatus('idle');+ return 'idle';+ }log.info('Superseding download failed — rolling back to ready v%s', previousReadyVersion);readyVersion = previousReadyVersion;readyFilePath = previousReadyFilePath;@@ -1183,6 +1247,70 @@ export function initUpdateService(): void {return autoUpdateSettingsWire();});+ // beta 测试渠道(设备级)开关。开关本身即时落盘,但 manifest 通道只在+ // 下一次 fetchManifest(后台轮询)或重启后才会切换;设置页打开后引导用户重启。+ // 这些 handler 写本地设置 / 触发重启,按 electron-security-and-process-boundaries.md+ // §5 必须做 trusted-renderer 来源断言——utility/Ghost 等带 preload 的窗口不应能改+ // 更新设置或重启应用(旧 update-auto-settings 没断言是历史债,不构成豁免)。+ ipcMain.handle('update-channel-settings-get', (event) => {+ assertTrustedAppRendererEvent(event);+ const state = readUpdateChannelSettingsState();+ return { enableBeta: state.value.enableBeta, isCustomized: state.isCustomized };+ });++ ipcMain.handle('update-channel-settings-set', (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (!payload || typeof payload !== 'object') {+ throwIpcError('INVALID_PARAMS', 'update channel settings payload required');+ }+ const next = (payload as { enableBeta?: unknown }).enableBeta;+ if (typeof next !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'enableBeta required (boolean)');+ }+ const wasBeta = readUpdateChannelSettings().enableBeta;+ writeEnableBeta(next);+ // 渠道一变(无论 opt-in 还是 opt-out)就作废已 staged 的旧渠道补丁:+ // - opt-out(beta→release):否则用户关掉 beta 后仍被装到 beta 版本;+ // - opt-in(release→beta):否则旧 release 补丁仍 staged,重启后 beta manifest+ // 拉取失败时 checkExistingPatch() 会兜底把用户装到 release 版本。+ // 切渠道不等于切版本,两个方向都要清。+ if (wasBeta !== next) {+ clearStagedPatch();+ }+ const state = readUpdateChannelSettingsState();+ return { enableBeta: state.value.enableBeta, isCustomized: state.isCustomized };+ });++ ipcMain.handle('update-channel-settings-reset', (event) => {+ assertTrustedAppRendererEvent(event);+ const wasBeta = readUpdateChannelSettings().enableBeta;+ resetUpdateChannelSettings();+ // 恢复默认 = 关闭 beta;同 set(false),渠道变化即作废已 staged 的补丁。+ if (wasBeta) {+ clearStagedPatch();+ }+ const state = readUpdateChannelSettingsState();+ return { enableBeta: state.value.enableBeta, isCustomized: state.isCustomized };+ });++ // 打开 beta 前的预检:探测 manifest-{platform}-beta.json 是否可达。+ ipcMain.handle('update-channel-probe-beta', async (event) => {+ assertTrustedAppRendererEvent(event);+ const available = await probeBetaManifest();+ return { available };+ });++ // 用户主动重启:让 beta 通道切换在下次冷启动的 manifest 拉取前生效。+ // 用 app.quit() 而非 app.exit(0):切渠道重启不是 updater 替换场景,没有独立更新器+ // 进程负责收尾,必须走 before-quit 链优雅停掉 Codex/IM/后台服务、落盘本地状态。+ // app.relaunch() 只是标记「退出后重启」,真正触发重启的是 app.quit() 的退出流程。+ ipcMain.handle('update-channel-relaunch', (event) => {+ assertTrustedAppRendererEvent(event);+ log.info('relaunch requested for update channel change');+ app.relaunch();+ app.quit();+ });+ipcMain.on('update-set-relaunch-theme', (_event, theme: 'light' | 'dark') => {if (theme === 'light' || theme === 'dark') {resolvedRelaunchTheme = theme;diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6b1ce91a35..11590fed55 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2238,6 +2238,25 @@ contextBridge.exposeInMainWorld('electronAPI', {isCustomized?: boolean;defaultAutoRelaunchOnIdle?: boolean;}> => ipcRenderer.invoke('update-auto-settings-reset'),+ // beta 测试渠道(设备级)开关+ getUpdateChannelSettings: (): Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }> => ipcRenderer.invoke('update-channel-settings-get'),+ setUpdateChannelSettings: (settings: {+ enableBeta: boolean;+ }): Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }> => ipcRenderer.invoke('update-channel-settings-set', settings),+ resetUpdateChannelSettings: (): Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }> => ipcRenderer.invoke('update-channel-settings-reset'),+ relaunchForChannelChange: (): Promise<void> =>+ ipcRenderer.invoke('update-channel-relaunch'),+ probeBetaChannel: (): Promise<{ available: boolean }> =>+ ipcRenderer.invoke('update-channel-probe-beta'),setUpdateRelaunchTheme: (theme: 'light' | 'dark'): void => {ipcRenderer.send('update-set-relaunch-theme', theme);},diff --git a/apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx b/apps/desktop/src/renderer/components/settings/BetaChannelCell.tsxnew file mode 100644index 0000000000..99e59dfc73--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx@@ -0,0 +1,115 @@+/**+ * BetaChannelCell — Settings → 实验功能区块下的 "Beta 测试渠道" 卡片。+ *+ * 设备级开关:落盘 userData/update-channel-settings.json,登出/换号不清。+ * 与 canary(账号级、服务端下发)不同,beta 是本地设置;优先级 canary > beta > release,+ * 由 main 侧 manifestService 的 resolveUpdateChannel 收敛。+ *+ * 开关本身即时落盘,但 manifest 通道只在后台轮询(30min)或重启后才切换;+ * 打开后引导用户立即重启(app.relaunch),关闭则仅提示重启后生效。+ */++import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { Switch } from '@/components/ui/switch';+import { cn } from '@/lib/utils';+import { toast } from '@/lib/toast';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { useBetaChannelSettings } from '@/hooks/useBetaChannelSettings';++export function BetaChannelCell() {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const { state, setEnableBeta } = useBetaChannelSettings();+ const [pending, setPending] = useState(false);++ const handleToggle = useCallback(+ async (next: boolean) => {+ setPending(true);+ try {+ if (next) {+ // 预检:CDN 尚未部署 manifest-{platform}-beta.json 时拒绝开启。+ // 否则用户开了 beta 却连 agent 二进制都拉不到(beta 失败不回落 stable)。+ const { available } = await window.electronAPI.probeBetaChannel();+ if (!available) {+ toast.error(t('settings.betaChannel.unavailable'));+ return; // 不落盘,开关保持关闭+ }+ }+ await setEnableBeta(next);+ if (next) {+ const restart = await confirm({+ title: t('settings.betaChannel.restartTitle'),+ description: t('settings.betaChannel.restartDescription'),+ confirmText: t('settings.betaChannel.restartNow'),+ cancelText: t('settings.betaChannel.restartLater'),+ autoFocusConfirm: true,+ });+ if (!restart) return;+ // 与 UpdateBanner 同一口径:重启会杀掉 in-flight turn / 后台活动 / Ghost+ // card-action,属于不可撤销动作。探针失败 = 无法确认 → 按「有任务在跑」保守+ // 处理,多要一次确认,而不是静默打断用户任务。+ let hasInFlight = true;+ try {+ hasInFlight = await window.electronAPI.anyActivityBlockingRelaunch();+ } catch {+ hasInFlight = true;+ }+ if (hasInFlight) {+ const confirmed = await confirm({+ title: t('settings.betaChannel.restartTitle'),+ description: t('settings.betaChannel.restartBusyDescription'),+ confirmText: t('settings.betaChannel.restartNow'),+ cancelText: t('settings.betaChannel.restartLater'),+ });+ if (!confirmed) return;+ }+ await window.electronAPI.relaunchForChannelChange();+ } else {+ toast.success(t('settings.betaChannel.toast.disabled'));+ }+ } catch (err) {+ toast.error(+ err instanceof Error+ ? err.message+ : t('settings.betaChannel.toast.toggleFailed'),+ );+ } finally {+ setPending(false);+ }+ },+ [confirm, setEnableBeta, t],+ );++ return (+ <div+ className={cn(+ 'flex flex-col gap-3 rounded-xl p-5',+ 'bg-[var(--settings-theme-card-bg)]',+ 'border border-[var(--settings-theme-card-border)]',+ )}+ >+ <div className="flex items-start justify-between gap-3">+ <div className="flex min-w-0 flex-col gap-1">+ <p+ className="text-13 font-medium text-[var(--settings-section-sublabel)]"+ style={{ letterSpacing: '0.12px' }}+ >+ {t('settings.betaChannel.title')}+ </p>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">+ {t('settings.betaChannel.description')}+ </p>+ </div>++ <Switch+ checked={state.enableBeta}+ disabled={pending || state.loading}+ onCheckedChange={(v) => void handleToggle(v)}+ aria-label={t('settings.betaChannel.toggleAria')}+ />+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx b/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsxindex b911ba24d4..280577dff8 100644--- a/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx@@ -19,6 +19,7 @@ import {type ExperimentalFeatureMeta,} from '@/hooks/useExperimentalFeatures';import { LspBetaCell } from './LspBetaCell';+import { BetaChannelCell } from './BetaChannelCell';export function ExperimentalSection() {const { t } = useTranslation();@@ -31,6 +32,7 @@ export function ExperimentalSection() {<div className="flex flex-col gap-3"><LspBetaCell />+ <BetaChannelCell />{EXPERIMENTAL_FEATURES.map((feature) => (<ExperimentalFeatureRow key={feature.key} feature={feature} />))}diff --git a/apps/desktop/src/renderer/hooks/useBetaChannelSettings.ts b/apps/desktop/src/renderer/hooks/useBetaChannelSettings.tsnew file mode 100644index 0000000000..d18eb46ee5--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useBetaChannelSettings.ts@@ -0,0 +1,67 @@+import { useCallback, useEffect, useState } from 'react';++export interface BetaChannelSettingsState {+ enableBeta: boolean;+ isCustomized: boolean;+ loading: boolean;+}++interface BetaChannelSettingsPayload {+ enableBeta: boolean;+ isCustomized?: boolean;+}++const INITIAL: BetaChannelSettingsState = {+ enableBeta: false,+ isCustomized: false,+ loading: true,+};++function normalize(payload: BetaChannelSettingsPayload): BetaChannelSettingsState {+ return {+ enableBeta: payload.enableBeta === true,+ isCustomized: payload.isCustomized === true,+ loading: false,+ };+}++/**+ * beta 测试渠道(设备级)开关的状态与写操作。+ * 语义与 auto-update-settings 一致:默认值 + override,恢复默认只删 override。+ */+export function useBetaChannelSettings(): {+ state: BetaChannelSettingsState;+ setEnableBeta: (enabled: boolean) => Promise<void>;+ reset: () => Promise<void>;+} {+ const [state, setState] = useState<BetaChannelSettingsState>(INITIAL);++ useEffect(() => {+ let cancelled = false;+ void window.electronAPI+ .getUpdateChannelSettings()+ .then((payload) => {+ if (!cancelled) setState(normalize(payload));+ })+ .catch(() => {+ if (!cancelled) setState((current) => ({ ...current, loading: false }));+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const setEnableBeta = useCallback(async (enabled: boolean) => {+ const payload = await window.electronAPI.setUpdateChannelSettings({+ enableBeta: enabled,+ });+ setState(normalize(payload));+ }, []);++ const reset = useCallback(async () => {+ const payload = await window.electronAPI.resetUpdateChannelSettings();+ setState(normalize(payload));+ }, []);++ return { state, setEnableBeta, reset };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 3dbfa71296..32b7f80140 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1760,6 +1760,21 @@"toggleFailed": "Failed to toggle LSP"}},+ "betaChannel": {+ "title": "Beta channel",+ "description": "Join the beta channel to receive upcoming client updates early. Takes effect after restart.",+ "toggleAria": "Beta channel toggle",+ "restartTitle": "Restart Cindy",+ "restartDescription": "The beta channel requires a restart to take effect. Restart now?",+ "restartNow": "Restart now",+ "restartLater": "Later",+ "restartBusyDescription": "Tasks are currently in progress and restarting will interrupt them. Restart now anyway?",+ "unavailable": "The beta channel is unavailable — could not reach the beta update server.",+ "toast": {+ "disabled": "Beta channel disabled; takes effect after restart",+ "toggleFailed": "Failed to toggle beta channel"+ }+ },"gitSafety": {"title": "Git Safety","autoSnapshotTitle": "Git safety snapshots",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 3ff84b50d4..12110849b0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1759,6 +1759,21 @@"toggleFailed": "LSP の切り替えに失敗しました"}},+ "betaChannel": {+ "title": "Beta チャンネル",+ "description": "Beta チャンネルに参加すると、今後のクライアント更新を先行して受け取れます。再起動後に反映されます。",+ "toggleAria": "Beta チャンネルの切り替え",+ "restartTitle": "クライアントを再起動",+ "restartDescription": "Beta チャンネルは再起動後に反映されます。今すぐ再起動しますか?",+ "restartNow": "今すぐ再起動",+ "restartLater": "後で",+ "restartBusyDescription": "進行中のタスクがあります。再起動すると中断されます。今すぐ再起動しますか?",+ "unavailable": "Beta チャンネルは利用できません。Beta 更新サーバーに接続できませんでした。",+ "toast": {+ "disabled": "Beta チャンネルをオフにしました。再起動後に反映されます",+ "toggleFailed": "Beta チャンネルの切り替えに失敗しました"+ }+ },"gitSafety": {"title": "Git セーフティ","autoSnapshotTitle": "Git セーフティ保存点",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 114c479548..5f43e4a296 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1759,6 +1759,21 @@"toggleFailed": "LSP 전환에 실패했습니다"}},+ "betaChannel": {+ "title": "베타 채널",+ "description": "베타 채널에 참여하면 출시 예정인 클라이언트 업데이트를 먼저 받을 수 있습니다. 재시작 후 적용됩니다.",+ "toggleAria": "베타 채널 토글",+ "restartTitle": "클라이언트 재시작",+ "restartDescription": "베타 채널은 재시작해야 적용됩니다. 지금 재시작할까요?",+ "restartNow": "지금 재시작",+ "restartLater": "나중에",+ "restartBusyDescription": "진행 중인 작업이 있어 재시작하면 중단됩니다. 그래도 지금 재시작할까요?",+ "unavailable": "베타 채널을 사용할 수 없습니다. 베타 업데이트 서버에 연결할 수 없습니다.",+ "toast": {+ "disabled": "베타 채널이 꺼졌습니다. 재시작 후 적용됩니다",+ "toggleFailed": "베타 채널 전환 실패"+ }+ },"gitSafety": {"title": "Git 안전","autoSnapshotTitle": "Git 안전 저장점",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 23253eb3a4..2a9cb3ebc0 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1759,6 +1759,21 @@"toggleFailed": "切换 LSP 开关失败"}},+ "betaChannel": {+ "title": "Beta 测试渠道",+ "description": "加入 Beta 测试渠道,提前接收即将发布的客户端更新。开启后需重启客户端生效。",+ "toggleAria": "Beta 测试渠道开关",+ "restartTitle": "重启客户端",+ "restartDescription": "Beta 测试渠道需要重启客户端后才能生效,是否立即重启?",+ "restartNow": "立即重启",+ "restartLater": "稍后",+ "restartBusyDescription": "当前有任务正在进行中,重启会打断它们。确定要立即重启吗?",+ "unavailable": "Beta 测试渠道暂不可用,无法连接到 Beta 更新服务器。",+ "toast": {+ "disabled": "Beta 测试渠道已关闭,重启后生效",+ "toggleFailed": "切换 Beta 测试渠道失败"+ }+ },"gitSafety": {"title": "Git 安全","autoSnapshotTitle": "Git 安全保存点",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 00dac4d299..445f1fa45f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1759,6 +1759,21 @@"toggleFailed": "切換 LSP 開關失敗"}},+ "betaChannel": {+ "title": "Beta 測試管道",+ "description": "加入 Beta 測試管道,提前接收即將發布的客戶端更新。開啟後需重新啟動客戶端生效。",+ "toggleAria": "Beta 測試管道開關",+ "restartTitle": "重新啟動客戶端",+ "restartDescription": "Beta 測試管道需要重新啟動客戶端後才能生效,是否立即重新啟動?",+ "restartNow": "立即重新啟動",+ "restartLater": "稍後",+ "restartBusyDescription": "目前有任務進行中,重新啟動會中斷它們。確定要立即重新啟動嗎?",+ "unavailable": "Beta 測試管道暫不可用,無法連接到 Beta 更新伺服器。",+ "toast": {+ "disabled": "Beta 測試管道已關閉,重新啟動後生效",+ "toggleFailed": "切換 Beta 測試管道失敗"+ }+ },"gitSafety": {"title": "Git 安全","autoSnapshotTitle": "Git 安全儲存點",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 7bf33a637f..dff29509a2 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3416,6 +3416,25 @@ interface ElectronAPI {autoRelaunchOnIdle: boolean;}) => Promise<AutoUpdateSettingsPayload>;resetAutoUpdateSettings: () => Promise<AutoUpdateSettingsPayload>;+ /** beta 测试渠道(设备级)开关的读/写/恢复默认。 */+ getUpdateChannelSettings: () => Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }>;+ setUpdateChannelSettings: (settings: {+ enableBeta: boolean;+ }) => Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }>;+ resetUpdateChannelSettings: () => Promise<{+ enableBeta: boolean;+ isCustomized?: boolean;+ }>;+ /** 用户主动重启,让 beta 通道切换在下次冷启动前生效。 */+ relaunchForChannelChange: () => Promise<void>;+ /** 打开 beta 前预检:探测 beta manifest 是否可达(HTTP 200)。 */+ probeBetaChannel: () => Promise<{ available: boolean }>;setUpdateRelaunchTheme: (theme: 'light' | 'dark') => void;// E4D 毛玻璃:family 切换/启动通知 main 开关 vibrancy(仅 CINDY 透壁纸)theme: { applyVibrancy: (familyId: string, isDark: boolean) => void };diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex 6cac556548..8fb1988771 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -61,7 +61,8 @@ import {markStartupOtaLaunchSuccess,useStartupOtaGate,} from '@/update/useStartupOtaGate';-import { useCanaryChannelGate } from '@/update/useCanaryChannelGate';+import { useUpdateChannelGate } from '@/update/useUpdateChannelGate';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';import { useStartupEndpointGate } from '@/config/useStartupEndpointGate';import { IS_OTA_SELFHOST } from '@/config/env';import { getNewSessionCreationTask } from '@/session/newSessionCreation';@@ -294,10 +295,10 @@ function PrecreatedWorktreeRecoveryBridge() {return null;}-function RootAfterUpdateChannel({ isCanary }: { isCanary: boolean }) {+function RootAfterUpdateChannel({ channel }: { channel: UpdateChannel }) {// 自建变体:启动即生效的 JS 热更门(冷启动 check→fetch→reload,本次启动就跑上最新 JS)。// 内部 gate 自建 + 非 dev + updates 可用,其余直接 ready=true 不阻塞。见 useStartupOtaGate。- const otaReady = useStartupOtaGate(isCanary);+ const otaReady = useStartupOtaGate(channel);// handoff reporter:OTA 门就绪在本层上报(reload 期间保持 pending,readiness 不推进)const handoff = useLoginHandoff();const dispatchHandoff = handoff.dispatch;@@ -306,10 +307,10 @@ function RootAfterUpdateChannel({ isCanary }: { isCanary: boolean }) {}, [otaReady, dispatchHandoff]);// 符合整包分发策略的自建变体:启动时检查整包更新(runtimeVersion 变化 → 引导安装)。// TestFlight / 审核 / EAS 包为 no-op。JS 热更由上面的门 + expo-updates 处理,与此互补。- useBundleUpdatePrompt({ auto: true, isCanary });+ useBundleUpdatePrompt({ auto: true, channel });// 自建变体:后台切回前台时静默补一次检查(OTA 静默 fetch 不 reload、整包仅强更提示)。// TestFlight 保留 OTA、跳过整包分支;非自建为 no-op。见 useResumeUpdateCheck。- useResumeUpdateCheck(isCanary);+ useResumeUpdateCheck(channel);// 热更门未就绪(自建变体冷启动正在 check/fetch/reload)时不挂载业务树,避免闪旧 UI;// 期间根部常驻 splash 覆盖层在上面顶着,这里返回 null 即可。if (!otaReady) {@@ -333,12 +334,12 @@ function RootAfterUpdateChannel({ isCanary }: { isCanary: boolean }) {* 严格先于「检查更新」(本组件只在端点闸门 ready 后才挂载)。*/function RootAfterEndpoints() {- // 更新检查早于 AuthProvider,必须先恢复上次登录同步到本机的 canary 快照。- // 未持久化/读取失败一律 stable;读取完成前不允许发任何 /manifest 或 /latest 请求。- const channel = useCanaryChannelGate(IS_OTA_SELFHOST);+ // 更新检查早于 AuthProvider,必须先恢复上次登录同步到本机的 canary 快照 + 设备 beta 开关。+ // 未持久化/读取失败一律 release;读取完成前不允许发任何 /manifest 或 /latest 请求。+ const channelGate = useUpdateChannelGate(IS_OTA_SELFHOST);// 未就绪期间由根部常驻 splash 覆盖层顶着,不再各自渲染 splash 实例(避免交接闪帧)。- if (!channel.ready) return null;- return <RootAfterUpdateChannel isCanary={channel.isCanary} />;+ if (!channelGate.ready) return null;+ return <RootAfterUpdateChannel channel={channelGate.channel} />;}function RootLayout() {diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex 8fc28273c7..978ebf722a 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -5,6 +5,7 @@ import { useUpdates } from 'expo-updates';import { useRouter } from 'expo-router';import { Children, Fragment, isValidElement, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';import {+ Alert,FlatList,Image,Linking,@@ -87,7 +88,9 @@ import {type ManualUpdateCheckOutcome,} from '@/update/manualUpdateCheck';import { useBundleUpdatePrompt } from '@/update/useBundleUpdatePrompt';-import { useCanaryChannelGate } from '@/update/useCanaryChannelGate';+import { useUpdateChannelGate } from '@/update/useUpdateChannelGate';+import { useBetaChannel } from '@/update/useBetaChannel';+import { probeBetaChannel } from '@/update/fetchLatestRelease';import { MobileChoicePickerList } from '@/session/MobileChoicePickerList';import { SheetModal } from '@/session/SheetModal';import { SheetSurface } from '@/session/SheetSurface';@@ -140,6 +143,9 @@ export default function SettingsScreen() {// 相反;放行点击会让 toggleAnalytics 对着真值取反,做出与所见相反的动作。const [analyticsReady, setAnalyticsReady] = useState(false);const [analyticsMessage, setAnalyticsMessage] = useState<string | null>(null);+ // beta 测试渠道(设备级)开关。真相在 betaChannelStore;hydrate 完成前禁用,避免对陈旧值取反。+ const { enabled: betaEnabled, ready: betaReady, setEnabled: setBetaEnabled } = useBetaChannel();+ const [betaBusy, setBetaBusy] = useState(false);const updateCheckInFlightRef = useRef(false);// 语音词典:手机只读展示被控桌面的词典快照(正本在桌面,手机不参与合并)。const [dictionaryScreenOpen, setDictionaryScreenOpen] = useState(false);@@ -191,11 +197,11 @@ export default function SettingsScreen() {// t 依赖同 overview:行构造走 i18n.t,语言切换时重算。const updateInfoRows = useMemo(() => buildMobileUpdateInfoRows(currentlyRunning), [currentlyRunning, t]);const otaVersion = useMemo(() => currentMobileOtaVersion(currentlyRunning), [currentlyRunning, t]);- const canaryChannel = useCanaryChannelGate(IS_OTA_SELFHOST);+ const updateChannel = useUpdateChannelGate(IS_OTA_SELFHOST);// 允许整包分发时统一入口先查整包;TestFlight 等禁用整包的环境直接进入 JS OTA。const { checkNow: checkBundleUpdate } = useBundleUpdatePrompt({auto: false,- isCanary: canaryChannel.isCanary,+ channel: updateChannel.channel,});const bundleCheckEnabled = shouldCheckBundleUpdate({isSelfHosted: IS_OTA_SELFHOST,@@ -604,6 +610,40 @@ export default function SettingsScreen() {setDebugExpanded((value) => !value);}, []);+ // beta 测试渠道开关:落盘即时生效,但 manifest 通道只在下次冷启动/后台轮询切换。+ // 打开后引导用户手动重启,让下次启动的更新检查前就切到 beta。+ const toggleBeta = useCallback(async () => {+ if (betaBusy) return;+ setBetaBusy(true);+ const next = !betaEnabled;+ try {+ if (next) {+ // 打开 beta 前预检(与桌面端 probeBetaManifest 对称):探测 /latest?channel=beta+ // 是否可达。服务端未部署 beta 时拒绝开启,避免设备静默收不到 OTA/整包/强更记录。+ const available = await probeBetaChannel(+ Platform.OS === 'android' ? 'android' : 'ios',+ );+ if (!available) {+ Alert.alert(t('settings.betaChannel.title'), t('settings.betaChannel.unavailable'));+ return; // 不落盘,开关保持关闭+ }+ }+ await setBetaEnabled(next);+ if (next) {+ Alert.alert(+ t('settings.betaChannel.title'),+ t('settings.betaChannel.restartHint'),+ [{ text: t('settings.betaChannel.ok'), style: 'default' }],+ );+ }+ } catch {+ // 只可能是本机存储异常;store 会回推真值,这里仅提示未保存成功。+ Alert.alert(t('settings.betaChannel.title'), t('settings.betaChannel.saveFailed'));+ } finally {+ setBetaBusy(false);+ }+ }, [betaBusy, betaEnabled, setBetaEnabled, t]);+/* ── 使用统计(TapDB)开关 ──语义是 opt-out:用户在登录页同意《隐私政策》后默认开启,这里随时可关。关闭后立即解绑账号标识、不再主动上报;原生 SDK 不支持反初始化,本次进程内@@ -941,6 +981,20 @@ export default function SettingsScreen() {<InfoRow key={row.id} detail={row.detail} label={row.label} testID={`settings.row.${row.id}`} value={row.value} />))),+ <View key="beta-channel-toggle" style={styles.switchRow} testID="settings.betaChannelToggleRow">+ <View style={styles.switchTexts}>+ <Text style={styles.rowLabel}>{t('settings.betaChannel.title')}</Text>+ <Text style={styles.hint}>{t('settings.betaChannel.description')}</Text>+ </View>+ <Switch+ accessibilityLabel={t('settings.betaChannel.title')}+ disabled={betaBusy || !betaReady}+ onValueChange={() => void toggleBeta()}+ testID="settings.betaChannelToggle"+ trackColor={{ true: colors.inputCaret }}+ value={betaEnabled}+ />+ </View>,...updateInfoRows.map((row) => (<InfoRow key={row.id} label={row.label} testID={`settings.updateInfo.${row.id}`} value={row.value} />)),diff --git a/apps/mobile/src/__tests__/startupSplashOverlay.test.ts b/apps/mobile/src/__tests__/startupSplashOverlay.test.tsindex 1eb8235aec..2c147feeea 100644--- a/apps/mobile/src/__tests__/startupSplashOverlay.test.ts+++ b/apps/mobile/src/__tests__/startupSplashOverlay.test.ts@@ -35,7 +35,7 @@ describe("startup splash overlay", () => {const index = read("app/index.tsx");expect(layout).toContain("if (!otaReady) {\n return null;\n }");- expect(layout).toContain("if (!channel.ready) return null;");+ expect(layout).toContain("if (!channelGate.ready) return null;");expect(index).toContain("if (!auth.initialized) return null;");expect(index).not.toContain('variant="splash"');});diff --git a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts b/apps/mobile/src/auth/__tests__/loginHandoffState.test.tsindex 58a8825489..a189b157b3 100644--- a/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts+++ b/apps/mobile/src/auth/__tests__/loginHandoffState.test.ts@@ -182,9 +182,13 @@ describe('loginHandoff 接线(Provider/reporter 拓扑 + 清理,读源码断言)expect(loginSource).toContain("handoffDispatch?.({ type: 'panel-mounted' })");expect(stageSource).toContain("handoff?.dispatch({ type: 'assets-ready' })");// endpoint→OTA→auth 既有挂载顺序不变:OTA 上报在 RootAfterEndpoints、auth 桥在 AuthProvider 内- expect(layoutSource.indexOf('useStartupOtaGate()')).toBeLessThan(- layoutSource.indexOf('<AuthHandoffBridge />'),- );+ const otaIndex = layoutSource.indexOf('useStartupOtaGate(');+ const authBridgeIndex = layoutSource.indexOf('<AuthHandoffBridge />');+ // 两处都必须真实存在(indexOf >= 0),否则顺序比较会因 -1 而空转;+ // 再断言 OTA 调用先于 auth 桥挂载(与上文注释的既有顺序一致)。+ expect(otaIndex).toBeGreaterThanOrEqual(0);+ expect(authBridgeIndex).toBeGreaterThanOrEqual(0);+ expect(otaIndex).toBeLessThan(authBridgeIndex);});it('reduced-motion:AccessibilityInfo 拉取 + 订阅,unmount 移除;直落终态由 Provider 收敛', () => {diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.jsonindex 86c520577b..75e6d87548 100644--- a/apps/mobile/src/i18n/locales/en/settings.json+++ b/apps/mobile/src/i18n/locales/en/settings.json@@ -37,6 +37,14 @@"checkFailedDetail": "Update check failed: {{detail}}","checkFailed": "Update check failed. Try again later."},+ "betaChannel": {+ "title": "Beta channel",+ "description": "Join the beta channel to receive upcoming client updates early.",+ "restartHint": "The beta channel takes effect after restarting the app. Please restart to apply.",+ "ok": "Got it",+ "saveFailed": "Failed to save beta channel setting",+ "unavailable": "The beta channel is unavailable — could not reach the beta update server."+ },"notifications": {"sectionTitle": "Notifications","taskDone": "Task Completion Notifications",diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.jsonindex 781aa52dd8..80f1638b2b 100644--- a/apps/mobile/src/i18n/locales/ja/settings.json+++ b/apps/mobile/src/i18n/locales/ja/settings.json@@ -37,6 +37,14 @@"checkFailedDetail": "更新の確認に失敗しました:{{detail}}","checkFailed": "更新の確認に失敗しました。しばらくしてからもう一度お試しください。"},+ "betaChannel": {+ "title": "Beta チャンネル",+ "description": "Beta チャンネルに参加すると、今後のクライアント更新を先行して受け取れます。",+ "restartHint": "Beta チャンネルは再起動後に反映されます。アプリを再起動してください。",+ "ok": "わかりました",+ "saveFailed": "Beta チャンネル設定の保存に失敗しました",+ "unavailable": "Beta チャンネルは利用できません。Beta 更新サーバーに接続できませんでした。"+ },"notifications": {"sectionTitle": "通知","taskDone": "タスク完了通知",diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.jsonindex 557f486f98..c2cf61bd04 100644--- a/apps/mobile/src/i18n/locales/ko/settings.json+++ b/apps/mobile/src/i18n/locales/ko/settings.json@@ -37,6 +37,14 @@"checkFailedDetail": "업데이트 확인에 실패했습니다: {{detail}}","checkFailed": "업데이트 확인에 실패했습니다. 잠시 후 다시 시도해 주세요."},+ "betaChannel": {+ "title": "베타 채널",+ "description": "베타 채널에 참여하면 출시 예정인 클라이언트 업데이트를 먼저 받을 수 있습니다.",+ "restartHint": "베타 채널은 앱을 재시작해야 적용됩니다. 앱을 다시 시작해 주세요.",+ "ok": "확인",+ "saveFailed": "베타 채널 설정 저장 실패",+ "unavailable": "베타 채널을 사용할 수 없습니다. 베타 업데이트 서버에 연결할 수 없습니다."+ },"notifications": {"sectionTitle": "알림","taskDone": "작업 완료 알림",diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.jsonindex 31796fa081..6f643476c5 100644--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json@@ -37,6 +37,14 @@"checkFailedDetail": "检查更新失败:{{detail}}","checkFailed": "检查更新失败,请稍后重试"},+ "betaChannel": {+ "title": "Beta 测试渠道",+ "description": "加入 Beta 测试渠道,提前接收即将发布的客户端更新。",+ "restartHint": "Beta 测试渠道需要重启客户端后才能生效,请重启应用。",+ "ok": "我知道了",+ "saveFailed": "保存 Beta 测试渠道设置失败",+ "unavailable": "Beta 测试渠道暂不可用,无法连接到 Beta 更新服务器。"+ },"notifications": {"sectionTitle": "通知","taskDone": "任务完成通知",diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.jsonindex cfbd53197d..86adee983b 100644--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json@@ -37,6 +37,14 @@"checkFailedDetail": "檢查更新失敗:{{detail}}","checkFailed": "檢查更新失敗,請稍後重試"},+ "betaChannel": {+ "title": "Beta 測試管道",+ "description": "加入 Beta 測試管道,提前接收即將發布的客戶端更新。",+ "restartHint": "Beta 測試管道需要重新啟動客戶端後才能生效,請重新啟動應用。",+ "ok": "我知道了",+ "saveFailed": "儲存 Beta 測試管道設定失敗",+ "unavailable": "Beta 測試管道暫不可用,無法連接到 Beta 更新伺服器。"+ },"notifications": {"sectionTitle": "通知","taskDone": "任務完成通知",diff --git a/apps/mobile/src/update/betaChannelStore.test.ts b/apps/mobile/src/update/betaChannelStore.test.tsnew file mode 100644index 0000000000..2270bd11e4--- /dev/null+++ b/apps/mobile/src/update/betaChannelStore.test.ts@@ -0,0 +1,107 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import AsyncStorage from '@react-native-async-storage/async-storage';++const storage = new Map<string, string>();+vi.mock('@react-native-async-storage/async-storage', () => ({+ default: {+ getItem: vi.fn(async (key: string) => storage.get(key) ?? null),+ setItem: vi.fn(async (key: string, value: string) => { storage.set(key, value); }),+ removeItem: vi.fn(async (key: string) => { storage.delete(key); }),+ },+}));++import {+ __testing,+ hydrateBetaChannel,+ isBetaChannel,+ subscribeBetaChannel,+ syncBetaChannel,+} from './betaChannelStore';++beforeEach(async () => {+ storage.clear();+ await __testing.resetMemory();+ vi.clearAllMocks();+});++describe('betaChannelStore', () => {+ it('首次安装/坏值默认不启用 beta', async () => {+ expect(isBetaChannel()).toBe(false);+ await expect(hydrateBetaChannel()).resolves.toBe(false);+ expect(isBetaChannel()).toBe(false);++ await __testing.resetMemory();+ storage.set(__testing.storageKey, 'not-true');+ await expect(hydrateBetaChannel()).resolves.toBe(false);+ });++ it('同步 true 跨冷启动恢复;false 删除标记', async () => {+ await syncBetaChannel(true);+ expect(isBetaChannel()).toBe(true);+ expect(storage.get(__testing.storageKey)).toBe('true');++ await __testing.resetMemory();+ await expect(hydrateBetaChannel()).resolves.toBe(true);++ await syncBetaChannel(false);+ expect(isBetaChannel()).toBe(false);+ expect(storage.has(__testing.storageKey)).toBe(false);+ });++ it('切换会通知订阅者,且取消订阅后不再通知', async () => {+ const changes: boolean[] = [];+ const unsubscribe = subscribeBetaChannel(() => changes.push(isBetaChannel()));++ await syncBetaChannel(true);+ await syncBetaChannel(false);+ expect(changes).toEqual([true, false]);++ unsubscribe();+ await syncBetaChannel(true);+ expect(changes).toEqual([true, false]);+ });++ it('落盘失败回滚内存态并 reject,避免「本次按 beta 检查、重启后回 release」漂移', async () => {+ await hydrateBetaChannel();+ expect(isBetaChannel()).toBe(false);++ // 模拟 AsyncStorage.setItem 失败+ vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('disk full'));++ await expect(syncBetaChannel(true)).rejects.toThrow('disk full');+ // 回滚到落盘前的旧值(未启用)+ expect(isBetaChannel()).toBe(false);+ });++ it('连续两次落盘都失败时,回滚到磁盘确认态而非上一次的乐观值', async () => {+ await hydrateBetaChannel();+ expect(isBetaChannel()).toBe(false);++ // release → 开 → 关,两次存储操作都失败。+ vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('full'));+ vi.mocked(AsyncStorage.removeItem).mockRejectedValueOnce(new Error('full'));++ await expect(syncBetaChannel(true)).rejects.toThrow('full');+ await expect(syncBetaChannel(false)).rejects.toThrow('full');+ // 磁盘仍是 release;内存不得停留在第一次的乐观值(已开)。+ expect(isBetaChannel()).toBe(false);+ });++ it('前一次失败、后一次成功时,后一次成功不把内存覆盖成磁盘旧值', async () => {+ await hydrateBetaChannel();+ expect(isBetaChannel()).toBe(false);++ // 第一次开:失败;第二次开(同值):成功。两次并发在同一个 mutation 队列里。+ vi.mocked(AsyncStorage.setItem)+ .mockRejectedValueOnce(new Error('full')) // 第一次失败+ .mockResolvedValueOnce(undefined); // 第二次成功++ // 第二次调用(成功)先入队、第一次失败后到 —— 用两个 promise 同时发起。+ const p1 = syncBetaChannel(true);+ const p2 = syncBetaChannel(true);+ await expect(p1).rejects.toThrow('full');+ await expect(p2).resolves.toBeUndefined();+ // 磁盘已是 beta(第二次成功落盘);内存不得被第一次失败回滚成 release。+ expect(isBetaChannel()).toBe(true);+ });+});diff --git a/apps/mobile/src/update/betaChannelStore.ts b/apps/mobile/src/update/betaChannelStore.tsnew file mode 100644index 0000000000..10581a6447--- /dev/null+++ b/apps/mobile/src/update/betaChannelStore.ts@@ -0,0 +1,139 @@+/**+ * Mobile beta 测试渠道的**设备级**本地快照。+ *+ * 与 canaryChannelStore 的关键区别:+ * - canary 是账号级、服务端下发(login 后 feature-flags → 本地持久化 → 登出清);+ * - beta 是设备级、客户端本地设置(设置页开关),登出/换号都不清。+ *+ * 所以这里没有 clearBetaChannel(登出清理):开关只随设备走,不随账号生命周期。+ * 其余机制(AsyncStorage 快照 + hydrate 门 + mutation 队列)与 canaryChannelStore 一致,+ * 保证「冷启动任何更新请求前先恢复本地快照」、损坏 fail-safe 到 stable。+ *+ * 标记不敏感(只选择公开 CDN 指针),AsyncStorage 即可。+ */+import AsyncStorage from '@react-native-async-storage/async-storage';++const STORAGE_KEY = 'cindy.mobile.update.beta';++let beta = false;+/** 磁盘确认态:最近一次成功落盘的值。回滚一律回到它,而非上一次调用的乐观值。 */+let committed = false;+let hydrated = false;+let hydratePromise: Promise<boolean> | null = null;+let mutationEpoch = 0;+let mutationQueue: Promise<void> = Promise.resolve();+const listeners = new Set<() => void>();++function notifyListeners(): void {+ for (const listener of [...listeners]) {+ try {+ listener();+ } catch {+ // ignore listener failures+ }+ }+}++function enqueueMutation(operation: () => Promise<void>): Promise<void> {+ const run = mutationQueue.then(operation, operation);+ mutationQueue = run.catch(() => undefined);+ return run;+}++/** 冷启动时调用一次;损坏/不可读一律 fail-safe 到 false(不启用 beta)。 */+export function hydrateBetaChannel(): Promise<boolean> {+ if (hydrated) return Promise.resolve(beta);+ if (hydratePromise) return hydratePromise;+ const epoch = mutationEpoch;+ hydratePromise = AsyncStorage.getItem(STORAGE_KEY)+ .then((raw) => {+ if (epoch === mutationEpoch) {+ const next = raw === 'true';+ committed = next;+ if (beta !== next || !hydrated) {+ beta = next;+ notifyListeners();+ }+ }+ hydrated = true;+ return beta;+ })+ .catch(() => {+ if (epoch === mutationEpoch) {+ committed = false;+ if (beta || !hydrated) {+ beta = false;+ notifyListeners();+ }+ }+ hydrated = true;+ return beta;+ })+ .finally(() => {+ hydratePromise = null;+ });+ return hydratePromise;+}++/** 启动 gate 完成后可同步读取。未 hydrate 时按 false(不启用 beta)。 */+export function isBetaChannel(): boolean {+ return hydrated && beta;+}++/** 订阅开关变化;返回取消订阅函数。 */+export function subscribeBetaChannel(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+}++/**+ * 设置页开关写入;内存态先行、串行落盘。落盘失败回滚内存态并重新抛错。+ *+ * 与 canaryChannelStore.syncCanaryChannel 的差异:canary 是服务端下发、落盘失败+ * 下次登录会重新同步;beta 是**用户可见**的设置开关,若不回滚会出现「设置页显示已开、+ * 本次运行按 beta 检查更新、重启后却回 release」的漂移,所以这里额外做失败回滚。+ *+ * 回滚目标是 `committed`(磁盘确认态)而非「本次调用前的内存态」:连续两次落盘都失败时,+ * 后一次的「调用前内存态」是前一次尚未落盘的乐观值,回滚到它会得到错误结果+ * (例如 release→开→关 都失败,内存反而停在「已开」)。回滚到磁盘真实值总是安全的。+ */+export function syncBetaChannel(next: boolean): Promise<void> {+ const value = next === true;+ mutationEpoch += 1;+ const epoch = mutationEpoch;+ hydrated = true;+ beta = value;+ notifyListeners();+ return enqueueMutation(async () => {+ if (value) await AsyncStorage.setItem(STORAGE_KEY, 'true');+ else await AsyncStorage.removeItem(STORAGE_KEY);+ }).then(+ () => {+ committed = value;+ },+ (err) => {+ // 只有自己仍是最新 mutation 时才回滚:若有更新的 mutation 已乐观设置了+ // beta(它自己负责成功/失败),这里回滚 committed 会把它的乐观值覆盖掉,+ // 造成「内存 release、磁盘 beta」的漂移。更新 mutation 会处理它自己的结果。+ if (epoch === mutationEpoch) {+ beta = committed;+ notifyListeners();+ }+ throw err;+ },+ );+}++export const __testing = {+ storageKey: STORAGE_KEY,+ async resetMemory(): Promise<void> {+ await mutationQueue.catch(() => undefined);+ beta = false;+ committed = false;+ hydrated = false;+ hydratePromise = null;+ mutationEpoch = 0;+ mutationQueue = Promise.resolve();+ listeners.clear();+ },+};diff --git a/apps/mobile/src/update/canaryChannelStore.test.ts b/apps/mobile/src/update/canaryChannelStore.test.tsindex 2e2f93e814..b2b55d56c9 100644--- a/apps/mobile/src/update/canaryChannelStore.test.ts+++ b/apps/mobile/src/update/canaryChannelStore.test.ts@@ -54,9 +54,10 @@ describe('canaryChannelStore', () => {expect(storage.has(__testing.storageKey)).toBe(false);});- it('只有 canary 请求携带公开通道 header', () => {- expect(updateChannelRequestHeaders(false)).toEqual({});- expect(updateChannelRequestHeaders(true)).toEqual({ 'x-cindy-update-channel': 'canary' });+ it('按发布通道决定 header:release 无 header,canary/beta 携带对应值', () => {+ expect(updateChannelRequestHeaders('release')).toEqual({});+ expect(updateChannelRequestHeaders('canary')).toEqual({ 'x-cindy-update-channel': 'canary' });+ expect(updateChannelRequestHeaders('beta')).toEqual({ 'x-cindy-update-channel': 'beta' });});it('登录/登出切换会通知订阅者,且取消订阅后不再通知', async () => {diff --git a/apps/mobile/src/update/canaryChannelStore.ts b/apps/mobile/src/update/canaryChannelStore.tsindex 0341cf7c28..36b9b42553 100644--- a/apps/mobile/src/update/canaryChannelStore.ts+++ b/apps/mobile/src/update/canaryChannelStore.ts@@ -7,6 +7,10 @@*/import AsyncStorage from '@react-native-async-storage/async-storage';+import { resolveUpdateChannel, type UpdateChannel } from '@cindy/maker-shared/update-channel';++import { isBetaChannel } from './betaChannelStore';+export const CANARY_UPDATE_HEADER = 'x-cindy-update-channel';const STORAGE_KEY = 'cindy.mobile.update.canary';@@ -103,8 +107,17 @@ export function clearCanaryChannel(): Promise<void> {return enqueueMutation(() => AsyncStorage.removeItem(STORAGE_KEY));}-export function updateChannelRequestHeaders(isCanary: boolean): Record<string, string> {- return isCanary ? { [CANARY_UPDATE_HEADER]: 'canary' } : {};+export function updateChannelRequestHeaders(channel: UpdateChannel): Record<string, string> {+ return channel === 'release' ? {} : { [CANARY_UPDATE_HEADER]: channel };+}++/**+ * 设备级发布通道收敛:账号 canary 快照 + 设备 beta 开关。+ * 优先级 canary > beta > release(canary 命中时忽略 beta)。+ * 未 hydrate 时两个 store 都返回 stable,结果即 release(与启动 gate 一致)。+ */+export function resolveUpdateChannelForDevice(): UpdateChannel {+ return resolveUpdateChannel(isCanaryChannel(), isBetaChannel());}export const __testing = {diff --git a/apps/mobile/src/update/fetchLatestRelease.test.ts b/apps/mobile/src/update/fetchLatestRelease.test.tsindex 3b72e7e49d..eda489f6ee 100644--- a/apps/mobile/src/update/fetchLatestRelease.test.ts+++ b/apps/mobile/src/update/fetchLatestRelease.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { fetchLatestRelease } from './fetchLatestRelease';+import { fetchLatestRelease, probeBetaChannel } from './fetchLatestRelease';const BASE = 'https://ota.example.com';const resp = (status: number, json?: unknown) => ({@@ -40,12 +40,15 @@ describe('fetchLatestRelease —— 区分"无更新"与"连不上"', () => {expectCacheBustedUrl(url, `${BASE}/latest?platform=ios`);});- it('canary 显式追加 channel,stable URL 保持旧契约', async () => {+ it('canary/beta 显式追加 channel,release URL 保持旧契约', async () => {const fetchMock = vi.fn(async () => resp(200, { runtimeVersion: 'rtv1' }));vi.stubGlobal('fetch', fetchMock);- await fetchLatestRelease('android', 8000, BASE, true);- const [url] = fetchMock.mock.calls[0] as unknown as [string];+ await fetchLatestRelease('android', 8000, BASE, 'canary');+ let [url] = fetchMock.mock.calls[0] as unknown as [string];expectCacheBustedUrl(url, `${BASE}/latest?platform=android&channel=canary`);+ await fetchLatestRelease('android', 8000, BASE, 'beta');+ [url] = fetchMock.mock.calls[1] as unknown as [string];+ expectCacheBustedUrl(url, `${BASE}/latest?platform=android&channel=beta`);});it('一律绕缓存:每次请求都带 cache-buster + no-cache 头', async () => {@@ -76,3 +79,26 @@ describe('fetchLatestRelease —— 区分"无更新"与"连不上"', () => {await expect(fetchLatestRelease('ios', 8000, BASE)).rejects.toThrow(/Network request failed/);});});++describe('probeBetaChannel —— 打开 beta 前的可用性探测', () => {+ it('404(无 beta 记录)视为不可达——「未部署」与「未发版本」不可区分,都不该开', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => resp(404)));+ await expect(probeBetaChannel('ios', 8000, BASE)).resolves.toBe(false);+ });++ it('200 返回记录视为可达', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => resp(200, { runtimeVersion: 'rtv1' })));+ await expect(probeBetaChannel('android', 8000, BASE)).resolves.toBe(true);+ });++ it('5xx / 网络失败视为不可达', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => resp(500)));+ await expect(probeBetaChannel('ios', 8000, BASE)).resolves.toBe(false);+ vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('Network request failed'); }));+ await expect(probeBetaChannel('ios', 8000, BASE)).resolves.toBe(false);+ });++ it('非自建变体(baseUrl 为空)不可达', async () => {+ await expect(probeBetaChannel('ios', 8000, '')).resolves.toBe(false);+ });+});diff --git a/apps/mobile/src/update/fetchLatestRelease.ts b/apps/mobile/src/update/fetchLatestRelease.tsindex 35811c0856..3008156388 100644--- a/apps/mobile/src/update/fetchLatestRelease.ts+++ b/apps/mobile/src/update/fetchLatestRelease.ts@@ -1,6 +1,7 @@// 拉 mobile-update-server 的 `/latest`(整包版本记录)。薄 IO 封装,判定逻辑在 bundleUpdate.ts。import { i18n } from '@/i18n';import { OTA_SERVER_BASE_URL } from '@/config/env';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';const DEFAULT_TIMEOUT_MS = 8000;@@ -17,18 +18,19 @@ const DEFAULT_TIMEOUT_MS = 8000;* 强更闸门外,旧记录没门槛时又把该挡的用户**放行**。两者都不可接受,所以四条调用路径* (启动 / resume / 设置页 / 阻断屏核对)统一不吃缓存,代价只是每次多一个小 JSON 请求。* @param platform 目标平台(默认 ios)+ * @param channel 发布通道(默认 release;canary/beta 分别追加 &channel=canary/beta)*/export async function fetchLatestRelease(platform = 'ios',timeoutMs = DEFAULT_TIMEOUT_MS,baseUrl = OTA_SERVER_BASE_URL,- isCanary = false,+ channel: UpdateChannel = 'release',): Promise<unknown | null> {if (!baseUrl) return null; // 非自建变体,无自托管服务const controller = new AbortController();const timer = setTimeout(() => controller.abort(), timeoutMs);try {- const channelQuery = isCanary ? '&channel=canary' : '';+ const channelQuery = channel === 'release' ? '' : `&channel=${channel}`;const res = await fetch(`${baseUrl}/latest?platform=${encodeURIComponent(platform)}${channelQuery}&t=${Date.now()}`, {signal: controller.signal,headers: { accept: 'application/json', 'cache-control': 'no-cache' },@@ -40,3 +42,35 @@ export async function fetchLatestRelease(clearTimeout(timer);}}++/**+ * 探测 beta 渠道是否可达(整包 `/latest?channel=beta`)。+ * 打开 beta 开关前的预检,与桌面端 probeBetaManifest 对称。+ *+ * 判定口径(**只有 200 有记录才算可达**):+ * - 200 返回记录 → 可达;+ * - 404 → 不可达。fetchLatestRelease 对 404 返回 null;这里刻意把「无 beta 记录」+ * 也判为不可达——「服务端未部署 beta 路由」与「已部署但尚未发第一个 beta 版本」+ * 在 404 上不可区分,但两者都意味着「现在没有 beta 可测」,拒绝开启是一致的+ * (与桌面端「文件不存在 = 404 = 不可开」对齐;用户诉求就是「取不到就提示无法开」)。+ * - 5xx / 网络 / 超时 → 不可达。+ *+ * 已知限制(如实说明,非密闭):`channel=beta` 是 query 参数,若服务端**忽略**该参数+ * 而返回 release 记录(200),本探测会误判为「已部署」——客户端无法区分「认识 beta」+ * 与「忽略 beta 返回 release」。这点做不到桌面端 `-beta.json` 那种泾渭分明的精度,+ * 但至少拦住「baseUrl 不可达」「channel=beta 返回 5xx」「无 beta 记录(404)」三类。+ * 是否部署 beta 分支仍以服务端为准。+ */+export async function probeBetaChannel(+ platform = 'ios',+ timeoutMs = DEFAULT_TIMEOUT_MS,+ baseUrl = OTA_SERVER_BASE_URL,+): Promise<boolean> {+ if (!baseUrl) return false; // 非自建变体:无自托管服务,beta 不可用+ try {+ const record = await fetchLatestRelease(platform, timeoutMs, baseUrl, 'beta');+ return record !== null; // 200 有记录 = 可达;404(null) = 不可达+ } catch {+ return false;+ }+}diff --git a/apps/mobile/src/update/useBetaChannel.ts b/apps/mobile/src/update/useBetaChannel.tsnew file mode 100644index 0000000000..1e3ad39f21--- /dev/null+++ b/apps/mobile/src/update/useBetaChannel.ts@@ -0,0 +1,46 @@+import { useCallback, useEffect, useState } from 'react';++import {+ hydrateBetaChannel,+ isBetaChannel,+ subscribeBetaChannel,+ syncBetaChannel,+} from './betaChannelStore';++/**+ * 设备级 beta 开关的状态与写操作(设置页用)。+ * hydrate 完成前 ready=false,开关应禁用(显示的是 fail-safe 默认值,避免对陈旧值取反)。+ */+export function useBetaChannel(): {+ enabled: boolean;+ ready: boolean;+ setEnabled: (next: boolean) => Promise<void>;+} {+ const [enabled, setEnabledState] = useState(false);+ const [ready, setReady] = useState(false);++ useEffect(() => {+ let cancelled = false;+ const sync = () => {+ if (!cancelled) setEnabledState(isBetaChannel());+ };+ const unsubscribe = subscribeBetaChannel(sync);+ void hydrateBetaChannel().then(() => {+ if (!cancelled) {+ sync();+ setReady(true);+ }+ });+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);++ const setEnabled = useCallback(async (next: boolean) => {+ await syncBetaChannel(next);+ setEnabledState(next);+ }, []);++ return { enabled, ready, setEnabled };+}diff --git a/apps/mobile/src/update/useBundleUpdatePrompt.ts b/apps/mobile/src/update/useBundleUpdatePrompt.tsindex d62cf487ea..e6e3313068 100644--- a/apps/mobile/src/update/useBundleUpdatePrompt.ts+++ b/apps/mobile/src/update/useBundleUpdatePrompt.ts@@ -23,7 +23,8 @@ import {} from './bundleUpdate';import type { BundleUpdateCheckOutcome } from './manualUpdateCheck';import { enterForcedUpdate } from './forcedUpdateStore';-import { isCanaryChannel } from './canaryChannelStore';+import { resolveUpdateChannelForDevice } from './canaryChannelStore';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';type CheckState = 'idle' | 'checking' | 'up-to-date' | 'update-available' | 'error';@@ -32,8 +33,8 @@ interface Options {auto?: boolean;/** 无更新时是否提示(设置页手动检查用 true,启动静默用 false)。 */notifyWhenUpToDate?: boolean;- /** 自建更新通道;缺省读取启动时已 hydrate 的本地快照。 */- isCanary?: boolean;+ /** 自建更新通道;缺省读取启动时已 hydrate 的本地快照(canary+beta 收敛)。 */+ channel?: UpdateChannel;}async function openInstall(url: string): Promise<void> {@@ -91,7 +92,7 @@ export function promptBundleUpdate(evaluation: ReturnType<typeof evaluateBundleUexport function useBundleUpdatePrompt({auto = true,notifyWhenUpToDate = false,- isCanary = isCanaryChannel(),+ channel = resolveUpdateChannelForDevice(),}: Options = {}) {const [state, setState] = useState<CheckState>('idle');const bundleCheckEnabled = shouldCheckBundleUpdate({@@ -99,21 +100,21 @@ export function useBundleUpdatePrompt({isReviewMode: REVIEW_MODE,isTestFlightBuild: IS_TESTFLIGHT_BUILD,});- const inFlightChannels = useRef(new Set<boolean>());+ const inFlightChannels = useRef(new Set<UpdateChannel>());const channelEpochRef = useRef(0);- const previousChannelRef = useRef(isCanary);+ const previousChannelRef = useRef(channel);// render 已经是 channel 切换对本 hook 可见的最早时点;在这里递增 epoch,// 让旧账号请求即使恰好晚返回,也不能更新新账号的 UI。- if (previousChannelRef.current !== isCanary) {- previousChannelRef.current = isCanary;+ if (previousChannelRef.current !== channel) {+ previousChannelRef.current = channel;channelEpochRef.current += 1;}const checkNow = useCallback(async (): Promise<BundleUpdateCheckOutcome> => {// 审核模式与 TestFlight 都禁止整包外跳;这里再挡一层,不依赖调用方记得隐藏入口。if (!bundleCheckEnabled) return 'skipped';- if (inFlightChannels.current.has(isCanary)) return 'busy';- inFlightChannels.current.add(isCanary);+ if (inFlightChannels.current.has(channel)) return 'busy';+ inFlightChannels.current.add(channel);const requestEpoch = channelEpochRef.current;setState('checking');try {@@ -123,7 +124,7 @@ export function useBundleUpdatePrompt({Platform.OS === 'android' ? 'android' : 'ios',undefined,undefined,- isCanary,+ channel,);if (requestEpoch !== channelEpochRef.current) return 'skipped';const evaluation = evaluateBundleUpdate({@@ -150,16 +151,16 @@ export function useBundleUpdatePrompt({if (notifyWhenUpToDate) Alert.alert(i18n.t('update.checkFailedTitle'), i18n.t('update.checkFailedBody'));return 'error';} finally {- inFlightChannels.current.delete(isCanary);+ inFlightChannels.current.delete(channel);}- }, [bundleCheckEnabled, isCanary, notifyWhenUpToDate]);+ }, [bundleCheckEnabled, channel, notifyWhenUpToDate]);useEffect(() => {if (auto && bundleCheckEnabled) void checkNow();// auto hook 在登录/切账号导致 channel 变化时再检查一次,避免新的账号// 继续沿用旧账号的 release 指针;手动检查入口仍由调用方通过 checkNow 触发。// eslint-disable-next-line react-hooks/exhaustive-deps- }, [auto, bundleCheckEnabled, isCanary]);+ }, [auto, bundleCheckEnabled, channel]);return { state, checkNow };}diff --git a/apps/mobile/src/update/useCanaryChannelGate.ts b/apps/mobile/src/update/useCanaryChannelGate.tsdeleted file mode 100644index 912b9f23d7..0000000000--- a/apps/mobile/src/update/useCanaryChannelGate.ts+++ /dev/null@@ -1,44 +0,0 @@-import { useEffect, useState } from 'react';--import {- hydrateCanaryChannel,- isCanaryChannel,- subscribeCanaryChannel,-} from './canaryChannelStore';--export interface CanaryChannelGateState {- ready: boolean;- isCanary: boolean;-}--/** 在所有自建更新请求之前恢复本地 canary 快照。 */-export function useCanaryChannelGate(enabled = true): CanaryChannelGateState {- const [state, setState] = useState<CanaryChannelGateState>(() => (- enabled ? { ready: false, isCanary: false } : { ready: true, isCanary: false }- ));-- useEffect(() => {- if (!enabled) {- setState({ ready: true, isCanary: false });- return undefined;- }- let cancelled = false;- let hydrated = false;- const syncFromStore = () => {- if (!cancelled && hydrated) {- setState({ ready: true, isCanary: isCanaryChannel() });- }- };- const unsubscribe = subscribeCanaryChannel(syncFromStore);- void hydrateCanaryChannel().then((isCanary) => {- hydrated = true;- if (!cancelled) setState({ ready: true, isCanary });- });- return () => {- cancelled = true;- unsubscribe();- };- }, [enabled]);-- return state;-}diff --git a/apps/mobile/src/update/useForcedUpdateRecheck.ts b/apps/mobile/src/update/useForcedUpdateRecheck.tsindex 43bd51933a..a95cacd285 100644--- a/apps/mobile/src/update/useForcedUpdateRecheck.ts+++ b/apps/mobile/src/update/useForcedUpdateRecheck.ts@@ -16,12 +16,20 @@ import {getForcedUpdateRevision,getForcedUpdateTarget,} from './forcedUpdateStore';-import { isCanaryChannel } from './canaryChannelStore';+import { resolveUpdateChannelForDevice } from './canaryChannelStore';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';/** 定时敲门间隔;真实请求频率仍由核对器内部节流决定(默认 30s)。 */const RECHECK_TICK_MS = 30_000;-export function useForcedUpdateRecheck(isCanary = isCanaryChannel()): void {+export function useForcedUpdateRecheck(+ channel: UpdateChannel = resolveUpdateChannelForDevice(),+): void {+ // 通道正确性不变量:强更阻断屏在业务树之外、channel gate(useUpdateChannelGate)+ // 不挂载;但 canary/beta 两个 store 是模块级单例,强更只会在它们 hydrate 之后才被+ // 检测到(_layout.tsx 的 RootAfterEndpoints → useUpdateChannelGate 先于+ // useBundleUpdatePrompt/useResumeUpdateCheck 触发 enterForcedUpdate)。因此这里的+ // resolveUpdateChannelForDevice() 读到的必是已 hydrate 的真实通道,不会回落 release。useEffect(() => {let current = true;const rechecker = createForcedUpdateRechecker({@@ -29,7 +37,7 @@ export function useForcedUpdateRecheck(isCanary = isCanaryChannel()): void {Platform.OS === 'android' ? 'android' : 'ios',undefined,undefined,- isCanary,+ channel,),getCurrentRuntimeVersion: () => Updates.runtimeVersion,// 与 useBundleUpdatePrompt 同口径:强更解除也按原生真值比,热更后不漂移。@@ -66,5 +74,5 @@ export function useForcedUpdateRecheck(isCanary = isCanaryChannel()): void {subscription.remove();clearInterval(timer);};- }, [isCanary]);+ }, [channel]);}diff --git a/apps/mobile/src/update/useResumeUpdateCheck.ts b/apps/mobile/src/update/useResumeUpdateCheck.tsindex 8a49f7c555..c111e75363 100644--- a/apps/mobile/src/update/useResumeUpdateCheck.ts+++ b/apps/mobile/src/update/useResumeUpdateCheck.ts@@ -18,9 +18,12 @@ import { shouldCheckBundleUpdate } from './bundleUpdate';import { fetchLatestRelease } from './fetchLatestRelease';import { createResumeUpdateChecker } from './resumeUpdateCheck';import { promptBundleUpdate } from './useBundleUpdatePrompt';-import { isCanaryChannel } from './canaryChannelStore';+import { resolveUpdateChannelForDevice } from './canaryChannelStore';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';-export function useResumeUpdateCheck(isCanary = isCanaryChannel()): void {+export function useResumeUpdateCheck(+ channel: UpdateChannel = resolveUpdateChannelForDevice(),+): void {const bundleCheckEnabled = shouldCheckBundleUpdate({isSelfHosted: IS_OTA_SELFHOST,isReviewMode: REVIEW_MODE,@@ -41,7 +44,7 @@ export function useResumeUpdateCheck(isCanary = isCanaryChannel()): void {Platform.OS === 'android' ? 'android' : 'ios',undefined,undefined,- isCanary,+ channel,),getCurrentRuntimeVersion: () => Updates.runtimeVersion,// 与 useBundleUpdatePrompt / useForcedUpdateRecheck 同口径:强更比较按原生真值,热更后不漂移。@@ -58,5 +61,5 @@ export function useResumeUpdateCheck(isCanary = isCanaryChannel()): void {current = false;subscription.remove();};- }, [bundleCheckEnabled, isCanary]);+ }, [bundleCheckEnabled, channel]);}diff --git a/apps/mobile/src/update/useStartupOtaGate.ts b/apps/mobile/src/update/useStartupOtaGate.tsindex 6943c17e09..8df0cebab8 100644--- a/apps/mobile/src/update/useStartupOtaGate.ts+++ b/apps/mobile/src/update/useStartupOtaGate.ts@@ -11,6 +11,7 @@ import {type StartupOtaOutcome,} from './startupOtaUpdate';import { updateChannelRequestHeaders } from './canaryChannelStore';+import type { UpdateChannel } from '@cindy/maker-shared/update-channel';import {clearOtaReloadGuardIfLaunched,readOtaReloadGuard,@@ -49,7 +50,7 @@ function logStartupOtaLaunch(outcome: StartupOtaOutcome): void {);}-export function useStartupOtaGate(isCanary = false): boolean {+export function useStartupOtaGate(channel: UpdateChannel = 'release'): boolean {// 仅自建变体 + 非 dev + expo-updates 运行时可用才走热更门;其余一律直接放行。// 审核模式(清单 review 送审版本号命中当前二进制版本)本门关闭:启动不走 JS// 显式 check→fetch→reload,直接进主界面(expo-updates 原生层的后台静默检查是@@ -59,7 +60,7 @@ export function useStartupOtaGate(isCanary = false): boolean {const enabled = IS_OTA_SELFHOST && !__DEV__ && Updates.isEnabled && !REVIEW_MODE;const [ready, setReady] = useState(!enabled);const started = useRef(false);- const configuredChannelRef = useRef<boolean | null>(null);+ const configuredChannelRef = useRef<UpdateChannel | null>(null);const configureUpdateUrl = useCallback(() => {if (!OTA_SERVER_BASE_URL) {@@ -67,24 +68,24 @@ export function useStartupOtaGate(isCanary = false): boolean {}Updates.setUpdateURLAndRequestHeadersOverride({updateUrl: `${OTA_SERVER_BASE_URL}/manifest`,- requestHeaders: updateChannelRequestHeaders(isCanary),+ requestHeaders: updateChannelRequestHeaders(channel),});- configuredChannelRef.current = isCanary;- }, [isCanary]);+ configuredChannelRef.current = channel;+ }, [channel]);// feature-flags 在登录/切账号后可能更新 channel;启动检查只跑一次,但// expo-updates 仍必须马上切换 request header,否则本进程会把下一个账号// 的请求发到上一个账号的 canary/stable 指针。stable 的空 header 也会// 覆盖掉之前的 canary header。useEffect(() => {- if (!enabled || configuredChannelRef.current === isCanary) return;+ if (!enabled || configuredChannelRef.current === channel) return;try {configureUpdateUrl();} catch {// 真正的启动检查会把配置异常按 fail-open 处理;这里仅提前同步配置,// 失败不能阻断主界面或后续重试。}- }, [configureUpdateUrl, enabled, isCanary]);+ }, [configureUpdateUrl, enabled, channel]);useEffect(() => {if (!enabled || started.current) return;diff --git a/apps/mobile/src/update/useUpdateChannelGate.ts b/apps/mobile/src/update/useUpdateChannelGate.tsnew file mode 100644index 0000000000..0237b11d5e--- /dev/null+++ b/apps/mobile/src/update/useUpdateChannelGate.ts@@ -0,0 +1,57 @@+import { useEffect, useState } from 'react';++import type { UpdateChannel } from '@cindy/maker-shared/update-channel';++import {+ hydrateCanaryChannel,+ resolveUpdateChannelForDevice,+ subscribeCanaryChannel,+} from './canaryChannelStore';+import { hydrateBetaChannel, subscribeBetaChannel } from './betaChannelStore';++export interface UpdateChannelGateState {+ ready: boolean;+ channel: UpdateChannel;+}++/**+ * 在所有自建更新请求之前恢复本地发布通道快照(canary 账号级 + beta 设备级)。+ * 组合结果按 resolveUpdateChannelForDevice 收敛为 canary > beta > release;+ * 读取完成前 ready=false,调用方不发任何 /manifest 或 /latest 请求。+ */+export function useUpdateChannelGate(enabled = true): UpdateChannelGateState {+ const [state, setState] = useState<UpdateChannelGateState>(() => (+ enabled+ ? { ready: false, channel: 'release' }+ : { ready: true, channel: 'release' }+ ));++ useEffect(() => {+ if (!enabled) {+ setState({ ready: true, channel: 'release' });+ return undefined;+ }+ let cancelled = false;+ let hydrated = false;+ const syncFromStore = () => {+ if (!cancelled && hydrated) {+ setState({ ready: true, channel: resolveUpdateChannelForDevice() });+ }+ };+ const unsubscribeCanary = subscribeCanaryChannel(syncFromStore);+ const unsubscribeBeta = subscribeBetaChannel(syncFromStore);+ void Promise.all([hydrateCanaryChannel(), hydrateBetaChannel()]).then(() => {+ hydrated = true;+ if (!cancelled) {+ setState({ ready: true, channel: resolveUpdateChannelForDevice() });+ }+ });+ return () => {+ cancelled = true;+ unsubscribeCanary();+ unsubscribeBeta();+ };+ }, [enabled]);++ return state;+}diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex ac81555324..d497346663 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -62,6 +62,7 @@"./thinking-text": "./src/thinkingText.ts","./turn-continuation": "./src/turnContinuation.ts","./tool-use-descriptor": "./src/toolUseDescriptor.ts",+ "./update-channel": "./src/updateChannel.ts","./usage-format": "./src/usageFormat.ts","./work-activity-projection": "./src/workActivityProjection.ts","./worktree-paths": "./src/worktreePaths.ts",diff --git a/packages/maker-shared/src/__tests__/updateChannel.test.ts b/packages/maker-shared/src/__tests__/updateChannel.test.tsnew file mode 100644index 0000000000..c7668ebe18--- /dev/null+++ b/packages/maker-shared/src/__tests__/updateChannel.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';++import { resolveUpdateChannel } from '../updateChannel.js';++describe('resolveUpdateChannel', () => {+ it('canary 优先于 beta 与 release', () => {+ expect(resolveUpdateChannel(true, true)).toBe('canary');+ expect(resolveUpdateChannel(true, false)).toBe('canary');+ });++ it('canary 不生效时才看 beta', () => {+ expect(resolveUpdateChannel(false, true)).toBe('beta');+ });++ it('两者都不生效走 release', () => {+ expect(resolveUpdateChannel(false, false)).toBe('release');+ });+});diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.tsindex 4c3505c764..3fd2a0f1fd 100644--- a/packages/maker-shared/src/index.ts+++ b/packages/maker-shared/src/index.ts@@ -47,5 +47,6 @@ export * from './systemCard.js';export * from './toolUseDescriptor.js';export * from './thinkingText.js';export * from './turnContinuation.js';+export * from './updateChannel.js';export * from './workActivityProjection.js';export * from './worktreePaths.js';diff --git a/packages/maker-shared/src/updateChannel.ts b/packages/maker-shared/src/updateChannel.tsnew file mode 100644index 0000000000..f40a65c117--- /dev/null+++ b/packages/maker-shared/src/updateChannel.ts@@ -0,0 +1,21 @@+/**+ * 客户端更新通道三态(2026-08 新增 beta 测试渠道)。+ *+ * 与 canary 不同:canary 是**账号级、服务端下发**的灰度标记(feature-flags →+ * 本地持久化 → 登出清);beta 是**设备级、客户端本地开关**(设置页开关,登出不清)。+ * 两者来源与生命周期不同,但最终都收敛成同一个发布通道选择。+ *+ * 优先级固定:canary > beta > release。canary 命中时完全忽略 beta(避免 beta 开关+ * 把灰度用户从 canary 指针切走),canary 不生效才看 beta,都不生效走 release。+ *+ * 桌面/手机共用这一判定;消费点只拿最终 channel,不再各自写 if-else。+ */++export type UpdateChannel = 'canary' | 'beta' | 'release';++/** 优先级收敛:canary > beta > release。 */+export function resolveUpdateChannel(isCanary: boolean, isBeta: boolean): UpdateChannel {+ if (isCanary) return 'canary';+ if (isBeta) return 'beta';+ return 'release';+}