fix(webui): open the preset for blocked image input (#6724)
This commit is contained in:
1 parent
607de63fb4
commit
ce12bfdd0d
38 files changed
+430
-78
No files matched your search
@@ -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.
|
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.
|
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
|
### Model Fallbacks
|
||||||
|
|||||||
@@ -1044,7 +1044,7 @@ class LLMProvider(ABC):
|
|||||||
return None
|
return None
|
||||||
return LLMResponse(
|
return LLMResponse(
|
||||||
content="This model preset does not support image input. Select an image-capable preset in model settings.",
|
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,
|
error_should_retry=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1436,7 +1436,7 @@ class LLMProvider(ABC):
|
|||||||
) as compaction:
|
) as compaction:
|
||||||
if isinstance(context, ProviderCallContext):
|
if isinstance(context, ProviderCallContext):
|
||||||
kw["provider_context"] = replace(context, compaction=compaction)
|
kw["provider_context"] = replace(context, compaction=compaction)
|
||||||
return await self._run_with_retry(
|
response = await self._run_with_retry(
|
||||||
attributed_call,
|
attributed_call,
|
||||||
kw,
|
kw,
|
||||||
retry_mode=retry_mode,
|
retry_mode=retry_mode,
|
||||||
@@ -1446,6 +1446,16 @@ class LLMProvider(ABC):
|
|||||||
should_retry_guard=should_retry_guard,
|
should_retry_guard=should_retry_guard,
|
||||||
on_stream_recover=on_stream_recover,
|
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
|
@classmethod
|
||||||
def _extract_retry_after(cls, content: str | None) -> float | None:
|
def _extract_retry_after(cls, content: str | None) -> float | None:
|
||||||
@@ -1571,6 +1581,8 @@ class LLMProvider(ABC):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def public_error_kind(cls, response: LLMResponse) -> str:
|
def public_error_kind(cls, response: LLMResponse) -> str:
|
||||||
"""Return a stable public category without exposing provider details."""
|
"""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:
|
if response.primary_error_kind is not None:
|
||||||
return response.primary_error_kind
|
return response.primary_error_kind
|
||||||
if cls.is_arrearage_response(response):
|
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.
|
# 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:
|
if kind in {"authentication", "oauth_auth_required"} or response.error_status_code == 401:
|
||||||
return "authentication"
|
return "authentication"
|
||||||
if kind in {"connection", "timeout"}:
|
if kind in {"connection", "timeout", "image_request_rejected"}:
|
||||||
return kind
|
return kind
|
||||||
if response.error_status_code == 429:
|
if response.error_status_code == 429:
|
||||||
return "rate_limit"
|
return "rate_limit"
|
||||||
|
|||||||
@@ -701,7 +701,8 @@ class FallbackProvider(LLMProvider):
|
|||||||
last_response,
|
last_response,
|
||||||
preserve_provider_state_on_error=preserve_primary_state,
|
preserve_provider_state_on_error=preserve_primary_state,
|
||||||
primary_error_kind=(
|
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
|
# Primary was skipped and no fallback returned a response. Keep the result
|
||||||
|
|||||||
@@ -511,6 +511,7 @@ def recovery_state_from_metadata(metadata: Mapping[str, Any] | None) -> dict[str
|
|||||||
failure_error_kind = state.get("failure_error_kind")
|
failure_error_kind = state.get("failure_error_kind")
|
||||||
if isinstance(failure_error_kind, str) and failure_error_kind in {
|
if isinstance(failure_error_kind, str) and failure_error_kind in {
|
||||||
"authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown",
|
"authentication", "billing", "connection", "timeout", "rate_limit", "server", "unknown",
|
||||||
|
"unsupported_image", "image_request_rejected",
|
||||||
}:
|
}:
|
||||||
payload["failure_error_kind"] = failure_error_kind
|
payload["failure_error_kind"] = failure_error_kind
|
||||||
if state.get("reply_preserved") is True:
|
if state.get("reply_preserved") is True:
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from nanobot.bus.outbound_events import (
|
|||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.session import turn_continuation
|
from nanobot.session import turn_continuation
|
||||||
from nanobot.session.display_history import HistoryFact, HistoryKind, HistoryReader
|
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.manager import Session, SessionManager
|
||||||
from nanobot.session.recovery import (
|
from nanobot.session.recovery import (
|
||||||
KNOWN_CHECKPOINT_PHASES,
|
KNOWN_CHECKPOINT_PHASES,
|
||||||
@@ -169,19 +170,25 @@ class RecoveryCoordinator:
|
|||||||
if failure_kind == "model":
|
if failure_kind == "model":
|
||||||
# The turn has already saved its transcript and tool results. Use
|
# The turn has already saved its transcript and tool results. Use
|
||||||
# that context, never resend the user's message or replay tools.
|
# 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,
|
session,
|
||||||
status="awaiting_user",
|
status="recovered" if input_rejected else "awaiting_user",
|
||||||
recovery_id=uuid4().hex,
|
recovery_id=uuid4().hex,
|
||||||
attempts=cast(int, state.get("attempts", 0)) if state else 0,
|
attempts=cast(int, state.get("attempts", 0)) if state else 0,
|
||||||
reason="model_request_failed",
|
reason="input_rejected" if input_rejected else "model_request_failed",
|
||||||
can_continue=any(message.get("role") == "user" for message in session.messages),
|
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"
|
result["failure_error_kind"] = failure_error_kind or "unknown"
|
||||||
if session.messages and session.messages[-1].get("_interrupted") is True:
|
if reply_preserved:
|
||||||
waiting["reply_preserved"] = True
|
result["reply_preserved"] = True
|
||||||
await self.sessions.state.restore_interruption(session)
|
await self.sessions.state.restore_interruption(session)
|
||||||
await self._publish(chat_id, waiting)
|
await self._publish(chat_id, result)
|
||||||
return
|
return
|
||||||
if not state or state["status"] != "resuming":
|
if not state or state["status"] != "resuming":
|
||||||
return
|
return
|
||||||
@@ -494,13 +501,14 @@ class RecoveryCoordinator:
|
|||||||
return state
|
return state
|
||||||
|
|
||||||
@staticmethod
|
@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."""
|
"""Whether an interrupted turn left model-visible context to continue from."""
|
||||||
last_user = next(
|
last_user = next(
|
||||||
(
|
(
|
||||||
index
|
index
|
||||||
for index in range(len(session.messages) - 1, -1, -1)
|
for index in range(len(session.messages) - 1, -1, -1)
|
||||||
if session.messages[index].get("role") == "user"
|
if session.messages[index].get("role") == "user"
|
||||||
|
and not (skip_hidden_user and is_hidden_history_message(session.messages[index]))
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ class ModelSettingsPayload(TypedDict):
|
|||||||
model_presets: list[dict[str, Any]]
|
model_presets: list[dict[str, Any]]
|
||||||
model_call_order: list[str]
|
model_call_order: list[str]
|
||||||
model_call_order_editable: bool
|
model_call_order_editable: bool
|
||||||
|
image_fallback_configured: bool
|
||||||
model_configuration_migratable: bool
|
model_configuration_migratable: bool
|
||||||
model_api_resolution_supported: bool
|
model_api_resolution_supported: bool
|
||||||
provider_api_configuration_supported: bool
|
provider_api_configuration_supported: bool
|
||||||
@@ -1226,6 +1227,10 @@ def model_settings_payload(
|
|||||||
"model_request_overrides_supported": True,
|
"model_request_overrides_supported": True,
|
||||||
"model_call_order": model_call_order,
|
"model_call_order": model_call_order,
|
||||||
"model_call_order_editable": model_call_order_editable,
|
"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(
|
"model_configuration_migratable": _legacy_model_configuration_migratable(
|
||||||
config,
|
config,
|
||||||
oauth_status,
|
oauth_status,
|
||||||
|
|||||||
@@ -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
|
call = chain.chat_stream_with_retry if stream else chain.chat_with_retry
|
||||||
response = await call(messages=[{"role": "user", "content": [_IMAGE]}])
|
response = await call(messages=[{"role": "user", "content": [_IMAGE]}])
|
||||||
assert response.error_code == "unsupported_image"
|
assert response.error_code == "unsupported_image"
|
||||||
|
assert LLMProvider.public_error_kind(response) == "unsupported_image"
|
||||||
assert response.error_should_retry is False
|
assert response.error_should_retry is False
|
||||||
assert primary.calls == created == []
|
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])
|
@pytest.mark.parametrize("stream", [False, True])
|
||||||
async def test_declared_vision_does_not_hide_actual_upstream_rejection(stream):
|
async def test_declared_vision_does_not_hide_actual_upstream_rejection(stream):
|
||||||
upstream = LLMResponse("unsupported image format", finish_reason="error", error_status_code=400)
|
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)
|
response = await call(messages=messages)
|
||||||
assert response.content == upstream.content
|
assert response.content == upstream.content
|
||||||
assert response.error_status_code == 400
|
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 len(primary.calls) == 1
|
||||||
assert created == []
|
assert created == []
|
||||||
assert messages == before
|
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():
|
def test_factory_resolves_independent_capabilities_and_refresh_signature():
|
||||||
config = Config.model_validate({
|
config = Config.model_validate({
|
||||||
"agents": {"defaults": {"modelPreset": "text", "fallbackModels": ["vision", {"provider": "custom", "model": "inline"}]}},
|
"agents": {"defaults": {"modelPreset": "text", "fallbackModels": ["vision", {"provider": "custom", "model": "inline"}]}},
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import copy
|
import copy
|
||||||
import random
|
import random
|
||||||
|
from dataclasses import replace
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -475,7 +476,7 @@ _IMAGE_MSG = [
|
|||||||
error_status_code=400, error_code="unsupported_image", error_should_retry=False,
|
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")])
|
provider = ScriptedProvider([error, LLMResponse(content="unexpected text-only answer")])
|
||||||
messages = copy.deepcopy(_IMAGE_MSG)
|
messages = copy.deepcopy(_IMAGE_MSG)
|
||||||
original = copy.deepcopy(messages)
|
original = copy.deepcopy(messages)
|
||||||
@@ -483,10 +484,11 @@ async def test_nontransient_image_error_returns_original_response(streaming, err
|
|||||||
|
|
||||||
response = await call(messages=messages)
|
response = await call(messages=messages)
|
||||||
|
|
||||||
assert response is error
|
assert response == replace(error, error_kind="image_request_rejected")
|
||||||
assert provider.calls == 1
|
assert provider.calls == 1
|
||||||
assert messages == original
|
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
|
@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 provider.calls == (2 if transient else 1)
|
||||||
assert messages == original
|
assert messages == original
|
||||||
assert state.to_private_record() == original_state
|
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
|
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||||
response = await call(messages=messages, on_retry_status=status)
|
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 provider.calls == 2
|
||||||
assert messages == original
|
assert messages == original
|
||||||
assert [event.state for event in statuses] == ["waiting", "cleared"]
|
assert [event.state for event in statuses] == ["waiting", "cleared"]
|
||||||
|
|||||||
@@ -880,6 +880,43 @@ async def test_model_failure_waits_across_restart_and_rejects_duplicate_continue
|
|||||||
await coordinator.handle_action("continue", payload)
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_new_input_after_model_failure_does_not_change_saved_context(tmp_path: Path) -> None:
|
async def test_new_input_after_model_failure_does_not_change_saved_context(tmp_path: Path) -> None:
|
||||||
coordinator, _, sessions = _coordinator(tmp_path)
|
coordinator, _, sessions = _coordinator(tmp_path)
|
||||||
|
|||||||
@@ -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
|
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"]})
|
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 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
|
||||||
@@ -156,6 +156,7 @@ def test_model_domain_owns_dto_and_config_updates() -> None:
|
|||||||
"model_presets",
|
"model_presets",
|
||||||
"model_call_order",
|
"model_call_order",
|
||||||
"model_call_order_editable",
|
"model_call_order_editable",
|
||||||
|
"image_fallback_configured",
|
||||||
"model_configuration_migratable",
|
"model_configuration_migratable",
|
||||||
"model_api_resolution_supported",
|
"model_api_resolution_supported",
|
||||||
"provider_api_configuration_supported",
|
"provider_api_configuration_supported",
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ function retryFailureLabel(errorKind: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function terminalModelFailureLine(errorKind?: string, attempts?: number): 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")
|
const reason = retryFailureLabel(errorKind || "unknown")
|
||||||
if (errorKind === "billing") {
|
if (errorKind === "billing") {
|
||||||
return `${reason}. Add credit or check billing for the provider account, then try again.`
|
return `${reason}. Add credit or check billing for the provider account, then try again.`
|
||||||
|
|||||||
+13
-2
@@ -272,7 +272,11 @@ function readShellRoute(): ShellRoute {
|
|||||||
activeKey,
|
activeKey,
|
||||||
temporary,
|
temporary,
|
||||||
settingsSection,
|
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") {
|
if (path === "/apps") {
|
||||||
@@ -333,7 +337,7 @@ function shellRouteHash(route: ShellRoute): string {
|
|||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (route.view === "settings" && route.settingsSection !== "overview") {
|
if (route.view === "settings" && route.settingsSection !== "overview") {
|
||||||
params.set("section", route.settingsSection);
|
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") {
|
if (route.view === "apps" && route.settingsSection !== "apps") {
|
||||||
params.set("section", route.settingsSection);
|
params.set("section", route.settingsSection);
|
||||||
@@ -1890,6 +1894,11 @@ function Shell({
|
|||||||
const onOpenModelSettings = useCallback(() => {
|
const onOpenModelSettings = useCallback(() => {
|
||||||
onOpenSettings("models");
|
onOpenSettings("models");
|
||||||
}, [onOpenSettings]);
|
}, [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) => {
|
const onOpenSandboxSettings = useCallback((target: SettingsFocusTarget) => {
|
||||||
setSessionSearchOpen(false);
|
setSessionSearchOpen(false);
|
||||||
navigate({ view: "settings", activeKey, settingsSection: "advanced", settingsFocus: target });
|
navigate({ view: "settings", activeKey, settingsSection: "advanced", settingsFocus: target });
|
||||||
@@ -2693,6 +2702,7 @@ function Shell({
|
|||||||
settingsSnapshot={settingsSnapshot}
|
settingsSnapshot={settingsSnapshot}
|
||||||
settingsLoading={settingsLoading}
|
settingsLoading={settingsLoading}
|
||||||
onOpenModelSettings={onOpenModelSettings}
|
onOpenModelSettings={onOpenModelSettings}
|
||||||
|
onInspectImagePreset={onInspectImagePreset}
|
||||||
onOpenSandboxSettings={onOpenSandboxSettings}
|
onOpenSandboxSettings={onOpenSandboxSettings}
|
||||||
skills={skills}
|
skills={skills}
|
||||||
/>
|
/>
|
||||||
@@ -2760,6 +2770,7 @@ function Shell({
|
|||||||
settingsSnapshot={settingsSnapshot}
|
settingsSnapshot={settingsSnapshot}
|
||||||
settingsLoading={settingsLoading}
|
settingsLoading={settingsLoading}
|
||||||
onOpenModelSettings={onOpenModelSettings}
|
onOpenModelSettings={onOpenModelSettings}
|
||||||
|
onInspectImagePreset={onInspectImagePreset}
|
||||||
onOpenSandboxSettings={onOpenSandboxSettings}
|
onOpenSandboxSettings={onOpenSandboxSettings}
|
||||||
skills={skills}
|
skills={skills}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { ChevronLeft } from "lucide-react";
|
|||||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogLayoutContext, DialogTitle } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogLayoutContext, DialogTitle } from "@/components/ui/dialog";
|
||||||
import { Button } from "@/components/ui/button";
|
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 { isAppsSection, isCapabilitySection, type AppsSectionKey, type SettingsSectionKey } from "@/components/settings/contracts";
|
||||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||||
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
|
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
|
||||||
@@ -291,6 +291,7 @@ export function SettingsPage({
|
|||||||
form={modelState.form}
|
form={modelState.form}
|
||||||
setForm={modelState.setForm}
|
setForm={modelState.setForm}
|
||||||
editingPresetName={modelState.modelPresetEditingName}
|
editingPresetName={modelState.modelPresetEditingName}
|
||||||
|
imageInputPreset={imageInputPresetFromFocus(focusTarget)}
|
||||||
presetNameError={modelState.modelPresetNameError}
|
presetNameError={modelState.modelPresetNameError}
|
||||||
error={error}
|
error={error}
|
||||||
settings={settings}
|
settings={settings}
|
||||||
|
|||||||
@@ -46,4 +46,8 @@ export type ApplySettingsPayload = (
|
|||||||
) => void;
|
) => void;
|
||||||
|
|
||||||
export type MaybeRestartHostEngine = (payload: RestartAwarePayload) => Promise<void>;
|
export type MaybeRestartHostEngine = (payload: RestartAwarePayload) => Promise<void>;
|
||||||
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;
|
||||||
|
}
|
||||||
@@ -212,6 +212,7 @@ export function ModelsSettings({
|
|||||||
form,
|
form,
|
||||||
setForm,
|
setForm,
|
||||||
editingPresetName,
|
editingPresetName,
|
||||||
|
imageInputPreset,
|
||||||
presetNameError,
|
presetNameError,
|
||||||
error,
|
error,
|
||||||
settings,
|
settings,
|
||||||
@@ -243,6 +244,7 @@ export function ModelsSettings({
|
|||||||
form: AgentSettingsDraft;
|
form: AgentSettingsDraft;
|
||||||
setForm: Dispatch<SetStateAction<AgentSettingsDraft>>;
|
setForm: Dispatch<SetStateAction<AgentSettingsDraft>>;
|
||||||
editingPresetName: string;
|
editingPresetName: string;
|
||||||
|
imageInputPreset?: string;
|
||||||
presetNameError: string | null;
|
presetNameError: string | null;
|
||||||
error?: string | null;
|
error?: string | null;
|
||||||
settings: SettingsPayload;
|
settings: SettingsPayload;
|
||||||
@@ -286,6 +288,9 @@ export function ModelsSettings({
|
|||||||
});
|
});
|
||||||
const editorTriggerRef = useRef<HTMLElement | null>(null);
|
const editorTriggerRef = useRef<HTMLElement | null>(null);
|
||||||
const presetNameInputRef = useRef<HTMLInputElement>(null);
|
const presetNameInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const imageInputRef = useRef<HTMLButtonElement>(null);
|
||||||
|
const openedImagePreset = useRef<string>();
|
||||||
|
const focusImageInput = useRef(false);
|
||||||
const suggestedPresetNameRef = useRef<string | null>(null);
|
const suggestedPresetNameRef = useRef<string | null>(null);
|
||||||
const presetContextInitializedRef = useRef(false);
|
const presetContextInitializedRef = useRef(false);
|
||||||
const [editorRowKey, setEditorRowKey] = useState<string | null>(null);
|
const [editorRowKey, setEditorRowKey] = useState<string | null>(null);
|
||||||
@@ -404,20 +409,11 @@ export function ModelsSettings({
|
|||||||
disabled: callOrderBusy,
|
disabled: callOrderBusy,
|
||||||
onReorder: (keys) => onChangeCallOrder(keys.map((key) => presetRows.find((row) => row.key === key)!.name)),
|
onReorder: (keys) => onChangeCallOrder(keys.map((key) => presetRows.find((row) => row.key === key)!.name)),
|
||||||
});
|
});
|
||||||
const selectPreset = async (
|
const openPreset = (
|
||||||
preset: SettingsPayload["model_presets"][number],
|
preset: SettingsPayload["model_presets"][number],
|
||||||
rowKey: string,
|
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);
|
onSelectConfiguration(preset.name);
|
||||||
if (toggleCurrentPreset) {
|
|
||||||
setEditorOpen((open) => !open);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setForm((prev) => ({
|
setForm((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
modelPreset: preset.name,
|
modelPreset: preset.name,
|
||||||
@@ -437,6 +433,28 @@ export function ModelsSettings({
|
|||||||
setEditorRowKey(rowKey);
|
setEditorRowKey(rowKey);
|
||||||
setEditorOpen(true);
|
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) => {
|
const moveCallOrderItem = (index: number, offset: -1 | 1) => {
|
||||||
if (callOrderBusy) return;
|
if (callOrderBusy) return;
|
||||||
@@ -575,6 +593,7 @@ export function ModelsSettings({
|
|||||||
description={t("settings.models.imageInputHelp")}
|
description={t("settings.models.imageInputHelp")}
|
||||||
>
|
>
|
||||||
<ToggleButton
|
<ToggleButton
|
||||||
|
ref={imageInputRef}
|
||||||
checked={form.supportsImages}
|
checked={form.supportsImages}
|
||||||
label={t("settings.models.imageInput")}
|
label={t("settings.models.imageInput")}
|
||||||
disabled={saving || creatingSaving}
|
disabled={saving || creatingSaving}
|
||||||
@@ -994,6 +1013,12 @@ export function ModelsSettings({
|
|||||||
onBlurCapture={edits.onBlurCapture}
|
onBlurCapture={edits.onBlurCapture}
|
||||||
onEscapeKeyDown={() => setHideEditorReturnFocus(true)}
|
onEscapeKeyDown={() => setHideEditorReturnFocus(true)}
|
||||||
className="relative max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none gap-0 overflow-y-auto p-0"
|
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) => {
|
onCloseAutoFocus={(event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
editorTriggerRef.current?.focus();
|
editorTriggerRef.current?.focus();
|
||||||
|
|||||||
@@ -8,16 +8,18 @@ import { useTranslation } from "react-i18next";
|
|||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { RecoveryState } from "@/lib/types";
|
import type { RecoveryState } from "@/lib/types";
|
||||||
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
|
import { isImageRequestFailure, resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
|
||||||
|
|
||||||
interface RecoveryNoticeProps {
|
interface RecoveryNoticeProps {
|
||||||
state: RecoveryState;
|
state: RecoveryState;
|
||||||
onContinue: () => Promise<void>;
|
onContinue: () => Promise<void>;
|
||||||
onDismiss: () => Promise<void>;
|
onDismiss: () => Promise<void>;
|
||||||
onOpenSettings?: () => void;
|
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 { t } = useTranslation();
|
||||||
const [pending, setPending] = useState<"continue" | "dismiss" | null>(null);
|
const [pending, setPending] = useState<"continue" | "dismiss" | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -38,6 +40,8 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }:
|
|||||||
const modelFailure = state.reason === "model_request_failed"
|
const modelFailure = state.reason === "model_request_failed"
|
||||||
? resolveModelRequestFailureCopy({ errorKind: state.failure_error_kind }, t)
|
? resolveModelRequestFailureCopy({ errorKind: state.failure_error_kind }, t)
|
||||||
: null;
|
: null;
|
||||||
|
const imageFailure = modelFailure !== null && isImageRequestFailure(state.failure_error_kind);
|
||||||
|
const openSettings = imageFailure ? onInspectImagePreset : onOpenSettings;
|
||||||
const title = modelFailure?.title ?? (state.status === "failed"
|
const title = modelFailure?.title ?? (state.status === "failed"
|
||||||
? t("recovery.failed", { defaultValue: "Task recovery failed" })
|
? t("recovery.failed", { defaultValue: "Task recovery failed" })
|
||||||
: t("recovery.interrupted", { defaultValue: "Task interrupted" }));
|
: t("recovery.interrupted", { defaultValue: "Task interrupted" }));
|
||||||
@@ -45,7 +49,7 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }:
|
|||||||
? t("recovery.failedHelp", {
|
? t("recovery.failedHelp", {
|
||||||
defaultValue: "The saved task could not be restored safely. Review it before continuing.",
|
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." })
|
? 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." });
|
: modelFailure?.body ?? t("recovery.review", { defaultValue: "Review the task before continuing. Tools will not be replayed automatically." });
|
||||||
const run = (action: "continue" | "dismiss") => {
|
const run = (action: "continue" | "dismiss") => {
|
||||||
@@ -74,9 +78,9 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }:
|
|||||||
<p className="font-medium">
|
<p className="font-medium">
|
||||||
{title}
|
{title}
|
||||||
</p>
|
</p>
|
||||||
{modelFailure && onOpenSettings ? (
|
{modelFailure && openSettings ? (
|
||||||
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={onOpenSettings}>
|
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={openSettings}>
|
||||||
{t("thread.composer.reauthSettings")}
|
{t(imageFailure ? "settings.models.viewPreset" : "thread.composer.reauthSettings")}
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
<p className={cn(
|
<p className={cn(
|
||||||
@@ -97,7 +101,7 @@ export function RecoveryNotice({ state, onContinue, onDismiss, onOpenSettings }:
|
|||||||
<X className="mr-1 h-3.5 w-3.5" aria-hidden />
|
<X className="mr-1 h-3.5 w-3.5" aria-hidden />
|
||||||
{t("recovery.dismiss", { defaultValue: "Dismiss" })}
|
{t("recovery.dismiss", { defaultValue: "Dismiss" })}
|
||||||
</Button>
|
</Button>
|
||||||
{!contextUnavailable ? (
|
{!contextUnavailable && !(state.failure_error_kind === "unsupported_image" && imageInputBlocked) ? (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ interface StreamErrorNoticeProps {
|
|||||||
*/
|
*/
|
||||||
export function StreamErrorNotice({ error, onDismiss, onOpenSettings }: StreamErrorNoticeProps) {
|
export function StreamErrorNotice({ error, onDismiss, onOpenSettings }: StreamErrorNoticeProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const { title, body } = resolveCopy(error, t);
|
const { title, body } = resolveCopy(error, t);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -238,6 +238,8 @@ interface ThreadComposerProps {
|
|||||||
modelOptionsControl?: ModelOptionsControlProps;
|
modelOptionsControl?: ModelOptionsControlProps;
|
||||||
onModelMenuOpenChange?: (open: boolean) => void;
|
onModelMenuOpenChange?: (open: boolean) => void;
|
||||||
onModelPresetChange?: (name: string) => void;
|
onModelPresetChange?: (name: string) => void;
|
||||||
|
imageInputBlocked?: boolean;
|
||||||
|
onInspectImagePreset?: () => void;
|
||||||
modelProvider?: string | null;
|
modelProvider?: string | null;
|
||||||
modelProviderLabel?: string | null;
|
modelProviderLabel?: string | null;
|
||||||
modelNeedsSetup?: boolean;
|
modelNeedsSetup?: boolean;
|
||||||
@@ -571,6 +573,8 @@ export function ThreadComposer({
|
|||||||
modelOptionsControl,
|
modelOptionsControl,
|
||||||
onModelMenuOpenChange,
|
onModelMenuOpenChange,
|
||||||
onModelPresetChange,
|
onModelPresetChange,
|
||||||
|
imageInputBlocked = false,
|
||||||
|
onInspectImagePreset,
|
||||||
modelProvider = null,
|
modelProvider = null,
|
||||||
modelProviderLabel = null,
|
modelProviderLabel = null,
|
||||||
modelNeedsSetup = false,
|
modelNeedsSetup = false,
|
||||||
@@ -705,6 +709,22 @@ export function ThreadComposer({
|
|||||||
return null;
|
return null;
|
||||||
}, [formatRejection, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]);
|
}, [formatRejection, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]);
|
||||||
|
|
||||||
|
const validatePrompt = useCallback((prompt: QueuedPromptContent): boolean => {
|
||||||
|
if (imageInputBlocked && prompt.images?.some(({ kind }) => kind === "image")) {
|
||||||
|
showToast?.({
|
||||||
|
message: t("errors.modelRequestFailed.imageInputTitle"),
|
||||||
|
tone: "error",
|
||||||
|
action: onInspectImagePreset
|
||||||
|
? { label: t("settings.models.viewPreset"), run: onInspectImagePreset }
|
||||||
|
: undefined,
|
||||||
|
});
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const error = queuedPromptError(prompt);
|
||||||
|
if (error) setInlineError(error);
|
||||||
|
return error === null;
|
||||||
|
}, [imageInputBlocked, onInspectImagePreset, queuedPromptError, showToast, t]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
snapshot: queueSnapshot,
|
snapshot: queueSnapshot,
|
||||||
collect: collectQueuedPrompt,
|
collect: collectQueuedPrompt,
|
||||||
@@ -715,8 +735,7 @@ export function ThreadComposer({
|
|||||||
} = useQueuedPrompt(pendingQueueKey, { isStreaming, activeTurnId, completedTurnIds }, {
|
} = useQueuedPrompt(pendingQueueKey, { isStreaming, activeTurnId, completedTurnIds }, {
|
||||||
disabled: !!disabled || sendPending,
|
disabled: !!disabled || sendPending,
|
||||||
onSend,
|
onSend,
|
||||||
validate: queuedPromptError,
|
validate: validatePrompt,
|
||||||
onValidationError: setInlineError,
|
|
||||||
onSendAttempt: focusTextarea,
|
onSendAttempt: focusTextarea,
|
||||||
});
|
});
|
||||||
const queuedPrompt = queueSnapshot.prompt;
|
const queuedPrompt = queueSnapshot.prompt;
|
||||||
@@ -1711,11 +1730,7 @@ export function ThreadComposer({
|
|||||||
slashLifecycle === "finalize_active_turn";
|
slashLifecycle === "finalize_active_turn";
|
||||||
if (!isUserShell && !slashLifecycle) {
|
if (!isUserShell && !slashLifecycle) {
|
||||||
const prompt = collectGuidancePrompt();
|
const prompt = collectGuidancePrompt();
|
||||||
const error = queuedPromptError(prompt);
|
if (!validatePrompt(prompt)) return;
|
||||||
if (error) {
|
|
||||||
setInlineError(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (queuedPrompt) {
|
if (queuedPrompt) {
|
||||||
sendQueuedPrompt(prompt, options);
|
sendQueuedPrompt(prompt, options);
|
||||||
if (draftKey) draftStore?.delete(draftKey);
|
if (draftKey) draftStore?.delete(draftKey);
|
||||||
@@ -1774,7 +1789,7 @@ export function ThreadComposer({
|
|||||||
clearComposerText,
|
clearComposerText,
|
||||||
collectGuidancePrompt,
|
collectGuidancePrompt,
|
||||||
queuedPrompt,
|
queuedPrompt,
|
||||||
queuedPromptError,
|
validatePrompt,
|
||||||
sendQueuedPrompt,
|
sendQueuedPrompt,
|
||||||
clearQueuedPrompt,
|
clearQueuedPrompt,
|
||||||
hasTouchPrimaryPointer,
|
hasTouchPrimaryPointer,
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ import { ThreadHeader } from "@/components/thread/ThreadHeader";
|
|||||||
import { GoalIsland } from "@/components/thread/GoalIsland";
|
import { GoalIsland } from "@/components/thread/GoalIsland";
|
||||||
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
|
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
|
||||||
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
|
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
|
||||||
|
import { useToast } from "@/components/ui/toast";
|
||||||
|
import { isImageRequestFailure, resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
|
||||||
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
|
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
|
||||||
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
import { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
||||||
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
|
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
|
||||||
@@ -261,6 +263,7 @@ interface ThreadShellProps {
|
|||||||
settingsSnapshot?: SettingsPayload | null;
|
settingsSnapshot?: SettingsPayload | null;
|
||||||
settingsLoading?: boolean;
|
settingsLoading?: boolean;
|
||||||
onOpenModelSettings?: () => void;
|
onOpenModelSettings?: () => void;
|
||||||
|
onInspectImagePreset?: (name: string) => void;
|
||||||
onOpenSandboxSettings?: (target: "sandbox" | "sandbox-launcher") => void;
|
onOpenSandboxSettings?: (target: "sandbox" | "sandbox-launcher") => void;
|
||||||
skills?: SkillSummary[];
|
skills?: SkillSummary[];
|
||||||
}
|
}
|
||||||
@@ -401,10 +404,12 @@ export function ThreadShell({
|
|||||||
settingsSnapshot = null,
|
settingsSnapshot = null,
|
||||||
settingsLoading = false,
|
settingsLoading = false,
|
||||||
onOpenModelSettings,
|
onOpenModelSettings,
|
||||||
|
onInspectImagePreset,
|
||||||
onOpenSandboxSettings,
|
onOpenSandboxSettings,
|
||||||
skills = [],
|
skills = [],
|
||||||
}: ThreadShellProps) {
|
}: ThreadShellProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const showToast = useToast();
|
||||||
const chatId = session?.chatId ?? null;
|
const chatId = session?.chatId ?? null;
|
||||||
const historyKey = temporary ? null : session?.key ?? null;
|
const historyKey = temporary ? null : session?.key ?? null;
|
||||||
const [visibleWindow, setVisibleWindow] = useState<{ key: string | null; turnIds: string[]; hasMessages: boolean } | null>(null);
|
const [visibleWindow, setVisibleWindow] = useState<{ key: string | null; turnIds: string[]; hasMessages: boolean } | null>(null);
|
||||||
@@ -802,6 +807,24 @@ export function ThreadShell({
|
|||||||
|| settings?.agent.model_preset
|
|| settings?.agent.model_preset
|
||||||
|| "default"
|
|| "default"
|
||||||
);
|
);
|
||||||
|
const imageInputBlocked = settings?.image_fallback_configured === false
|
||||||
|
&& settings.model_presets.find((preset) => preset.name === activeModelPreset)?.supports_images === false;
|
||||||
|
const inspectImagePreset = useMemo(() => onInspectImagePreset
|
||||||
|
? () => onInspectImagePreset(activeModelPreset)
|
||||||
|
: onOpenModelSettings, [activeModelPreset, onInspectImagePreset, onOpenModelSettings]);
|
||||||
|
const imageRequestError = streamError?.kind === "model_request_failed" && isImageRequestFailure(streamError.errorKind)
|
||||||
|
? streamError
|
||||||
|
: null;
|
||||||
|
useEffect(() => {
|
||||||
|
if (!imageRequestError) return;
|
||||||
|
showToast?.({
|
||||||
|
message: resolveModelRequestFailureCopy(imageRequestError, t).title,
|
||||||
|
tone: "error",
|
||||||
|
dedupeKey: `image-request-failed:${imageRequestError.chatId}`,
|
||||||
|
action: inspectImagePreset ? { label: t("settings.models.viewPreset"), run: inspectImagePreset } : undefined,
|
||||||
|
});
|
||||||
|
dismissStreamError();
|
||||||
|
}, [dismissStreamError, imageRequestError, inspectImagePreset, showToast, t]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setModelFallback(null);
|
setModelFallback(null);
|
||||||
if (!chatId) return;
|
if (!chatId) return;
|
||||||
@@ -1295,9 +1318,11 @@ export function ThreadShell({
|
|||||||
onContinue={continueRecovery}
|
onContinue={continueRecovery}
|
||||||
onDismiss={dismissRecovery}
|
onDismiss={dismissRecovery}
|
||||||
onOpenSettings={onOpenModelSettings}
|
onOpenSettings={onOpenModelSettings}
|
||||||
|
onInspectImagePreset={inspectImagePreset}
|
||||||
|
imageInputBlocked={imageInputBlocked}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{streamError && !hasInlineDeliveryError(messages, streamError) ? (
|
{streamError && !imageRequestError && !hasInlineDeliveryError(messages, streamError) ? (
|
||||||
<StreamErrorNotice
|
<StreamErrorNotice
|
||||||
error={streamError}
|
error={streamError}
|
||||||
onDismiss={dismissStreamError}
|
onDismiss={dismissStreamError}
|
||||||
@@ -1322,6 +1347,8 @@ export function ThreadShell({
|
|||||||
draftStore={draftStore}
|
draftStore={draftStore}
|
||||||
persistDraft={persistDraft}
|
persistDraft={persistDraft}
|
||||||
onSend={handleThreadSend}
|
onSend={handleThreadSend}
|
||||||
|
imageInputBlocked={imageInputBlocked}
|
||||||
|
onInspectImagePreset={inspectImagePreset}
|
||||||
disabled={!chatId}
|
disabled={!chatId}
|
||||||
inputAriaLabel={composerInputAriaLabel}
|
inputAriaLabel={composerInputAriaLabel}
|
||||||
isStreaming={turnActive}
|
isStreaming={turnActive}
|
||||||
@@ -1380,6 +1407,8 @@ export function ThreadShell({
|
|||||||
draftStore={draftStore}
|
draftStore={draftStore}
|
||||||
persistDraft={persistDraft}
|
persistDraft={persistDraft}
|
||||||
onSend={handleWelcomeSend}
|
onSend={handleWelcomeSend}
|
||||||
|
imageInputBlocked={imageInputBlocked}
|
||||||
|
onInspectImagePreset={inspectImagePreset}
|
||||||
disabled={booting}
|
disabled={booting}
|
||||||
inputAriaLabel={composerInputAriaLabel}
|
inputAriaLabel={composerInputAriaLabel}
|
||||||
isStreaming={turnActive}
|
isStreaming={turnActive}
|
||||||
|
|||||||
@@ -311,8 +311,7 @@ interface QueuedPromptDelivery {
|
|||||||
images?: SendAttachment[],
|
images?: SendAttachment[],
|
||||||
options?: SendOptions,
|
options?: SendOptions,
|
||||||
) => boolean | void | Promise<boolean | void>;
|
) => boolean | void | Promise<boolean | void>;
|
||||||
validate: (prompt: QueuedPromptContent) => string | null;
|
validate: (prompt: QueuedPromptContent) => boolean;
|
||||||
onValidationError: (error: string) => void;
|
|
||||||
onSendAttempt: () => void;
|
onSendAttempt: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,7 +319,7 @@ interface QueuedPromptDelivery {
|
|||||||
export function useQueuedPrompt(
|
export function useQueuedPrompt(
|
||||||
pendingQueueKey: string | null,
|
pendingQueueKey: string | null,
|
||||||
{ isStreaming, activeTurnId, completedTurnIds = EMPTY_COMPLETED_TURN_IDS }: QueuedPromptRun,
|
{ isStreaming, activeTurnId, completedTurnIds = EMPTY_COMPLETED_TURN_IDS }: QueuedPromptRun,
|
||||||
{ disabled, onSend, validate, onValidationError, onSendAttempt }: QueuedPromptDelivery,
|
{ disabled, onSend, validate, onSendAttempt }: QueuedPromptDelivery,
|
||||||
) {
|
) {
|
||||||
const storageKey = queuedPromptsStorageKey(pendingQueueKey);
|
const storageKey = queuedPromptsStorageKey(pendingQueueKey);
|
||||||
const store = useMemo(() => queuedPromptStoreFor(storageKey), [storageKey]);
|
const store = useMemo(() => queuedPromptStoreFor(storageKey), [storageKey]);
|
||||||
@@ -356,14 +355,10 @@ export function useQueuedPrompt(
|
|||||||
}, [activeTurnId, queuedPrompt]);
|
}, [activeTurnId, queuedPrompt]);
|
||||||
|
|
||||||
const enqueue = useCallback((prompt: QueuedPrompt): boolean => {
|
const enqueue = useCallback((prompt: QueuedPrompt): boolean => {
|
||||||
const error = validate(prompt);
|
if (!validate(prompt)) return false;
|
||||||
if (error) {
|
|
||||||
onValidationError(error);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
setQueuedPrompt(prompt);
|
setQueuedPrompt(prompt);
|
||||||
return true;
|
return true;
|
||||||
}, [onValidationError, setQueuedPrompt, validate]);
|
}, [setQueuedPrompt, validate]);
|
||||||
|
|
||||||
const clear = useCallback(() => {
|
const clear = useCallback(() => {
|
||||||
setQueuedPrompt(null);
|
setQueuedPrompt(null);
|
||||||
@@ -376,10 +371,8 @@ export function useQueuedPrompt(
|
|||||||
const send = useCallback(
|
const send = useCallback(
|
||||||
(prompt: QueuedPrompt, extraOptions?: SendOptions) => {
|
(prompt: QueuedPrompt, extraOptions?: SendOptions) => {
|
||||||
if (interactionDisabled) return;
|
if (interactionDisabled) return;
|
||||||
const error = validate(prompt);
|
if (!validate(prompt)) {
|
||||||
if (error) {
|
|
||||||
setQueuedPrompt(pauseQueuedPrompt(prompt));
|
setQueuedPrompt(pauseQueuedPrompt(prompt));
|
||||||
onValidationError(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const text = prompt.text.trim();
|
const text = prompt.text.trim();
|
||||||
@@ -401,7 +394,7 @@ export function useQueuedPrompt(
|
|||||||
));
|
));
|
||||||
onSendAttempt();
|
onSendAttempt();
|
||||||
},
|
},
|
||||||
[interactionDisabled, isStreaming, onSend, onSendAttempt, onValidationError, store, validate, setQueuedPrompt],
|
[interactionDisabled, isStreaming, onSend, onSendAttempt, store, validate, setQueuedPrompt],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { useClient } from "@/providers/ClientProvider";
|
|||||||
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||||
import { ApiError, fetchWebuiThread, fetchWebuiThreadTraceDetail } from "@/lib/api";
|
import { ApiError, fetchWebuiThread, fetchWebuiThreadTraceDetail } from "@/lib/api";
|
||||||
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
|
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
|
||||||
|
import { isImageRequestFailure } from "@/lib/model-request-failure";
|
||||||
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot";
|
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot";
|
||||||
import { historyContentSnapshot, sameHistoryContent } from "@/lib/thread-display-projection";
|
import { historyContentSnapshot, sameHistoryContent } from "@/lib/thread-display-projection";
|
||||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||||
@@ -897,7 +898,8 @@ export function useNanobotStream(
|
|||||||
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
|
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
|
||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
if (modelFailure) setStreamError(modelFailure);
|
// Recovery decides whether an image failure needs an action card or just a toast.
|
||||||
|
if (modelFailure && !isImageRequestFailure(modelFailure.errorKind)) setStreamError(modelFailure);
|
||||||
applyProjectionEvent(ev);
|
applyProjectionEvent(ev);
|
||||||
playTurnCompleteSound();
|
playTurnCompleteSound();
|
||||||
onTurnEnd?.();
|
onTurnEnd?.();
|
||||||
@@ -920,8 +922,11 @@ export function useNanobotStream(
|
|||||||
? { reply_preserved: ev.reply_preserved }
|
? { reply_preserved: ev.reply_preserved }
|
||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
setRecoveryState(next);
|
const inputRejected = ev.status === "recovered" && ev.reason === "input_rejected";
|
||||||
if (ev.reason === "model_request_failed" || ev.status === "resuming") {
|
setRecoveryState(inputRejected ? null : next);
|
||||||
|
if (inputRejected) {
|
||||||
|
setStreamError({ kind: "model_request_failed", chatId, errorKind: next.failure_error_kind });
|
||||||
|
} else if (ev.reason === "model_request_failed" || ev.status === "resuming") {
|
||||||
setStreamError(null);
|
setStreamError(null);
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
@@ -938,7 +943,7 @@ export function useNanobotStream(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (ev.event === "attached") {
|
if (ev.event === "attached") {
|
||||||
setRecoveryState(ev.recovery_state ?? null);
|
setRecoveryState(ev.recovery_state?.reason === "input_rejected" ? null : ev.recovery_state ?? null);
|
||||||
if (
|
if (
|
||||||
ev.recovery_state?.reason === "model_request_failed"
|
ev.recovery_state?.reason === "model_request_failed"
|
||||||
|| ev.recovery_state?.status === "resuming"
|
|| ev.recovery_state?.status === "resuming"
|
||||||
|
|||||||
@@ -877,7 +877,8 @@
|
|||||||
"maxTokens": "Max output tokens",
|
"maxTokens": "Max output tokens",
|
||||||
"temperature": "Temperature",
|
"temperature": "Temperature",
|
||||||
"imageInput": "Image input",
|
"imageInput": "Image input",
|
||||||
"imageInputHelp": "When off, requests containing images skip this preset.",
|
"imageInputHelp": "Turn on only if the model supports images. When off, requests containing images skip this preset.",
|
||||||
|
"viewPreset": "View preset",
|
||||||
"reasoningEffort": "Reasoning effort",
|
"reasoningEffort": "Reasoning effort",
|
||||||
"convertTitle": "Convert setup",
|
"convertTitle": "Convert setup",
|
||||||
"convertHelp": "Convert primary and fallback models to presets.",
|
"convertHelp": "Convert primary and fallback models to presets.",
|
||||||
@@ -2760,6 +2761,9 @@
|
|||||||
"timeoutTitle": "Model provider request timed out",
|
"timeoutTitle": "Model provider request timed out",
|
||||||
"rateLimitTitle": "Model provider rate limit reached",
|
"rateLimitTitle": "Model provider rate limit reached",
|
||||||
"serverTitle": "Model provider service error",
|
"serverTitle": "Model provider service error",
|
||||||
|
"imageInputTitle": "Image input is off for this preset",
|
||||||
|
"imageRequestRejectedTitle": "The model rejected the image request",
|
||||||
|
"imageInputBody": "This request includes images. Check the preset or use one that supports images.",
|
||||||
"unknownTitle": "Model provider request failed",
|
"unknownTitle": "Model provider request failed",
|
||||||
"bodyWithAttempt": "Stopped after {{attempts}} attempts. Try again later or choose another model.",
|
"bodyWithAttempt": "Stopped after {{attempts}} attempts. Try again later or choose another model.",
|
||||||
"body": "Try again later or choose another model."
|
"body": "Try again later or choose another model."
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "Máx. tokens de salida",
|
"maxTokens": "Máx. tokens de salida",
|
||||||
"temperature": "Temperatura",
|
"temperature": "Temperatura",
|
||||||
"imageInput": "Entrada de imágenes",
|
"imageInput": "Entrada de imágenes",
|
||||||
"imageInputHelp": "Al desactivarla, las solicitudes con imágenes omiten este preajuste.",
|
"imageInputHelp": "Actívala solo si el modelo admite imágenes. Al desactivarla, las solicitudes con imágenes omiten este preajuste.",
|
||||||
|
"viewPreset": "Ver preajuste",
|
||||||
"reasoningEffort": "Esfuerzo de razonamiento",
|
"reasoningEffort": "Esfuerzo de razonamiento",
|
||||||
"convertTitle": "Convertir ajustes",
|
"convertTitle": "Convertir ajustes",
|
||||||
"convertHelp": "Convierte los modelos principal y de respaldo en preajustes.",
|
"convertHelp": "Convierte los modelos principal y de respaldo en preajustes.",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "La solicitud al proveedor del modelo agotó el tiempo de espera",
|
"timeoutTitle": "La solicitud al proveedor del modelo agotó el tiempo de espera",
|
||||||
"rateLimitTitle": "Se alcanzó el límite de solicitudes del proveedor del modelo",
|
"rateLimitTitle": "Se alcanzó el límite de solicitudes del proveedor del modelo",
|
||||||
"serverTitle": "Error del servicio del proveedor del modelo",
|
"serverTitle": "Error del servicio del proveedor del modelo",
|
||||||
|
"imageInputTitle": "La entrada de imágenes está desactivada en este preajuste",
|
||||||
|
"imageRequestRejectedTitle": "El modelo rechazó la solicitud con imagen",
|
||||||
|
"imageInputBody": "Esta solicitud incluye imágenes. Revisa este preajuste o usa uno compatible con imágenes.",
|
||||||
"unknownTitle": "La solicitud al proveedor del modelo falló",
|
"unknownTitle": "La solicitud al proveedor del modelo falló",
|
||||||
"bodyWithAttempt": "Se detuvo tras {{attempts}} intentos. Inténtalo más tarde o elige otro modelo.",
|
"bodyWithAttempt": "Se detuvo tras {{attempts}} intentos. Inténtalo más tarde o elige otro modelo.",
|
||||||
"body": "Inténtalo más tarde o elige otro modelo."
|
"body": "Inténtalo más tarde o elige otro modelo."
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "Tokens de sortie max.",
|
"maxTokens": "Tokens de sortie max.",
|
||||||
"temperature": "Température",
|
"temperature": "Température",
|
||||||
"imageInput": "Entrée d’images",
|
"imageInput": "Entrée d’images",
|
||||||
"imageInputHelp": "Si désactivée, les requêtes contenant des images ignorent ce préréglage.",
|
"imageInputHelp": "Activez cette option uniquement si le modèle accepte les images. Sinon, les requêtes contenant des images ignorent ce préréglage.",
|
||||||
|
"viewPreset": "Voir le préréglage",
|
||||||
"reasoningEffort": "Effort de raisonnement",
|
"reasoningEffort": "Effort de raisonnement",
|
||||||
"convertTitle": "Convertir les réglages",
|
"convertTitle": "Convertir les réglages",
|
||||||
"convertHelp": "Convertissez les modèles principal et de secours en préréglages.",
|
"convertHelp": "Convertissez les modèles principal et de secours en préréglages.",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "La requête au fournisseur du modèle a expiré",
|
"timeoutTitle": "La requête au fournisseur du modèle a expiré",
|
||||||
"rateLimitTitle": "Limite de requêtes du fournisseur du modèle atteinte",
|
"rateLimitTitle": "Limite de requêtes du fournisseur du modèle atteinte",
|
||||||
"serverTitle": "Erreur du service du fournisseur du modèle",
|
"serverTitle": "Erreur du service du fournisseur du modèle",
|
||||||
|
"imageInputTitle": "L’entrée d’images est désactivée pour ce préréglage",
|
||||||
|
"imageRequestRejectedTitle": "Le modèle a rejeté la requête avec image",
|
||||||
|
"imageInputBody": "Cette requête contient des images. Vérifiez le préréglage ou utilisez-en un qui accepte les images.",
|
||||||
"unknownTitle": "Échec de la requête au fournisseur du modèle",
|
"unknownTitle": "Échec de la requête au fournisseur du modèle",
|
||||||
"bodyWithAttempt": "Arrêt après {{attempts}} tentatives. Réessayez plus tard ou choisissez un autre modèle.",
|
"bodyWithAttempt": "Arrêt après {{attempts}} tentatives. Réessayez plus tard ou choisissez un autre modèle.",
|
||||||
"body": "Réessayez plus tard ou choisissez un autre modèle."
|
"body": "Réessayez plus tard ou choisissez un autre modèle."
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "Maks. token keluaran",
|
"maxTokens": "Maks. token keluaran",
|
||||||
"temperature": "Temperatur",
|
"temperature": "Temperatur",
|
||||||
"imageInput": "Input gambar",
|
"imageInput": "Input gambar",
|
||||||
"imageInputHelp": "Jika dinonaktifkan, permintaan berisi gambar akan melewati preset ini.",
|
"imageInputHelp": "Aktifkan hanya jika model mendukung gambar. Jika dinonaktifkan, permintaan berisi gambar akan melewati preset ini.",
|
||||||
|
"viewPreset": "Lihat preset",
|
||||||
"reasoningEffort": "Upaya penalaran",
|
"reasoningEffort": "Upaya penalaran",
|
||||||
"convertTitle": "Konversi pengaturan",
|
"convertTitle": "Konversi pengaturan",
|
||||||
"convertHelp": "Ubah model utama dan cadangan menjadi preset.",
|
"convertHelp": "Ubah model utama dan cadangan menjadi preset.",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "Permintaan ke penyedia model kehabisan waktu",
|
"timeoutTitle": "Permintaan ke penyedia model kehabisan waktu",
|
||||||
"rateLimitTitle": "Batas permintaan penyedia model tercapai",
|
"rateLimitTitle": "Batas permintaan penyedia model tercapai",
|
||||||
"serverTitle": "Kesalahan layanan penyedia model",
|
"serverTitle": "Kesalahan layanan penyedia model",
|
||||||
|
"imageInputTitle": "Input gambar dinonaktifkan untuk preset ini",
|
||||||
|
"imageRequestRejectedTitle": "Model menolak permintaan yang berisi gambar",
|
||||||
|
"imageInputBody": "Permintaan ini berisi gambar. Periksa preset ini atau gunakan preset yang mendukung gambar.",
|
||||||
"unknownTitle": "Permintaan ke penyedia model gagal",
|
"unknownTitle": "Permintaan ke penyedia model gagal",
|
||||||
"bodyWithAttempt": "Dihentikan setelah {{attempts}} percobaan. Coba lagi nanti atau pilih model lain.",
|
"bodyWithAttempt": "Dihentikan setelah {{attempts}} percobaan. Coba lagi nanti atau pilih model lain.",
|
||||||
"body": "Coba lagi nanti atau pilih model lain."
|
"body": "Coba lagi nanti atau pilih model lain."
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "最大出力トークン",
|
"maxTokens": "最大出力トークン",
|
||||||
"temperature": "温度",
|
"temperature": "温度",
|
||||||
"imageInput": "画像入力",
|
"imageInput": "画像入力",
|
||||||
"imageInputHelp": "オフにすると、画像を含むリクエストではこのプリセットをスキップします。",
|
"imageInputHelp": "モデルが画像に対応している場合のみオンにしてください。オフにすると、画像を含むリクエストではこのプリセットをスキップします。",
|
||||||
|
"viewPreset": "プリセットを確認",
|
||||||
"reasoningEffort": "推論の強度",
|
"reasoningEffort": "推論の強度",
|
||||||
"convertTitle": "設定を変換",
|
"convertTitle": "設定を変換",
|
||||||
"convertHelp": "主モデルと予備モデルをプリセットに変換します。",
|
"convertHelp": "主モデルと予備モデルをプリセットに変換します。",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
|
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
|
||||||
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
|
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
|
||||||
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
|
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
|
||||||
|
"imageInputTitle": "このプリセットでは画像入力がオフです",
|
||||||
|
"imageRequestRejectedTitle": "モデルが画像付きのリクエストを拒否しました",
|
||||||
|
"imageInputBody": "このリクエストには画像が含まれています。プリセットを確認するか、画像対応のプリセットを使用してください。",
|
||||||
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
|
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
|
||||||
"bodyWithAttempt": "{{attempts}} 回試行して停止しました。後でもう一度試すか、別のモデルを選んでください。",
|
"bodyWithAttempt": "{{attempts}} 回試行して停止しました。後でもう一度試すか、別のモデルを選んでください。",
|
||||||
"body": "後でもう一度試すか、別のモデルを選んでください。"
|
"body": "後でもう一度試すか、別のモデルを選んでください。"
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "최대 출력 토큰",
|
"maxTokens": "최대 출력 토큰",
|
||||||
"temperature": "온도",
|
"temperature": "온도",
|
||||||
"imageInput": "이미지 입력",
|
"imageInput": "이미지 입력",
|
||||||
"imageInputHelp": "끄면 이미지가 포함된 요청에서 이 프리셋을 건너뜁니다.",
|
"imageInputHelp": "모델이 이미지를 지원할 때만 켜세요. 끄면 이미지가 포함된 요청에서 이 프리셋을 건너뜁니다.",
|
||||||
|
"viewPreset": "프리셋 보기",
|
||||||
"reasoningEffort": "추론 강도",
|
"reasoningEffort": "추론 강도",
|
||||||
"convertTitle": "설정 변환",
|
"convertTitle": "설정 변환",
|
||||||
"convertHelp": "주 모델과 대체 모델을 프리셋으로 변환하세요.",
|
"convertHelp": "주 모델과 대체 모델을 프리셋으로 변환하세요.",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "모델 제공업체 요청 시간 초과",
|
"timeoutTitle": "모델 제공업체 요청 시간 초과",
|
||||||
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
|
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
|
||||||
"serverTitle": "모델 제공업체 서비스 오류",
|
"serverTitle": "모델 제공업체 서비스 오류",
|
||||||
|
"imageInputTitle": "이 프리셋의 이미지 입력이 꺼져 있습니다",
|
||||||
|
"imageRequestRejectedTitle": "모델이 이미지가 포함된 요청을 거부했습니다",
|
||||||
|
"imageInputBody": "이 요청에 이미지가 포함되어 있습니다. 프리셋을 확인하거나 이미지를 지원하는 프리셋을 사용하세요.",
|
||||||
"unknownTitle": "모델 제공업체 요청 실패",
|
"unknownTitle": "모델 제공업체 요청 실패",
|
||||||
"bodyWithAttempt": "{{attempts}}회 시도 후 중지했습니다. 나중에 다시 시도하거나 다른 모델을 선택하세요.",
|
"bodyWithAttempt": "{{attempts}}회 시도 후 중지했습니다. 나중에 다시 시도하거나 다른 모델을 선택하세요.",
|
||||||
"body": "나중에 다시 시도하거나 다른 모델을 선택하세요."
|
"body": "나중에 다시 시도하거나 다른 모델을 선택하세요."
|
||||||
|
|||||||
@@ -697,7 +697,8 @@
|
|||||||
"maxTokens": "Máx. de tokens de saída",
|
"maxTokens": "Máx. de tokens de saída",
|
||||||
"temperature": "Temperatura",
|
"temperature": "Temperatura",
|
||||||
"imageInput": "Entrada de imagens",
|
"imageInput": "Entrada de imagens",
|
||||||
"imageInputHelp": "Quando desativada, solicitações com imagens ignoram esta predefinição.",
|
"imageInputHelp": "Ative apenas se o modelo aceitar imagens. Quando desativada, solicitações com imagens ignoram esta predefinição.",
|
||||||
|
"viewPreset": "Ver predefinição",
|
||||||
"reasoningEffort": "Esforço de raciocínio",
|
"reasoningEffort": "Esforço de raciocínio",
|
||||||
"convertTitle": "Converter ajustes",
|
"convertTitle": "Converter ajustes",
|
||||||
"convertHelp": "Converta os modelos principal e alternativo em presets.",
|
"convertHelp": "Converta os modelos principal e alternativo em presets.",
|
||||||
@@ -2580,6 +2581,9 @@
|
|||||||
"timeoutTitle": "A solicitação ao provedor do modelo expirou",
|
"timeoutTitle": "A solicitação ao provedor do modelo expirou",
|
||||||
"rateLimitTitle": "Limite de solicitações do provedor do modelo atingido",
|
"rateLimitTitle": "Limite de solicitações do provedor do modelo atingido",
|
||||||
"serverTitle": "Erro no serviço do provedor do modelo",
|
"serverTitle": "Erro no serviço do provedor do modelo",
|
||||||
|
"imageInputTitle": "A entrada de imagens está desativada nesta predefinição",
|
||||||
|
"imageRequestRejectedTitle": "O modelo rejeitou a solicitação com imagem",
|
||||||
|
"imageInputBody": "Esta solicitação inclui imagens. Confira a predefinição ou use uma que aceite imagens.",
|
||||||
"unknownTitle": "Falha na solicitação ao provedor do modelo",
|
"unknownTitle": "Falha na solicitação ao provedor do modelo",
|
||||||
"bodyWithAttempt": "Interrompido após {{attempts}} tentativas. Tente mais tarde ou escolha outro modelo.",
|
"bodyWithAttempt": "Interrompido após {{attempts}} tentativas. Tente mais tarde ou escolha outro modelo.",
|
||||||
"body": "Tente mais tarde ou escolha outro modelo."
|
"body": "Tente mais tarde ou escolha outro modelo."
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "Token đầu ra tối đa",
|
"maxTokens": "Token đầu ra tối đa",
|
||||||
"temperature": "Nhiệt độ",
|
"temperature": "Nhiệt độ",
|
||||||
"imageInput": "Đầu vào hình ảnh",
|
"imageInput": "Đầu vào hình ảnh",
|
||||||
"imageInputHelp": "Khi tắt, yêu cầu chứa hình ảnh sẽ bỏ qua cấu hình này.",
|
"imageInputHelp": "Chỉ bật nếu mô hình hỗ trợ hình ảnh. Khi tắt, yêu cầu chứa hình ảnh sẽ bỏ qua cấu hình này.",
|
||||||
|
"viewPreset": "Xem cấu hình",
|
||||||
"reasoningEffort": "Mức suy luận",
|
"reasoningEffort": "Mức suy luận",
|
||||||
"convertTitle": "Chuyển thiết lập",
|
"convertTitle": "Chuyển thiết lập",
|
||||||
"convertHelp": "Chuyển mô hình chính và dự phòng thành bộ thiết lập.",
|
"convertHelp": "Chuyển mô hình chính và dự phòng thành bộ thiết lập.",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "Yêu cầu tới nhà cung cấp mô hình đã hết thời gian chờ",
|
"timeoutTitle": "Yêu cầu tới nhà cung cấp mô hình đã hết thời gian chờ",
|
||||||
"rateLimitTitle": "Đã đạt giới hạn yêu cầu của nhà cung cấp mô hình",
|
"rateLimitTitle": "Đã đạt giới hạn yêu cầu của nhà cung cấp mô hình",
|
||||||
"serverTitle": "Lỗi dịch vụ nhà cung cấp mô hình",
|
"serverTitle": "Lỗi dịch vụ nhà cung cấp mô hình",
|
||||||
|
"imageInputTitle": "Đầu vào hình ảnh đã tắt cho cấu hình này",
|
||||||
|
"imageRequestRejectedTitle": "Mô hình đã từ chối yêu cầu có hình ảnh",
|
||||||
|
"imageInputBody": "Yêu cầu này có hình ảnh. Hãy kiểm tra cấu hình hoặc dùng cấu hình hỗ trợ hình ảnh.",
|
||||||
"unknownTitle": "Yêu cầu tới nhà cung cấp mô hình không thành công",
|
"unknownTitle": "Yêu cầu tới nhà cung cấp mô hình không thành công",
|
||||||
"bodyWithAttempt": "Đã dừng sau {{attempts}} lần thử. Hãy thử lại sau hoặc chọn mô hình khác.",
|
"bodyWithAttempt": "Đã dừng sau {{attempts}} lần thử. Hãy thử lại sau hoặc chọn mô hình khác.",
|
||||||
"body": "Hãy thử lại sau hoặc chọn mô hình khác."
|
"body": "Hãy thử lại sau hoặc chọn mô hình khác."
|
||||||
|
|||||||
@@ -877,7 +877,8 @@
|
|||||||
"maxTokens": "输出 Token 上限",
|
"maxTokens": "输出 Token 上限",
|
||||||
"temperature": "温度",
|
"temperature": "温度",
|
||||||
"imageInput": "图像输入",
|
"imageInput": "图像输入",
|
||||||
"imageInputHelp": "关闭后,含图片的请求会跳过此预设。",
|
"imageInputHelp": "仅当模型支持图片时开启。关闭后,含图片的请求会跳过此预设。",
|
||||||
|
"viewPreset": "查看预设",
|
||||||
"reasoningEffort": "推理强度",
|
"reasoningEffort": "推理强度",
|
||||||
"convertTitle": "转换设置",
|
"convertTitle": "转换设置",
|
||||||
"convertHelp": "将主模型和备用模型转为预设",
|
"convertHelp": "将主模型和备用模型转为预设",
|
||||||
@@ -2760,6 +2761,9 @@
|
|||||||
"timeoutTitle": "模型提供商请求超时",
|
"timeoutTitle": "模型提供商请求超时",
|
||||||
"rateLimitTitle": "模型提供商请求受限",
|
"rateLimitTitle": "模型提供商请求受限",
|
||||||
"serverTitle": "模型提供商服务异常",
|
"serverTitle": "模型提供商服务异常",
|
||||||
|
"imageInputTitle": "此预设的图像输入已关闭",
|
||||||
|
"imageRequestRejectedTitle": "含图请求被模型拒绝",
|
||||||
|
"imageInputBody": "这次请求包含图片。请检查此预设,或使用支持图片的预设。",
|
||||||
"unknownTitle": "模型提供商请求失败",
|
"unknownTitle": "模型提供商请求失败",
|
||||||
"bodyWithAttempt": "已尝试 {{attempts}} 次,仍未成功。可稍后继续或切换模型。",
|
"bodyWithAttempt": "已尝试 {{attempts}} 次,仍未成功。可稍后继续或切换模型。",
|
||||||
"body": "可稍后继续或切换模型。"
|
"body": "可稍后继续或切换模型。"
|
||||||
|
|||||||
@@ -1067,7 +1067,8 @@
|
|||||||
"maxTokens": "輸出 Token 上限",
|
"maxTokens": "輸出 Token 上限",
|
||||||
"temperature": "溫度",
|
"temperature": "溫度",
|
||||||
"imageInput": "圖像輸入",
|
"imageInput": "圖像輸入",
|
||||||
"imageInputHelp": "關閉後,含圖片的請求會略過此預設。",
|
"imageInputHelp": "僅在模型支援圖片時開啟。關閉後,含圖片的請求會略過此預設。",
|
||||||
|
"viewPreset": "查看預設",
|
||||||
"reasoningEffort": "推理強度",
|
"reasoningEffort": "推理強度",
|
||||||
"convertTitle": "轉換設定",
|
"convertTitle": "轉換設定",
|
||||||
"convertHelp": "將主模型和備用模型轉為預設",
|
"convertHelp": "將主模型和備用模型轉為預設",
|
||||||
@@ -2578,6 +2579,9 @@
|
|||||||
"timeoutTitle": "模型供應商請求逾時",
|
"timeoutTitle": "模型供應商請求逾時",
|
||||||
"rateLimitTitle": "模型供應商請求受到限制",
|
"rateLimitTitle": "模型供應商請求受到限制",
|
||||||
"serverTitle": "模型供應商服務發生錯誤",
|
"serverTitle": "模型供應商服務發生錯誤",
|
||||||
|
"imageInputTitle": "此預設的圖像輸入已關閉",
|
||||||
|
"imageRequestRejectedTitle": "模型拒絕了含有圖片的請求",
|
||||||
|
"imageInputBody": "這次請求包含圖片。請檢查此預設,或使用支援圖片的預設。",
|
||||||
"unknownTitle": "模型供應商請求失敗",
|
"unknownTitle": "模型供應商請求失敗",
|
||||||
"bodyWithAttempt": "已嘗試 {{attempts}} 次,仍未成功。可稍後繼續或切換模型。",
|
"bodyWithAttempt": "已嘗試 {{attempts}} 次,仍未成功。可稍後繼續或切換模型。",
|
||||||
"body": "可稍後繼續或切換模型。"
|
"body": "可稍後繼續或切換模型。"
|
||||||
|
|||||||
@@ -5,10 +5,22 @@ export interface ModelRequestFailureDetails {
|
|||||||
attempts?: number;
|
attempts?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isImageRequestFailure(errorKind?: string): boolean {
|
||||||
|
return errorKind === "unsupported_image" || errorKind === "image_request_rejected";
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveModelRequestFailureCopy(
|
export function resolveModelRequestFailureCopy(
|
||||||
details: ModelRequestFailureDetails,
|
details: ModelRequestFailureDetails,
|
||||||
t: TFunction,
|
t: TFunction,
|
||||||
): { title: string; body: string } {
|
): { title: string; body: string } {
|
||||||
|
if (isImageRequestFailure(details.errorKind)) {
|
||||||
|
return {
|
||||||
|
title: t(details.errorKind === "unsupported_image"
|
||||||
|
? "errors.modelRequestFailed.imageInputTitle"
|
||||||
|
: "errors.modelRequestFailed.imageRequestRejectedTitle"),
|
||||||
|
body: t("errors.modelRequestFailed.imageInputBody"),
|
||||||
|
};
|
||||||
|
}
|
||||||
let titleKey = "errors.modelRequestFailed.unknownTitle";
|
let titleKey = "errors.modelRequestFailed.unknownTitle";
|
||||||
if (details.errorKind === "billing") {
|
if (details.errorKind === "billing") {
|
||||||
titleKey = "errors.modelRequestFailed.billingTitle";
|
titleKey = "errors.modelRequestFailed.billingTitle";
|
||||||
|
|||||||
@@ -800,6 +800,7 @@ export interface SettingsPayload {
|
|||||||
}>;
|
}>;
|
||||||
model_call_order: string[];
|
model_call_order: string[];
|
||||||
model_call_order_editable: boolean;
|
model_call_order_editable: boolean;
|
||||||
|
image_fallback_configured?: boolean;
|
||||||
/** Whether an actual legacy model configuration is available to convert. */
|
/** Whether an actual legacy model configuration is available to convert. */
|
||||||
model_configuration_migratable?: boolean;
|
model_configuration_migratable?: boolean;
|
||||||
/** Host can resolve the default request API for an unsaved model configuration. */
|
/** Host can resolve the default request API for an unsaved model configuration. */
|
||||||
|
|||||||
@@ -137,6 +137,20 @@ describe("RecoveryNotice", () => {
|
|||||||
expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps image recovery available without offering the same blocked retry", () => {
|
||||||
|
const onInspectImagePreset = vi.fn();
|
||||||
|
const state = { ...INTERRUPTED, reason: "model_request_failed", failure_error_kind: "unsupported_image" };
|
||||||
|
const actions = { onContinue: vi.fn(), onDismiss: vi.fn(), onInspectImagePreset };
|
||||||
|
const { rerender } = render(<RecoveryNotice state={state} {...actions} imageInputBlocked />);
|
||||||
|
expect(screen.getByRole("alert")).toHaveTextContent("This request includes images");
|
||||||
|
expect(screen.queryByRole("button", { name: "Continue" })).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "View preset" }));
|
||||||
|
expect(onInspectImagePreset).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
rerender(<RecoveryNotice state={state} {...actions} imageInputBlocked={false} />);
|
||||||
|
expect(screen.getByRole("button", { name: "Continue" })).toBeEnabled();
|
||||||
|
});
|
||||||
|
|
||||||
it("shows model authorization recovery after loading saved state", () => {
|
it("shows model authorization recovery after loading saved state", () => {
|
||||||
const onOpenSettings = vi.fn();
|
const onOpenSettings = vi.fn();
|
||||||
render(
|
render(
|
||||||
|
|||||||
@@ -83,6 +83,19 @@ function autoDynamicProviderPayload(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
it("opens the targeted backup preset and focuses its Image input switch", async () => {
|
||||||
|
const { payload, backupPreset } = settingsPayloadWithBackup();
|
||||||
|
payload.model_presets[1] = { ...backupPreset, supports_images: false };
|
||||||
|
requestMutationMock.mockResolvedValue(payload);
|
||||||
|
renderSettingsView({ initialSection: "models", initialSettings: payload, focusTarget: "image-input:backup" });
|
||||||
|
|
||||||
|
const editor = await screen.findByRole("dialog", { name: "backup" });
|
||||||
|
const toggle = within(editor).getByRole("switch", { name: "Image input" });
|
||||||
|
expect(toggle).not.toBeChecked();
|
||||||
|
await waitFor(() => expect(toggle).toHaveFocus());
|
||||||
|
expect(requestMutationMock).not.toHaveBeenCalledWith("settings.model_configuration.update", expect.anything(), expect.anything());
|
||||||
|
});
|
||||||
|
|
||||||
async function togglePresetEditor(name = "primary") {
|
async function togglePresetEditor(name = "primary") {
|
||||||
const row = await screen.findByTestId(`model-call-order-row-${name}`);
|
const row = await screen.findByTestId(`model-call-order-row-${name}`);
|
||||||
fireEvent.click(within(row).getAllByRole("button")[0]);
|
fireEvent.click(within(row).getAllByRole("button")[0]);
|
||||||
|
|||||||
@@ -88,6 +88,56 @@ beforeEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("ThreadComposer — attachments", () => {
|
describe("ThreadComposer — attachments", () => {
|
||||||
|
it.each([false, true])("keeps a blocked image draft and opens the preset (active turn: %s)", async (isStreaming) => {
|
||||||
|
const file = pngFile("screenshot.png");
|
||||||
|
encodeImage.mockResolvedValueOnce(resolveReady(file));
|
||||||
|
const onSend = vi.fn();
|
||||||
|
const onInspectImagePreset = vi.fn();
|
||||||
|
const renderComposer = (imageInputBlocked: boolean, active = false) => (
|
||||||
|
<ThreadComposer isStreaming={active} {...{ onSend, imageInputBlocked, onInspectImagePreset }} />
|
||||||
|
);
|
||||||
|
const { rerender } = render(renderComposer(true, isStreaming), { wrapper: ToastProvider });
|
||||||
|
const textarea = screen.getByLabelText(/message input/i);
|
||||||
|
const input = textarea.closest("form")!.querySelector('input[type="file"]')!;
|
||||||
|
await act(async () => fireEvent.change(input, { target: { files: [file] } }));
|
||||||
|
fireEvent.change(textarea, { target: { value: "Please describe this" } });
|
||||||
|
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||||
|
|
||||||
|
expect(screen.getByRole("alert")).toHaveTextContent("Image input is off for this preset");
|
||||||
|
expect(onSend).not.toHaveBeenCalled();
|
||||||
|
expect(textarea).toHaveValue("Please describe this");
|
||||||
|
expect(screen.getByTestId("composer-chip")).toBeVisible();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "View preset" }));
|
||||||
|
expect(onInspectImagePreset).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
rerender(renderComposer(false));
|
||||||
|
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||||
|
expect(onSend).toHaveBeenCalledWith("Please describe this", [expect.objectContaining({
|
||||||
|
preview: expect.objectContaining({ name: file.name, kind: "image" }),
|
||||||
|
})], undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("pauses an already queued image when the next preset cannot process it", async () => {
|
||||||
|
const file = pngFile("queued.png");
|
||||||
|
encodeImage.mockResolvedValueOnce(resolveReady(file));
|
||||||
|
const onSend = vi.fn();
|
||||||
|
const { rerender } = render(<ThreadComposer isStreaming onSend={onSend} />, { wrapper: ToastProvider });
|
||||||
|
const textarea = screen.getByLabelText(/message input/i);
|
||||||
|
const input = textarea.closest("form")!.querySelector('input[type="file"]')!;
|
||||||
|
await act(async () => fireEvent.change(input, { target: { files: [file] } }));
|
||||||
|
fireEvent.change(textarea, { target: { value: "Queued with image" } });
|
||||||
|
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||||
|
const queue = screen.getByRole("group", { name: "Waiting to send" });
|
||||||
|
expect(queue).toHaveTextContent("Queued with image");
|
||||||
|
|
||||||
|
rerender(<ThreadComposer imageInputBlocked onSend={onSend} />);
|
||||||
|
expect(await screen.findByRole("alert")).toHaveTextContent("Image input is off for this preset");
|
||||||
|
expect(onSend).not.toHaveBeenCalled();
|
||||||
|
fireEvent.click(within(queue).getByRole("button", { name: "Edit message" }));
|
||||||
|
expect(textarea).toHaveValue("Queued with image");
|
||||||
|
expect(screen.getByTestId("composer-chip")).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
it("previews a picked image with size details on hover and includes its data url on send", async () => {
|
it("previews a picked image with size details on hover and includes its data url on send", async () => {
|
||||||
const user = userEvent.setup();
|
const user = userEvent.setup();
|
||||||
const file = pngFile("a.png", 100);
|
const file = pngFile("a.png", 100);
|
||||||
@@ -150,11 +200,11 @@ describe("ThreadComposer — attachments", () => {
|
|||||||
expect(onSend.mock.calls[0][1].map((attachment: { media: { name: string } }) => attachment.media.name)).toEqual([first.name]);
|
expect(onSend.mock.calls[0][1].map((attachment: { media: { name: string } }) => attachment.media.name)).toEqual([first.name]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("attaches a picked PDF and includes its data url on send", async () => {
|
it("attaches and sends a PDF even when the preset does not accept images", async () => {
|
||||||
const file = pdfFile();
|
const file = pdfFile();
|
||||||
const onSend = vi.fn();
|
const onSend = vi.fn();
|
||||||
|
|
||||||
render(<ThreadComposer onSend={onSend} />);
|
render(<ThreadComposer onSend={onSend} imageInputBlocked />);
|
||||||
|
|
||||||
const input = screen
|
const input = screen
|
||||||
.getByLabelText(/message input/i)
|
.getByLabelText(/message input/i)
|
||||||
|
|||||||
@@ -5746,6 +5746,42 @@ describe("ThreadShell", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
["unsupported_image", "Image input is off for this preset"],
|
||||||
|
["image_request_rejected", "The model rejected the image request"],
|
||||||
|
])("shows %s as a preset action toast when there is no work to recover", async (errorKind, toastTitle) => {
|
||||||
|
const chatId = "chat-image-failure";
|
||||||
|
const client = makeClient();
|
||||||
|
const inspectPreset = vi.fn();
|
||||||
|
render(wrap(client, <ToastProvider>
|
||||||
|
<ThreadShell
|
||||||
|
session={{ ...session(chatId), modelPreset: "test-vision" }}
|
||||||
|
title="Chat image failure"
|
||||||
|
onToggleSidebar={() => {}}
|
||||||
|
onInspectImagePreset={inspectPreset}
|
||||||
|
/>
|
||||||
|
</ToastProvider>));
|
||||||
|
await act(async () => {});
|
||||||
|
|
||||||
|
act(() => client._emitChat(chatId, {
|
||||||
|
event: "turn_end", chat_id: chatId, turn_id: "image-turn",
|
||||||
|
outcome: "failed", failure_kind: "model", failure_error_kind: errorKind,
|
||||||
|
}));
|
||||||
|
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||||
|
act(() => client._emitChat(chatId, {
|
||||||
|
event: "recovery_state", chat_id: chatId, recovery_id: "image-attempt",
|
||||||
|
status: "recovered", reason: "input_rejected", failure_error_kind: errorKind,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const toast = await screen.findByRole("alert");
|
||||||
|
expect(toast.closest('[data-toast-tone="error"]')).not.toBeNull();
|
||||||
|
expect(toast).toHaveTextContent(toastTitle);
|
||||||
|
expect(screen.queryByRole("button", { name: "Continue" })).not.toBeInTheDocument();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "View preset" }));
|
||||||
|
expect(inspectPreset).toHaveBeenCalledOnce();
|
||||||
|
expect(inspectPreset).toHaveBeenCalledWith("test-vision");
|
||||||
|
});
|
||||||
|
|
||||||
it.each([false, true])("keeps one terminal model failure visible until the next user action (recovery: %s)", async (recoverable) => {
|
it.each([false, true])("keeps one terminal model failure visible until the next user action (recovery: %s)", async (recoverable) => {
|
||||||
const client = makeClient();
|
const client = makeClient();
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
|
|||||||
Reference in new issue
Block a user