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): 修复自定义模型粘贴图片被静默丢弃 (#1402)

Chris Zhangf78ec6e38232
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 663124c87a..50728cece9 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -128,6 +128,17 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
runtimes: { codex: { baseUrl: 'https://x/v1', models: [{ id: '', name: 'y' }] } },
}).ok,
).toBe(false);
+ expect(
+ validateCustomProviderConfig({
+ ...valid,
+ runtimes: {
+ pi: {
+ baseUrl: 'https://x/v1',
+ models: [{ id: 'm', name: 'M', supportsImageInput: 'yes' }],
+ },
+ },
+ }).ok,
+ ).toBe(false);
expect(
validateCustomProviderConfig({
...valid,
@@ -274,6 +285,30 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
expect(got?.runtimes.codex?.headers).toBeUndefined();
});
+ it('round-trips only an explicitly enabled Pi image-input capability', async () => {
+ mountDb();
+ await createCustomProvider({
+ id: 'visual-pi',
+ name: 'Visual Pi',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: {
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ models: [
+ { id: 'vision', name: 'Vision', supportsImageInput: true },
+ { id: 'legacy', name: 'Legacy' },
+ { id: 'explicit-text', name: 'Explicit text', supportsImageInput: false },
+ ],
+ },
+ },
+ });
+ expect((await getCustomProvider('visual-pi'))?.runtimes.pi?.models).toEqual([
+ { id: 'vision', name: 'Vision', supportsImageInput: true },
+ { id: 'legacy', name: 'Legacy' },
+ { id: 'explicit-text', name: 'Explicit text' },
+ ]);
+ });
+
it('round-trips an explicit Chat Completions protocol', async () => {
mountDb();
await createCustomProvider({
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index 24f5c62ca4..72a4975326 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -145,4 +145,27 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(Object.values(env)).toEqual(expect.arrayContaining(['acme', 'Bearer header-secret']));
expect(providers[0].models[0]).toMatchObject({ id: 'm1', name: 'M1', contextWindow: 8000 });
});
+
+ it('maps an explicit custom-model image capability into the Pi native model spec', () => {
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'visual',
+ name: 'Visual',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ models: [
+ { id: 'vision', name: 'Vision', supportsImageInput: true },
+ { id: 'legacy', name: 'Legacy' },
+ ],
+ }),
+ },
+ }],
+ () => null,
+ );
+ expect(providers[0].models).toEqual([
+ { id: 'vision', name: 'Vision', contextWindow: undefined, input: ['text', 'image'] },
+ { id: 'legacy', name: 'Legacy', contextWindow: undefined },
+ ]);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index 6df8aa1e20..73ce56b34f 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -112,6 +112,9 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {
if (mm.defaultEnabled !== undefined && typeof mm.defaultEnabled !== 'boolean') {
return invalid(`runtime '${agent}' model.defaultEnabled must be a boolean`);
}
+ if (mm.supportsImageInput !== undefined && typeof mm.supportsImageInput !== 'boolean') {
+ return invalid(`runtime '${agent}' model.supportsImageInput must be a boolean`);
+ }
}
if (r.wireProtocol !== undefined) {
// Pi 是多协议 harness;Codex 也具备 Responses / Chat / Anthropic bridge。
@@ -324,6 +327,7 @@ function normalizeRuntime(rt: CustomProviderRuntimeConfig): CustomProviderRuntim
name: m.name.trim(),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
}))
.filter((m) => {
if (!m.id || !m.name || seen.has(m.id)) return false;
@@ -463,6 +467,7 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun
? { contextWindow: m.contextWindow }
: {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
}))
: [];
const entry: CustomProviderRuntimeConfig = {
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index b9b6332f56..3f8b3290f4 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -227,7 +227,12 @@ export function buildPiNativeProvidersFromConfigs(
baseUrl: string;
wireProtocol?: ProviderWireProtocol;
headers?: Record<string, string>;
- models: Array<{ id: string; name?: string; contextWindow?: number }>;
+ models: Array<{
+ id: string;
+ name?: string;
+ contextWindow?: number;
+ supportsImageInput?: boolean;
+ }>;
};
};
}>,
@@ -290,7 +295,14 @@ export function buildPiNativeProvidersFromConfigs(
api: wireProtocolToPiApi(rt.wireProtocol),
apiKeyEnvVar,
...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
- models: rt.models.map((m) => ({ id: m.id, name: m.name, contextWindow: m.contextWindow })),
+ models: rt.models.map((m) => ({
+ id: m.id,
+ name: m.name,
+ contextWindow: m.contextWindow,
+ ...(m.supportsImageInput === true
+ ? { input: ['text', 'image'] as Array<'text' | 'image'> }
+ : {}),
+ })),
});
}
return { providers, env };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 51736f262b..3f71b57bec 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -2776,6 +2776,23 @@ describe('AgentInputCoordinator send transaction', () => {
expect(mocks.createMessage).toHaveBeenCalledTimes(1);
});
+ it('preserves the Pi image-capability marker for display-side localization', async () => {
+ const h = createHarness();
+ const sid = 'pi-image-capability';
+ h.sendToAgent.mockRejectedValueOnce(Object.assign(
+ new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),
+ { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },
+ ));
+
+ h.coordinator.enqueue(sid, makeItem('q-image', 'describe the screenshot'));
+ await flush();
+
+ const projection = latestProjection(h.projections);
+ expect(projection.error).toBe('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled');
+ expect(projection.pendingQueue.map((item) => item.clientId)).toEqual(['q-image']);
+ expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-image' });
+ });
+
it('retries a queue-head recovery when an external live reservation clears without a terminal event', async () => {
vi.useFakeTimers();
try {
@@ -4317,6 +4334,101 @@ describe('AgentInputCoordinator steer transaction', () => {
expect(afterDone.pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
});
+ it('restores a capability-rejected steer to the queue head for retry after switching models', async () => {
+ const h = createHarness();
+ h.setAgentKind('pi');
+ const sid = 'steer-pi-image-capability-retry';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'describe the screenshot');
+ h.steerToAgent.mockRejectedValueOnce(Object.assign(
+ new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),
+ { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },
+ ));
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(false);
+ await flush();
+
+ let projection = latestProjection(h.projections);
+ expect(projection.error).toBe('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled');
+ expect(projection.pendingQueue.map((item) => item.clientId)).toEqual(['q-2']);
+ expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-2' });
+ expect(projection.errorRetryText).toBe('describe the screenshot');
+ expect(projection.queuePaused).toBe(false);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ // Capability rejection is pre-RPC, so finishing the old turn must not auto-send. Once the
+ // user has switched models, the explicit Retry consumes the preserved queue row exactly once.
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ await h.coordinator.retryLastError(sid);
+ await flush();
+
+ projection = latestProjection(h.projections);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: 'describe the screenshot',
+ });
+ expect(projection.pendingQueue).toEqual([]);
+ expect(projection.error).toBeNull();
+ expect(projection.recovery).toBeNull();
+ });
+
+ it('preserves a capability-rejected steer when the original active turn errors concurrently', async () => {
+ const h = createHarness();
+ h.setAgentKind('pi');
+ const sid = 'steer-pi-image-capability-active-error';
+ const first = makeItem('q-1', 'first');
+ const second = makeItem('q-2', 'describe the screenshot');
+ h.steerToAgent.mockRejectedValueOnce(Object.assign(
+ new Error('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled'),
+ { code: 'PI_IMAGE_INPUT_UNSUPPORTED' },
+ ));
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+ h.coordinator.enqueue(sid, second);
+ await flush();
+
+ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(false);
+ await flush();
+
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', 'original turn failed');
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+
+ let projection = latestProjection(h.projections);
+ expect(projection.error).toBe('[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled');
+ expect(projection.pendingQueue.map((item) => item.clientId)).toEqual(['q-2']);
+ expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-2' });
+ expect(projection.errorRetryText).toBe('describe the screenshot');
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+
+ // Switching to an image-capable model is represented by the next host send succeeding.
+ // Only the explicit Retry may consume the preserved steer, and it must do so once.
+ await h.coordinator.retryLastError(sid);
+ await flush();
+
+ projection = latestProjection(h.projections);
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: 'describe the screenshot',
+ });
+ expect(projection.pendingQueue).toEqual([]);
+ expect(projection.error).toBeNull();
+ expect(projection.recovery).toBeNull();
+ });
+
it('screens same-turn steers through ghost hooks: block discards without injecting or persisting', async () => {
// review #939 第四轮:steer 直达 steerToAgent 不经 drain,必须补同一道
// will-user-message 筛查,否则被拦消息可经插话原样注入并落库。
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 690076b529..67e668a8f7 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -25,6 +25,7 @@
*/
import { isUnsupportedResponsesImageErrorPayload } from '@cindy/responses-chat-bridge';
+import { isPiImageInputUnsupportedError } from '../../shared/inputError.js';
import { createLogger } from '../logger.js';
import { createMessage as createDbMessage } from '../localDb/ipc/messages.js';
import { touchUserSendInDb } from '../localDb/ipc/sessions.js';
@@ -1417,12 +1418,23 @@ export class AgentInputCoordinator {
if (markerStillPresent) {
latest.error = errorMessage(err);
latest.recovery = null;
+ // 视觉 capability 拒绝发生在 Pi RPC 之前,投递结果确定为“未接收”。把原消息
+ // 恢复到队首并留下 typed recovery;用户切换到视觉模型后可原样重试。与 ack
+ // 超时不同,这里不暂停队列,因为不存在重复投递风险。marker 已被 Stop/clear
+ // 清掉时不会进本分支,因此不会把显式丢弃的消息复活。
+ if (isPiImageInputUnsupportedError(err)) {
+ this.movePreparedItemToQueueFront(latest, item, true);
+ this.movePendingCompactWaitClientIdToFront(latest, item.clientId);
+ latest.recovery = { kind: 'queue-head', clientId: item.clientId };
+ latest.queuePaused = false;
+ latest.queuePausedByRestore = false;
+ }
// 投递结果不确定(ack 超时 / post-send abort,见 isSteerDeliveryUncertainError):
// 把该消息物化到队首(composer 入口的插话不在队列里,不物化则"结果不确定"
// 没有落点——用户按草稿重发同一段文字时模型可能双份消费,review #939 第三轮)
// 并暂停队列,不让 turn 结束后的自动 drain 把它再派发一遍。用户确认模型
// 已回应就删行,没回应就点「继续发送」。队列行入口 prepend 幂等,无副作用。
- if (isSteerDeliveryUncertainError(err)) {
+ else if (isSteerDeliveryUncertainError(err)) {
this.prependQueueHeadIfMissing(latest, item);
latest.queuePaused = true;
// 不确定投递的保护性暂停必须由用户显式处置,不许新输入静默放行。
@@ -2073,6 +2085,20 @@ export class AgentInputCoordinator {
state.queueAbortPending = false;
state.abortBoundaryToken = null;
if (type === 'error') {
+ if (
+ active &&
+ state.recovery?.kind === 'queue-head' &&
+ isPiImageInputUnsupportedError(state.error)
+ ) {
+ // A Pi capability guard rejected a newer steer before RPC and restored it as the
+ // recoverable queue head. The terminal error belongs to the original active turn: close
+ // that old boundary, but do not replace the newer queue-head recovery/banner with an
+ // active-turn retry. The paired done path below preserves the same recovery as well.
+ state.activeTurn = null;
+ state.stickyError = null;
+ this.emit(sessionId);
+ return;
+ }
if (active?.persisted) {
state.activeTurn = null;
state.stickyError = null;
@@ -2218,10 +2244,10 @@ export class AgentInputCoordinator {
// 同轮注入的 steer 在飞期间,老 turn 的 done 可能先到(注入前 turn 恰好收尾)。
// marker 属于 steer 事务而不是老 turn,必须留到 steer() 自己 resolve/reject
// 或 Stop/close 取消,这里不动 steeringQueueClientIds。
- if (!active && state.recovery?.kind === 'queue-head') {
- // A pre-accept rollback has already restored the failed head. A late
- // done/closed-style wake from the old turn must not clear that recovery,
- // otherwise the next drain tick would silently resend it without Retry.
+ if (state.recovery?.kind === 'queue-head') {
+ // A pre-accept rollback or a capability-rejected steer has already restored the failed
+ // head. The latter can still have the original active turn here; its done boundary must
+ // not clear the steer recovery, otherwise the next drain silently resends without Retry.
this.emit(sessionId);
return;
}
@@ -3420,6 +3446,13 @@ export class AgentInputCoordinator {
}));
}
+ private movePendingCompactWaitClientIdToFront(state: SessionInputState, clientId: string): void {
+ state.pendingCompacts = state.pendingCompacts.map((entry) => ({
+ ...entry,
+ waitForClientIds: [clientId, ...entry.waitForClientIds.filter((id) => id !== clientId)],
+ }));
+ }
+
/**
* **唯一的 active-turn recovery 出口。**任何终态路径想留「重试上一轮」入口都必须经这里,
* 不要再直接写 `state.recovery = { kind: 'active-turn', ... }`。
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index f5fd993b0f..fa0c794e18 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -31,6 +31,7 @@ import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
import { isOverloadErrorMessage, parseOverloadRetryProgress } from '@/utils/overloadError';
import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../shared/claudeGatewayError';
+import { isPiImageInputUnsupportedError } from '../../../shared/inputError';
interface ErrorBannerProps {
error: string;
@@ -240,7 +241,9 @@ export function ErrorBanner({
// 加 else if, 标志自动保持 true, 折扣版提示不会误叠加 (无需记得同步维护条件表)。
let displayError: string;
let hasSpecialGuidance = true;
- if (isCredentialSwitchBusy) {
+ if (isPiImageInputUnsupportedError(error)) {
+ displayError = t('ipcError.PI_IMAGE_INPUT_UNSUPPORTED');
+ } else if (isCredentialSwitchBusy) {
displayError = t('chat.errorBanner.credentialSwitchBusy');
} else if (isCodexThreadStale) {
displayError = t('chat.errorBanner.codexThreadStale');
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 63ffed5475..c684ac8b6c 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -782,6 +782,7 @@ export function AddProviderWizard({
id: m.id,
name: m.name,
...(contextWindow !== undefined ? { contextWindow } : {}),
+ ...(presetModel?.supportsImageInput === true ? { supportsImageInput: true } : {}),
};
});
if (agentModels.length === 0) continue;
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
index b3e7e626cc..cafb8b5e10 100644
--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
@@ -30,6 +30,7 @@ import {
createCustomProvider,
readCustomProviderKey,
replaceCustomProviderModelId,
+ setCustomProviderModelSupportsImageInput,
updateCustomProvider,
type RuntimeKeys,
} from '@/lib/customProviders';
@@ -656,6 +657,7 @@ export function CustomProviderDialog({
name: m.name.trim(),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
}))
.filter((m) => m.id.length > 0);
const currentById = new Map(current.map((m) => [m.id, m]));
@@ -676,6 +678,7 @@ export function CustomProviderDialog({
name: cur?.name || m.name,
...(contextWindow !== undefined ? { contextWindow } : {}),
...(cur?.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(cur?.supportsImageInput === true ? { supportsImageInput: true } : {}),
};
}),
];
@@ -727,11 +730,13 @@ export function CustomProviderDialog({
const latest = latestById.get(m.id);
const contextWindow = latest?.contextWindow ?? m.contextWindow;
const defaultEnabled = latest?.defaultEnabled ?? m.defaultEnabled;
+ const supportsImageInput = latest ? latest.supportsImageInput : m.supportsImageInput;
return {
id: m.id,
name: latest?.name.trim() ? latest.name.trim() : m.name,
...(contextWindow !== undefined ? { contextWindow } : {}),
...(defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(supportsImageInput === true ? { supportsImageInput: true } : {}),
};
});
for (const m of previousModels) {
@@ -742,6 +747,7 @@ export function CustomProviderDialog({
name: m.name.trim() || id,
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
});
}
}
@@ -843,6 +849,7 @@ export function CustomProviderDialog({
name: m.name.trim(),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
}))
.filter((m) => m.id && m.name);
const requestPath = rf.requestPath.trim();
@@ -1342,7 +1349,7 @@ export function CustomProviderDialog({
<div className="flex flex-col gap-2">
<FieldLabel>{t('settings.providers.custom.fields.models')}</FieldLabel>
{f.models.map((m, i) => (
- <div key={i} className="flex items-center gap-2">
+ <div key={i} className="flex flex-wrap items-center gap-2">
<div className="flex-1">
<SettingsTextInput
surface="ivory"
@@ -1458,6 +1465,34 @@ export function CustomProviderDialog({
>
<Trash2 size={16} />
</button>
+ {activeTab === 'pi' && (
+ <label className="flex basis-full cursor-pointer items-start gap-2 pr-12 text-[var(--settings-section-desc)]">
+ <input
+ type="checkbox"
+ checked={m.supportsImageInput === true}
+ onChange={(event) => {
+ const supportsImageInput = event.currentTarget.checked;
+ patch(activeTab, (x) => ({
+ ...x,
+ models: setCustomProviderModelSupportsImageInput(
+ x.models,
+ i,
+ supportsImageInput,
+ ),
+ }));
+ }}
+ className="mt-0.5 h-4 w-4 shrink-0 cursor-pointer accent-[var(--settings-menu-text-selected)]"
+ />
+ <span className="flex flex-col gap-0.5 leading-snug">
+ <span className="text-12 font-medium text-[var(--settings-section-sublabel)]">
+ {t('settings.providers.custom.fields.modelSupportsImageInput')}
+ </span>
+ <span className="text-11">
+ {t('settings.providers.custom.fields.modelSupportsImageInputHelp')}
+ </span>
+ </span>
+ </label>
+ )}
</div>
))}
<button
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4650ad7dfc..6ca03f31a2 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1,6 +1,7 @@
{
"ipcError": {
"SESSION_RUNNING": "This session is currently running a task. Please try again shortly.",
+ "PI_IMAGE_INPUT_UNSUPPORTED": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.",
"CREDENTIAL_SWITCH_BUSY": "Another Codex task is still running, so this provider switch was not applied (the session keeps its previous provider). Try again after those tasks finish.",
"REMOTE_WORKDIR_INVALID": "The remote project path is invalid. Choose the project directory again.",
"REMOTE_WORKDIR_NOT_FOUND": "The remote project directory no longer exists. Choose it again.",
@@ -1310,6 +1311,8 @@
"modelNamePlaceholder": "Display name",
"modelContextWindowPlaceholder": "Context (tokens)",
"modelContextWindowTitle": "Context window in tokens. Leave empty for the conservative 200K default; affects the window display and compaction threshold.",
+ "modelSupportsImageInput": "Supports image input",
+ "modelSupportsImageInputHelp": "Enable only when the model actually accepts visual input. Start a new Pi task after saving.",
"addModel": "Add model",
"headers": "Headers (optional)",
"headerNamePlaceholder": "Header-Name",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 99cefe5703..0745e2904a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1,6 +1,7 @@
{
"ipcError": {
"SESSION_RUNNING": "このセッションは現在タスクを実行中です。しばらくしてからもう一度お試しください。",
+ "PI_IMAGE_INPUT_UNSUPPORTED": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。",
"CREDENTIAL_SWITCH_BUSY": "他の Codex タスクが実行中のため、今回のプロバイダー切り替えは適用されませんでした(セッションは元のプロバイダーのままです)。他のタスクが終わってからもう一度お試しください。",
"REMOTE_WORKDIR_INVALID": "リモートプロジェクトのパスが無効です。プロジェクトディレクトリを選び直してください。",
"REMOTE_WORKDIR_NOT_FOUND": "リモートプロジェクトのディレクトリが見つかりません。選び直してください。",
@@ -1310,6 +1311,8 @@
"modelNamePlaceholder": "表示名",
"modelContextWindowPlaceholder": "コンテキスト(tokens)",
"modelContextWindowTitle": "コンテキストウィンドウ(トークン数)。空欄の場合は保守的な既定値 200K。ウィンドウ表示と圧縮しきい値に影響します。",
+ "modelSupportsImageInput": "画像入力に対応",
+ "modelSupportsImageInputHelp": "モデルが実際に画像入力へ対応している場合のみ有効にしてください。保存後、新しい Pi タスクで反映されます。",
"addModel": "モデルを追加",
"headers": "リクエストヘッダー(任意)",
"headerNamePlaceholder": "Header-Name",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 1419845cdc..e84e78663b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1,6 +1,7 @@
{
"ipcError": {
"SESSION_RUNNING": "이 세션은 현재 작업을 실행 중입니다. 잠시 후 다시 시도해 주세요.",
+ "PI_IMAGE_INPUT_UNSUPPORTED": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.",
"CREDENTIAL_SWITCH_BUSY": "다른 Codex 작업이 실행 중이어서 이번 제공자 전환은 적용되지 않았습니다(세션은 기존 제공자를 유지합니다). 다른 작업이 끝난 후 다시 시도해 주세요.",
"REMOTE_WORKDIR_INVALID": "원격 프로젝트 경로가 올바르지 않습니다. 프로젝트 폴더를 다시 선택하세요.",
"REMOTE_WORKDIR_NOT_FOUND": "원격 프로젝트 폴더가 없습니다. 프로젝트 폴더를 다시 선택하세요.",
@@ -1310,6 +1311,8 @@
"modelNamePlaceholder": "표시 이름",
"modelContextWindowPlaceholder": "컨텍스트(tokens)",
"modelContextWindowTitle": "컨텍스트 윈도우(토큰 수). 비워 두면 보수적 기본값 200K가 적용되며, 윈도우 표시와 압축 임계값에 영향을 줍니다.",
+ "modelSupportsImageInput": "이미지 입력 지원",
+ "modelSupportsImageInputHelp": "모델이 실제로 시각 입력을 지원할 때만 켜세요. 저장 후 새 Pi 작업부터 적용됩니다.",
"addModel": "모델 추가",
"headers": "요청 헤더(선택)",
"headerNamePlaceholder": "Header-Name",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 01adc62087..743d8a9817 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1,6 +1,7 @@
{
"ipcError": {
"SESSION_RUNNING": "当前任务正在运行,请稍后再试。",
+ "PI_IMAGE_INPUT_UNSUPPORTED": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。",
"CREDENTIAL_SWITCH_BUSY": "Codex 正在其它任务中运行,本次来源切换未生效(本任务仍使用原来源)。等它结束后再试。",
"REMOTE_MODEL_SWITCH_ROUTE_CHANGE": "目标模型或来源需要不同的远端路由,请关闭并重新创建远程任务后生效。",
"REMOTE_PROVIDER_UPDATING": "供应商凭证正在更新,请稍后重试",
@@ -1310,6 +1311,8 @@
"modelNamePlaceholder": "显示名称",
"modelContextWindowPlaceholder": "上下文(tokens)",
"modelContextWindowTitle": "上下文窗口(tokens)。留空按 200K 保守默认;影响窗口显示与压缩阈值。",
+ "modelSupportsImageInput": "支持图片输入",
+ "modelSupportsImageInputHelp": "仅在该模型确实支持视觉输入时开启。保存后新建 Pi 任务生效。",
"addModel": "添加模型",
"headers": "请求头(可选)",
"headerNamePlaceholder": "Header-Name",
diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
index fbc44b64b0..10446e561e 100644
--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
@@ -6,6 +6,7 @@ import {
customProviderModelConfigFromCatalogModel,
providerViewToCustomProviderConfig,
replaceCustomProviderModelId,
+ setCustomProviderModelSupportsImageInput,
updateCustomProvider,
} from '../customProviders';
import type { ProviderView } from '@cindy/model-providers';
@@ -19,6 +20,7 @@ describe('replaceCustomProviderModelId', () => {
id: 'MiniMax-M3',
name: 'MiniMax M3',
contextWindow: 1_000_000,
+ supportsImageInput: true,
}, 'another-model')).toEqual({
id: 'another-model',
name: 'MiniMax M3',
@@ -35,6 +37,19 @@ describe('replaceCustomProviderModelId', () => {
});
});
+describe('setCustomProviderModelSupportsImageInput', () => {
+ it('updates only the selected model row', () => {
+ const models = [
+ { id: 'text', name: 'Text' },
+ { id: 'vision', name: 'Vision' },
+ ];
+ expect(setCustomProviderModelSupportsImageInput(models, 1, true)).toEqual([
+ models[0],
+ { id: 'vision', name: 'Vision', supportsImageInput: true },
+ ]);
+ });
+});
+
describe('customProviderModelConfigFromCatalogModel', () => {
it('does not freeze the materialized custom-provider default into user config', () => {
expect(customProviderModelConfigFromCatalogModel({
@@ -86,6 +101,19 @@ describe('customProviderModelConfigFromCatalogModel', () => {
defaultEnabled: false,
});
});
+
+ it('preserves an explicit Pi image-input capability through the edit round trip', () => {
+ expect(customProviderModelConfigFromCatalogModel({
+ id: 'vision-model',
+ name: 'Vision Model',
+ contextWindow: 200_000,
+ supportsImageInput: true,
+ })).toEqual({
+ id: 'vision-model',
+ name: 'Vision Model',
+ supportsImageInput: true,
+ });
+ });
});
describe('providerViewToCustomProviderConfig', () => {
diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.ts
index 576aa28d47..2e65ec801a 100644
--- a/apps/desktop/src/renderer/lib/customProviders.ts
+++ b/apps/desktop/src/renderer/lib/customProviders.ts
@@ -35,6 +35,17 @@ export function replaceCustomProviderModelId(
return { id: nextId, name: model.name };
}
+export function setCustomProviderModelSupportsImageInput(
+ models: readonly ProviderRuntimeModelConfig[],
+ targetIndex: number,
+ supportsImageInput: boolean,
+): ProviderRuntimeModelConfig[] {
+ return models.map((model, index) => {
+ if (index !== targetIndex) return model;
+ return { ...model, supportsImageInput };
+ });
+}
+
/**
* 运行期 CatalogModel 已把缺省 contextWindow 物化为通用默认值;转回用户配置时不能把该
* 默认快照写成 override,否则未来默认升级后老配置无法跟随。判据以 contextWindowExplicit
@@ -42,7 +53,15 @@ export function replaceCustomProviderModelId(
* 推断(PR review P1);无标记的旧视图快照回退等值判断,行为不变。
*/
export function customProviderModelConfigFromCatalogModel(
- model: Pick<CatalogModel, 'id' | 'name' | 'contextWindow' | 'contextWindowExplicit' | 'defaultEnabled'>,
+ model: Pick<
+ CatalogModel,
+ | 'id'
+ | 'name'
+ | 'contextWindow'
+ | 'contextWindowExplicit'
+ | 'defaultEnabled'
+ | 'supportsImageInput'
+ >,
): ProviderRuntimeModelConfig {
return {
id: model.id,
@@ -51,6 +70,7 @@ export function customProviderModelConfigFromCatalogModel(
? { contextWindow: model.contextWindow }
: {}),
...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(model.supportsImageInput === true ? { supportsImageInput: true } : {}),
};
}
diff --git a/apps/desktop/src/shared/__tests__/inputError.test.ts b/apps/desktop/src/shared/__tests__/inputError.test.ts
new file mode 100644
index 0000000000..50dbc94836
--- /dev/null
+++ b/apps/desktop/src/shared/__tests__/inputError.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { PI_IMAGE_INPUT_UNSUPPORTED_MARKER, isPiImageInputUnsupportedError } from '../inputError';
+
+describe('isPiImageInputUnsupportedError', () => {
+ it('recognizes both the structured code and the wire-safe marker', () => {
+ expect(
+ isPiImageInputUnsupportedError(
+ Object.assign(new Error('disabled'), { code: 'PI_IMAGE_INPUT_UNSUPPORTED' }),
+ ),
+ ).toBe(true);
+ expect(isPiImageInputUnsupportedError(`${PI_IMAGE_INPUT_UNSUPPORTED_MARKER} disabled`)).toBe(
+ true,
+ );
+ });
+
+ it('does not classify unrelated image errors', () => {
+ expect(isPiImageInputUnsupportedError('image omitted: model does not support images')).toBe(
+ false,
+ );
+ });
+});
diff --git a/apps/desktop/src/shared/inputError.ts b/apps/desktop/src/shared/inputError.ts
new file mode 100644
index 0000000000..3484762467
--- /dev/null
+++ b/apps/desktop/src/shared/inputError.ts
@@ -0,0 +1,14 @@
+export const PI_IMAGE_INPUT_UNSUPPORTED_CODE = 'PI_IMAGE_INPUT_UNSUPPORTED';
+export const PI_IMAGE_INPUT_UNSUPPORTED_MARKER = `[${PI_IMAGE_INPUT_UNSUPPORTED_CODE}]`;
+
+/** Stable Desktop main -> renderer/device-link marker; presentation localizes at display time. */
+export function isPiImageInputUnsupportedError(value: unknown): boolean {
+ const message = value instanceof Error ? value.message : String(value ?? '');
+ const code =
+ value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as { code?: unknown }).code
+ : null;
+ return (
+ code === PI_IMAGE_INPUT_UNSUPPORTED_CODE || message.includes(PI_IMAGE_INPUT_UNSUPPORTED_MARKER)
+ );
+}
diff --git a/apps/mobile/src/__tests__/inputProjectionError.test.ts b/apps/mobile/src/__tests__/inputProjectionError.test.ts
new file mode 100644
index 0000000000..a76a435763
--- /dev/null
+++ b/apps/mobile/src/__tests__/inputProjectionError.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { isPiImageInputUnsupportedProjectionError } from '@/session/inputProjectionError';
+
+describe('isPiImageInputUnsupportedProjectionError', () => {
+ it('recognizes the Desktop projection marker without depending on host locale', () => {
+ expect(
+ isPiImageInputUnsupportedProjectionError(
+ '[PI_IMAGE_INPUT_UNSUPPORTED] image input disabled',
+ ),
+ ).toBe(true);
+ });
+
+ it('leaves ordinary remote errors untouched', () => {
+ expect(isPiImageInputUnsupportedProjectionError('provider unavailable')).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.json
index 59310f06eb..6b38120c5e 100644
--- a/apps/mobile/src/i18n/locales/en/message.json
+++ b/apps/mobile/src/i18n/locales/en/message.json
@@ -147,6 +147,7 @@
"systemInstruction": "System instruction",
"retrySend": "Retry Send",
"clearError": "Clear Error",
+ "piImageInputUnsupported": "Image input is not enabled for the current Pi model. Switch to a model that supports images. For a custom model, enable “Supports image input” in provider settings, then start a new Pi task.",
"credentialSwitchWait": "Waiting for another Codex task to finish; it will send automatically once done",
"aborting": "Stopping; queued messages will stay here",
"paused": "Queue paused; queued messages won't send automatically",
diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.json
index c20b477973..9d155a6fe3 100644
--- a/apps/mobile/src/i18n/locales/ja/message.json
+++ b/apps/mobile/src/i18n/locales/ja/message.json
@@ -147,6 +147,7 @@
"systemInstruction": "システム指令",
"retrySend": "送信を再試行",
"clearError": "エラーをクリア",
+ "piImageInputUnsupported": "現在の Pi モデルでは画像入力が有効になっていません。画像に対応するモデルへ切り替えてください。カスタムモデルの場合は、プロバイダー設定で「画像入力に対応」を有効にしてから、新しい Pi タスクを開始してください。",
"credentialSwitchWait": "他の Codex タスクの終了を待っています。終了後に自動で送信します",
"aborting": "停止中です。キュー内のメッセージはここに保持されます",
"paused": "キューを一時停止しました。キュー内のメッセージは自動送信されません",
diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.json
index deb4a09992..fd1bcb6382 100644
--- a/apps/mobile/src/i18n/locales/ko/message.json
+++ b/apps/mobile/src/i18n/locales/ko/message.json
@@ -147,6 +147,7 @@
"systemInstruction": "시스템 지시",
"retrySend": "전송 재시도",
"clearError": "오류 지우기",
+ "piImageInputUnsupported": "현재 Pi 모델에는 이미지 입력이 활성화되어 있지 않습니다. 이미지를 지원하는 모델로 전환하세요. 사용자 지정 모델이라면 제공자 설정에서 ‘이미지 입력 지원’을 켠 다음 새 Pi 작업을 시작하세요.",
"credentialSwitchWait": "다른 Codex 작업이 끝나기를 기다리는 중입니다. 끝나면 자동으로 전송합니다",
"aborting": "중지 중입니다. 대기 중인 메시지는 여기에 유지됩니다",
"paused": "큐가 일시정지되었습니다. 대기 중인 메시지는 자동으로 전송되지 않습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.json
index ed4a184e24..a5d7b0809a 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/message.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json
@@ -147,6 +147,7 @@
"systemInstruction": "系统指令",
"retrySend": "重试发送",
"clearError": "清除错误",
+ "piImageInputUnsupported": "当前 Pi 模型未启用图片输入。请切换到支持图片的模型;如果这是自定义模型,请在供应商设置中开启“支持图片输入”,然后新建 Pi 任务。",
"credentialSwitchWait": "正在等待其它 Codex 任务结束,结束后自动发送",
"aborting": "正在停止,排队消息会保留在这里",
"paused": "队列已暂停,排队消息不会自动发送",
diff --git a/apps/mobile/src/session/InlineQueueSection.tsx b/apps/mobile/src/session/InlineQueueSection.tsx
index e8d637ea5c..c7495f9765 100644
--- a/apps/mobile/src/session/InlineQueueSection.tsx
+++ b/apps/mobile/src/session/InlineQueueSection.tsx
@@ -24,6 +24,7 @@ import { Text } from '@/components/AppText';
import { Pause, Play } from 'lucide-react-native';
import { describeAgentAuthError } from '@/device-link/remoteStatus';
import type { InputProjection } from '@/session/types';
+import { isPiImageInputUnsupportedProjectionError } from '@/session/inputProjectionError';
import {
fontWeight,
iconSize,
@@ -63,13 +64,18 @@ export function InlineQueueSection({
if (!hasBanner) return null;
const controlsDisabled = busy || !!readOnlyReason;
+ const projectionError = projection.error
+ ? isPiImageInputUnsupportedProjectionError(projection.error)
+ ? t('message.queue.piImageInputUnsupported')
+ : (describeAgentAuthError(projection.error) ?? projection.error)
+ : null;
return (
<View style={styles.container} testID="queue.inline.section">
{projection.error ? (
<View style={styles.errorBox} testID="queue.inline.error">
- {/* agent 未鉴权错误换成带引导的中文提示;其它错误维持原文 */}
- <Text style={styles.errorText}>{describeAgentAuthError(projection.error) ?? projection.error}</Text>
+ {/* 稳定错误 marker 按当前显示端语言翻译;其它错误维持既有 auth 映射或原文。 */}
+ <Text style={styles.errorText}>{projectionError}</Text>
<View style={styles.errorActions}>
<ActionPill
busy={busy}
diff --git a/apps/mobile/src/session/inputProjectionError.ts b/apps/mobile/src/session/inputProjectionError.ts
new file mode 100644
index 0000000000..608be51d05
--- /dev/null
+++ b/apps/mobile/src/session/inputProjectionError.ts
@@ -0,0 +1,5 @@
+export const PI_IMAGE_INPUT_UNSUPPORTED_MARKER = '[PI_IMAGE_INPUT_UNSUPPORTED]';
+
+export function isPiImageInputUnsupportedProjectionError(error: string): boolean {
+ return error.includes(PI_IMAGE_INPUT_UNSUPPORTED_MARKER);
+}
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index d36fbf1eca..39288145bd 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -246,6 +246,83 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
+ it('guards image prompts by the actual provider-model capability and follows model switches', async () => {
+ const agent = new PiAgent(byomDeps(async () => ({
+ providers: [
+ {
+ id: 'native-text',
+ name: 'Native Text',
+ baseUrl: 'http://text.test',
+ api: 'openai-completions',
+ models: [{ id: 'local-model', input: ['text'] }],
+ },
+ {
+ id: 'native-vision',
+ name: 'Native Vision',
+ baseUrl: 'http://vision.test',
+ api: 'openai-completions',
+ models: [{ id: 'local-model', input: ['text', 'image'] }],
+ },
+ ],
+ env: {},
+ })));
+ const handle = await agent.startSession({
+ sessionId: 'image-capability',
+ workingDir: cwd,
+ model: 'local-model',
+ providerId: 'native-text',
+ });
+ const imagePath = path.join(cwd, 'screenshot.png');
+ writeFileSync(
+ imagePath,
+ Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ 'base64',
+ ),
+ );
+ const imageMessage = {
+ type: 'user' as const,
+ content: [{ type: 'image' as const, path: imagePath }],
+ };
+
+ captured.requests.length = 0;
+ await expect(handle.send(imageMessage)).rejects.toMatchObject({
+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ });
+ await expect(handle.steer!(imageMessage)).rejects.toMatchObject({
+ code: 'PI_IMAGE_INPUT_UNSUPPORTED',
+ });
+ expect(captured.requests.some((request) => request.type === 'prompt' || request.type === 'steer'))
+ .toBe(false);
+
+ await handle.setModel!('local-model', { providerId: 'native-vision' });
+ captured.requests.length = 0;
+ await handle.send(imageMessage);
+ expect(captured.requests).toContainEqual(expect.objectContaining({
+ type: 'prompt',
+ images: [expect.objectContaining({ type: 'image', mimeType: 'image/png' })],
+ }));
+
+ // 显式清除来源后实际路由回到 cindy 网关;同名 BYOM 不能抢走能力判断。
+ await handle.setModel!('local-model', { providerId: null });
+ captured.requests.length = 0;
+ await handle.send(imageMessage);
+ expect(captured.requests.some((request) => request.type === 'prompt')).toBe(true);
+
+ // 文件读失败不会生成 image block,仍保留既有的“图片不可读”文本语义。
+ await handle.setModel!('local-model', { providerId: 'native-text' });
+ captured.requests.length = 0;
+ await handle.send({
+ type: 'user',
+ content: [{ type: 'image', path: path.join(cwd, 'missing.png') }],
+ });
+ expect(captured.requests).toContainEqual(expect.objectContaining({
+ type: 'prompt',
+ message: expect.stringContaining('(image unavailable:'),
+ }));
+ await handle.close();
+ });
+
it('keeps a leading /skill: command at the prompt start even when Extra Dirs are configured', async () => {
const agent = new PiAgent(byomDeps(async () => ({ providers: [], env: {} })));
const handle = await agent.startSession({
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 559fc25ae2..dc79a4d3f2 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -95,11 +95,24 @@ const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';
const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';
const PI_MCP_BRIDGE_ENV = 'CINDY_PI_MCP_BRIDGE';
const PI_SECRET_ENV_NAMES_ENV = 'CINDY_PI_SECRET_ENV_NAMES';
+const PI_IMAGE_INPUT_UNSUPPORTED_CODE = 'PI_IMAGE_INPUT_UNSUPPORTED';
/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */
const PI_COMPACT_TIMEOUT_MS = 600_000;
/** 分支摘要同样可能触发一次完整 LLM 调用。 */
const PI_BRANCH_NAVIGATION_TIMEOUT_MS = 600_000;
+class PiImageInputUnsupportedError extends Error {
+ readonly code = PI_IMAGE_INPUT_UNSUPPORTED_CODE;
+
+ constructor() {
+ super(
+ `[${PI_IMAGE_INPUT_UNSUPPORTED_CODE}] Image input is not enabled for the current Pi model. ` +
+ 'Switch to an image-capable model, or enable image input for this custom model and start a new Pi task.',
+ );
+ this.name = 'PiImageInputUnsupportedError';
+ }
+}
+
/**
* digest 分片 body 的**字节**上限(硬上限 8192,留 headroom)。存储层按 UTF-8 字节
* 卡 hardShardBytes,故截断必须按字节而非字符 —— 否则中文摘要(每字 3 字节)会在
@@ -764,6 +777,9 @@ export class PiAgent extends BaseAgent {
const ctx: PiTranslateContext = createPiTranslateContext(this.deps.logger);
let interactionResolver: InteractionResolver | null = null;
let mutableModel = opts.model;
+ // Pi RPC 实际选中的 provider。与用于宿主鉴权/审阅元数据的 mutableProviderId 分开:
+ // null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。
+ let mutablePiProviderId = initialProvider;
let mutableProviderId: string | null | undefined = opts.providerId ?? authProviderId;
let currentAutoReviewIntent = '';
const autoReviewDecisionCache = new Map<string, Promise<AutoReviewDecision>>();
@@ -1121,6 +1137,15 @@ export class PiAgent extends BaseAgent {
}
};
+ const assertImageInputSupported = (images: readonly PiPromptImage[]): void => {
+ if (images.length === 0 || mutablePiProviderId === PI_PROVIDER_ID) return;
+ const nativeModel = nativeProviderById
+ .get(mutablePiProviderId)
+ ?.models.find((candidate) => candidate.id === mutableModel);
+ if (nativeModel?.input?.includes('image')) return;
+ throw new PiImageInputUnsupportedError();
+ };
+
const handle: AgentSessionHandle = {
// getter 而非固定值:setModel / commitRewindFiles 会更新闭包里的 mutableModel /
// sdkSessionId,Session.model / Session.sdkSessionId 直读这两个 handle 属性 ——
@@ -1144,9 +1169,10 @@ export class PiAgent extends BaseAgent {
async send(message: UserMessage, sendOpts?: SendOptions): Promise<void> {
rejectIfCancelled(sendOpts, 'send');
if (sendOpts) handle.validateSendOptions?.(sendOpts);
- setAutoReviewIntent(message.content);
const { text, images } = await buildPiPrompt(message);
rejectIfCancelled(sendOpts, 'send');
+ assertImageInputSupported(images);
+ setAutoReviewIntent(message.content);
// setExtraDirs 是热更新;Pi 没有独立的 mid-session system-prompt RPC,所以在
// 后续 user turn 前附上短引用目录段(但 /skill: 起始时不前置,见 composePiPromptText)。
const promptText = composePiPromptText(text, piExtraDirsPrompt(mutableExtraDirs));
@@ -1168,9 +1194,10 @@ export class PiAgent extends BaseAgent {
async steer(message: UserMessage, sendOpts?: SendOptions): Promise<void> {
rejectIfCancelled(sendOpts, 'steer');
if (sendOpts) handle.validateSendOptions?.(sendOpts);
- setAutoReviewIntent(message.content);
const { text, images } = await buildPiPrompt(message);
rejectIfCancelled(sendOpts, 'steer');
+ assertImageInputSupported(images);
+ setAutoReviewIntent(message.content);
// /skill: 起始时不前置 Extra Dir 引用段(否则命令退化成文本),与 send 同口径。
const promptText = composePiPromptText(text, piExtraDirsPrompt(mutableExtraDirs));
const command: Record<string, unknown> = { type: 'steer', message: escapeLeadingSlashCommand(promptText) };
@@ -1236,6 +1263,7 @@ export class PiAgent extends BaseAgent {
const resp = await proc.request({ type: 'set_model', provider, modelId: model });
if (!resp.success) throw new Error(`pi set_model failed: ${resp.error ?? 'unknown'}`);
mutableModel = model;
+ mutablePiProviderId = provider;
if (setOpts && Object.hasOwn(setOpts, 'providerId')) mutableProviderId = setOpts.providerId;
autoReviewDecisionCache.clear();
const data = (resp.data ?? {}) as { contextWindow?: number };
diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.ts
index c23148a7d3..6d2089f405 100644
--- a/packages/model-providers/src/__tests__/presets.test.ts
+++ b/packages/model-providers/src/__tests__/presets.test.ts
@@ -112,6 +112,29 @@ describe('sanitizePresets', () => {
}])).toEqual([]);
});
+ it('Pi 图片输入能力只接受显式布尔值', () => {
+ const visual = {
+ id: 'visual-pi',
+ name: 'Visual Pi',
+ runtimes: {
+ pi: {
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ models: [{ id: 'vision', name: 'Vision', supportsImageInput: true }],
+ },
+ },
+ };
+ expect(sanitizePresets([visual])).toEqual([visual]);
+ expect(sanitizePresets([{
+ ...visual,
+ runtimes: {
+ pi: {
+ ...visual.runtimes.pi,
+ models: [{ id: 'vision', name: 'Vision', supportsImageInput: 'yes' }],
+ },
+ },
+ }])).toEqual([]);
+ });
+
it('requestPath 合法时保留;跨主机、fragment 与 CRLF 形态剥字段但保留预设', () => {
const runtime = (requestPath: unknown) => ({
codex: {
diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.ts
index 63affbbe8a..8077025e2b 100644
--- a/packages/model-providers/src/__tests__/user-provider.test.ts
+++ b/packages/model-providers/src/__tests__/user-provider.test.ts
@@ -279,7 +279,7 @@ describe('buildUserProvider (per-runtime)', () => {
pi: {
baseUrl: 'http://127.0.0.1:11434/v1',
wireProtocol: 'openai-chat',
- models: [{ id: 'qwen3:8b', name: 'Qwen3 8B' }],
+ models: [{ id: 'qwen3:8b', name: 'Qwen3 8B', supportsImageInput: true }],
},
},
});
@@ -290,6 +290,7 @@ describe('buildUserProvider (per-runtime)', () => {
expect((p.models.pi ?? [])[0]?.efforts).toEqual(['minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
expect((p.models.pi ?? [])[0]?.defaultEffort).toBe('high');
expect((p.models.pi ?? [])[0]?.group).toBe('custom:localollama');
+ expect((p.models.pi ?? [])[0]?.supportsImageInput).toBe(true);
});
it('orders pi after claude-code and codex (AGENT_ORDER)', () => {
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index e5d77bceb5..2ed0b624c4 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -378,6 +378,9 @@ function isValidPreset(v: unknown): v is ProviderPreset {
mm.contextWindow !== undefined
&& (typeof mm.contextWindow !== 'number' || !Number.isFinite(mm.contextWindow) || mm.contextWindow <= 0)
) return false;
+ if (mm.supportsImageInput !== undefined && typeof mm.supportsImageInput !== 'boolean') {
+ return false;
+ }
}
if (r.wireProtocol !== undefined && !isWireProtocol(r.wireProtocol)) return false;
if (agent === 'claude-code' && r.wireProtocol === 'openai-chat') return false;
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 150003edc7..54dc147cdd 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -345,6 +345,12 @@ export interface CatalogModel {
* 新增模型缺省 = 默认开,符合「未自定义用户随版本吃到新默认」(CLAUDE.md 规则 20)。
*/
defaultEnabled?: boolean;
+ /**
+ * 该来源下的模型是否已由用户确认支持图片输入。目前只供 Pi 自定义 provider 使用;
+ * 缺省按 false 处理,避免把纯文本端点误报成视觉模型。它是 per-provider 能力,不参与
+ * `modelSignature` 的同 id 跨供应商一致性校验。
+ */
+ supportsImageInput?: boolean;
/**
* **视图层字段**:该 (供应商, 模型) 已被用户「停用」(准入关,与 `defaultEnabled` 的
* 「显示」轴正交)。由 `buildRegistry` 按 host 注入的 ModelDisableOverrides 填充,
@@ -432,6 +438,8 @@ export interface ProviderRuntimeModelConfig {
contextWindow?: number;
/** 模型未被用户显式开关时的可见性;缺省保持历史行为(默认可见)。 */
defaultEnabled?: boolean;
+ /** Pi 自定义模型是否支持原生图片输入;缺省保守视为不支持。 */
+ supportsImageInput?: boolean;
}
/**
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index 1bbf1c7967..677c26636e 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -70,6 +70,8 @@ function toCatalogModel(
group: `custom:${providerId}`,
// 手填模型保持历史默认可见;刷新发现的模型可显式声明默认隐藏。
defaultEnabled: m.defaultEnabled ?? true,
+ // 图片能力必须由用户/预设明确确认;缺省不猜,防止 Pi 静默把截图降级成占位文本。
+ ...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
};
}