Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ vi.mock('electron', () => ({

import {
buildXaiPiNativeProvider,
createPiSubscriptionConnectionReader,
buildPiNativeProvidersFromConfigs,
buildPiSubscriptionNativeProviders,
mergePiNativeProviderResults,
Expand All @@ -67,6 +68,10 @@ import { deriveAvailableModels } from '../catalog-to-descriptors.js';

type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];

/** 连接态判定只需要目录里的 provider 身份与 auth 家族标记。 */
const catalogOf = (providers: unknown[]): Catalog =>
({ providers } as unknown as Catalog);

// #10434, unit: an empty UI intensity ladder must not disable the native switch.
it.each(['xiaomi', 'xiaomi-token-plan-cn', 'xiaomi-token-plan-ams', 'xiaomi-token-plan-sgp'])(
'retains the %s native Pi on/off map behind the visible switch', source => {
Expand Down Expand Up @@ -169,6 +174,106 @@ it('materializes a separate native ChatGPT provider for each independent account
expect(account.models.map((model) => model.id)).toEqual(builtin.models.map((model) => model.id));
});

// #12298: 订阅来源的连接态判定(桌面装配用的纯读判据)。
describe('Pi subscription connection reader (#12298)', () => {
const build = (options: {
providers?: unknown[];
grokLogin?: boolean;
codexAuthenticated?: boolean;
codexLogin?: boolean;
poolConnected?: boolean;
onReadFailure?: (providerId: string, error: unknown) => void;
}) => {
const hasGrokOAuthLogin = vi.fn(() => options.grokLogin ?? false);
const codexAccountState = vi.fn(() => ({ authenticated: options.codexAuthenticated ?? false }));
const hasCodexOAuthLoginReadOnly = vi.fn(() => options.codexLogin ?? false);
const hasConnectedSubscriptionPool = vi.fn(() => options.poolConnected ?? false);
const reader = createPiSubscriptionConnectionReader({
getActiveCatalog: () => catalogOf(options.providers ?? []),
hasGrokOAuthLogin,
codexAccountState,
hasCodexOAuthLoginReadOnly,
hasConnectedSubscriptionPool,
onReadFailure: options.onReadFailure,
});
return {
reader,
hasGrokOAuthLogin,
codexAccountState,
hasCodexOAuthLoginReadOnly,
hasConnectedSubscriptionPool,
};
};

it('reports the ChatGPT subscription as connected through either credential path', () => {
const viaLogin = build({ codexLogin: true });
expect(viaLogin.reader('openai')).toBe(true);
expect(viaLogin.hasConnectedSubscriptionPool).not.toHaveBeenCalled();

const viaPool = build({ poolConnected: true });
expect(viaPool.reader('openai')).toBe(true);
expect(viaPool.hasConnectedSubscriptionPool)
.toHaveBeenCalledWith('openai', { includeBoundAccounts: true });
});

it('reports the ChatGPT subscription as disconnected when neither path has a credential', () => {
const { reader } = build({});
expect(reader('openai')).toBe(false);
});

it('reads the xAI family from the Grok OAuth login state', () => {
const connected = build({
providers: [{ id: 'xai', auth: { method: 'oauth' } }],
grokLogin: true,
});
expect(connected.reader('xai')).toBe(true);
expect(connected.hasGrokOAuthLogin).toHaveBeenCalledWith('xai');

const disconnected = build({
providers: [{ id: 'xai', auth: { method: 'oauth' } }],
grokLogin: false,
});
expect(disconnected.reader('xai')).toBe(false);
});

it('reads an independent Codex account from its own login state', () => {
const { reader, codexAccountState } = build({
providers: [{ id: 'openai-a', auth: { method: 'oauth', native: 'codex' } }],
codexAuthenticated: true,
});
expect(reader('openai-a')).toBe(true);
expect(codexAccountState).toHaveBeenCalledWith('openai-a');
});

it('reads the ChatGPT subscription without a pool to read', () => {
// Node Host 没有账号池可读(它的订阅账号各自判自己的登录态):只有本机登录这一条。
const reader = createPiSubscriptionConnectionReader({
getActiveCatalog: () => catalogOf([]),
hasGrokOAuthLogin: () => false,
codexAccountState: () => ({ authenticated: false }),
hasCodexOAuthLoginReadOnly: () => true,
});
expect(reader('openai')).toBe(true);
});

it('keeps a source listed when the connection read fails', () => {
const onReadFailure = vi.fn();
const reader = createPiSubscriptionConnectionReader({
getActiveCatalog: () => catalogOf([{ id: 'openai-a', auth: { method: 'oauth', native: 'codex' } }]),
hasGrokOAuthLogin: () => false,
codexAccountState: () => { throw new Error('secret store unavailable'); },
hasCodexOAuthLoginReadOnly: () => false,
hasConnectedSubscriptionPool: () => false,
onReadFailure,
});
// 读不到结论时不得剔除来源。
expect(reader('openai-a')).toBe(true);
expect(onReadFailure).toHaveBeenCalledWith('openai-a', expect.any(Error));
// 目录里没有的来源也不剔除。
expect(reader('unknown-provider')).toBe(true);
});
});

it.each(['google/gemini-3.8-flash', 'google/gemini-99-pro-preview'])(
'uses the Global Gateway Responses route for %s in local and remote Pi',
(id) => {
Expand Down
29 changes: 28 additions & 1 deletion apps/desktop/src/main/maker-host/pi-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ import {
} from './anthropic-compat-proxy-host.js';
import { hostCredentialEndpointAllowed } from './pi-provider-transport.js';
import { hasGrokOAuthLogin } from './grok-oauth-login.desktop.js';
import { isOpenAiSubscriptionProviderId } from './codex-account-auth.desktop.js';
import { codexAccountState, isOpenAiSubscriptionProviderId } from './codex-account-auth.desktop.js';
import { hasConnectedSubscriptionPool } from '../subscription-accounts/runtime.js';
import { withProviderAppAttribution } from './provider-app-attribution.js';
import { createLogger } from '../logger.js';
import { registerPiProxySession } from './pi-proxy-session-auth.js';
Expand All @@ -107,11 +108,13 @@ import {
import { mutateAuthorizedPiManagedPackage } from './pi-managed-package-mutation.js';
import {
createPiNativeProviderResolver,
createPiSubscriptionConnectionReader,
resolvePiCindyGatewayModelApi,
resolvePiCindyGatewayModelSpec,
} from './piNativeProvidersCore.js';
export {
buildPiSubscriptionNativeProviders,
createPiSubscriptionConnectionReader,
listedPiModelIds,
mergePiNativeProviderResults,
parsePiListModels,
Expand Down Expand Up @@ -140,6 +143,28 @@ export function resolvePiBinaryPath(): string | null {
return getReadyBinaryPath('pi') ?? null;
}

/**
* #12298: 订阅来源的连接态(与「设置 → 模型供应商」列表同口径,纯读、无自愈副作用)。
* 断开的订阅仍留在会话目录里(重连后父会话可直接切换),但子代理路由不能列它。
*
* 它接在 AgentDeps.isNativeProviderSourceConnected 上,不进入 provider 清单本身 ——
* 清单是桌面与 Node Host 的逐字节契约(host↔desktop parity),连接态是宿主各自的凭证事实。
*/
const subscriptionSourceConnected = createPiSubscriptionConnectionReader({
getActiveCatalog,
hasGrokOAuthLogin,
codexAccountState,
hasCodexOAuthLoginReadOnly: () => desktopCodexAuthAdapter.hasCodexOAuthLoginReadOnly(),
hasConnectedSubscriptionPool,
onReadFailure: (providerId, error) => log.warn(
'pi: subscription connection read failed; keeping the source listed',
{
providerId,
message: error instanceof Error ? error.message : String(error),
},
),
});

// The desktop's ports for the Pi native providers shared with the Node Host (piNativeProvidersCore.ts).
const piNativeProviderResolver = createPiNativeProviderResolver({
getClaudeEndpoint: () => getClaudeEndpoint(),
Expand Down Expand Up @@ -393,6 +418,8 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
},
registerPiProxySession,
resolvePiNativeProviders: (ctx) => resolvePiNativeProviders(ctx),
// #12298: 子代理路由不列确知断开的订阅来源(连接态是桌面宿主的凭证事实,纯读)。
isNativeProviderSourceConnected: subscriptionSourceConnected,
resolvePiRuntimeModelDescriptor: opts.resolvePiRuntimeModelDescriptor,
resolvePiRuntimeModels: opts.resolvePiRuntimeModels,
resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor,
Expand Down
66 changes: 66 additions & 0 deletions apps/desktop/src/main/maker-host/piNativeProvidersCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,72 @@ export async function readPiBundledModels(
}


/**
* #12298: 订阅来源的连接态判定(供启动器接到 AgentDeps.isNativeProviderSourceConnected)。
*
* 断开的订阅仍留在会话目录里(重连后父会话可直接切换),但子代理路由不能列它:
* 按这些名字派发的子任务会在首次上游请求时必败(空 runId + 噪声失败通知)。
*
* 判定口径与「设置 → 模型供应商」列表一致,且是纯读(不触发绑定自愈、不写凭证文件):
* · xAI 家族(内置 SuperGrok 与独立账号)读 Grok OAuth 登录态;
* · Codex 家族账号读该账号自己的登录态(bridge 对非 'openai' 的 providerId 也用这一条);
* · 'openai'(ChatGPT 订阅)两条凭证路径任一可用即算连接 —— 本机 Codex 登录与账号池,
* bridge 实际按会话绑定的账号取凭证,只判一条会把仍可用的来源误删。
*
* 读不到结论的来源一律按「连接」处理:只在确知断开时剔除,宁可多列也不误伤可用来源。
*
* 桌面与 Node Host 各接各的凭证读数(port 注入),但判定规则共用这一份;连接态不进入
* provider 清单本身 —— 清单是桌面与 Host 的逐字节契约(host↔desktop parity)。
*/
export interface PiSubscriptionConnectionPorts {
/** 当前生效目录(判断来源属于哪个订阅家族)。 */
getActiveCatalog: () => Catalog;
/** SuperGrok OAuth 登录态(providerId 缺省即内置 'xai')。 */
hasGrokOAuthLogin: (providerId?: string) => boolean;
/** 独立 Codex 账号的登录态。 */
codexAccountState: (providerId: string) => { authenticated: boolean };
/** 本机 Codex(ChatGPT 订阅)登录态,纯读版。 */
hasCodexOAuthLoginReadOnly: () => boolean;
/**
* ChatGPT 账号池里是否还有已连接的账号。桌面有这个账号池;Node Host 的订阅账号以
* 独立来源出现(各自判自己的登录态),没有池可读 → 缺省即不读这一条。
*/
hasConnectedSubscriptionPool?: (
providerId: string,
options?: { includeBoundAccounts?: boolean },
) => boolean;
/** 读取结论失败时的兜底日志。 */
onReadFailure?: (providerId: string, error: unknown) => void;
}

export function createPiSubscriptionConnectionReader(
ports: PiSubscriptionConnectionPorts,
): (providerId: string) => boolean {
const {
getActiveCatalog,
hasGrokOAuthLogin,
codexAccountState,
hasCodexOAuthLoginReadOnly,
hasConnectedSubscriptionPool,
onReadFailure,
} = ports;
return (providerId: string): boolean => {
try {
const account = getActiveCatalog().providers.find((provider) => provider.id === providerId);
const native = account?.auth.native;
if (native === 'xai' || providerId === 'xai') return hasGrokOAuthLogin(providerId);
if (native === 'codex') return codexAccountState(providerId).authenticated;
if (providerId === 'openai') {
return hasCodexOAuthLoginReadOnly()
|| Boolean(hasConnectedSubscriptionPool?.('openai', { includeBoundAccounts: true }));
}
} catch (error) {
onReadFailure?.(providerId, error);
}
return true;
};
}

/**
* Overlay Cindy's host-managed subscription endpoints onto PI's bundled
* provider catalog. Resolved catalog metadata is authoritative for all subscription
Expand Down
3 changes: 3 additions & 0 deletions apps/host/src/agent/agent-deps-engines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ export const PORTS_ONLY_PI_READS = {
getRemotePiAgentProxyEnv: undefined,
getRemotePiFileOps: undefined,
getRemotePiTransport: undefined,
// #12298: the Pi agent reads the host's subscription connection state; Claude and Codex route
// subagent models from their own catalogs and never consult it.
isNativeProviderSourceConnected: undefined,
mutatePiManagedPackage: undefined,
onPiManagedPackageMutationSettled: undefined,
preparePiExtraSpawnConfig: undefined,
Expand Down
40 changes: 38 additions & 2 deletions apps/host/src/agent/pi-native-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@
* - The Host has no managed local model runtime (Ollama, llama.cpp). It answers as the desktop's
* preflight answers when that runtime is not ready: the same error codes and wording.
*/
import path from 'node:path';
import { MANAGED_OLLAMA_PROVIDER_ID } from '../../../desktop/src/shared/localModelRuntime.js';
import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../../desktop/src/shared/llamaCpp.js';
import {
createPiNativeProviderResolver,
createPiSubscriptionConnectionReader,
type PiNativeProviderPorts,
} from '../../../desktop/src/main/maker-host/piNativeProvidersCore.js';
import { getActiveCatalog } from '../../../desktop/src/main/maker-host/active-catalog.js';
import { isNativeProviderAuthBound } from '../../../desktop/src/main/maker-host/nativeProviderAuthBinding.js';
import { shouldSuppressLocalCodexAuth } from '../../../desktop/src/main/maker-host/codex-auth-invalidation.js';
import { hasCodexOAuthLoginUnbound } from './codex-system-login.js';
import { createLogger } from '../../../desktop/src/main/logger.js';

const log = createLogger('host-pi-native-providers');

/** The desktop preflight's not-ready errors (local-model-runtime/preflight.ts). */
export async function hostManagedLocalModelNotReady(input: { providerId: string; remoteHostId: string | null }): Promise<void> {
Expand All @@ -37,13 +46,16 @@ export function createHostPiNativeProviders(options: {
list: PiNativeProviderPorts['listCustomProvidersWithSecureHeaders'];
readKey: PiNativeProviderPorts['readCustomProviderKey'];
grok: { hasGrokOAuthLogin(providerId?: string): boolean };
codexAccounts: { isOpenAiSubscriptionProviderId(providerId?: string | null): boolean };
codexAccounts: {
isOpenAiSubscriptionProviderId(providerId?: string | null): boolean;
codexAccountState(providerId: string): { authenticated: boolean };
};
};
/** The desktop's first step before a local Pi (release table row 25); no-op when absent. */
ensureSharedGlobalSkills?: () => Promise<void>;
}) {
const config = options.providerConfig;
return createPiNativeProviderResolver({
const resolver = createPiNativeProviderResolver({
getClaudeEndpoint: () => options.endpoint(),
isAnthropicCompatProxyHandleReady: () => options.claudeProxy?.isReady() ?? false,
ensureAnthropicCompatProxyReady: () => options.claudeProxy?.ready?.() ?? Promise.resolve(),
Expand All @@ -56,4 +68,28 @@ export function createHostPiNativeProviders(options: {
ensureManagedOllamaReadyForSession: input => hostManagedLocalModelNotReady(input),
getUserDataDir: () => options.userDataDir,
});
/**
* #12298: the Host's own credential state per subscription source (read-only). The
* desktop reads the desktop's stores; the Host reads the profile's — same rules,
* different facts. The state stays out of the provider list: that list is the
* byte-for-byte contract between the desktop and the Host.
*/
const subscriptionSourceConnected = createPiSubscriptionConnectionReader({
getActiveCatalog,
hasGrokOAuthLogin: id => config.grok.hasGrokOAuthLogin(id),
codexAccountState: id => config.codexAccounts.codexAccountState(id),
hasCodexOAuthLoginReadOnly: () => hasHostCodexHomeLogin(path.join(options.userDataDir, 'codex-home')),
onReadFailure: (providerId, error) => log.warn(
'pi: subscription connection read failed; keeping the source listed',
{ providerId, message: error instanceof Error ? error.message : String(error) },
),
});
return { ...resolver, subscriptionSourceConnected };
}

/** The profile's own Codex (ChatGPT subscription) login, as the desktop's read-only check. */
function hasHostCodexHomeLogin(codexHome: string): boolean {
if (!isNativeProviderAuthBound('openai')) return false;
if (shouldSuppressLocalCodexAuth(codexHome, path.join(codexHome, 'auth.json'))) return false;
return hasCodexOAuthLoginUnbound(codexHome);
}
3 changes: 3 additions & 0 deletions apps/host/src/agent/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,9 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) {
// As the desktop (pi-host.ts): the shared resolver with the Host's ports (pi-native-providers.ts),
// and the Cindy gateway block's API and compat from the same probe state.
resolvePiNativeProviders: (ctx) => piNativeProviders.resolvePiNativeProviders(ctx),
// #12298: the Host's own subscription connection state (read-only), so subagent
// routes skip a source the Host knows is disconnected.
isNativeProviderSourceConnected: piNativeProviders.subscriptionSourceConnected,
// As the desktop (pi-host.ts): durable Subagent runners, forked as Node child processes (pi-subagent-runner.ts).
spawnPiSubagentRunner: (request) => spawnHostPiSubagentRunner(request),
resolvePiManagedPackageResources: piPackages.deps.resolvePiManagedPackageResources,
Expand Down
11 changes: 11 additions & 0 deletions packages/maker-core/src/agents/base-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -907,6 +907,17 @@ export interface AgentDeps {
},
) => Promise<PiNativeProvidersResult | null>;

/**
* Pi-only:宿主已知的订阅来源连接态(纯读,无自愈副作用)。
*
* 子代理路由不列确知断开的来源:账号断开或被移除后目录里的模型名仍在,按这些名字
* 派发的子任务会先建 run、随后在首次上游请求时因缺凭证必败(#12298)。
*
* 入参是 provider 的**来源 id**(spec.sourceProviderId ?? spec.id),不是 Pi 侧的 provider id。
* 缺省 / 读不到结论 → 视为连接,不过滤(宁可多列也不误伤可用来源)。
*/
isNativeProviderSourceConnected?: (sourceProviderId: string) => boolean;

/**
* Pi-only:按实际 provider/model 路由解析运行时描述符。用于启动前校验已持久化 effort,
* 以及恢复已 retired 模型时补齐当前 session 的私有 models.json;结果不得进入公开
Expand Down
Loading
Loading