Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(update): default-enable beta for xd org on login restore

guyong2351bf4bd859
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index 8779d0a1da..241cddd45a 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -298,16 +298,26 @@ describe('auth login-flow reset', () => {
it('synchronizes canary flags on every path that establishes a new auth identity', () => {
expect(source).not.toContain('canaryFlagStore.sync(false)');
expect(source.match(/scheduleCanaryFlagSync\(\{/g)).toHaveLength(3);
+ expect(source.match(/scheduleXdOrgBetaDefault\(\{/g)).toHaveLength(3);
expect(source).toContain("getClientEndpoint('oauthBrokerApiBaseUrl')");
expect(source).toContain("apiFetch('/api/user/feature-flags'");
const syncStart = source.indexOf('function scheduleCanaryFlagSync(');
- const syncEnd = source.indexOf('\n}\n\n/**\n * 冷启动流程的进程内去重', syncStart);
+ const syncEnd = source.indexOf('\n}\n\n/**\n * 登录态落地后为 xd 组织补一次设备级 beta 默认值', syncStart);
expect(syncEnd).toBeGreaterThan(syncStart);
const syncBody = source.slice(syncStart, syncEnd);
expect(syncBody).toContain("if (outcome.kind === 'synced')");
expect(syncBody).toContain('notifyRenderer();');
+ const betaStart = source.indexOf('function scheduleXdOrgBetaDefault(');
+ const betaEnd = source.indexOf('\n}\n\n/**\n * 冷启动流程的进程内去重', betaStart);
+ expect(betaEnd).toBeGreaterThan(betaStart);
+ const betaBody = source.slice(betaStart, betaEnd);
+ expect(betaBody).toContain('if (isPassiveSharedUserDataInstance()) return;');
+ expect(betaBody).toContain('decodeAccessTokenOrgSlug(accessToken)');
+ expect(betaBody).toContain('enableUncustomizedBetaChannel()');
+ expect(source).not.toContain('relaunchForChannelChange');
+
const clearIntegrationsStart = source.indexOf('async function clearPerAccountIntegrations(');
const clearIntegrationsEnd = source.indexOf('\n}', clearIntegrationsStart);
expect(source.slice(clearIntegrationsStart, clearIntegrationsEnd)).not.toContain(
diff --git a/apps/desktop/src/main/__tests__/updateChannelStore.test.ts b/apps/desktop/src/main/__tests__/updateChannelStore.test.ts
new file mode 100644
index 0000000000..edc55eb7d4
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/updateChannelStore.test.ts
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+const appGetPath = vi.fn();
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: appGetPath,
+ },
+}));
+
+vi.mock('../maker-host/logger-adapter.js', () => ({
+ desktopMakerLogger: {
+ child: () => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ },
+}));
+
+let tempDir: string;
+
+async function loadStore() {
+ vi.resetModules();
+ return import('../updateChannelStore');
+}
+
+beforeEach(() => {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-update-channel-'));
+ appGetPath.mockImplementation((name: string) => {
+ if (name === 'userData') return tempDir;
+ return tempDir;
+ });
+});
+
+afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+});
+
+describe('tryEnableUncustomizedBeta', () => {
+ it('writes enableBeta=true when the device has never customized the switch', async () => {
+ const store = await loadStore();
+
+ expect(store.readUpdateChannelSettingsState()).toMatchObject({
+ value: { enableBeta: false },
+ isCustomized: false,
+ });
+ expect(store.tryEnableUncustomizedBeta()).toBe(true);
+ expect(store.readUpdateChannelSettingsState()).toMatchObject({
+ value: { enableBeta: true },
+ isCustomized: true,
+ });
+ });
+
+ it('does not reopen beta after the user turned it off', async () => {
+ const store = await loadStore();
+ store.writeEnableBeta(true);
+ store.writeEnableBeta(false);
+
+ expect(store.readUpdateChannelSettingsState()).toMatchObject({
+ value: { enableBeta: false },
+ isCustomized: true,
+ });
+ expect(store.tryEnableUncustomizedBeta()).toBe(false);
+ expect(store.readUpdateChannelSettings()).toEqual({ enableBeta: false });
+ });
+
+ it('keeps a never-enabled opt-out as customized', async () => {
+ const store = await loadStore();
+ store.writeEnableBeta(false);
+
+ expect(store.readUpdateChannelSettingsState()).toMatchObject({
+ value: { enableBeta: false },
+ isCustomized: true,
+ });
+ expect(store.tryEnableUncustomizedBeta()).toBe(false);
+ });
+
+ it('is a no-op when beta is already on', async () => {
+ const store = await loadStore();
+ store.writeEnableBeta(true);
+
+ expect(store.tryEnableUncustomizedBeta()).toBe(false);
+ expect(store.readUpdateChannelSettings()).toEqual({ enableBeta: true });
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts b/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts
new file mode 100644
index 0000000000..7e8d8c9b3d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts
@@ -0,0 +1,165 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ isXdOrgUser,
+ maybeEnableXdOrgBetaDefault,
+ type XdOrgBetaDefaultDeps,
+ type XdOrgBetaDefaultRequest,
+ type XdOrgBetaUser,
+} from '../xdOrgBetaDefault';
+
+const REQUEST: XdOrgBetaDefaultRequest = {
+ expectedAuthEpoch: 7,
+ expectedUserId: 'user-1',
+ user: {
+ membershipKind: 'org',
+ orgSlug: 'xd',
+ orgName: '心动网络',
+ },
+};
+
+function user(overrides: Partial<XdOrgBetaUser> = {}): XdOrgBetaUser {
+ return {
+ membershipKind: 'org',
+ orgSlug: 'xd',
+ orgName: '心动网络',
+ ...overrides,
+ };
+}
+
+function makeDeps(
+ overrides: Partial<{
+ authEpoch: number;
+ userId: string | null;
+ enableBeta: boolean;
+ isCustomized: boolean;
+ available: boolean;
+ probeThrows: boolean;
+ }> = {},
+): XdOrgBetaDefaultDeps & { enableBeta: ReturnType<typeof vi.fn>; probeBetaManifest: ReturnType<typeof vi.fn> } {
+ return {
+ readCurrentAuthIdentity: vi.fn(() => ({
+ authEpoch: overrides.authEpoch ?? REQUEST.expectedAuthEpoch,
+ userId: overrides.userId === undefined ? REQUEST.expectedUserId : overrides.userId,
+ })),
+ readChannelState: vi.fn(() => ({
+ enableBeta: overrides.enableBeta === true,
+ isCustomized: overrides.isCustomized === true,
+ })),
+ probeBetaManifest: overrides.probeThrows
+ ? vi.fn().mockRejectedValue(new Error('offline'))
+ : vi.fn().mockResolvedValue(overrides.available !== false),
+ enableBeta: vi.fn(),
+ };
+}
+
+describe('isXdOrgUser', () => {
+ it('allows xd org members by orgSlug', () => {
+ expect(isXdOrgUser(user({ orgSlug: 'xd', orgName: '心动网络' }))).toBe(true);
+ });
+
+ it('denies non-xd slugs even when the display name looks like xd', () => {
+ expect(isXdOrgUser(user({ orgSlug: 'disco-corp', orgName: '心动网络' }))).toBe(false);
+ expect(isXdOrgUser(user({ orgSlug: 'xd-partner', orgName: 'xd' }))).toBe(false);
+ });
+
+ it('falls back to orgName only when orgSlug is missing', () => {
+ expect(isXdOrgUser(user({ orgSlug: null, orgName: 'xd' }))).toBe(true);
+ expect(isXdOrgUser(user({ orgSlug: null, orgName: ' XD ' }))).toBe(true);
+ expect(isXdOrgUser(user({ orgSlug: null, orgName: '心动网络' }))).toBe(true);
+ expect(isXdOrgUser(user({ orgSlug: null, orgName: 'Disco Corp' }))).toBe(false);
+ });
+
+ it('denies personal accounts and missing login state', () => {
+ expect(isXdOrgUser(user({ membershipKind: 'personal', orgSlug: 'xd' }))).toBe(false);
+ expect(isXdOrgUser(null)).toBe(false);
+ });
+});
+
+describe('maybeEnableXdOrgBetaDefault', () => {
+ it('enables beta for an unused xd-org device after the probe succeeds', async () => {
+ const deps = makeDeps();
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({ kind: 'enabled' });
+ expect(deps.probeBetaManifest).toHaveBeenCalledOnce();
+ expect(deps.enableBeta).toHaveBeenCalledOnce();
+ });
+
+ it('does not reopen beta after the user customized the switch off', async () => {
+ const deps = makeDeps({ isCustomized: true, enableBeta: false });
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({
+ kind: 'skipped',
+ reason: 'user-customized',
+ });
+ expect(deps.probeBetaManifest).not.toHaveBeenCalled();
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it('skips non-xd accounts without probing', async () => {
+ const deps = makeDeps();
+
+ await expect(
+ maybeEnableXdOrgBetaDefault({ ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) }, deps),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'not-xd-org' });
+ expect(deps.probeBetaManifest).not.toHaveBeenCalled();
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it('skips when beta is already on', async () => {
+ const deps = makeDeps({ enableBeta: true, isCustomized: true });
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({
+ kind: 'skipped',
+ reason: 'already-enabled',
+ });
+ expect(deps.probeBetaManifest).not.toHaveBeenCalled();
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { available: false },
+ { probeThrows: true },
+ ])('skips when the beta manifest is unavailable: %j', async (overrides) => {
+ const deps = makeDeps(overrides);
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({
+ kind: 'skipped',
+ reason: 'beta-unavailable',
+ });
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { authEpoch: REQUEST.expectedAuthEpoch + 1, userId: REQUEST.expectedUserId },
+ { authEpoch: REQUEST.expectedAuthEpoch, userId: 'user-2' },
+ { authEpoch: REQUEST.expectedAuthEpoch, userId: null },
+ ])('discards the write after auth changes: %j', async (current) => {
+ const deps = makeDeps(current);
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({
+ kind: 'skipped',
+ reason: 'stale-auth',
+ });
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it('discards a late probe success after logout or account switch', async () => {
+ const deps = makeDeps();
+ let identity = {
+ authEpoch: REQUEST.expectedAuthEpoch,
+ userId: REQUEST.expectedUserId as string | null,
+ };
+ deps.readCurrentAuthIdentity = vi.fn(() => identity);
+ vi.mocked(deps.probeBetaManifest).mockImplementation(async () => {
+ identity = { authEpoch: REQUEST.expectedAuthEpoch + 1, userId: 'user-2' };
+ return true;
+ });
+
+ await expect(maybeEnableXdOrgBetaDefault(REQUEST, deps)).resolves.toEqual({
+ kind: 'skipped',
+ reason: 'stale-auth',
+ });
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index eef5596887..91124f9c37 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -41,7 +41,9 @@ import {
type ProviderConfig,
type SocialProvider,
} from '@cindy/auth-client';
-import { readReloginFlag, clearReloginFlag } from './updateService';
+import { readReloginFlag, clearReloginFlag, enableUncustomizedBetaChannel } from './updateService';
+import { probeBetaManifest } from './manifestService';
+import { readUpdateChannelSettingsState } from './updateChannelStore';
import * as canaryFlagStore from './canaryFlagStore';
import { decodeAccessTokenOrgSlug } from './authTokenClaims';
import { getProviderSecretStore } from './secrets/providerSecretStore.js';
@@ -55,6 +57,7 @@ import {
} from './authRefreshFailure';
import { awaitWithStartupTimeout } from './authStartupGate';
import { syncCanaryFlagAfterAuth } from './canaryFlagSync';
+import { maybeEnableXdOrgBetaDefault } from './xdOrgBetaDefault';
import { canRestoreAuthSessionForMembership } from './authRealmPolicy';
import {
createAuthBrowserAuthorizationSlot,
@@ -1437,6 +1440,63 @@ function scheduleCanaryFlagSync(input: {
});
}
+/**
+ * 登录态落地后为 xd 组织补一次设备级 beta 默认值,不阻塞进主界面。
+ *
+ * expectedAuthEpoch + expectedUserId 防止探测完成时已经登出 / 换号。
+ * 用户手动关过(isCustomized)后不再打开;probe 失败也不写盘,下次登录再试。
+ */
+function scheduleXdOrgBetaDefault(input: {
+ expectedAuthEpoch: number;
+ expectedUserId: string;
+}): void {
+ if (isPassiveSharedUserDataInstance()) return;
+ const user = currentUser;
+ if (!user) return;
+ void maybeEnableXdOrgBetaDefault(
+ {
+ expectedAuthEpoch: input.expectedAuthEpoch,
+ expectedUserId: input.expectedUserId,
+ user: {
+ membershipKind: user.membershipKind,
+ orgName: user.orgName,
+ orgSlug: decodeAccessTokenOrgSlug(accessToken),
+ },
+ },
+ {
+ readCurrentAuthIdentity: () => ({
+ authEpoch: authStateEpoch,
+ userId: currentUser?.id ?? null,
+ }),
+ readChannelState: () => {
+ const state = readUpdateChannelSettingsState();
+ return {
+ enableBeta: state.value.enableBeta,
+ isCustomized: state.isCustomized,
+ };
+ },
+ probeBetaManifest,
+ enableBeta: () => {
+ enableUncustomizedBetaChannel();
+ },
+ },
+ )
+ .then((outcome) => {
+ if (outcome.kind === 'enabled') {
+ log.info('xd org beta channel default enabled');
+ return;
+ }
+ if (outcome.reason === 'stale-auth') {
+ log.debug('discarded stale xd org beta default');
+ return;
+ }
+ log.debug('xd org beta channel default skipped: reason=%s', outcome.reason);
+ })
+ .catch((err) => {
+ log.error('xd org beta channel default threw unexpectedly', err);
+ });
+}
+
/**
* 冷启动流程的进程内去重:主窗超时转后台之后,副窗 / 右侧栏窗口 mount 再调
* initialize() 时复用同一个 in-flight promise(各自套各自的超时),避免两条流程
@@ -2600,6 +2660,10 @@ async function runColdStartRefreshFlow(
expectedAuthEpoch: epochAtStart,
expectedUserId: refreshData.membership.id,
});
+ scheduleXdOrgBetaDefault({
+ expectedAuthEpoch: epochAtStart,
+ expectedUserId: refreshData.membership.id,
+ });
scheduleRefresh(refreshData.accessToken);
// XD / Mivo key 均为本地 only,不再在冷启动从服务器同步到本地。
// 账号边界对账:换账号则清掉上一个账号留在本机的 provider key,同账号保留(不必重填)。
@@ -2770,6 +2834,10 @@ async function completeLogin(
expectedAuthEpoch: loginEpoch,
expectedUserId: nextUser.id,
});
+ scheduleXdOrgBetaDefault({
+ expectedAuthEpoch: loginEpoch,
+ expectedUserId: nextUser.id,
+ });
scheduleRefresh(outcome.accessToken);
getProviderSecretStore().reconcileOwner(outcome.membership.id);
pendingLoginTicket = null;
@@ -3369,6 +3437,10 @@ export async function refresh(): Promise<boolean> {
expectedAuthEpoch: refreshEpoch,
expectedUserId: nextUser.id,
});
+ scheduleXdOrgBetaDefault({
+ expectedAuthEpoch: refreshEpoch,
+ expectedUserId: nextUser.id,
+ });
scheduleRefresh(data.accessToken);
notifyRenderer();
if (previousUserId !== nextUser.id || authRealmChanged) {
diff --git a/apps/desktop/src/main/updateChannelStore.ts b/apps/desktop/src/main/updateChannelStore.ts
index 4063929279..f6ee7fdad9 100644
--- a/apps/desktop/src/main/updateChannelStore.ts
+++ b/apps/desktop/src/main/updateChannelStore.ts
@@ -10,6 +10,8 @@
* 所以这里用 createOverrideSettingsFile(与 auto-update-settings 同一套
* override 语义:默认值 + 用户 override、恢复默认只删 override),而不是仿
* canaryFlagStore 的裸 JSON。
+ * - xd 组织登录后可由 authManager 在「尚未自定义」时补一次默认打开;用户
+ * 手动关过(isCustomized)后重启 / 重登都不再打开。
*
* 落盘:userData/update-channel-settings.json,字段 { enableBeta: boolean }。
* 默认关闭。manifestService.fetchManifest() 用 resolveUpdateChannel 把本开关与
@@ -65,10 +67,26 @@ export function readUpdateChannelSettingsState(): OverrideSettingsState<UpdateCh
}
export function writeEnableBeta(enableBeta: boolean): void {
- store.writePatch({ enableBeta });
+ // 关 beta 的值等于系统默认 false。若不 preserveDefaults,override 会被删掉,
+ // isCustomized 变回 false,xd 组织下次登录又会把开关默认打开,盖掉用户的
+ // 手动关闭。设置页每次拨动都算显式自定义。
+ store.writePatch({ enableBeta }, { preserveDefaults: true });
log.info('beta update channel setting written', { enableBeta });
}
+/**
+ * 仅在用户从没改过这个开关时打开 beta。
+ * 给 xd 组织默认打开用:用户手动关过(isCustomized)后必须保持关。
+ * 返回是否实际写入了 true。
+ */
+export function tryEnableUncustomizedBeta(): boolean {
+ const state = store.readState();
+ if (state.value.enableBeta || state.isCustomized) return false;
+ store.writePatch({ enableBeta: true });
+ log.info('beta update channel setting written', { enableBeta: true, source: 'xd-org-default' });
+ return true;
+}
+
export function resetUpdateChannelSettings(): UpdateChannelSettings {
return store.reset();
}
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index 7eb1eba8b7..20fbd817fe 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -44,6 +44,7 @@ import {
readUpdateChannelSettings,
readUpdateChannelSettingsState,
resetUpdateChannelSettings,
+ tryEnableUncustomizedBeta,
writeEnableBeta,
} from './updateChannelStore';
import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';
@@ -1470,6 +1471,20 @@ export function initUpdateService(): void {
log.info('Initialized — first check in 10s, polling every 30min');
}
+/**
+ * 登录态落地后给尚未自定义过开关的设备打开 beta。
+ * 渠道从关变开时作废已 staged 的旧渠道补丁,与设置页手动打开同一口径。
+ * 不 relaunch:本次进程继续走当前通道,下次冷启动 / 用户自行重启再生效。
+ */
+export function enableUncustomizedBetaChannel(): boolean {
+ const wasBeta = readUpdateChannelSettings().enableBeta;
+ const wrote = tryEnableUncustomizedBeta();
+ if (wrote && !wasBeta) {
+ clearStagedPatch();
+ }
+ return wrote;
+}
+
export function stopUpdateService(): void {
if (pollTimer) {
clearInterval(pollTimer);
diff --git a/apps/desktop/src/main/xdOrgBetaDefault.ts b/apps/desktop/src/main/xdOrgBetaDefault.ts
new file mode 100644
index 0000000000..33386a92fe
--- /dev/null
+++ b/apps/desktop/src/main/xdOrgBetaDefault.ts
@@ -0,0 +1,106 @@
+/**
+ * xdOrgBetaDefault — 心动 / xd 组织的 beta 测试渠道默认打开策略。
+ *
+ * beta 本身是设备级本地开关(update-channel-settings.json,登出不清)。
+ * 这里只在 cloud 登录态落地后补一次默认值:
+ * - 仅 xd 组织账号;
+ * - 用户从没改过这个开关(isCustomized === false);
+ * - 当前仍是关的;
+ * - CDN 上 beta manifest 可达。
+ *
+ * 用户手动关掉后 isCustomized 为 true,重启 / 重登都不再打开。
+ * 真正的发布通道切换仍留给下次 fetchManifest / 用户自行重启,这里不 relaunch。
+ */
+
+export const XD_ORG_SLUG = 'xd';
+
+const XD_ORG_NAME_FALLBACKS = new Set(['xd', '心动网络']);
+
+export interface XdOrgBetaUser {
+ membershipKind: 'personal' | 'org';
+ orgSlug: string | null;
+ orgName: string | null;
+}
+
+export interface XdOrgBetaChannelState {
+ enableBeta: boolean;
+ isCustomized: boolean;
+}
+
+export interface XdOrgBetaDefaultRequest {
+ expectedAuthEpoch: number;
+ expectedUserId: string;
+ user: XdOrgBetaUser;
+}
+
+export interface XdOrgBetaDefaultDeps {
+ readCurrentAuthIdentity(): { authEpoch: number; userId: string | null };
+ readChannelState(): XdOrgBetaChannelState;
+ probeBetaManifest(): Promise<boolean>;
+ enableBeta(): void;
+}
+
+export type XdOrgBetaDefaultOutcome =
+ | { kind: 'enabled' }
+ | {
+ kind: 'skipped';
+ reason:
+ | 'not-xd-org'
+ | 'already-enabled'
+ | 'user-customized'
+ | 'beta-unavailable'
+ | 'stale-auth';
+ };
+
+/** 当前登录用户是否是 xd 组织。orgSlug 优先,旧 token 才回退显示名。 */
+export function isXdOrgUser(user: XdOrgBetaUser | null | undefined): boolean {
+ if (!user || user.membershipKind !== 'org') return false;
+ if (user.orgSlug !== null) return user.orgSlug === XD_ORG_SLUG;
+ const name = user.orgName?.trim().toLocaleLowerCase();
+ return name !== undefined && XD_ORG_NAME_FALLBACKS.has(name);
+}
+
+function isCurrentAuth(request: XdOrgBetaDefaultRequest, deps: XdOrgBetaDefaultDeps): boolean {
+ const current = deps.readCurrentAuthIdentity();
+ return current.authEpoch === request.expectedAuthEpoch && current.userId === request.expectedUserId;
+}
+
+/**
+ * 登录态落地后尝试为 xd 组织打开设备级 beta。
+ * 任何「不应改用户选择 / 身份已变 / CDN 不可达」的情况都 skip,不写盘。
+ */
+export async function maybeEnableXdOrgBetaDefault(
+ request: XdOrgBetaDefaultRequest,
+ deps: XdOrgBetaDefaultDeps,
+): Promise<XdOrgBetaDefaultOutcome> {
+ if (!isXdOrgUser(request.user)) {
+ return { kind: 'skipped', reason: 'not-xd-org' };
+ }
+ if (!isCurrentAuth(request, deps)) {
+ return { kind: 'skipped', reason: 'stale-auth' };
+ }
+
+ const state = deps.readChannelState();
+ if (state.enableBeta) {
+ return { kind: 'skipped', reason: 'already-enabled' };
+ }
+ if (state.isCustomized) {
+ return { kind: 'skipped', reason: 'user-customized' };
+ }
+
+ let available = false;
+ try {
+ available = await deps.probeBetaManifest();
+ } catch {
+ return { kind: 'skipped', reason: 'beta-unavailable' };
+ }
+ if (!available) {
+ return { kind: 'skipped', reason: 'beta-unavailable' };
+ }
+ if (!isCurrentAuth(request, deps)) {
+ return { kind: 'skipped', reason: 'stale-auth' };
+ }
+
+ deps.enableBeta();
+ return { kind: 'enabled' };
+}