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。

fix(pi): gate Pi creation entries by runtime-registered agents (desktop + mobile)

Chrisa99c475e6c95
diff --git a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
index aa19e0ad00..cf8cb200b4 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerProjectPicker.test.ts
@@ -53,6 +53,8 @@ const branchPickSource = readSource('components', 'new-chat', 'branchPick.ts');
const deviceProvidersHookSource = readSource('hooks', 'useDeviceProviders.ts');
const agentCapabilitiesHookSource = readSource('hooks', 'useAgentCapabilities.ts');
+const availableAgentsHookSource = readSource('hooks', 'useAvailableAgents.ts');
+const vendorSwitcherSource = readSource('components', 'new-chat', 'VendorSegmentedSwitcher.tsx');
const scheduleFormDialogSource = readSource(
'features',
@@ -266,6 +268,28 @@ describe('Shared create project picker', () => {
// codex review P1:Pi 是本地专属 agent(startSession 拒绝任何 remoteHostId),SSH 目标
// 会建出永远起不来的会话。两道防线:dialog 按 agentVendor 过滤掉 SSH 主机(proactive),
// handleRemoteProjectAdded 的 SSH 分支再 fail-closed 兜底(防非 UI 路径漏进 Pi+SSH)。
+ // codex review P2:Pi 二进制缺失时 buildPiAgent() 返回 null → agent map 无 pi,但模型目录仍
+ // 投影 Pi。创建入口必须按 maker:list-available-agents(runtime 注册结果)过滤,否则一路创建到
+ // requireAgent 的 not-registered。远程草稿以被控端注册结果为准(hook 传 deviceId 走隧道)。
+ it('gates the vendor switcher by runtime-registered agents (list-available-agents)', () => {
+ // hook 用权威的 runtime 注册来源,而非模型目录;远程走 device-link 隧道。
+ expect(availableAgentsHookSource).toContain("api.listAvailableAgents()");
+ expect(availableAgentsHookSource).toContain("dl.invoke(deviceId, 'maker:list-available-agents', [])");
+ // claude-code → cc 归一,fail-open(未加载不隐藏)。
+ expect(availableAgentsHookSource).toContain("agent === 'claude-code' ? 'cc' : agent");
+ // 未加载完成时不隐藏任何入口(loaded 保持 false → 空 hidden)。
+ expect(availableAgentsHookSource).toMatch(/loaded/);
+
+ // 开关按 hiddenVendors 过滤 OPTIONS,但保留当前选中段避免"无选中"过渡帧。
+ expect(vendorSwitcherSource).toContain('hiddenVendors');
+ expect(vendorSwitcherSource).toMatch(/opt\.vendor === value \|\| !hiddenVendors\.includes\(opt\.vendor\)/);
+
+ // 路由:以被控端(deviceId)为准计算 hidden;两处开关都传;选中值被隐藏时 coerce 到首个可用。
+ expect(newMakerDraftRouteSource).toContain('useAvailableAgents(effectiveDeviceLinkDeviceId)');
+ expect(newMakerDraftRouteSource).toContain('hiddenVendors={hiddenSwitcherVendors}');
+ expect(newMakerDraftRouteSource).toMatch(/hiddenSwitcherVendors\.includes\(draft\.vendor\)/);
+ });
+
it('hides SSH targets for Pi and fail-closed guards Pi+SSH session creation', () => {
// dialog:选中 Pi 时把 SSH 主机从可选目标里剔除。
expect(addRemoteProjectDialogSource).toContain("agentVendor === 'pi'");
diff --git a/apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx b/apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx
index ae5d178dc3..101ab34b18 100644
--- a/apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx
@@ -51,6 +51,12 @@ interface VendorSegmentedSwitcherProps {
* 的名字,否则读屏用户听到的全是同一个英文兜底,行与行无法分辨。
*/
ariaLabel?: string;
+ /**
+ * 从选择器里**隐藏**的 vendor(如 runtime 未注册的 Pi、SSH 远程草稿下的 Pi)。
+ * 创建入口据 `maker:list-available-agents` 计算,避免用户创建出最终 `Agent 'pi' is not
+ * registered` 的会话(codex review P2)。调用方需保证 `value` 不在此列表(或自行 coerce)。
+ */
+ hiddenVendors?: readonly MakerVendor[];
}
interface SegmentOption {
@@ -77,8 +83,14 @@ export function VendorSegmentedSwitcher({
visualVariant = 'default',
reselectEmitsChange = false,
ariaLabel,
+ hiddenVendors,
}: VendorSegmentedSwitcherProps) {
const isCreateAgentVariant = visualVariant === 'create-agent';
+ // 隐藏 runtime 未注册 / 当前上下文不支持的 vendor;当前选中值即便被隐藏也保留一段(调用方
+ // coerce 前的过渡帧),避免 tablist 出现"无选中段"。
+ const visibleOptions = hiddenVendors && hiddenVendors.length > 0
+ ? OPTIONS.filter((opt) => opt.vendor === value || !hiddenVendors.includes(opt.vendor))
+ : OPTIONS;
return (
<div
className={cn(
@@ -101,7 +113,7 @@ export function VendorSegmentedSwitcher({
role="tablist"
aria-label={ariaLabel ?? 'Vendor switcher'}
>
- {OPTIONS.map((opt) => {
+ {visibleOptions.map((opt) => {
const isActive = value === opt.vendor;
return (
<button
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 5fa3111db7..693a2e9d18 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -184,6 +184,7 @@ import {
type AgentCapabilities,
} from '@/hooks/useAgentCapabilities';
import { useProviders } from '@/hooks/useProviders';
+import { useAvailableAgents } from '@/hooks/useAvailableAgents';
import {
useDeviceProviders,
evictDeviceProviders,
@@ -656,6 +657,16 @@ export function NewMakerDraftRoute() {
// 下面 isDeviceLinkDraft 与 create 分支的真值收窄对 undefined 同样成立)。
const effectiveDeviceLinkDeviceId = draft.deviceLinkDeviceId ?? undefined;
const effectiveDeviceLinkDeviceName = draft.deviceLinkDeviceName;
+ // 入口门控:只在 runtime 已注册的 agent 上开放创建入口(Pi 二进制缺失时 buildPiAgent 返回
+ // null,agent map 无 pi,但模型目录仍投影 Pi → 需按 maker:list-available-agents 过滤,
+ // 否则一路创建到 requireAgent 的 not-registered 报错,codex review P2)。远程草稿以被控端
+ // 的注册结果为准(hook 传 deviceId 走隧道)。未加载完成时不隐藏任何入口(fail-open)。
+ const { availableVendors, loaded: availableAgentsLoaded } =
+ useAvailableAgents(effectiveDeviceLinkDeviceId);
+ const hiddenSwitcherVendors = useMemo<MakerVendor[]>(() => {
+ if (!availableAgentsLoaded) return [];
+ return (['cc', 'codex', 'pi'] as const).filter((vendor) => !availableVendors.has(vendor));
+ }, [availableAgentsLoaded, availableVendors]);
/**
* 「这份草稿要建到对端设备上」—— 只看 deviceId,**不再要求 workingDir**(#807)。
*
@@ -1748,6 +1759,16 @@ export function NewMakerDraftRoute() {
[currentPrefs],
);
+ // 当前草稿选中的 vendor 变为不可用(如 Pi 未注册 / 被控端无 Pi)时,coerce 到首个可用来源
+ // (优先 cc),避免 tablist 卡在被隐藏段、且防止创建出注定 requireAgent 报错的会话。
+ // 只在已加载可用性后收敛;fallback 一定可见,收敛一次即稳定(switchVendor 同值早返,不成环)。
+ useEffect(() => {
+ if (!availableAgentsLoaded) return;
+ if (!hiddenSwitcherVendors.includes(draft.vendor)) return;
+ const fallback = (['cc', 'codex', 'pi'] as const).find((vendor) => availableVendors.has(vendor));
+ if (fallback && fallback !== draft.vendor) handleVendorChange(fallback);
+ }, [availableAgentsLoaded, hiddenSwitcherVendors, availableVendors, draft.vendor, handleVendorChange]);
+
// ─── 用户在 ChatInput 改 model/effort/permission 后,落进当前 vendor 的 prefs ──
const patchActivePrefs = useCallback((patch: Partial<VendorPrefs>) => {
patchCurrentVendorPrefs(patch);
@@ -3484,6 +3505,7 @@ export function NewMakerDraftRoute() {
visualVariant="create-agent"
className="shrink-0"
disabled={wtCreating}
+ hiddenVendors={hiddenSwitcherVendors}
/>
}
// 协同 toggle(与对话界面同一控件):本地 / SSH 远端 / device-link 项目 draft
@@ -3541,6 +3563,7 @@ export function NewMakerDraftRoute() {
visualVariant="create-agent"
className="shrink-0"
disabled={wtCreating}
+ hiddenVendors={hiddenSwitcherVendors}
/>
}
narrowToolbar={isDraftToolbarNarrow}
diff --git a/apps/desktop/src/renderer/hooks/useAvailableAgents.ts b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
new file mode 100644
index 0000000000..4001a17304
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useAvailableAgents.ts
@@ -0,0 +1,102 @@
+/**
+ * useAvailableAgents — 当前会话上下文里**运行时已注册**的 agent 集合。
+ *
+ * 为什么需要:Pi 的二进制经 postinstall best-effort 下载,可能失败/开发环境未装/当前
+ * 平台无资产 → `buildPiAgent()` 返回 null → maker 的 agent map 里没有 `pi`。但 provider
+ * 模型目录仍会照常投影 Pi 模型,创建入口若只看目录就会让用户一路创建,最终在
+ * `Maker.requireAgent()` 撞上 `Agent 'pi' is not registered`(codex review P2)。
+ * 权威来源是 `maker:list-available-agents`(runtime 注册结果),不是模型目录。
+ *
+ * device-link:远程草稿的可用性以**被控端**为准 —— 传 deviceId 时走隧道 invoke
+ * (channel 在 REMOTE_INVOKE_ALLOWLIST 内)。省略 = 本机。
+ *
+ * 加载语义:未加载完成时 `loaded=false` 且 `availableVendors` 为空;消费方必须把
+ * "未加载" 当作 "先别隐藏任何入口"(避免异步 fetch 期间误隐藏合法 agent)。
+ */
+import { useEffect, useState } from 'react';
+
+import type { MakerVendor } from '@/lib/ccAgent.types';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('useAvailableAgents');
+
+type RuntimeAgentKind = 'claude-code' | 'codex' | 'pi';
+
+/** runtime agent id → NewMaker vendor(其余保持同名)。 */
+function toVendor(agent: RuntimeAgentKind): MakerVendor {
+ return agent === 'claude-code' ? 'cc' : agent;
+}
+
+interface MakerApiShape {
+ listAvailableAgents: () => Promise<RuntimeAgentKind[]>;
+}
+interface DeviceLinkShape {
+ invoke: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;
+}
+
+function getMakerApi(): MakerApiShape | null {
+ return (window as unknown as { electronAPI?: { maker?: MakerApiShape } }).electronAPI?.maker ?? null;
+}
+function getDeviceLink(): DeviceLinkShape | null {
+ return (window as unknown as { electronAPI?: { deviceLink?: DeviceLinkShape } }).electronAPI?.deviceLink ?? null;
+}
+
+async function fetchAvailableAgents(deviceId?: string | null): Promise<RuntimeAgentKind[]> {
+ if (deviceId) {
+ const dl = getDeviceLink();
+ if (!dl) throw new Error('device-link IPC not available');
+ const raw = await dl.invoke(deviceId, 'maker:list-available-agents', []);
+ return Array.isArray(raw) ? (raw.filter((v): v is RuntimeAgentKind =>
+ v === 'claude-code' || v === 'codex' || v === 'pi') as RuntimeAgentKind[]) : [];
+ }
+ const api = getMakerApi();
+ if (!api) throw new Error('maker IPC not available');
+ return api.listAvailableAgents();
+}
+
+export interface UseAvailableAgentsResult {
+ /** runtime 已注册的 vendor 集合(cc/codex/pi);loaded=false 时为空。 */
+ availableVendors: ReadonlySet<MakerVendor>;
+ /** 首次结果是否已返回。未加载完成时消费方不应据此隐藏任何入口。 */
+ loaded: boolean;
+}
+
+/**
+ * @param deviceId 省略/undefined = 本机;传值 = 该被控端(device-link)。
+ */
+export function useAvailableAgents(deviceId?: string | null): UseAvailableAgentsResult {
+ const [availableVendors, setAvailableVendors] = useState<ReadonlySet<MakerVendor>>(new Set());
+ const [loaded, setLoaded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoaded(false);
+ setAvailableVendors(new Set());
+ const run = (): void => {
+ fetchAvailableAgents(deviceId)
+ .then((agents) => {
+ if (cancelled) return;
+ setAvailableVendors(new Set(agents.map(toVendor)));
+ setLoaded(true);
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ // fail-open:查询失败时不隐藏任何入口(loaded 保持 false)——宁可多显示一个
+ // 也不因一次 IPC 抖动把合法 agent 从创建入口里抹掉。真正的兜底是创建期 requireAgent。
+ log.warn('listAvailableAgents failed; not gating agent entries this cycle', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ });
+ };
+ run();
+ // 会话期间 Pi 二进制可能被按需下载补齐:窗口重新聚焦时再拉一次,让入口及时出现。
+ const onFocus = (): void => run();
+ window.addEventListener('focus', onFocus);
+ return () => {
+ cancelled = true;
+ window.removeEventListener('focus', onFocus);
+ };
+ }, [deviceId]);
+
+ return { availableVendors, loaded };
+}
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 4cedcf7dfe..9899de764a 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -130,6 +130,7 @@ import {
import {
DEFAULT_NEW_SESSION_DRAFT,
NEW_SESSION_AGENT_OPTIONS,
+ availableNewSessionAgentOptions,
defaultPermissionModeForNewSessionAgent,
buildRemoteCreateSessionOptions,
buildRecentWorkspaceOptions,
@@ -413,6 +414,11 @@ export default function NewRemoteSessionScreen() {
const [permissionSheetOpen, setPermissionSheetOpen] = useState(false);
const [permissionSheetSnap, setPermissionSheetSnap] = useState<ContextSheetSnap>('half');
const [agentPickerOpen, setAgentPickerOpen] = useState(false);
+ // 被控端 runtime 已注册的 agent 集合(null = 未拉到 → fail-open 不过滤入口)。据此过滤新建
+ // agent 选项:被控端 Pi 二进制缺失时其 agent map 无 pi,但模型目录仍投影 Pi,不过滤会让用户
+ // 建出最终 requireAgent 报 not-registered 的会话(codex review P2)。
+ const [availableAgentKinds, setAvailableAgentKinds] =
+ useState<ReadonlySet<NewSessionAgentKind> | null>(null);
// worktree 开关(project 模式 + 已选目录时显示):勾选值存工作端(get-new-maker-defaults
// 播种 / 显式点击写穿),资格由 worktree:detect-cwd 探测(目录变化即重探,seq 防竞态)。
const [worktreeProbe, setWorktreeProbe] = useState<NewSessionWorktreeProbeSnapshot | null>(null);
@@ -1189,6 +1195,37 @@ export default function NewRemoteSessionScreen() {
};
}, [selectedDeviceId, draft.agentKind, maker, openLink]);
+ // 拉被控端 runtime 已注册的 agent 集合(过滤新建 agent 入口)。fail-open:失败/无设备时置 null
+ // (不过滤),真正的兜底是被控端 requireAgent。窗口/设备切换重拉,让按需下载补齐的 Pi 及时出现。
+ useEffect(() => {
+ if (!selectedDeviceId) {
+ setAvailableAgentKinds(null);
+ return;
+ }
+ let cancelled = false;
+ setAvailableAgentKinds(null);
+ void withTransientRemoteRetry(async () => {
+ await openLink(selectedDeviceId);
+ return maker.listAvailableAgents();
+ })
+ .then((agents) => {
+ if (cancelled) return;
+ setAvailableAgentKinds(
+ new Set(
+ (Array.isArray(agents) ? agents : []).filter(
+ (a): a is NewSessionAgentKind => a === 'claude-code' || a === 'codex' || a === 'pi',
+ ),
+ ),
+ );
+ })
+ .catch(() => {
+ /* fail-open:拉取失败不过滤入口(不因一次隧道抖动抹掉合法 agent)。 */
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [selectedDeviceId, maker, openLink]);
+
useEffect(() => {
if (!selectedDeviceId || composerTrigger.kind !== 'slash') {
slashLoadSeqRef.current += 1;
@@ -2226,6 +2263,15 @@ export default function NewRemoteSessionScreen() {
});
}, [draft.agentKind, draft.permissionMode, deviceProviders.providers, deviceProviders.modelVisibilityOverrides, newSessionPreferences, sessions, selectedDeviceId]);
+ // 选中的 agent 在被控端未注册(如 Pi 二进制缺失)时,coerce 到首个可用来源,避免用户停在
+ // 被隐藏的选项、并防止创建出注定 requireAgent 报错的会话。仅在已拉到可用集后收敛一次。
+ useEffect(() => {
+ if (!availableAgentKinds) return;
+ if (availableAgentKinds.has(draft.agentKind)) return;
+ const fallback = NEW_SESSION_AGENT_OPTIONS.find((option) => availableAgentKinds.has(option.kind));
+ if (fallback && fallback.kind !== draft.agentKind) switchAgent(fallback.kind);
+ }, [availableAgentKinds, draft.agentKind, switchAgent]);
+
useEffect(() => {
if (!selectedDeviceId || draft.workspaceKind !== 'project' || draft.workingDir.trim()) return;
@@ -2960,7 +3006,7 @@ export default function NewRemoteSessionScreen() {
</Pressable>
{agentPickerOpen ? (
<View style={styles.agentPickerPanel} testID="newSession.agentPickerPanel">
- {NEW_SESSION_AGENT_OPTIONS.map((option) => {
+ {availableNewSessionAgentOptions(availableAgentKinds).map((option) => {
const selected = draft.agentKind === option.kind;
return (
<Pressable
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index ee75485603..164212f2b7 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -5,6 +5,7 @@ import { i18n } from '@/i18n';
import {
DEFAULT_NEW_SESSION_DRAFT,
NEW_SESSION_AGENT_OPTIONS,
+ availableNewSessionAgentOptions,
buildNewSessionCreatePreview,
buildRecentWorkspaceOptions,
buildRemoteCreateSessionOptions,
@@ -452,6 +453,33 @@ describe('new session model', () => {
})).toMatchObject({ agentKind: 'pi', fastMode: true });
});
+ it('filters the new-session agent options by the controlled device runtime-registered set', () => {
+ // null(未拉到)→ fail-open,全部保留。
+ expect(availableNewSessionAgentOptions(null).map((o) => o.kind)).toEqual([
+ 'claude-code', 'codex', 'pi',
+ ]);
+ // 被控端无 Pi(二进制缺失)→ 隐藏 Pi,避免建出 requireAgent 报 not-registered 的会话。
+ expect(
+ availableNewSessionAgentOptions(new Set(['claude-code', 'codex'])).map((o) => o.kind),
+ ).toEqual(['claude-code', 'codex']);
+ // 只有 Pi 注册(理论)→ 只留 Pi。
+ expect(availableNewSessionAgentOptions(new Set(['pi'])).map((o) => o.kind)).toEqual(['pi']);
+ // 空集(被控端异常)→ 退回至少 Claude,不把入口清空到无法创建。
+ expect(availableNewSessionAgentOptions(new Set()).map((o) => o.kind)).toEqual(['claude-code']);
+ });
+
+ it('wires the new-session screen to gate agents by list-available-agents and coerce off unavailable', () => {
+ const newSource = readTextLf(resolve(process.cwd(), 'app/sessions/new.tsx'), 'utf8');
+ // 拉被控端 runtime 注册集合,渲染按可用集过滤,选中不可用时 coerce。
+ expect(newSource).toContain('maker.listAvailableAgents()');
+ expect(newSource).toContain('availableNewSessionAgentOptions(availableAgentKinds).map');
+ expect(newSource).toMatch(/availableAgentKinds\.has\(draft\.agentKind\)/);
+ // 传输层 passthrough 到 allowlisted channel。
+ const transportSource = readTextLf(
+ resolve(process.cwd(), 'src/device-link/mobileMakerTransport.ts'), 'utf8');
+ expect(transportSource).toContain("listAvailableAgents: () => call('maker:list-available-agents', [])");
+ });
+
it('uses safe per-agent permission defaults for new interactive sessions', () => {
expect(defaultPermissionModeForNewSessionAgent('claude-code')).toBe('auto');
expect(defaultPermissionModeForNewSessionAgent('codex')).toBe('auto');
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 94fea24ee3..778d3f7580 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -350,6 +350,12 @@ export type MobileWorktreeCreateResult =
export interface MobileMakerTransport {
createSession(opts: CreateSessionOptions): Promise<CreateSessionResult>;
getCapabilities(agentKind: MobileAgentKind): Promise<unknown>;
+ /**
+ * 被控端 runtime 已注册的 agent 集合(maker:list-available-agents,在 REMOTE_INVOKE_ALLOWLIST 内)。
+ * 新建会话入口据此过滤:Pi 二进制缺失时被控端 agent map 无 pi,但模型目录仍投影 Pi,不过滤
+ * 会让用户建出最终 requireAgent 报 not-registered 的会话(codex review P2)。
+ */
+ listAvailableAgents(): Promise<MobileAgentKind[]>;
getSessionTree(sessionId: string): Promise<unknown | null>;
navigateSessionTree(
sessionId: string,
@@ -601,6 +607,7 @@ export function createMobileMakerTransport({
return {
createSession: (opts) => call('maker:create-session', [opts]),
getCapabilities: (agentKind) => call('maker:get-capabilities', [agentKind]),
+ listAvailableAgents: () => call('maker:list-available-agents', []),
// 分支(session tree)读取/切换:transport passthrough 已就位,但**移动端会话页尚无
// 分支列表/切换 UI 调用它们**——明确标记为 deferred(不是遗漏)。这两个 channel 已在
// MOBILE_REMOTE_INVOKE_CHANNELS allowlist 内,供被控桌面端经 device-link 复用及未来
diff --git a/apps/mobile/src/session/newSession.ts b/apps/mobile/src/session/newSession.ts
index 1af0fb8466..98f5644009 100644
--- a/apps/mobile/src/session/newSession.ts
+++ b/apps/mobile/src/session/newSession.ts
@@ -13,6 +13,21 @@ export const NEW_SESSION_AGENT_OPTIONS: readonly { kind: NewSessionAgentKind; la
{ kind: 'pi', label: 'Pi' },
];
+/**
+ * 按被控端 runtime 已注册的 agent 集合过滤新建入口(maker:list-available-agents)。
+ * `available === null` = 尚未拉到 → fail-open 返回全部(避免异步期间误隐藏合法 agent);
+ * 拉到后只保留已注册的 kind —— Pi 二进制缺失时被控端无 pi,过滤掉可防用户建出最终
+ * requireAgent 报 not-registered 的会话(codex review P2)。
+ */
+export function availableNewSessionAgentOptions(
+ available: ReadonlySet<NewSessionAgentKind> | null,
+): readonly { kind: NewSessionAgentKind; label: string }[] {
+ if (!available) return NEW_SESSION_AGENT_OPTIONS;
+ const filtered = NEW_SESSION_AGENT_OPTIONS.filter((option) => available.has(option.kind));
+ // 防御:被控端异常返回空集时不至于把入口清空到无法创建(至少保留 Claude)。
+ return filtered.length > 0 ? filtered : NEW_SESSION_AGENT_OPTIONS.filter((o) => o.kind === 'claude-code');
+}
+
export interface NewSessionDraft {
agentKind: NewSessionAgentKind;
workspaceKind: NewSessionWorkspaceKind;