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): 非 xd 企业可用 feature-flag 默认打开 beta (#3051)

fmfsaisai0711c7f3514f
diff --git a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
index 8008a9f3c7..61ba579f28 100644
--- a/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginFlowReset.test.ts
@@ -299,22 +299,31 @@ describe('auth login-flow reset', () => {
expect(source).not.toContain('canaryFlagStore.sync(false)');
expect(source.match(/scheduleCanaryFlagSync\(\{/g)).toHaveLength(3);
expect(source.match(/scheduleXdOrgBetaDefault\(\{/g)).toHaveLength(3);
+ expect(source.match(/scheduleNonXdOrgBetaDefault\(\{/g)).toHaveLength(1);
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 * 登录态落地后为 xd 组织补一次设备级 beta 默认值', 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);
+ const betaEnd = source.indexOf('function scheduleNonXdOrgBetaDefault(', betaStart);
expect(betaEnd).toBeGreaterThan(betaStart);
const betaBody = source.slice(betaStart, betaEnd);
expect(betaBody).toContain('if (isPassiveSharedUserDataInstance()) return;');
expect(betaBody).toContain('decodeAccessTokenOrgSlug(accessToken)');
+ expect(betaBody).not.toContain('shouldAttemptOrgBetaDefault');
+ const nonXdStart = source.indexOf('function scheduleNonXdOrgBetaDefault(');
+ const nonXdEnd = source.indexOf('\n}\n\n/**\n * 冷启动流程的进程内去重', nonXdStart);
+ const nonXdBody = source.slice(nonXdStart, nonXdEnd);
+ expect(nonXdBody).toContain('shouldAttemptOrgBetaDefault');
expect(betaBody).toContain('enableUncustomizedBetaChannel');
expect(betaBody).toContain('authStateEpoch === input.expectedAuthEpoch');
expect(source).not.toContain('relaunchForChannelChange');
diff --git a/apps/desktop/src/main/__tests__/canaryFlagSync.test.ts b/apps/desktop/src/main/__tests__/canaryFlagSync.test.ts
index 99d8f0ef74..8d45acda6c 100644
--- a/apps/desktop/src/main/__tests__/canaryFlagSync.test.ts
+++ b/apps/desktop/src/main/__tests__/canaryFlagSync.test.ts
@@ -38,6 +38,47 @@ describe('syncCanaryFlagAfterAuth', () => {
expect(deps.persistFlag).toHaveBeenCalledWith(isCanary);
});
+ it('extracts an optional beta default without changing canary validation', async () => {
+ const deps = makeDeps({
+ ok: true,
+ status: 200,
+ data: { isCanary: false, defaultEnableBeta: true },
+ });
+ await expect(syncCanaryFlagAfterAuth(REQUEST, deps)).resolves.toEqual({
+ kind: 'synced',
+ isCanary: false,
+ defaultEnableBeta: true,
+ });
+ });
+
+ it.each([false, undefined, 'true', 1])(
+ 'ignores non-true defaultEnableBeta values: %j',
+ async (defaultEnableBeta) => {
+ const deps = makeDeps({
+ ok: true,
+ status: 200,
+ data: { isCanary: false, defaultEnableBeta },
+ });
+ const outcome = await syncCanaryFlagAfterAuth(REQUEST, deps);
+ expect(outcome).toEqual({ kind: 'synced', isCanary: false });
+ expect(outcome).not.toHaveProperty('defaultEnableBeta', true);
+ },
+ );
+
+ it('preserves canary while retaining a valid beta default when isCanary is invalid', async () => {
+ const deps = makeDeps({
+ ok: true,
+ status: 200,
+ data: { isCanary: 'true', defaultEnableBeta: true },
+ });
+ await expect(syncCanaryFlagAfterAuth(REQUEST, deps)).resolves.toEqual({
+ kind: 'preserved',
+ reason: 'invalid-response',
+ status: 200,
+ defaultEnableBeta: true,
+ });
+ });
+
it('preserves the existing flag when the server request fails', async () => {
const deps = makeDeps({
ok: false,
@@ -51,6 +92,12 @@ describe('syncCanaryFlagAfterAuth', () => {
status: 503,
});
expect(deps.persistFlag).not.toHaveBeenCalled();
+ expect(
+ await syncCanaryFlagAfterAuth(
+ REQUEST,
+ makeDeps({ ok: false, status: 503, data: { defaultEnableBeta: true } }),
+ ),
+ ).not.toHaveProperty('defaultEnableBeta');
});
it('preserves the existing flag when the request throws', async () => {
diff --git a/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts b/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts
index cd916efa2d..e0ea2631b4 100644
--- a/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts
+++ b/apps/desktop/src/main/__tests__/xdOrgBetaDefault.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it, vi } from 'vitest';
import {
isXdOrgUser,
maybeEnableXdOrgBetaDefault,
+ maybeEnableNonXdOrgBetaDefault,
+ shouldAttemptOrgBetaDefault,
type XdOrgBetaDefaultDeps,
type XdOrgBetaDefaultRequest,
type XdOrgBetaUser,
@@ -36,7 +38,10 @@ function makeDeps(
available: boolean;
probeThrows: boolean;
}> = {},
-): XdOrgBetaDefaultDeps & { enableBeta: ReturnType<typeof vi.fn>; probeBetaManifest: ReturnType<typeof vi.fn> } {
+): XdOrgBetaDefaultDeps & {
+ enableBeta: ReturnType<typeof vi.fn>;
+ probeBetaManifest: ReturnType<typeof vi.fn>;
+} {
return {
readCurrentAuthIdentity: vi.fn(() => ({
authEpoch: overrides.authEpoch ?? REQUEST.expectedAuthEpoch,
@@ -74,6 +79,42 @@ describe('isXdOrgUser', () => {
expect(isXdOrgUser(user({ membershipKind: 'personal', orgSlug: 'xd' }))).toBe(false);
expect(isXdOrgUser(null)).toBe(false);
});
+
+});
+
+describe('shouldAttemptOrgBetaDefault', () => {
+ it.each([
+ ['false', false],
+ ['missing', undefined],
+ ['string', 'true' as unknown as boolean],
+ ['number', 1 as unknown as boolean],
+ ])('非 xd + %s 走 skip', (_label, defaultEnableBeta) => {
+ expect(
+ shouldAttemptOrgBetaDefault({
+ user: user({ orgSlug: 'other' }),
+ defaultEnableBeta,
+ }),
+ ).toBe('skip');
+ });
+
+ it('非 xd 只有 flag=true 才尝试,xd 无论 flag 都走老逻辑', () => {
+ expect(shouldAttemptOrgBetaDefault({ user: user(), defaultEnableBeta: false })).toBe(
+ 'xd-legacy',
+ );
+ expect(shouldAttemptOrgBetaDefault({ user: user(), defaultEnableBeta: true })).toBe(
+ 'xd-legacy',
+ );
+ expect(
+ shouldAttemptOrgBetaDefault({ user: user({ orgSlug: 'other' }), defaultEnableBeta: true }),
+ ).toBe('flag-enable');
+ expect(shouldAttemptOrgBetaDefault({ user: user() })).toBe('xd-legacy');
+ expect(
+ shouldAttemptOrgBetaDefault({
+ user: user({ membershipKind: 'personal', orgSlug: 'xd' }),
+ defaultEnableBeta: true,
+ }),
+ ).toBe('skip');
+ });
});
describe('maybeEnableXdOrgBetaDefault', () => {
@@ -100,12 +141,63 @@ describe('maybeEnableXdOrgBetaDefault', () => {
const deps = makeDeps();
await expect(
- maybeEnableXdOrgBetaDefault({ ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) }, deps),
+ 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('enables beta for non-xd accounts only when feature flag allows it', async () => {
+ const deps = makeDeps();
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ { ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) },
+ deps,
+ ),
+ ).resolves.toEqual({ kind: 'enabled' });
+ expect(deps.enableBeta).toHaveBeenCalledOnce();
+ });
+
+ it('non-xd rejects customized devices before probing or writing', async () => {
+ const deps = makeDeps({ isCustomized: true });
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ { ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) },
+ deps,
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'user-customized' });
+ expect(deps.probeBetaManifest).not.toHaveBeenCalled();
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it('non-xd rejects stale auth before writing', async () => {
+ const deps = makeDeps({ authEpoch: REQUEST.expectedAuthEpoch + 1 });
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ { ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) },
+ deps,
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'stale-auth' });
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ });
+
+ it.each([{ available: false }, { probeThrows: true }])(
+ 'non-xd rejects unavailable manifest without writing: %j',
+ async (overrides) => {
+ const deps = makeDeps(overrides);
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ { ...REQUEST, user: user({ orgSlug: 'other', orgName: 'Other' }) },
+ deps,
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'beta-unavailable' });
+ expect(deps.enableBeta).not.toHaveBeenCalled();
+ },
+ );
+
it('skips when beta is already on', async () => {
const deps = makeDeps({ enableBeta: true, isCustomized: true });
@@ -117,18 +209,18 @@ describe('maybeEnableXdOrgBetaDefault', () => {
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);
+ 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();
- });
+ 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 },
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index c9783e78d4..cf8a495e2e 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -57,7 +57,11 @@ import {
} from './authRefreshFailure';
import { awaitWithStartupTimeout } from './authStartupGate';
import { syncCanaryFlagAfterAuth } from './canaryFlagSync';
-import { maybeEnableXdOrgBetaDefault } from './xdOrgBetaDefault';
+import {
+ maybeEnableNonXdOrgBetaDefault,
+ maybeEnableXdOrgBetaDefault,
+ shouldAttemptOrgBetaDefault,
+} from './xdOrgBetaDefault';
import { canRestoreAuthSessionForMembership } from './authRealmPolicy';
import {
createAuthBrowserAuthorizationSlot,
@@ -1417,6 +1421,11 @@ function scheduleCanaryFlagSync(input: {
persistFlag: canaryFlagStore.sync,
})
.then((outcome) => {
+ scheduleNonXdOrgBetaDefault({
+ expectedAuthEpoch: input.expectedAuthEpoch,
+ expectedUserId: input.expectedUserId,
+ defaultEnableBeta: outcome.defaultEnableBeta,
+ });
if (outcome.kind === 'synced') {
log.info('canary feature flag synced: isCanary=%s', outcome.isCanary);
// feature-flags 在登录态落地后异步返回;立即推送新快照,让 renderer
@@ -1497,6 +1506,56 @@ function scheduleXdOrgBetaDefault(input: {
});
}
+/** feature-flags 返回后,仅为非 xd 组织补一次设备级 beta 默认值。 */
+function scheduleNonXdOrgBetaDefault(input: {
+ expectedAuthEpoch: number;
+ expectedUserId: string;
+ defaultEnableBeta?: boolean;
+}): void {
+ if (isPassiveSharedUserDataInstance()) return;
+ const user = currentUser;
+ if (!user) return;
+ const request = {
+ expectedAuthEpoch: input.expectedAuthEpoch,
+ expectedUserId: input.expectedUserId,
+ user: {
+ membershipKind: user.membershipKind,
+ orgName: user.orgName,
+ orgSlug: decodeAccessTokenOrgSlug(accessToken),
+ },
+ } as const;
+ if (
+ shouldAttemptOrgBetaDefault({
+ user: request.user,
+ defaultEnableBeta: input.defaultEnableBeta,
+ }) !== 'flag-enable'
+ ) {
+ return;
+ }
+ void maybeEnableNonXdOrgBetaDefault(request, {
+ readCurrentAuthIdentity: () => ({
+ authEpoch: authStateEpoch,
+ userId: currentUser?.id ?? null,
+ }),
+ readChannelState: () => ({
+ enableBeta: readUpdateChannelSettings().enableBeta,
+ isCustomized: isEnableBetaUserCustomized(),
+ }),
+ probeBetaManifest,
+ enableBeta: () =>
+ enableUncustomizedBetaChannel(
+ () =>
+ authStateEpoch === input.expectedAuthEpoch && currentUser?.id === input.expectedUserId,
+ ),
+ })
+ .then((outcome) => {
+ if (outcome.kind === 'enabled') log.info('feature-flag beta channel default enabled');
+ else if (outcome.reason === 'stale-auth') log.debug('discarded stale non-xd beta default');
+ else log.debug('non-xd beta channel default skipped: reason=%s', outcome.reason);
+ })
+ .catch((err) => log.error('non-xd beta channel default threw unexpectedly', err));
+}
+
/**
* 冷启动流程的进程内去重:主窗超时转后台之后,副窗 / 右侧栏窗口 mount 再调
* initialize() 时复用同一个 in-flight promise(各自套各自的超时),避免两条流程
diff --git a/apps/desktop/src/main/canaryFlagSync.ts b/apps/desktop/src/main/canaryFlagSync.ts
index 70a85ffe9f..f8c506467c 100644
--- a/apps/desktop/src/main/canaryFlagSync.ts
+++ b/apps/desktop/src/main/canaryFlagSync.ts
@@ -28,11 +28,12 @@ export interface CanaryFlagSyncDeps {
/** Observable result used by the caller for structured logging. */
export type CanaryFlagSyncOutcome =
- | { kind: 'synced'; isCanary: boolean }
+ | { kind: 'synced'; isCanary: boolean; defaultEnableBeta?: boolean }
| {
kind: 'preserved';
reason: 'request-failed' | 'invalid-response' | 'stale-auth';
status?: number;
+ defaultEnableBeta?: boolean;
};
/**
@@ -59,12 +60,19 @@ export async function syncCanaryFlagAfterAuth(
return { kind: 'preserved', reason: 'request-failed', status: result.status };
}
- const isCanary =
+ const flags =
result.data && typeof result.data === 'object'
- ? (result.data as { isCanary?: unknown }).isCanary
+ ? (result.data as { isCanary?: unknown; defaultEnableBeta?: unknown })
: undefined;
+ const isCanary = flags?.isCanary;
+ const defaultEnableBeta = readOptionalDefaultEnableBeta(flags?.defaultEnableBeta);
if (typeof isCanary !== 'boolean') {
- return { kind: 'preserved', reason: 'invalid-response', status: result.status };
+ return {
+ kind: 'preserved',
+ reason: 'invalid-response',
+ status: result.status,
+ ...defaultEnableBeta,
+ };
}
const current = deps.readCurrentAuthIdentity();
@@ -72,9 +80,15 @@ export async function syncCanaryFlagAfterAuth(
current.authEpoch !== request.expectedAuthEpoch ||
current.userId !== request.expectedUserId
) {
- return { kind: 'preserved', reason: 'stale-auth' };
+ return { kind: 'preserved', reason: 'stale-auth', ...defaultEnableBeta };
}
deps.persistFlag(isCanary);
- return { kind: 'synced', isCanary };
+ return { kind: 'synced', isCanary, ...defaultEnableBeta };
+}
+
+function readOptionalDefaultEnableBeta(
+ value: unknown,
+): { defaultEnableBeta: true } | Record<string, never> {
+ return value === true ? { defaultEnableBeta: true } : {};
}
diff --git a/apps/desktop/src/main/xdOrgBetaDefault.ts b/apps/desktop/src/main/xdOrgBetaDefault.ts
index 4e7d082133..a682101655 100644
--- a/apps/desktop/src/main/xdOrgBetaDefault.ts
+++ b/apps/desktop/src/main/xdOrgBetaDefault.ts
@@ -34,6 +34,8 @@ export interface XdOrgBetaDefaultRequest {
user: XdOrgBetaUser;
}
+export type OrgBetaDefaultDecision = 'xd-legacy' | 'flag-enable' | 'skip';
+
export interface XdOrgBetaDefaultDeps {
readCurrentAuthIdentity(): { authEpoch: number; userId: string | null };
readChannelState(): XdOrgBetaChannelState;
@@ -46,11 +48,7 @@ export type XdOrgBetaDefaultOutcome =
| {
kind: 'skipped';
reason:
- | 'not-xd-org'
- | 'already-enabled'
- | 'user-customized'
- | 'beta-unavailable'
- | 'stale-auth';
+ 'not-xd-org' | 'already-enabled' | 'user-customized' | 'beta-unavailable' | 'stale-auth';
};
/** 当前登录用户是否是 xd 组织。orgSlug 优先,旧 token 才回退显示名。 */
@@ -61,9 +59,23 @@ export function isXdOrgUser(user: XdOrgBetaUser | null | undefined): boolean {
return name !== undefined && XD_ORG_NAME_FALLBACKS.has(name);
}
+/** 先按 xd 身份判定,只有非 xd 才允许 feature flag 打开设备默认值。 */
+export function shouldAttemptOrgBetaDefault(input: {
+ user: XdOrgBetaUser | null | undefined;
+ defaultEnableBeta?: boolean;
+}): OrgBetaDefaultDecision {
+ if (isXdOrgUser(input.user)) return 'xd-legacy';
+ if (input.user?.membershipKind !== 'org' || input.defaultEnableBeta !== true) {
+ return 'skip';
+ }
+ return 'flag-enable';
+}
+
function isCurrentAuth(request: XdOrgBetaDefaultRequest, deps: XdOrgBetaDefaultDeps): boolean {
const current = deps.readCurrentAuthIdentity();
- return current.authEpoch === request.expectedAuthEpoch && current.userId === request.expectedUserId;
+ return (
+ current.authEpoch === request.expectedAuthEpoch && current.userId === request.expectedUserId
+ );
}
/**
@@ -77,17 +89,31 @@ export async function maybeEnableXdOrgBetaDefault(
if (!isXdOrgUser(request.user)) {
return { kind: 'skipped', reason: 'not-xd-org' };
}
+ return maybeEnableBetaDefaultForEligibleUser(request, deps);
+}
+
+/** 为非 xd 组织复用同一套设备默认写盘保护,仅由 feature flag 显式开启。 */
+export async function maybeEnableNonXdOrgBetaDefault(
+ request: XdOrgBetaDefaultRequest,
+ deps: XdOrgBetaDefaultDeps,
+): Promise<XdOrgBetaDefaultOutcome> {
+ if (isXdOrgUser(request.user)) {
+ return { kind: 'skipped', reason: 'not-xd-org' };
+ }
+ return maybeEnableBetaDefaultForEligibleUser(request, deps);
+}
+
+async function maybeEnableBetaDefaultForEligibleUser(
+ request: XdOrgBetaDefaultRequest,
+ deps: XdOrgBetaDefaultDeps,
+): Promise<XdOrgBetaDefaultOutcome> {
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' };
- }
+ if (state.enableBeta) return { kind: 'skipped', reason: 'already-enabled' };
+ if (state.isCustomized) return { kind: 'skipped', reason: 'user-customized' };
let available = false;
try {
@@ -95,12 +121,8 @@ export async function maybeEnableXdOrgBetaDefault(
} 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' };
- }
+ if (!available) return { kind: 'skipped', reason: 'beta-unavailable' };
+ if (!isCurrentAuth(request, deps)) return { kind: 'skipped', reason: 'stale-auth' };
const wrote = await deps.enableBeta();
if (!wrote) {
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 622ca0d619..b54dbc84e5 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -64,7 +64,11 @@ import {
import { syncCanaryChannelAfterAuth } from '@/auth/canaryChannelSync';
import { ensureDeviceId, hasStoredDeviceId } from '@/auth/deviceId';
import { decodeJwtOrgSlug, isAccessTokenExpiring } from '@/auth/jwt';
-import { maybeEnableXdOrgBetaDefault } from '@/auth/xdOrgBetaDefault';
+import {
+ maybeEnableNonXdOrgBetaDefault,
+ maybeEnableXdOrgBetaDefault,
+ shouldAttemptOrgBetaDefault,
+} from '@/auth/xdOrgBetaDefault';
import { getAuthLocale, getLoginLanguage } from '@/auth/loginMessages';
import { acquireNativeSocialCredential } from '@/auth/nativeSocial';
import {
@@ -329,28 +333,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setDeferredSessionRecovery(false);
}, []);
- /** 登录态落地后异步刷新灰度标记;失败保留旧值,迟到响应按 auth generation 丢弃。 */
- const scheduleCanaryChannelSync = useCallback(
- (token: string, expectedAuthGeneration: number) => {
- // EAS/TestFlight 仍走 Expo 官方更新通道,不参与自建线 canary flag 请求;
- // 这样自建灰度新增的状态机不会改变 EAS 登录/发版流程。
- if (!IS_OTA_SELFHOST) return;
- void syncCanaryChannelAfterAuth(
- { token, expectedAuthGeneration },
- {
- fetchFeatureFlags: (accessToken) =>
- apiFetchRaw('/api/user/feature-flags', {
- baseUrl: OAUTH_BROKER_API_BASE_URL,
- token: accessToken,
- }),
- readCurrentAuthGeneration: () => authGenerationRef.current,
- persistFlag: syncCanaryChannel,
- },
- ).catch(() => undefined);
- },
- [],
- );
-
const prepareBetaChannelForCurrentDevice = useCallback((): Promise<string> => {
const existing = betaChannelPreparationRef.current;
if (existing) return existing;
@@ -372,6 +354,25 @@ export function AuthProvider({ children }: { children: ReactNode }) {
return run;
}, []);
+ const orgBetaDefaultDeps = useCallback(
+ (expectedAuthGeneration: number, expectedUserId: string) => ({
+ readCurrentAuthIdentity: () => ({
+ authGeneration: authGenerationRef.current,
+ userId: userRef.current?.id ?? null,
+ }),
+ readChannelState: readBetaChannelState,
+ probeBetaManifest: () =>
+ probeBetaChannel(Platform.OS === 'android' ? 'android' : 'ios'),
+ enableBeta: () =>
+ enableUncustomizedBetaChannel(
+ () =>
+ authGenerationRef.current === expectedAuthGeneration &&
+ userRef.current?.id === expectedUserId,
+ ),
+ }),
+ [],
+ );
+
/** 登录态落地后为 xd 组织尝试打开设备级 beta;不阻塞主界面。 */
const scheduleXdOrgBetaDefault = useCallback(
(token: string, expectedAuthGeneration: number) => {
@@ -391,25 +392,80 @@ export function AuthProvider({ children }: { children: ReactNode }) {
orgName: currentUser.orgName,
},
},
- {
- readCurrentAuthIdentity: () => ({
- authGeneration: authGenerationRef.current,
- userId: userRef.current?.id ?? null,
- }),
- readChannelState: readBetaChannelState,
- probeBetaManifest: () =>
- probeBetaChannel(Platform.OS === 'android' ? 'android' : 'ios'),
- enableBeta: () =>
- enableUncustomizedBetaChannel(
- () =>
- authGenerationRef.current === expectedAuthGeneration &&
- userRef.current?.id === expectedUserId,
- ),
- },
+ orgBetaDefaultDeps(expectedAuthGeneration, expectedUserId),
);
})().catch(() => undefined);
},
- [prepareBetaChannelForCurrentDevice],
+ [orgBetaDefaultDeps, prepareBetaChannelForCurrentDevice],
+ );
+
+ /** feature-flags 返回后,仅为非 xd 组织尝试打开设备级 beta。 */
+ const scheduleNonXdOrgBetaDefault = useCallback(
+ (
+ token: string,
+ expectedAuthGeneration: number,
+ defaultEnableBeta?: boolean,
+ ) => {
+ if (!IS_OTA_SELFHOST || defaultEnableBeta !== true) return;
+ const currentUser = userRef.current;
+ if (!currentUser) return;
+ const expectedUserId = currentUser.id;
+ const request = {
+ expectedAuthGeneration,
+ expectedUserId,
+ user: {
+ membershipKind: currentUser.membershipKind,
+ orgSlug: decodeJwtOrgSlug(token),
+ orgName: currentUser.orgName,
+ },
+ } as const;
+ if (
+ shouldAttemptOrgBetaDefault({
+ user: request.user,
+ defaultEnableBeta,
+ }) !== 'flag-enable'
+ ) {
+ return;
+ }
+ void (async () => {
+ await prepareBetaChannelForCurrentDevice();
+ await maybeEnableNonXdOrgBetaDefault(
+ request,
+ orgBetaDefaultDeps(expectedAuthGeneration, expectedUserId),
+ );
+ })().catch(() => undefined);
+ },
+ [orgBetaDefaultDeps, prepareBetaChannelForCurrentDevice],
+ );
+
+ /** 登录态落地后异步刷新灰度标记;失败保留旧值,迟到响应按 auth generation 丢弃。 */
+ const scheduleCanaryChannelSync = useCallback(
+ (token: string, expectedAuthGeneration: number) => {
+ // EAS/TestFlight 仍走 Expo 官方更新通道,不参与自建线 canary flag 请求;
+ // 这样自建灰度新增的状态机不会改变 EAS 登录/发版流程。
+ if (!IS_OTA_SELFHOST) return;
+ void syncCanaryChannelAfterAuth(
+ { token, expectedAuthGeneration },
+ {
+ fetchFeatureFlags: (accessToken) =>
+ apiFetchRaw('/api/user/feature-flags', {
+ baseUrl: OAUTH_BROKER_API_BASE_URL,
+ token: accessToken,
+ }),
+ readCurrentAuthGeneration: () => authGenerationRef.current,
+ persistFlag: syncCanaryChannel,
+ },
+ )
+ .then((outcome) => {
+ scheduleNonXdOrgBetaDefault(
+ token,
+ expectedAuthGeneration,
+ outcome.defaultEnableBeta,
+ );
+ })
+ .catch(() => undefined);
+ },
+ [scheduleNonXdOrgBetaDefault],
);
const serializeRefreshTokenMutation = useCallback(
diff --git a/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts b/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts
index f1da137873..87500e4d02 100644
--- a/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts
+++ b/apps/mobile/src/auth/__tests__/xdOrgBetaWiring.test.ts
@@ -11,7 +11,7 @@ const source = readFileSync(
describe('AuthContext xd org beta wiring', () => {
it('shares beta migration before cold start or login uses a device id', () => {
const preparation = source.indexOf(
- 'const prepareBetaChannelForCurrentDevice = useCallback',
+ 'const prepareBetaChannelForCurrentDevice',
);
const hasDevice = source.indexOf('await hasStoredDeviceId()', preparation);
const ensureDevice = source.indexOf('await ensureDeviceId()', hasDevice);
@@ -26,7 +26,9 @@ describe('AuthContext xd org beta wiring', () => {
'await prepareBetaChannelForCurrentDevice()',
coldStart + 1,
);
- const readSession = source.indexOf('let storedSession = await readPersistedAuthSession()');
+ const readSession = source.indexOf(
+ 'let storedSession = await readPersistedAuthSession()',
+ );
expect(preparation).toBeGreaterThan(-1);
expect(hasDevice).toBeGreaterThan(-1);
@@ -38,31 +40,51 @@ describe('AuthContext xd org beta wiring', () => {
});
it('waits for device migration before trying the xd default', () => {
- const schedule = source.indexOf('const scheduleXdOrgBetaDefault = useCallback');
+ const schedule = source.indexOf(
+ 'const scheduleXdOrgBetaDefault = useCallback',
+ );
const waitForPreparation = source.indexOf(
'await prepareBetaChannelForCurrentDevice();',
schedule,
);
- const applyDefault = source.indexOf('await maybeEnableXdOrgBetaDefault(', schedule);
+ const applyDefault = source.indexOf(
+ 'await maybeEnableXdOrgBetaDefault(',
+ schedule,
+ );
expect(waitForPreparation).toBeGreaterThan(schedule);
expect(applyDefault).toBeGreaterThan(waitForPreparation);
});
it('schedules the xd default after both login and refresh identity are applied', () => {
- expect(source.match(/scheduleXdOrgBetaDefault\([^)]*generation\);/g)).toHaveLength(2);
+ expect(
+ source.match(/scheduleCanaryChannelSync\([^)]*generation\);/g),
+ ).toHaveLength(2);
+ expect(
+ source.match(/scheduleXdOrgBetaDefault\([^)]*generation\);/g),
+ ).toHaveLength(2);
- const loginApply = source.indexOf('mergeMembershipWithExisting(outcome.membership');
+ const loginApply = source.indexOf(
+ 'mergeMembershipWithExisting(outcome.membership',
+ );
const loginSchedule = source.indexOf(
- 'scheduleXdOrgBetaDefault(outcome.accessToken, generation);',
+ 'scheduleCanaryChannelSync(outcome.accessToken, generation);',
);
expect(loginSchedule).toBeGreaterThan(loginApply);
- const refreshApply = source.indexOf('mergeMembershipWithExisting(pair.membership');
+ const refreshApply = source.indexOf(
+ 'mergeMembershipWithExisting(pair.membership',
+ );
const refreshSchedule = source.indexOf(
- 'scheduleXdOrgBetaDefault(pair.accessToken, generation);',
+ 'scheduleCanaryChannelSync(pair.accessToken, generation);',
);
expect(refreshSchedule).toBeGreaterThan(refreshApply);
+ const canarySync = source.indexOf('syncCanaryChannelAfterAuth(');
+ const canaryThen = source.indexOf(
+ 'scheduleNonXdOrgBetaDefault(',
+ canarySync,
+ );
+ expect(canaryThen).toBeGreaterThan(canarySync);
});
it('rechecks generation and user id before the automatic write', () => {
diff --git a/apps/mobile/src/auth/canaryChannelSync.test.ts b/apps/mobile/src/auth/canaryChannelSync.test.ts
index e73e7781e6..5933e7e905 100644
--- a/apps/mobile/src/auth/canaryChannelSync.test.ts
+++ b/apps/mobile/src/auth/canaryChannelSync.test.ts
@@ -13,28 +13,101 @@ function deps(value: unknown, generation = 3) {
describe('syncCanaryChannelAfterAuth', () => {
it.each([true, false])('合法 isCanary=%s 才持久化', async (isCanary) => {
const d = deps({ isCanary });
- await expect(syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, d))
- .resolves.toEqual({ kind: 'synced', isCanary });
+ await expect(
+ syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, d),
+ ).resolves.toEqual({ kind: 'synced', isCanary });
expect(d.persistFlag).toHaveBeenCalledWith(isCanary);
});
+ it('读取可选 beta 默认标记,且不改变 canary 校验', async () => {
+ const d = deps({ isCanary: false, defaultEnableBeta: true });
+ await expect(
+ syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, d),
+ ).resolves.toEqual({
+ kind: 'synced',
+ isCanary: false,
+ defaultEnableBeta: true,
+ });
+
+ const invalid = deps({ isCanary: 'true', defaultEnableBeta: true });
+ await expect(
+ syncCanaryChannelAfterAuth(
+ { token: 't', expectedAuthGeneration: 3 },
+ invalid,
+ ),
+ ).resolves.toEqual({
+ kind: 'preserved',
+ reason: 'invalid-response',
+ defaultEnableBeta: true,
+ });
+ });
+
+ it.each([false, undefined, 'true', 1])(
+ '非 true 的 defaultEnableBeta 不进入 outcome: %j',
+ async (defaultEnableBeta) => {
+ const outcome = await syncCanaryChannelAfterAuth(
+ { token: 't', expectedAuthGeneration: 3 },
+ deps({ isCanary: false, defaultEnableBeta }),
+ );
+ expect(outcome).toEqual({ kind: 'synced', isCanary: false });
+ expect(outcome).not.toHaveProperty('defaultEnableBeta', true);
+ },
+ );
+
it('请求失败/非法响应保留旧值', async () => {
const failed = deps({});
failed.fetchFeatureFlags.mockRejectedValueOnce(new Error('offline'));
- await expect(syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, failed))
- .resolves.toEqual({ kind: 'preserved', reason: 'request-failed' });
+ await expect(
+ syncCanaryChannelAfterAuth(
+ { token: 't', expectedAuthGeneration: 3 },
+ failed,
+ ),
+ ).resolves.toEqual({ kind: 'preserved', reason: 'request-failed' });
expect(failed.persistFlag).not.toHaveBeenCalled();
+ const failedWithFlag = deps({ defaultEnableBeta: true });
+ failedWithFlag.fetchFeatureFlags.mockRejectedValueOnce(
+ new Error('offline'),
+ );
+ const failedOutcome = await syncCanaryChannelAfterAuth(
+ { token: 't', expectedAuthGeneration: 3 },
+ failedWithFlag,
+ );
+ expect(failedOutcome).toEqual({
+ kind: 'preserved',
+ reason: 'request-failed',
+ });
+ expect(failedOutcome).not.toHaveProperty('defaultEnableBeta');
const invalid = deps({ isCanary: 'true' });
- await expect(syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, invalid))
- .resolves.toEqual({ kind: 'preserved', reason: 'invalid-response' });
+ await expect(
+ syncCanaryChannelAfterAuth(
+ { token: 't', expectedAuthGeneration: 3 },
+ invalid,
+ ),
+ ).resolves.toEqual({ kind: 'preserved', reason: 'invalid-response' });
expect(invalid.persistFlag).not.toHaveBeenCalled();
});
it('登出/换账号后的迟到响应不得覆盖', async () => {
const d = deps({ isCanary: true }, 4);
- await expect(syncCanaryChannelAfterAuth({ token: 'old', expectedAuthGeneration: 3 }, d))
- .resolves.toEqual({ kind: 'preserved', reason: 'stale-auth' });
+ await expect(
+ syncCanaryChannelAfterAuth(
+ { token: 'old', expectedAuthGeneration: 3 },
+ d,
+ ),
+ ).resolves.toEqual({ kind: 'preserved', reason: 'stale-auth' });
expect(d.persistFlag).not.toHaveBeenCalled();
});
+
+ it('canary 落盘失败时仍保留 beta 默认标记供非 xd 调度', async () => {
+ const d = deps({ isCanary: true, defaultEnableBeta: true });
+ d.persistFlag.mockRejectedValueOnce(new Error('storage offline'));
+ await expect(
+ syncCanaryChannelAfterAuth({ token: 't', expectedAuthGeneration: 3 }, d),
+ ).resolves.toEqual({
+ kind: 'preserved',
+ reason: 'persist-failed',
+ defaultEnableBeta: true,
+ });
+ });
});
diff --git a/apps/mobile/src/auth/canaryChannelSync.ts b/apps/mobile/src/auth/canaryChannelSync.ts
index 4097b03160..160cba88ca 100644
--- a/apps/mobile/src/auth/canaryChannelSync.ts
+++ b/apps/mobile/src/auth/canaryChannelSync.ts
@@ -12,8 +12,13 @@ export interface CanarySyncDeps {
}
export type CanarySyncOutcome =
- | { kind: 'synced'; isCanary: boolean }
- | { kind: 'preserved'; reason: 'request-failed' | 'invalid-response' | 'stale-auth' };
+ | { kind: 'synced'; isCanary: boolean; defaultEnableBeta?: boolean }
+ | {
+ kind: 'preserved';
+ reason:
+ 'request-failed' | 'invalid-response' | 'stale-auth' | 'persist-failed';
+ defaultEnableBeta?: boolean;
+ };
/** 请求失败/非法时保留旧值;登出或换账号后的迟到响应不得覆盖新身份。 */
export async function syncCanaryChannelAfterAuth(
@@ -26,15 +31,32 @@ export async function syncCanaryChannelAfterAuth(
} catch {
return { kind: 'preserved', reason: 'request-failed' };
}
- const isCanary = value && typeof value === 'object'
- ? (value as { isCanary?: unknown }).isCanary
- : undefined;
+ const flags =
+ value && typeof value === 'object'
+ ? (value as { isCanary?: unknown; defaultEnableBeta?: unknown })
+ : undefined;
+ const isCanary = flags?.isCanary;
+ const defaultEnableBeta = readOptionalDefaultEnableBeta(flags?.defaultEnableBeta);
if (typeof isCanary !== 'boolean') {
- return { kind: 'preserved', reason: 'invalid-response' };
+ return {
+ kind: 'preserved',
+ reason: 'invalid-response',
+ ...defaultEnableBeta,
+ };
}
if (deps.readCurrentAuthGeneration() !== request.expectedAuthGeneration) {
- return { kind: 'preserved', reason: 'stale-auth' };
+ return { kind: 'preserved', reason: 'stale-auth', ...defaultEnableBeta };
}
- await deps.persistFlag(isCanary);
- return { kind: 'synced', isCanary };
+ try {
+ await deps.persistFlag(isCanary);
+ } catch {
+ return { kind: 'preserved', reason: 'persist-failed', ...defaultEnableBeta };
+ }
+ return { kind: 'synced', isCanary, ...defaultEnableBeta };
+}
+
+function readOptionalDefaultEnableBeta(
+ value: unknown,
+): { defaultEnableBeta: true } | Record<string, never> {
+ return value === true ? { defaultEnableBeta: true } : {};
}
diff --git a/apps/mobile/src/auth/xdOrgBetaDefault.test.ts b/apps/mobile/src/auth/xdOrgBetaDefault.test.ts
index 1e64b0029e..00868ec415 100644
--- a/apps/mobile/src/auth/xdOrgBetaDefault.test.ts
+++ b/apps/mobile/src/auth/xdOrgBetaDefault.test.ts
@@ -1,8 +1,10 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
isXdOrgUser,
maybeEnableXdOrgBetaDefault,
+ maybeEnableNonXdOrgBetaDefault,
+ shouldAttemptOrgBetaDefault,
type XdOrgBetaDefaultDeps,
type XdOrgBetaUser,
} from './xdOrgBetaDefault';
@@ -29,10 +31,128 @@ describe('xd org beta default', () => {
it('orgSlug 是权威身份,只在缺失时回退组织名', () => {
expect(isXdOrgUser(XD_USER)).toBe(true);
expect(isXdOrgUser({ ...XD_USER, orgSlug: 'other' })).toBe(false);
- expect(isXdOrgUser({ ...XD_USER, orgSlug: null, orgName: ' XD ' })).toBe(true);
+ expect(isXdOrgUser({ ...XD_USER, orgSlug: null, orgName: ' XD ' })).toBe(
+ true,
+ );
expect(isXdOrgUser({ ...XD_USER, membershipKind: 'personal' })).toBe(false);
});
+ it('xd 永远走老逻辑,非 xd 只有 flag=true 才尝试', () => {
+ expect(
+ shouldAttemptOrgBetaDefault({ user: XD_USER, defaultEnableBeta: false }),
+ ).toBe('xd-legacy');
+ expect(
+ shouldAttemptOrgBetaDefault({
+ user: { ...XD_USER, orgSlug: 'other' },
+ defaultEnableBeta: true,
+ }),
+ ).toBe('flag-enable');
+ expect(
+ shouldAttemptOrgBetaDefault({ user: { ...XD_USER, orgSlug: 'other' } }),
+ ).toBe('skip');
+ expect(shouldAttemptOrgBetaDefault({ user: XD_USER })).toBe('xd-legacy');
+ expect(
+ shouldAttemptOrgBetaDefault({
+ user: { ...XD_USER, membershipKind: 'personal' },
+ defaultEnableBeta: true,
+ }),
+ ).toBe('skip');
+ });
+
+ it('非 xd 在 feature flag 允许时复用默认写盘路径', async () => {
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ {
+ expectedAuthGeneration: 3,
+ expectedUserId: 'user-1',
+ user: { ...XD_USER, orgSlug: 'other' },
+ },
+ deps(),
+ ),
+ ).resolves.toEqual({ kind: 'enabled' });
+ });
+
+ it.each([
+ ['false', false],
+ ['missing', undefined],
+ ['string', 'true' as unknown as boolean],
+ ['number', 1 as unknown as boolean],
+ ])('非 xd + %s 走 skip', (_label, defaultEnableBeta) => {
+ expect(
+ shouldAttemptOrgBetaDefault({
+ user: { ...XD_USER, orgSlug: 'other' },
+ defaultEnableBeta,
+ }),
+ ).toBe('skip');
+ });
+
+ it('非 xd 已自定义时不 probe、不写盘', async () => {
+ const probeBetaManifest = vi.fn(async () => true);
+ const enableBeta = vi.fn(async () => true);
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ {
+ expectedAuthGeneration: 3,
+ expectedUserId: 'user-1',
+ user: { ...XD_USER, orgSlug: 'other' },
+ },
+ deps({
+ readChannelState: () => ({ enableBeta: false, isCustomized: true }),
+ probeBetaManifest,
+ enableBeta,
+ }),
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'user-customized' });
+ expect(probeBetaManifest).not.toHaveBeenCalled();
+ expect(enableBeta).not.toHaveBeenCalled();
+ });
+
+ it('非 xd stale-auth 时不写盘', async () => {
+ const enableBeta = vi.fn(async () => true);
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ {
+ expectedAuthGeneration: 3,
+ expectedUserId: 'user-1',
+ user: { ...XD_USER, orgSlug: 'other' },
+ },
+ deps({
+ readCurrentAuthIdentity: () => ({
+ authGeneration: 4,
+ userId: 'user-2',
+ }),
+ enableBeta,
+ }),
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'stale-auth' });
+ expect(enableBeta).not.toHaveBeenCalled();
+ });
+
+ it.each([false, 'throw'])(
+ '非 xd manifest 不可用时不写盘: %s',
+ async (mode) => {
+ const probeBetaManifest = vi.fn(
+ mode === 'throw'
+ ? async () => {
+ throw new Error('offline');
+ }
+ : async () => false,
+ );
+ const enableBeta = vi.fn(async () => true);
+ await expect(
+ maybeEnableNonXdOrgBetaDefault(
+ {
+ expectedAuthGeneration: 3,
+ expectedUserId: 'user-1',
+ user: { ...XD_USER, orgSlug: 'other' },
+ },
+ deps({ probeBetaManifest, enableBeta }),
+ ),
+ ).resolves.toEqual({ kind: 'skipped', reason: 'beta-unavailable' });
+ expect(enableBeta).not.toHaveBeenCalled();
+ },
+ );
+
it('当前未自定义的 xd 身份且 beta 可用时开启', async () => {
await expect(
maybeEnableXdOrgBetaDefault(
@@ -46,7 +166,9 @@ describe('xd org beta default', () => {
await expect(
maybeEnableXdOrgBetaDefault(
{ expectedAuthGeneration: 3, expectedUserId: 'user-1', user: XD_USER },
- deps({ readChannelState: () => ({ enableBeta: false, isCustomized: true }) }),
+ deps({
+ readChannelState: () => ({ enableBeta: false, isCustomized: true }),
+ }),
),
).resolves.toEqual({ kind: 'skipped', reason: 'user-customized' });
@@ -54,7 +176,10 @@ describe('xd org beta default', () => {
maybeEnableXdOrgBetaDefault(
{ expectedAuthGeneration: 3, expectedUserId: 'user-1', user: XD_USER },
deps({
- readCurrentAuthIdentity: () => ({ authGeneration: 4, userId: 'user-2' }),
+ readCurrentAuthIdentity: () => ({
+ authGeneration: 4,
+ userId: 'user-2',
+ }),
}),
),
).resolves.toEqual({ kind: 'skipped', reason: 'stale-auth' });
diff --git a/apps/mobile/src/auth/xdOrgBetaDefault.ts b/apps/mobile/src/auth/xdOrgBetaDefault.ts
index a073369e43..8cb454f571 100644
--- a/apps/mobile/src/auth/xdOrgBetaDefault.ts
+++ b/apps/mobile/src/auth/xdOrgBetaDefault.ts
@@ -15,6 +15,8 @@ export interface XdOrgBetaDefaultRequest {
user: XdOrgBetaUser;
}
+export type OrgBetaDefaultDecision = 'xd-legacy' | 'flag-enable' | 'skip';
+
export interface XdOrgBetaDefaultDeps {
readCurrentAuthIdentity(): { authGeneration: number; userId: string | null };
readChannelState(): { enableBeta: boolean; isCustomized: boolean };
@@ -41,13 +43,27 @@ export function isXdOrgUser(user: XdOrgBetaUser | null | undefined): boolean {
return name !== undefined && XD_ORG_NAME_FALLBACKS.has(name);
}
+/** 先按 xd 身份判定,只有非 xd 才允许 feature flag 打开设备默认值。 */
+export function shouldAttemptOrgBetaDefault(input: {
+ user: XdOrgBetaUser | null | undefined;
+ defaultEnableBeta?: boolean;
+}): OrgBetaDefaultDecision {
+ if (isXdOrgUser(input.user)) return 'xd-legacy';
+ if (input.user?.membershipKind !== 'org' || input.defaultEnableBeta !== true) {
+ return 'skip';
+ }
+ return 'flag-enable';
+}
+
function isCurrentAuth(
request: XdOrgBetaDefaultRequest,
deps: XdOrgBetaDefaultDeps,
): boolean {
const current = deps.readCurrentAuthIdentity();
- return current.authGeneration === request.expectedAuthGeneration
- && current.userId === request.expectedUserId;
+ return (
+ current.authGeneration === request.expectedAuthGeneration &&
+ current.userId === request.expectedUserId
+ );
}
export async function maybeEnableXdOrgBetaDefault(
@@ -57,6 +73,24 @@ export async function maybeEnableXdOrgBetaDefault(
if (!isXdOrgUser(request.user)) {
return { kind: 'skipped', reason: 'not-xd-org' };
}
+ return maybeEnableBetaDefaultForEligibleUser(request, deps);
+}
+
+/** 为非 xd 组织复用同一套设备默认写盘保护,仅由 feature flag 显式开启。 */
+export async function maybeEnableNonXdOrgBetaDefault(
+ request: XdOrgBetaDefaultRequest,
+ deps: XdOrgBetaDefaultDeps,
+): Promise<XdOrgBetaDefaultOutcome> {
+ if (isXdOrgUser(request.user)) {
+ return { kind: 'skipped', reason: 'not-xd-org' };
+ }
+ return maybeEnableBetaDefaultForEligibleUser(request, deps);
+}
+
+async function maybeEnableBetaDefaultForEligibleUser(
+ request: XdOrgBetaDefaultRequest,
+ deps: XdOrgBetaDefaultDeps,
+): Promise<XdOrgBetaDefaultOutcome> {
if (!isCurrentAuth(request, deps)) {
return { kind: 'skipped', reason: 'stale-auth' };
}