diff --git a/docs/configuration.md b/docs/configuration.md index 62514d7a9..58671ab6c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1518,6 +1518,8 @@ OpenAI Codex, xAI Grok subscriptions, and Azure OpenAI use Responses; Anthropic Use the **Image input** switch in each preset to match the model's image capability. It is enabled by default; turn it off for text-only models. Requests containing images follow the configured primary and fallback order, using presets with **Image input** enabled. Text-only requests use the full configured order. If every candidate is text-only, nanobot returns an image-input error before sending the request. +In WebUI, if **Image input** is off and no fallback accepts images, the composer keeps the draft. Select **View preset** in the toast to check the switch. Turning it on lets nanobot send images, but the model must support them. If the provider rejects a request containing images before any work is saved, the toast also takes you to the preset. + For manual configuration, set `supportsImages` on a named preset, the implicit `agents.defaults` preset, or an inline fallback. Each defaults independently to `true`; use `false` for a text-only model. Transient retries preserve the original messages and images, and API validation errors are returned directly. ### Model Fallbacks diff --git a/nanobot/providers/base.py b/nanobot/providers/base.py index 4e3aa6ebd..4324b8f10 100644 --- a/nanobot/providers/base.py +++ b/nanobot/providers/base.py @@ -1044,7 +1044,7 @@ class LLMProvider(ABC): return None return LLMResponse( content="This model preset does not support image input. Select an image-capable preset in model settings.", - finish_reason="error", error_kind="invalid_request", error_code="unsupported_image", + finish_reason="error", error_kind="unsupported_image", error_code="unsupported_image", error_should_retry=False, ) @@ -1436,7 +1436,7 @@ class LLMProvider(ABC): ) as compaction: if isinstance(context, ProviderCallContext): kw["provider_context"] = replace(context, compaction=compaction) - return await self._run_with_retry( + response = await self._run_with_retry( attributed_call, kw, retry_mode=retry_mode, @@ -1446,6 +1446,16 @@ class LLMProvider(ABC): should_retry_guard=should_retry_guard, on_stream_recover=on_stream_recover, ) + # A generic 400 rejects the request, but does not establish why the image + # request failed or whether the model supports images at all. + if ( + response.finish_reason == "error" + and response.error_status_code == 400 + and self.public_error_kind(response) == "unknown" + and self._request_contains_images(kw["messages"], context) + ): + return replace(response, error_kind="image_request_rejected") + return response @classmethod def _extract_retry_after(cls, content: str | None) -> float | None: @@ -1571,6 +1581,8 @@ class LLMProvider(ABC): @classmethod def public_error_kind(cls, response: LLMResponse) -> str: """Return a stable public category without exposing provider details.""" + if response.error_kind == "unsupported_image": + return "unsupported_image" if response.primary_error_kind is not None: return response.primary_error_kind if cls.is_arrearage_response(response): @@ -1579,7 +1591,7 @@ class LLMProvider(ABC): # A plain 403 can be a policy or permission rejection, not bad credentials. if kind in {"authentication", "oauth_auth_required"} or response.error_status_code == 401: return "authentication" - if kind in {"connection", "timeout"}: + if kind in {"connection", "timeout", "image_request_rejected"}: return kind if response.error_status_code == 429: return "rate_limit" diff --git a/nanobot/providers/fallback_provider.py b/nanobot/providers/fallback_provider.py index 18978344d..9581baca6 100644 --- a/nanobot/providers/fallback_provider.py +++ b/nanobot/providers/fallback_provider.py @@ -701,7 +701,8 @@ class FallbackProvider(LLMProvider): last_response, preserve_provider_state_on_error=preserve_primary_state, primary_error_kind=( - self.public_error_kind(primary_response) if primary_response is not None else None + self.public_error_kind(primary_response) + if primary_response is not None and image_error is None else None ), ) # Primary was skipped and no fallback returned a response. Keep the result diff --git a/nanobot/session/recovery.py b/nanobot/session/recovery.py index f108a5348..35ac234b4 100644 --- a/nanobot/session/recovery.py +++ b/nanobot/session/recovery.py @@ -511,6 +511,7 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str failure_error_kind = state.get("failure_error_kind") if isinstance(failure_error_kind, str) and failure_error_kind in { "authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown", + "unsupported_image", "image_request_rejected", }: payload["failure_error_kind"] = failure_error_kind if state.get("reply_preserved") is True: diff --git a/nanobot/webui/recovery.py b/nanobot/webui/recovery.py index 654bceec3..2ba0658fb 100644 --- a/nanobot/webui/recovery.py +++ b/nanobot/webui/recovery.py @@ -18,6 +18,7 @@ from nanobot.bus.outbound_events import ( from nanobot.bus.queue import MessageBus from nanobot.session import turn_continuation from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader +from nanobot.session.history_visibility import is_hidden_history_message from nanobot.session.manager import Session, SessionManager from nanobot.session.recovery import ( KNOWN_CHECKPOINT_PHASES, @@ -169,19 +170,25 @@ class RecoveryCoordinator: if failure_kind == "model": # The turn has already saved its transcript and tool results. Use # that context, never resend the user's message or replay tools. - waiting = self._set_state( + reply_preserved = bool(session.messages and session.messages[-1].get("_interrupted") is True) + input_rejected = ( + failure_error_kind in {"unsupported_image", "image_request_rejected"} + and not reply_preserved + and not self._has_saved_continuation_context(session, skip_hidden_user=True) + ) + result = self._set_state( session, - status="awaiting_user", + status="recovered" if input_rejected else "awaiting_user", recovery_id=uuid4().hex, attempts=cast(int, state.get("attempts", 0)) if state else 0, - reason="model_request_failed", - can_continue=any(message.get("role") == "user" for message in session.messages), + reason="input_rejected" if input_rejected else "model_request_failed", + can_continue=not input_rejected and any(message.get("role") == "user" for message in session.messages), ) - waiting["failure_error_kind"] = failure_error_kind or "unknown" - if session.messages and session.messages[-1].get("_interrupted") is True: - waiting["reply_preserved"] = True + result["failure_error_kind"] = failure_error_kind or "unknown" + if reply_preserved: + result["reply_preserved"] = True await self.sessions.state.restore_interruption(session) - await self._publish(chat_id, waiting) + await self._publish(chat_id, result) return if not state or state["status"] != "resuming": return @@ -494,13 +501,14 @@ class RecoveryCoordinator: return state @staticmethod - def _has_saved_continuation_context(session: Session) -> bool: + def _has_saved_continuation_context(session: Session, *, skip_hidden_user: bool = False) -> bool: """Whether an interrupted turn left model-visible context to continue from.""" last_user = next( ( index for index in range(len(session.messages) - 1, -1, -1) if session.messages[index].get("role") == "user" + and not (skip_hidden_user and is_hidden_history_message(session.messages[index])) ), None, ) diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.py index 3c2a5e3b4..1288e2ab4 100644 --- a/nanobot/webui/settings_models.py +++ b/nanobot/webui/settings_models.py @@ -105,6 +105,7 @@ class ModelSettingsPayload(TypedDict): model_presets: list[dict[str, Any]] model_call_order: list[str] model_call_order_editable: bool + image_fallback_configured: bool model_configuration_migratable: bool model_api_resolution_supported: bool provider_api_configuration_supported: bool @@ -1226,6 +1227,10 @@ def model_settings_payload( "model_request_overrides_supported": True, "model_call_order": model_call_order, "model_call_order_editable": model_call_order_editable, + "image_fallback_configured": any( + (config.model_presets[fallback] if isinstance(fallback, str) else fallback).supports_images + for fallback in defaults.fallback_models + ), "model_configuration_migratable": _legacy_model_configuration_migratable( config, oauth_status, diff --git a/tests/providers/test_image_capability.py b/tests/providers/test_image_capability.py index 5758c0d09..37ddfc8c4 100644 --- a/tests/providers/test_image_capability.py +++ b/tests/providers/test_image_capability.py @@ -123,10 +123,22 @@ async def test_no_image_capable_candidate_fails_without_sending_or_stripping(str call = chain.chat_stream_with_retry if stream else chain.chat_with_retry response = await call(messages=[{"role": "user", "content": [_IMAGE]}]) assert response.error_code == "unsupported_image" + assert LLMProvider.public_error_kind(response) == "unsupported_image" assert response.error_should_retry is False assert primary.calls == created == [] +async def test_image_capable_fallback_reports_its_own_failure(): + primary = ImageProvider(False) + fallback = ImageProvider(response=LLMResponse( + "upstream rejection", finish_reason="error", error_status_code=401, error_code="unsupported_image", + )) + chain = FallbackProvider(primary, [ModelPresetConfig(model="vision")], lambda _: fallback) + response = await chain.chat_with_retry(messages=[{"role": "user", "content": [_IMAGE]}]) + assert not primary.calls and len(fallback.calls) == 1 + assert LLMProvider.public_error_kind(response) == "authentication" + + @pytest.mark.parametrize("stream", [False, True]) async def test_declared_vision_does_not_hide_actual_upstream_rejection(stream): upstream = LLMResponse("unsupported image format", finish_reason="error", error_status_code=400) @@ -139,11 +151,21 @@ async def test_declared_vision_does_not_hide_actual_upstream_rejection(stream): response = await call(messages=messages) assert response.content == upstream.content assert response.error_status_code == 400 + assert LLMProvider.public_error_kind(response) == "image_request_rejected" + assert LLMProvider.public_error_kind(upstream) == "unknown" assert len(primary.calls) == 1 assert created == [] assert messages == before +async def test_text_request_rejected_with_400_keeps_generic_diagnosis(): + provider = ImageProvider(response=LLMResponse( + "invalid request", finish_reason="error", error_status_code=400, + )) + response = await provider.chat_with_retry(messages=[{"role": "user", "content": "hi"}]) + assert LLMProvider.public_error_kind(response) == "unknown" + + def test_factory_resolves_independent_capabilities_and_refresh_signature(): config = Config.model_validate({ "agents": {"defaults": {"modelPreset": "text", "fallbackModels": ["vision", {"provider": "custom", "model": "inline"}]}}, diff --git a/tests/providers/test_provider_retry.py b/tests/providers/test_provider_retry.py index a57de9f03..5f6fe4dc0 100644 --- a/tests/providers/test_provider_retry.py +++ b/tests/providers/test_provider_retry.py @@ -1,6 +1,7 @@ import asyncio import copy import random +from dataclasses import replace import pytest @@ -475,7 +476,7 @@ _IMAGE_MSG = [ error_status_code=400, error_code="unsupported_image", error_should_retry=False, ), ]) -async def test_nontransient_image_error_returns_original_response(streaming, error) -> None: +async def test_nontransient_image_error_reports_rejection_without_retry(streaming, error) -> None: provider = ScriptedProvider([error, LLMResponse(content="unexpected text-only answer")]) messages = copy.deepcopy(_IMAGE_MSG) original = copy.deepcopy(messages) @@ -483,10 +484,11 @@ async def test_nontransient_image_error_returns_original_response(streaming, err response = await call(messages=messages) - assert response is error + assert response == replace(error, error_kind="image_request_rejected") assert provider.calls == 1 assert messages == original - assert LLMProvider.public_error_kind(response) == "unknown" + assert LLMProvider.public_error_kind(response) == "image_request_rejected" + assert LLMProvider.public_error_kind(error) == "unknown" @pytest.mark.asyncio @@ -543,7 +545,10 @@ async def test_image_requests_preserve_native_context_and_compaction_budget( ), ) - assert response is (success if transient else error) + if transient: + assert response is success + else: + assert response == replace(error, error_kind="image_request_rejected") assert provider.calls == (2 if transient else 1) assert messages == original assert state.to_private_record() == original_state @@ -580,7 +585,7 @@ async def test_transient_then_terminal_image_error_preserves_input(monkeypatch, call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry response = await call(messages=messages, on_retry_status=status) - assert response is error + assert response == replace(error, error_kind="image_request_rejected") assert provider.calls == 2 assert messages == original assert [event.state for event in statuses] == ["waiting", "cleared"] diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.py index 56e435a33..fd3ac9d44 100644 --- a/tests/session/test_recovery.py +++ b/tests/session/test_recovery.py @@ -880,6 +880,43 @@ async def test_model_failure_waits_across_restart_and_rejects_duplicate_continue await coordinator.handle_action("continue", payload) +@pytest.mark.asyncio +@pytest.mark.parametrize("progress", ["none", "reply", "tool"]) +async def test_image_request_rejection_only_waits_for_recovery_when_work_is_saved( + tmp_path: Path, progress: str, +) -> None: + coordinator, bus, sessions = _coordinator(tmp_path) + session = sessions.get_or_create("websocket:chat") + session.messages = [{"role": "user", "content": "read this image"}] + if progress == "reply": + session.messages.append({"role": "assistant", "content": "saved reply", "_interrupted": True}) + else: + if progress == "tool": + session.messages.extend([ + {"role": "assistant", "content": "", "tool_calls": [{"id": "call-1"}]}, + {"role": "tool", "content": "saved result", "tool_call_id": "call-1"}, + {"role": "user", "content": "continue", "_hidden_history": {"kind": "internal_continuation"}}, + ]) + session.messages.append({"role": "assistant", "content": "[Assistant reply unavailable due to model error.]"}) + _persist(sessions, session) + + await coordinator.turn_completed( + session.key, failure_kind="model", failure_error_kind="image_request_rejected", + ) + + event = bus.outbound.get_nowait().event + assert isinstance(event, RecoveryStateEvent) + assert event.failure_error_kind == "image_request_rejected" + saved = sessions.get_or_create(session.key) + assert saved.messages == session.messages + if progress == "none": + assert (event.status, event.reason) == ("recovered", "input_rejected") + assert saved.metadata[RECOVERY_METADATA_KEY]["status"] == "recovered" + else: + assert (event.status, event.reason) == ("awaiting_user", "model_request_failed") + assert saved.metadata[RECOVERY_METADATA_KEY]["status"] == "awaiting_user" + + @pytest.mark.asyncio async def test_new_input_after_model_failure_does_not_change_saved_context(tmp_path: Path) -> None: coordinator, _, sessions = _coordinator(tmp_path) diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py index c64495eb7..e063a4953 100644 --- a/tests/webui/test_settings_api.py +++ b/tests/webui/test_settings_api.py @@ -3012,3 +3012,6 @@ def test_preset_image_capability_persists_and_preserves_unrelated_edits(tmp_path assert json.loads(config_path.read_text(encoding="utf-8"))["modelPresets"]["Text"]["supportsImages"] is True defaulted = create_model_configuration({"name": ["Default vision"], "provider": ["openai"], "model": ["gpt-4.1"]}) assert next(row for row in defaulted["model_presets"] if row["name"] == "Default vision")["supports_images"] is True + assert defaulted["image_fallback_configured"] is False + order = update_model_call_order({"order": [json.dumps(["Text", "Default vision"])]}) + assert order["image_fallback_configured"] is True diff --git a/tests/webui/test_settings_models.py b/tests/webui/test_settings_models.py index e96a301a7..eb7d0609d 100644 --- a/tests/webui/test_settings_models.py +++ b/tests/webui/test_settings_models.py @@ -156,6 +156,7 @@ def test_model_domain_owns_dto_and_config_updates() -> None: "model_presets", "model_call_order", "model_call_order_editable", + "image_fallback_configured", "model_configuration_migratable", "model_api_resolution_supported", "provider_api_configuration_supported", diff --git a/tui/src/app/status.ts b/tui/src/app/status.ts index 14297a742..f8f0a8b9e 100644 --- a/tui/src/app/status.ts +++ b/tui/src/app/status.ts @@ -31,6 +31,9 @@ function retryFailureLabel(errorKind: string): string { } export function terminalModelFailureLine(errorKind?: string, attempts?: number): string { + if (errorKind === "unsupported_image") { + return "Image input is off for this preset. Check the preset or select a model that supports images." + } const reason = retryFailureLabel(errorKind || "unknown") if (errorKind === "billing") { return `${reason}. Add credit or check billing for the provider account, then try again.` diff --git a/webui/src/App.tsx b/webui/src/App.tsx index d015fd5c5..33d42116f 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -272,7 +272,11 @@ function readShellRoute(): ShellRoute { activeKey, temporary, settingsSection, - settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher") ? focus : undefined, + settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher") + ? focus + : settingsSection === "models" && focus?.startsWith("image-input:") + ? `image-input:${focus.slice("image-input:".length)}` + : undefined, }; } if (path === "/apps") { @@ -333,7 +337,7 @@ function shellRouteHash(route: ShellRoute): string { const params = new URLSearchParams(); if (route.view === "settings" && route.settingsSection !== "overview") { params.set("section", route.settingsSection); - if (route.settingsSection === "advanced" && route.settingsFocus) params.set("focus", route.settingsFocus); + if (route.settingsFocus) params.set("focus", route.settingsFocus); } if (route.view === "apps" && route.settingsSection !== "apps") { params.set("section", route.settingsSection); @@ -1890,6 +1894,11 @@ function Shell({ const onOpenModelSettings = useCallback(() => { onOpenSettings("models"); }, [onOpenSettings]); + const onInspectImagePreset = useCallback((name: string) => { + setSessionSearchOpen(false); + navigate({ view: "settings", activeKey, settingsSection: "models", settingsFocus: `image-input:${name}` }); + setMobileSidebarOpen(false); + }, [activeKey, navigate]); const onOpenSandboxSettings = useCallback((target: SettingsFocusTarget) => { setSessionSearchOpen(false); navigate({ view: "settings", activeKey, settingsSection: "advanced", settingsFocus: target }); @@ -2693,6 +2702,7 @@ function Shell({ settingsSnapshot={settingsSnapshot} settingsLoading={settingsLoading} onOpenModelSettings={onOpenModelSettings} + onInspectImagePreset={onInspectImagePreset} onOpenSandboxSettings={onOpenSandboxSettings} skills={skills} /> @@ -2760,6 +2770,7 @@ function Shell({ settingsSnapshot={settingsSnapshot} settingsLoading={settingsLoading} onOpenModelSettings={onOpenModelSettings} + onInspectImagePreset={onInspectImagePreset} onOpenSandboxSettings={onOpenSandboxSettings} skills={skills} /> diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index f17ec1049..fc0609b12 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -2,7 +2,7 @@ import { ChevronLeft } from "lucide-react"; import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogLayoutContext, DialogTitle } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; -import type { SettingsExitGuard, SettingsFocusTarget } from "@/components/settings/contracts"; +import { imageInputPresetFromFocus, type SettingsExitGuard, type SettingsFocusTarget } from "@/components/settings/contracts"; import { isAppsSection, isCapabilitySection, type AppsSectionKey, type SettingsSectionKey } from "@/components/settings/contracts"; import { SegmentedControl } from "@/components/ui/segmented-control"; import { SettingsFeature } from "@/components/settings/shared/SettingsFeature"; @@ -291,6 +291,7 @@ export function SettingsPage({ form={modelState.form} setForm={modelState.setForm} editingPresetName={modelState.modelPresetEditingName} + imageInputPreset={imageInputPresetFromFocus(focusTarget)} presetNameError={modelState.modelPresetNameError} error={error} settings={settings} diff --git a/webui/src/components/settings/contracts.ts b/webui/src/components/settings/contracts.ts index 9203f8d80..68b05b3ca 100644 --- a/webui/src/components/settings/contracts.ts +++ b/webui/src/components/settings/contracts.ts @@ -46,4 +46,8 @@ export type ApplySettingsPayload = ( ) => void; export type MaybeRestartHostEngine = (payload: RestartAwarePayload) => Promise; -export type SettingsFocusTarget = "sandbox" | "sandbox-launcher"; +export type SettingsFocusTarget = "sandbox" | "sandbox-launcher" | `image-input:${string}`; + +export function imageInputPresetFromFocus(target?: SettingsFocusTarget): string | undefined { + return target?.startsWith("image-input:") ? target.slice("image-input:".length) : undefined; +} diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsx index 2ebef6d1b..7310a43a0 100644 --- a/webui/src/components/settings/models/ModelsSettings.tsx +++ b/webui/src/components/settings/models/ModelsSettings.tsx @@ -212,6 +212,7 @@ export function ModelsSettings({ form, setForm, editingPresetName, + imageInputPreset, presetNameError, error, settings, @@ -243,6 +244,7 @@ export function ModelsSettings({ form: AgentSettingsDraft; setForm: Dispatch>; editingPresetName: string; + imageInputPreset?: string; presetNameError: string | null; error?: string | null; settings: SettingsPayload; @@ -286,6 +288,9 @@ export function ModelsSettings({ }); const editorTriggerRef = useRef(null); const presetNameInputRef = useRef(null); + const imageInputRef = useRef(null); + const openedImagePreset = useRef(); + const focusImageInput = useRef(false); const suggestedPresetNameRef = useRef(null); const presetContextInitializedRef = useRef(false); const [editorRowKey, setEditorRowKey] = useState(null); @@ -404,20 +409,11 @@ export function ModelsSettings({ disabled: callOrderBusy, onReorder: (keys) => onChangeCallOrder(keys.map((key) => presetRows.find((row) => row.key === key)!.name)), }); - const selectPreset = async ( + const openPreset = ( preset: SettingsPayload["model_presets"][number], rowKey: string, ) => { - setHideEditorReturnFocus(false); - editorTriggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; - const toggleCurrentPreset = - !creating && selectedPreset?.name === preset.name && activeEditorRowKey === rowKey; - if (edits.needsCompletion() && !(await edits.commit())) return; onSelectConfiguration(preset.name); - if (toggleCurrentPreset) { - setEditorOpen((open) => !open); - return; - } setForm((prev) => ({ ...prev, modelPreset: preset.name, @@ -437,6 +433,28 @@ export function ModelsSettings({ setEditorRowKey(rowKey); setEditorOpen(true); }; + const selectPreset = async ( + preset: SettingsPayload["model_presets"][number], + rowKey: string, + ) => { + setHideEditorReturnFocus(false); + editorTriggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; + if (edits.needsCompletion() && !(await edits.commit())) return; + if (!creating && selectedPreset?.name === preset.name && activeEditorRowKey === rowKey) { + setEditorOpen((open) => !open); + } else { + openPreset(preset, rowKey); + } + }; + + useEffect(() => { + if (openedImagePreset.current === imageInputPreset) return; + const row = presetRows.find(({ name }) => name === imageInputPreset); + openedImagePreset.current = imageInputPreset; + if (!row?.preset) return; + focusImageInput.current = true; + openPreset(row.preset, row.key); + }); const moveCallOrderItem = (index: number, offset: -1 | 1) => { if (callOrderBusy) return; @@ -575,6 +593,7 @@ export function ModelsSettings({ description={t("settings.models.imageInputHelp")} > setHideEditorReturnFocus(true)} className="relative max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none gap-0 overflow-y-auto p-0" + onOpenAutoFocus={(event) => { + if (!focusImageInput.current || !imageInputRef.current) return; + focusImageInput.current = false; + event.preventDefault(); + imageInputRef.current.focus(); + }} onCloseAutoFocus={(event) => { event.preventDefault(); editorTriggerRef.current?.focus(); diff --git a/webui/src/components/thread/RecoveryNotice.tsx b/webui/src/components/thread/RecoveryNotice.tsx index b3824b5fa..3f35709a2 100644 --- a/webui/src/components/thread/RecoveryNotice.tsx +++ b/webui/src/components/thread/RecoveryNotice.tsx @@ -8,16 +8,18 @@ import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import type { RecoveryState } from "@/lib/types"; -import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure"; +import { isImageRequestFailure, resolveModelRequestFailureCopy } from "@/lib/model-request-failure"; interface RecoveryNoticeProps { state: RecoveryState; onContinue: () => Promise; onDismiss: () => Promise; onOpenSettings?: () => void; + onInspectImagePreset?: () => void; + imageInputBlocked?: boolean; } -export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }: RecoveryNoticeProps) { +export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings, onInspectImagePreset, imageInputBlocked }: RecoveryNoticeProps) { const { t } = useTranslation(); const [pending, setPending] = useState<"continue" | "dismiss" | null>(null); const [error, setError] = useState(null); @@ -38,6 +40,8 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }: const modelFailure = state.reason === "model_request_failed" ? resolveModelRequestFailureCopy({ errorKind: state.failure_error_kind }, t) : null; + const imageFailure = modelFailure !== null && isImageRequestFailure(state.failure_error_kind); + const openSettings = imageFailure ? onInspectImagePreset : onOpenSettings; const title = modelFailure?.title ?? (state.status === "failed" ? t("recovery.failed", { defaultValue: "Task recovery failed" }) : t("recovery.interrupted", { defaultValue: "Task interrupted" })); @@ -45,7 +49,7 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }: ? t("recovery.failedHelp", { defaultValue: "The saved task could not be restored safely. Review it before continuing.", }) - : modelFailure && state.reply_preserved === true + : modelFailure && !imageFailure && state.reply_preserved === true ? t("recovery.replyPreserved", { defaultValue: "Reply saved. You can continue." }) : modelFailure?.body ?? t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." }); const run = (action: "continue" | "dismiss") => { @@ -74,9 +78,9 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }:

{title}

- {modelFailure && onOpenSettings ? ( - ) : null}

{t("recovery.dismiss", { defaultValue: "Dismiss" })} - {!contextUnavailable ? ( + {!contextUnavailable && !(state.failure_error_kind === "unsupported_image" && imageInputBlocked) ? (