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
+13
-2
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -46,4 +46,8 @@ export type ApplySettingsPayload = (
|
||||
) => 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,
|
||||
setForm,
|
||||
editingPresetName,
|
||||
imageInputPreset,
|
||||
presetNameError,
|
||||
error,
|
||||
settings,
|
||||
@@ -243,6 +244,7 @@ export function ModelsSettings({
|
||||
form: AgentSettingsDraft;
|
||||
setForm: Dispatch<SetStateAction<AgentSettingsDraft>>;
|
||||
editingPresetName: string;
|
||||
imageInputPreset?: string;
|
||||
presetNameError: string | null;
|
||||
error?: string | null;
|
||||
settings: SettingsPayload;
|
||||
@@ -286,6 +288,9 @@ export function ModelsSettings({
|
||||
});
|
||||
const editorTriggerRef = useRef<HTMLElement | null>(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 presetContextInitializedRef = useRef(false);
|
||||
const [editorRowKey, setEditorRowKey] = useState<string | null>(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")}
|
||||
>
|
||||
<ToggleButton
|
||||
ref={imageInputRef}
|
||||
checked={form.supportsImages}
|
||||
label={t("settings.models.imageInput")}
|
||||
disabled={saving || creatingSaving}
|
||||
@@ -994,6 +1013,12 @@ export function ModelsSettings({
|
||||
onBlurCapture={edits.onBlurCapture}
|
||||
onEscapeKeyDown={() => 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();
|
||||
|
||||
@@ -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<void>;
|
||||
onDismiss: () => Promise<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 [pending, setPending] = useState<"continue" | "dismiss" | 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"
|
||||
? 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 }:
|
||||
<p className="font-medium">
|
||||
{title}
|
||||
</p>
|
||||
{modelFailure && onOpenSettings ? (
|
||||
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={onOpenSettings}>
|
||||
{t("thread.composer.reauthSettings")}
|
||||
{modelFailure && openSettings ? (
|
||||
<Button variant="link" size="sm" className="h-auto px-0 py-1" onClick={openSettings}>
|
||||
{t(imageFailure ? "settings.models.viewPreset" : "thread.composer.reauthSettings")}
|
||||
</Button>
|
||||
) : null}
|
||||
<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 />
|
||||
{t("recovery.dismiss", { defaultValue: "Dismiss" })}
|
||||
</Button>
|
||||
{!contextUnavailable ? (
|
||||
{!contextUnavailable && !(state.failure_error_kind === "unsupported_image" && imageInputBlocked) ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
|
||||
@@ -20,7 +20,6 @@ interface StreamErrorNoticeProps {
|
||||
*/
|
||||
export function StreamErrorNotice({ error, onDismiss, onOpenSettings }: StreamErrorNoticeProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { title, body } = resolveCopy(error, t);
|
||||
|
||||
return (
|
||||
|
||||
@@ -238,6 +238,8 @@ interface ThreadComposerProps {
|
||||
modelOptionsControl?: ModelOptionsControlProps;
|
||||
onModelMenuOpenChange?: (open: boolean) => void;
|
||||
onModelPresetChange?: (name: string) => void;
|
||||
imageInputBlocked?: boolean;
|
||||
onInspectImagePreset?: () => void;
|
||||
modelProvider?: string | null;
|
||||
modelProviderLabel?: string | null;
|
||||
modelNeedsSetup?: boolean;
|
||||
@@ -571,6 +573,8 @@ export function ThreadComposer({
|
||||
modelOptionsControl,
|
||||
onModelMenuOpenChange,
|
||||
onModelPresetChange,
|
||||
imageInputBlocked = false,
|
||||
onInspectImagePreset,
|
||||
modelProvider = null,
|
||||
modelProviderLabel = null,
|
||||
modelNeedsSetup = false,
|
||||
@@ -705,6 +709,22 @@ export function ThreadComposer({
|
||||
return null;
|
||||
}, [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 {
|
||||
snapshot: queueSnapshot,
|
||||
collect: collectQueuedPrompt,
|
||||
@@ -715,8 +735,7 @@ export function ThreadComposer({
|
||||
} = useQueuedPrompt(pendingQueueKey, { isStreaming, activeTurnId, completedTurnIds }, {
|
||||
disabled: !!disabled || sendPending,
|
||||
onSend,
|
||||
validate: queuedPromptError,
|
||||
onValidationError: setInlineError,
|
||||
validate: validatePrompt,
|
||||
onSendAttempt: focusTextarea,
|
||||
});
|
||||
const queuedPrompt = queueSnapshot.prompt;
|
||||
@@ -1711,11 +1730,7 @@ export function ThreadComposer({
|
||||
slashLifecycle === "finalize_active_turn";
|
||||
if (!isUserShell && !slashLifecycle) {
|
||||
const prompt = collectGuidancePrompt();
|
||||
const error = queuedPromptError(prompt);
|
||||
if (error) {
|
||||
setInlineError(error);
|
||||
return;
|
||||
}
|
||||
if (!validatePrompt(prompt)) return;
|
||||
if (queuedPrompt) {
|
||||
sendQueuedPrompt(prompt, options);
|
||||
if (draftKey) draftStore?.delete(draftKey);
|
||||
@@ -1774,7 +1789,7 @@ export function ThreadComposer({
|
||||
clearComposerText,
|
||||
collectGuidancePrompt,
|
||||
queuedPrompt,
|
||||
queuedPromptError,
|
||||
validatePrompt,
|
||||
sendQueuedPrompt,
|
||||
clearQueuedPrompt,
|
||||
hasTouchPrimaryPointer,
|
||||
|
||||
@@ -38,6 +38,8 @@ import { ThreadHeader } from "@/components/thread/ThreadHeader";
|
||||
import { GoalIsland } from "@/components/thread/GoalIsland";
|
||||
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
|
||||
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 { ExecSessionCommandsContext } from "@/components/thread/activity/exec-session-context";
|
||||
import { execSessionCommands } from "@/components/thread/activity/exec-session-model";
|
||||
@@ -261,6 +263,7 @@ interface ThreadShellProps {
|
||||
settingsSnapshot?: SettingsPayload | null;
|
||||
settingsLoading?: boolean;
|
||||
onOpenModelSettings?: () => void;
|
||||
onInspectImagePreset?: (name: string) => void;
|
||||
onOpenSandboxSettings?: (target: "sandbox" | "sandbox-launcher") => void;
|
||||
skills?: SkillSummary[];
|
||||
}
|
||||
@@ -401,10 +404,12 @@ export function ThreadShell({
|
||||
settingsSnapshot = null,
|
||||
settingsLoading = false,
|
||||
onOpenModelSettings,
|
||||
onInspectImagePreset,
|
||||
onOpenSandboxSettings,
|
||||
skills = [],
|
||||
}: ThreadShellProps) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const chatId = session?.chatId ?? null;
|
||||
const historyKey = temporary ? null : session?.key ?? 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
|
||||
|| "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(() => {
|
||||
setModelFallback(null);
|
||||
if (!chatId) return;
|
||||
@@ -1295,9 +1318,11 @@ export function ThreadShell({
|
||||
onContinue={continueRecovery}
|
||||
onDismiss={dismissRecovery}
|
||||
onOpenSettings={onOpenModelSettings}
|
||||
onInspectImagePreset={inspectImagePreset}
|
||||
imageInputBlocked={imageInputBlocked}
|
||||
/>
|
||||
) : null}
|
||||
{streamError && !hasInlineDeliveryError(messages, streamError) ? (
|
||||
{streamError && !imageRequestError && !hasInlineDeliveryError(messages, streamError) ? (
|
||||
<StreamErrorNotice
|
||||
error={streamError}
|
||||
onDismiss={dismissStreamError}
|
||||
@@ -1322,6 +1347,8 @@ export function ThreadShell({
|
||||
draftStore={draftStore}
|
||||
persistDraft={persistDraft}
|
||||
onSend={handleThreadSend}
|
||||
imageInputBlocked={imageInputBlocked}
|
||||
onInspectImagePreset={inspectImagePreset}
|
||||
disabled={!chatId}
|
||||
inputAriaLabel={composerInputAriaLabel}
|
||||
isStreaming={turnActive}
|
||||
@@ -1380,6 +1407,8 @@ export function ThreadShell({
|
||||
draftStore={draftStore}
|
||||
persistDraft={persistDraft}
|
||||
onSend={handleWelcomeSend}
|
||||
imageInputBlocked={imageInputBlocked}
|
||||
onInspectImagePreset={inspectImagePreset}
|
||||
disabled={booting}
|
||||
inputAriaLabel={composerInputAriaLabel}
|
||||
isStreaming={turnActive}
|
||||
|
||||
@@ -311,8 +311,7 @@ interface QueuedPromptDelivery {
|
||||
images?: SendAttachment[],
|
||||
options?: SendOptions,
|
||||
) => boolean | void | Promise<boolean | void>;
|
||||
validate: (prompt: QueuedPromptContent) => string | null;
|
||||
onValidationError: (error: string) => void;
|
||||
validate: (prompt: QueuedPromptContent) => boolean;
|
||||
onSendAttempt: () => void;
|
||||
}
|
||||
|
||||
@@ -320,7 +319,7 @@ interface QueuedPromptDelivery {
|
||||
export function useQueuedPrompt(
|
||||
pendingQueueKey: string | null,
|
||||
{ isStreaming, activeTurnId, completedTurnIds = EMPTY_COMPLETED_TURN_IDS }: QueuedPromptRun,
|
||||
{ disabled, onSend, validate, onValidationError, onSendAttempt }: QueuedPromptDelivery,
|
||||
{ disabled, onSend, validate, onSendAttempt }: QueuedPromptDelivery,
|
||||
) {
|
||||
const storageKey = queuedPromptsStorageKey(pendingQueueKey);
|
||||
const store = useMemo(() => queuedPromptStoreFor(storageKey), [storageKey]);
|
||||
@@ -356,14 +355,10 @@ export function useQueuedPrompt(
|
||||
}, [activeTurnId, queuedPrompt]);
|
||||
|
||||
const enqueue = useCallback((prompt: QueuedPrompt): boolean => {
|
||||
const error = validate(prompt);
|
||||
if (error) {
|
||||
onValidationError(error);
|
||||
return false;
|
||||
}
|
||||
if (!validate(prompt)) return false;
|
||||
setQueuedPrompt(prompt);
|
||||
return true;
|
||||
}, [onValidationError, setQueuedPrompt, validate]);
|
||||
}, [setQueuedPrompt, validate]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setQueuedPrompt(null);
|
||||
@@ -376,10 +371,8 @@ export function useQueuedPrompt(
|
||||
const send = useCallback(
|
||||
(prompt: QueuedPrompt, extraOptions?: SendOptions) => {
|
||||
if (interactionDisabled) return;
|
||||
const error = validate(prompt);
|
||||
if (error) {
|
||||
if (!validate(prompt)) {
|
||||
setQueuedPrompt(pauseQueuedPrompt(prompt));
|
||||
onValidationError(error);
|
||||
return;
|
||||
}
|
||||
const text = prompt.text.trim();
|
||||
@@ -401,7 +394,7 @@ export function useQueuedPrompt(
|
||||
));
|
||||
onSendAttempt();
|
||||
},
|
||||
[interactionDisabled, isStreaming, onSend, onSendAttempt, onValidationError, store, validate, setQueuedPrompt],
|
||||
[interactionDisabled, isStreaming, onSend, onSendAttempt, store, validate, setQueuedPrompt],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useClient } from "@/providers/ClientProvider";
|
||||
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||
import { ApiError, fetchWebuiThread, fetchWebuiThreadTraceDetail } from "@/lib/api";
|
||||
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
|
||||
import { isImageRequestFailure } from "@/lib/model-request-failure";
|
||||
import { persistedCanonicalRunState } from "@/lib/canonical-run-snapshot";
|
||||
import { historyContentSnapshot, sameHistoryContent } from "@/lib/thread-display-projection";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
@@ -897,7 +898,8 @@ export function useNanobotStream(
|
||||
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
|
||||
}
|
||||
: 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);
|
||||
playTurnCompleteSound();
|
||||
onTurnEnd?.();
|
||||
@@ -920,8 +922,11 @@ export function useNanobotStream(
|
||||
? { reply_preserved: ev.reply_preserved }
|
||||
: {}),
|
||||
};
|
||||
setRecoveryState(next);
|
||||
if (ev.reason === "model_request_failed" || ev.status === "resuming") {
|
||||
const inputRejected = ev.status === "recovered" && ev.reason === "input_rejected";
|
||||
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);
|
||||
}
|
||||
if (
|
||||
@@ -938,7 +943,7 @@ export function useNanobotStream(
|
||||
}
|
||||
|
||||
if (ev.event === "attached") {
|
||||
setRecoveryState(ev.recovery_state ?? null);
|
||||
setRecoveryState(ev.recovery_state?.reason === "input_rejected" ? null : ev.recovery_state ?? null);
|
||||
if (
|
||||
ev.recovery_state?.reason === "model_request_failed"
|
||||
|| ev.recovery_state?.status === "resuming"
|
||||
|
||||
@@ -877,7 +877,8 @@
|
||||
"maxTokens": "Max output tokens",
|
||||
"temperature": "Temperature",
|
||||
"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",
|
||||
"convertTitle": "Convert setup",
|
||||
"convertHelp": "Convert primary and fallback models to presets.",
|
||||
@@ -2760,6 +2761,9 @@
|
||||
"timeoutTitle": "Model provider request timed out",
|
||||
"rateLimitTitle": "Model provider rate limit reached",
|
||||
"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",
|
||||
"bodyWithAttempt": "Stopped after {{attempts}} attempts. 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",
|
||||
"temperature": "Temperatura",
|
||||
"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",
|
||||
"convertTitle": "Convertir ajustes",
|
||||
"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",
|
||||
"rateLimitTitle": "Se alcanzó el límite de solicitudes 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ó",
|
||||
"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."
|
||||
|
||||
@@ -1067,7 +1067,8 @@
|
||||
"maxTokens": "Tokens de sortie max.",
|
||||
"temperature": "Température",
|
||||
"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",
|
||||
"convertTitle": "Convertir les 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é",
|
||||
"rateLimitTitle": "Limite de requêtes du fournisseur du modèle atteinte",
|
||||
"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",
|
||||
"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."
|
||||
|
||||
@@ -1067,7 +1067,8 @@
|
||||
"maxTokens": "Maks. token keluaran",
|
||||
"temperature": "Temperatur",
|
||||
"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",
|
||||
"convertTitle": "Konversi pengaturan",
|
||||
"convertHelp": "Ubah model utama dan cadangan menjadi preset.",
|
||||
@@ -2578,6 +2579,9 @@
|
||||
"timeoutTitle": "Permintaan ke penyedia model kehabisan waktu",
|
||||
"rateLimitTitle": "Batas permintaan penyedia model tercapai",
|
||||
"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",
|
||||
"bodyWithAttempt": "Dihentikan setelah {{attempts}} percobaan. Coba lagi nanti atau pilih model lain.",
|
||||
"body": "Coba lagi nanti atau pilih model lain."
|
||||
|
||||
@@ -1067,7 +1067,8 @@
|
||||
"maxTokens": "最大出力トークン",
|
||||
"temperature": "温度",
|
||||
"imageInput": "画像入力",
|
||||
"imageInputHelp": "オフにすると、画像を含むリクエストではこのプリセットをスキップします。",
|
||||
"imageInputHelp": "モデルが画像に対応している場合のみオンにしてください。オフにすると、画像を含むリクエストではこのプリセットをスキップします。",
|
||||
"viewPreset": "プリセットを確認",
|
||||
"reasoningEffort": "推論の強度",
|
||||
"convertTitle": "設定を変換",
|
||||
"convertHelp": "主モデルと予備モデルをプリセットに変換します。",
|
||||
@@ -2578,6 +2579,9 @@
|
||||
"timeoutTitle": "モデルプロバイダーへのリクエストがタイムアウトしました",
|
||||
"rateLimitTitle": "モデルプロバイダーのリクエスト上限に達しました",
|
||||
"serverTitle": "モデルプロバイダーでサービスエラーが発生しました",
|
||||
"imageInputTitle": "このプリセットでは画像入力がオフです",
|
||||
"imageRequestRejectedTitle": "モデルが画像付きのリクエストを拒否しました",
|
||||
"imageInputBody": "このリクエストには画像が含まれています。プリセットを確認するか、画像対応のプリセットを使用してください。",
|
||||
"unknownTitle": "モデルプロバイダーへのリクエストに失敗しました",
|
||||
"bodyWithAttempt": "{{attempts}} 回試行して停止しました。後でもう一度試すか、別のモデルを選んでください。",
|
||||
"body": "後でもう一度試すか、別のモデルを選んでください。"
|
||||
|
||||
@@ -1067,7 +1067,8 @@
|
||||
"maxTokens": "최대 출력 토큰",
|
||||
"temperature": "온도",
|
||||
"imageInput": "이미지 입력",
|
||||
"imageInputHelp": "끄면 이미지가 포함된 요청에서 이 프리셋을 건너뜁니다.",
|
||||
"imageInputHelp": "모델이 이미지를 지원할 때만 켜세요. 끄면 이미지가 포함된 요청에서 이 프리셋을 건너뜁니다.",
|
||||
"viewPreset": "프리셋 보기",
|
||||
"reasoningEffort": "추론 강도",
|
||||
"convertTitle": "설정 변환",
|
||||
"convertHelp": "주 모델과 대체 모델을 프리셋으로 변환하세요.",
|
||||
@@ -2578,6 +2579,9 @@
|
||||
"timeoutTitle": "모델 제공업체 요청 시간 초과",
|
||||
"rateLimitTitle": "모델 제공업체 요청 한도 초과",
|
||||
"serverTitle": "모델 제공업체 서비스 오류",
|
||||
"imageInputTitle": "이 프리셋의 이미지 입력이 꺼져 있습니다",
|
||||
"imageRequestRejectedTitle": "모델이 이미지가 포함된 요청을 거부했습니다",
|
||||
"imageInputBody": "이 요청에 이미지가 포함되어 있습니다. 프리셋을 확인하거나 이미지를 지원하는 프리셋을 사용하세요.",
|
||||
"unknownTitle": "모델 제공업체 요청 실패",
|
||||
"bodyWithAttempt": "{{attempts}}회 시도 후 중지했습니다. 나중에 다시 시도하거나 다른 모델을 선택하세요.",
|
||||
"body": "나중에 다시 시도하거나 다른 모델을 선택하세요."
|
||||
|
||||
@@ -697,7 +697,8 @@
|
||||
"maxTokens": "Máx. de tokens de saída",
|
||||
"temperature": "Temperatura",
|
||||
"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",
|
||||
"convertTitle": "Converter ajustes",
|
||||
"convertHelp": "Converta os modelos principal e alternativo em presets.",
|
||||
@@ -2580,6 +2581,9 @@
|
||||
"timeoutTitle": "A solicitação ao provedor do modelo expirou",
|
||||
"rateLimitTitle": "Limite de solicitações do provedor do modelo atingido",
|
||||
"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",
|
||||
"bodyWithAttempt": "Interrompido após {{attempts}} tentativas. 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",
|
||||
"temperature": "Nhiệt độ",
|
||||
"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",
|
||||
"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.",
|
||||
@@ -2578,6 +2579,9 @@
|
||||
"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",
|
||||
"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",
|
||||
"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."
|
||||
|
||||
@@ -877,7 +877,8 @@
|
||||
"maxTokens": "输出 Token 上限",
|
||||
"temperature": "温度",
|
||||
"imageInput": "图像输入",
|
||||
"imageInputHelp": "关闭后,含图片的请求会跳过此预设。",
|
||||
"imageInputHelp": "仅当模型支持图片时开启。关闭后,含图片的请求会跳过此预设。",
|
||||
"viewPreset": "查看预设",
|
||||
"reasoningEffort": "推理强度",
|
||||
"convertTitle": "转换设置",
|
||||
"convertHelp": "将主模型和备用模型转为预设",
|
||||
@@ -2760,6 +2761,9 @@
|
||||
"timeoutTitle": "模型提供商请求超时",
|
||||
"rateLimitTitle": "模型提供商请求受限",
|
||||
"serverTitle": "模型提供商服务异常",
|
||||
"imageInputTitle": "此预设的图像输入已关闭",
|
||||
"imageRequestRejectedTitle": "含图请求被模型拒绝",
|
||||
"imageInputBody": "这次请求包含图片。请检查此预设,或使用支持图片的预设。",
|
||||
"unknownTitle": "模型提供商请求失败",
|
||||
"bodyWithAttempt": "已尝试 {{attempts}} 次,仍未成功。可稍后继续或切换模型。",
|
||||
"body": "可稍后继续或切换模型。"
|
||||
|
||||
@@ -1067,7 +1067,8 @@
|
||||
"maxTokens": "輸出 Token 上限",
|
||||
"temperature": "溫度",
|
||||
"imageInput": "圖像輸入",
|
||||
"imageInputHelp": "關閉後,含圖片的請求會略過此預設。",
|
||||
"imageInputHelp": "僅在模型支援圖片時開啟。關閉後,含圖片的請求會略過此預設。",
|
||||
"viewPreset": "查看預設",
|
||||
"reasoningEffort": "推理強度",
|
||||
"convertTitle": "轉換設定",
|
||||
"convertHelp": "將主模型和備用模型轉為預設",
|
||||
@@ -2578,6 +2579,9 @@
|
||||
"timeoutTitle": "模型供應商請求逾時",
|
||||
"rateLimitTitle": "模型供應商請求受到限制",
|
||||
"serverTitle": "模型供應商服務發生錯誤",
|
||||
"imageInputTitle": "此預設的圖像輸入已關閉",
|
||||
"imageRequestRejectedTitle": "模型拒絕了含有圖片的請求",
|
||||
"imageInputBody": "這次請求包含圖片。請檢查此預設,或使用支援圖片的預設。",
|
||||
"unknownTitle": "模型供應商請求失敗",
|
||||
"bodyWithAttempt": "已嘗試 {{attempts}} 次,仍未成功。可稍後繼續或切換模型。",
|
||||
"body": "可稍後繼續或切換模型。"
|
||||
|
||||
@@ -5,10 +5,22 @@ export interface ModelRequestFailureDetails {
|
||||
attempts?: number;
|
||||
}
|
||||
|
||||
export function isImageRequestFailure(errorKind?: string): boolean {
|
||||
return errorKind === "unsupported_image" || errorKind === "image_request_rejected";
|
||||
}
|
||||
|
||||
export function resolveModelRequestFailureCopy(
|
||||
details: ModelRequestFailureDetails,
|
||||
t: TFunction,
|
||||
): { 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";
|
||||
if (details.errorKind === "billing") {
|
||||
titleKey = "errors.modelRequestFailed.billingTitle";
|
||||
|
||||
@@ -800,6 +800,7 @@ export interface SettingsPayload {
|
||||
}>;
|
||||
model_call_order: string[];
|
||||
model_call_order_editable: boolean;
|
||||
image_fallback_configured?: boolean;
|
||||
/** Whether an actual legacy model configuration is available to convert. */
|
||||
model_configuration_migratable?: boolean;
|
||||
/** 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();
|
||||
});
|
||||
|
||||
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", () => {
|
||||
const onOpenSettings = vi.fn();
|
||||
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") {
|
||||
const row = await screen.findByTestId(`model-call-order-row-${name}`);
|
||||
fireEvent.click(within(row).getAllByRole("button")[0]);
|
||||
|
||||
@@ -88,6 +88,56 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const user = userEvent.setup();
|
||||
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]);
|
||||
});
|
||||
|
||||
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 onSend = vi.fn();
|
||||
|
||||
render(<ThreadComposer onSend={onSend} />);
|
||||
render(<ThreadComposer onSend={onSend} imageInputBlocked />);
|
||||
|
||||
const input = screen
|
||||
.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) => {
|
||||
const client = makeClient();
|
||||
await act(async () => {
|
||||
|
||||
Reference in new issue
Block a user