fix(webui): merge consecutive waiting messages (#6309)
* fix(webui): merge consecutive waiting messages * fix(webui): retain legacy draft session targets on refresh
This commit is contained in:
1 parent
8778c69774
commit
125d9221d0
17 files changed
+680
-606
No files matched your search
@@ -32,6 +32,7 @@ import {
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
type CSSProperties,
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
type Ref,
|
||||
@@ -52,7 +53,6 @@ import {
|
||||
ChevronUp,
|
||||
CornerDownRight,
|
||||
FileText,
|
||||
GripVertical,
|
||||
ImageIcon,
|
||||
Loader2,
|
||||
Quote,
|
||||
@@ -91,6 +91,8 @@ import {
|
||||
import {
|
||||
ACCEPT_ATTR,
|
||||
MAX_ATTACHMENTS_PER_MESSAGE,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_TOTAL_ATTACHMENT_BYTES,
|
||||
useAttachedImages,
|
||||
type AttachedImage,
|
||||
type AttachmentError,
|
||||
@@ -299,7 +301,6 @@ const SLASH_RECENTS_LIMIT = 5;
|
||||
const QUEUED_PROMPTS_STORAGE_PREFIX = "nanobot.webui.composerQueuedGuidance.v1:";
|
||||
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
|
||||
const QUEUED_PROMPTS_LIMIT = 20;
|
||||
const QUEUED_PROMPT_MAX_CHARS = 4000;
|
||||
const SESSION_MENTIONS_LIMIT = 8;
|
||||
|
||||
function VoiceRecordingMeter({
|
||||
@@ -362,8 +363,29 @@ function pauseQueuedPrompt(prompt: QueuedPrompt): QueuedPrompt {
|
||||
return { ...prompt, autoAfterTurnId: undefined, autoPaused: true };
|
||||
}
|
||||
|
||||
function waitForNextQueuedTurn(prompt: QueuedPrompt): QueuedPrompt {
|
||||
return { ...prompt, autoAfterTurnId: undefined, autoPaused: false };
|
||||
function mergeQueuedPrompt(first: QueuedPrompt, next: QueuedPrompt): QueuedPrompt {
|
||||
const prompts = [first, next];
|
||||
const mentions = new Map<string, SessionMention>();
|
||||
for (const prompt of prompts) {
|
||||
for (const mention of prompt.sessionMentions ?? []) {
|
||||
if (!mentions.has(mention.session_key)) mentions.set(mention.session_key, mention);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: first.id,
|
||||
text: prompts.map((prompt) => prompt.text).filter(Boolean).join("\n"),
|
||||
images: prompts.flatMap((prompt) => prompt.images ?? []),
|
||||
quotedContext: [...new Set(prompts.map((prompt) => prompt.quotedContext).filter(Boolean))].join("\n\n"),
|
||||
sessionMentions: [...mentions.values()],
|
||||
autoAfterTurnId: first.autoAfterTurnId,
|
||||
autoPaused: prompts.some((prompt) => prompt.autoPaused),
|
||||
};
|
||||
}
|
||||
|
||||
function queuedAttachmentBytes(image: QueuedPromptImage): number {
|
||||
const base64 = image.dataUrl.slice(image.dataUrl.indexOf(",") + 1);
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
return Math.floor(base64.length * 3 / 4) - padding;
|
||||
}
|
||||
|
||||
interface QueuedPromptImage {
|
||||
@@ -508,14 +530,14 @@ function normalizeQueuedSessionMentions(value: unknown): SessionMention[] {
|
||||
session_key: sessionKey,
|
||||
title: candidate.title?.trim().slice(0, 160) ?? "",
|
||||
}];
|
||||
}).slice(0, SESSION_MENTIONS_LIMIT);
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | null {
|
||||
if (!item || typeof item !== "object") return null;
|
||||
const record = item as Partial<QueuedPrompt>;
|
||||
if (typeof record.text !== "string") return null;
|
||||
const text = record.text.trim().slice(0, QUEUED_PROMPT_MAX_CHARS);
|
||||
const text = record.text.trim();
|
||||
const images = Array.isArray(record.images)
|
||||
? record.images.flatMap((image) => {
|
||||
if (!image || typeof image !== "object") return [];
|
||||
@@ -535,10 +557,10 @@ function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | nul
|
||||
? { name: candidate.name.trim() }
|
||||
: {}),
|
||||
}];
|
||||
}).slice(0, MAX_ATTACHMENTS_PER_MESSAGE)
|
||||
})
|
||||
: [];
|
||||
const quotedContext = typeof record.quotedContext === "string"
|
||||
? record.quotedContext.trim().slice(0, QUEUED_PROMPT_MAX_CHARS)
|
||||
? record.quotedContext.trim()
|
||||
: "";
|
||||
const sessionMentions = normalizeQueuedSessionMentions(record.sessionMentions);
|
||||
if (!text && images.length === 0) return null;
|
||||
@@ -558,49 +580,115 @@ function normalizeQueuedPrompt(item: unknown, index: number): QueuedPrompt | nul
|
||||
};
|
||||
}
|
||||
|
||||
function readQueuedPrompts(storageKey: string): QueuedPrompt[] {
|
||||
if (typeof window === "undefined") return [];
|
||||
function readQueuedPrompt(storageKey: string): QueuedPrompt | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed
|
||||
if (!Array.isArray(parsed)) return null;
|
||||
return parsed.slice(0, QUEUED_PROMPTS_LIMIT)
|
||||
.map((item, index) => normalizeQueuedPrompt(item, index))
|
||||
.filter((item): item is QueuedPrompt => item != null)
|
||||
.slice(0, QUEUED_PROMPTS_LIMIT);
|
||||
.reduce<QueuedPrompt | null>((pending, prompt) => (
|
||||
pending ? mergeQueuedPrompt(pending, prompt) : prompt
|
||||
), null);
|
||||
} catch {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function storeQueuedPrompts(storageKey: string, prompts: QueuedPrompt[]): void {
|
||||
function storeQueuedPrompt(storageKey: string, prompt: QueuedPrompt | null): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
if (prompts.length === 0) {
|
||||
if (!prompt) {
|
||||
window.localStorage.removeItem(storageKey);
|
||||
return;
|
||||
}
|
||||
window.localStorage.setItem(
|
||||
storageKey,
|
||||
JSON.stringify(
|
||||
prompts.slice(0, QUEUED_PROMPTS_LIMIT).map((prompt) => ({
|
||||
id: prompt.id,
|
||||
text: prompt.text.slice(0, QUEUED_PROMPT_MAX_CHARS),
|
||||
...(prompt.images?.length ? { images: prompt.images.slice(0, MAX_ATTACHMENTS_PER_MESSAGE) } : {}),
|
||||
...(prompt.quotedContext ? { quotedContext: prompt.quotedContext } : {}),
|
||||
...(prompt.sessionMentions?.length
|
||||
? { sessionMentions: prompt.sessionMentions.slice(0, SESSION_MENTIONS_LIMIT) }
|
||||
: {}),
|
||||
...(prompt.autoAfterTurnId ? { autoAfterTurnId: prompt.autoAfterTurnId } : {}),
|
||||
...(prompt.autoPaused ? { autoPaused: true } : {}),
|
||||
})),
|
||||
),
|
||||
);
|
||||
// Retain the v1 array shape so existing queued drafts remain readable.
|
||||
window.localStorage.setItem(storageKey, JSON.stringify([prompt]));
|
||||
} catch {
|
||||
// localStorage persistence is a convenience; the in-memory queue still works.
|
||||
// localStorage persistence is a convenience; the in-memory draft still works.
|
||||
}
|
||||
}
|
||||
|
||||
interface QueuedPromptSnapshot {
|
||||
prompt: QueuedPrompt | null;
|
||||
sending: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
// Delivery can outlive the composer during attachment upload or topic navigation.
|
||||
// Keep one owner per mounted/sending topic; idle, unmounted owners are reloaded from storage.
|
||||
const queuedPromptStores = new Map<string, QueuedPromptStore>();
|
||||
|
||||
class QueuedPromptStore {
|
||||
private snapshot: QueuedPromptSnapshot;
|
||||
private listeners = new Set<() => void>();
|
||||
|
||||
constructor(private storageKey: string | null) {
|
||||
this.snapshot = { prompt: storageKey ? readQueuedPrompt(storageKey) : null, sending: false, error: null };
|
||||
}
|
||||
|
||||
getSnapshot = () => this.snapshot;
|
||||
|
||||
subscribe = (listener: () => void) => {
|
||||
if (this.storageKey) queuedPromptStores.set(this.storageKey, this);
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
this.release();
|
||||
};
|
||||
};
|
||||
|
||||
private release() {
|
||||
if (this.storageKey && !this.snapshot.sending && this.listeners.size === 0
|
||||
&& queuedPromptStores.get(this.storageKey) === this) queuedPromptStores.delete(this.storageKey);
|
||||
}
|
||||
|
||||
private publish(next: QueuedPromptSnapshot) {
|
||||
if (this.storageKey && next.prompt !== this.snapshot.prompt) storeQueuedPrompt(this.storageKey, next.prompt);
|
||||
this.snapshot = next;
|
||||
for (const listener of this.listeners) listener();
|
||||
this.release();
|
||||
}
|
||||
|
||||
set = (next: QueuedPrompt | null | ((current: QueuedPrompt | null) => QueuedPrompt | null)) => {
|
||||
const prompt = typeof next === "function" ? next(this.snapshot.prompt) : next;
|
||||
if (prompt !== this.snapshot.prompt) this.publish({ ...this.snapshot, prompt, error: null });
|
||||
};
|
||||
|
||||
send(prompt: QueuedPrompt, send: () => void | boolean | Promise<void | boolean>) {
|
||||
if (this.snapshot.sending) return;
|
||||
const retained = pauseQueuedPrompt(prompt);
|
||||
this.publish({ prompt: retained, sending: true, error: null });
|
||||
const finish = (accepted: void | boolean, error?: unknown) => {
|
||||
const failed = accepted === false || error !== undefined;
|
||||
this.publish({
|
||||
prompt: failed ? retained : null,
|
||||
sending: false,
|
||||
error: failed ? error instanceof Error ? error.message : "Message not sent; queued draft retained" : null,
|
||||
});
|
||||
};
|
||||
try {
|
||||
const result = send();
|
||||
if (result instanceof Promise) void result.then((accepted) => finish(accepted), (error: unknown) => finish(false, error));
|
||||
else finish(result);
|
||||
} catch (error) {
|
||||
finish(false, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function queuedPromptStoreFor(storageKey: string | null): QueuedPromptStore {
|
||||
if (!storageKey) return new QueuedPromptStore(null);
|
||||
let store = queuedPromptStores.get(storageKey);
|
||||
if (!store) {
|
||||
store = new QueuedPromptStore(storageKey);
|
||||
queuedPromptStores.set(storageKey, store);
|
||||
}
|
||||
return store;
|
||||
}
|
||||
|
||||
function readyImagesToQueuedImages(
|
||||
images: Array<AttachedImage & { dataUrl: string }>,
|
||||
): QueuedPromptImage[] {
|
||||
@@ -632,27 +720,6 @@ function queuedPromptLabel(prompt: QueuedPrompt): string {
|
||||
return prompt.images?.map((img) => img.name).filter(Boolean).join(", ") || "File attachment";
|
||||
}
|
||||
|
||||
function suppressNativeDragPreview(dataTransfer: DataTransfer): void {
|
||||
if (typeof document === "undefined" || typeof dataTransfer.setDragImage !== "function") {
|
||||
return;
|
||||
}
|
||||
const ghost = document.createElement("div");
|
||||
ghost.style.position = "fixed";
|
||||
ghost.style.left = "-9999px";
|
||||
ghost.style.top = "-9999px";
|
||||
ghost.style.width = "1px";
|
||||
ghost.style.height = "1px";
|
||||
ghost.style.opacity = "0";
|
||||
document.body.appendChild(ghost);
|
||||
try {
|
||||
dataTransfer.setDragImage(ghost, 0, 0);
|
||||
} catch {
|
||||
ghost.remove();
|
||||
return;
|
||||
}
|
||||
window.setTimeout(() => ghost.remove(), 0);
|
||||
}
|
||||
|
||||
function visualViewportBounds(): { top: number; bottom: number; height: number } {
|
||||
const viewport = window.visualViewport;
|
||||
if (!viewport) {
|
||||
@@ -1023,7 +1090,15 @@ export function ThreadComposer({
|
||||
const [inlineError, setInlineError] = useState<string | null>(null);
|
||||
const [sendPending, setSendPending] = useState(false);
|
||||
const [modelSetupAttentionRequest, setModelSetupAttentionRequest] = useState(0);
|
||||
const interactionDisabled = !!disabled || sendPending;
|
||||
const queuedPromptStorageKey = queuedPromptsStorageKey(pendingQueueKey);
|
||||
const queuedPromptStore = useMemo(() => queuedPromptStoreFor(queuedPromptStorageKey), [queuedPromptStorageKey]);
|
||||
const queueSnapshot = useSyncExternalStore(queuedPromptStore.subscribe, queuedPromptStore.getSnapshot);
|
||||
const queuedPrompt = queueSnapshot.prompt;
|
||||
const setQueuedPrompt = queuedPromptStore.set;
|
||||
const interactionDisabled = !!disabled || sendPending || queueSnapshot.sending;
|
||||
useEffect(() => {
|
||||
if (queueSnapshot.error) setInlineError(queueSnapshot.error);
|
||||
}, [queueSnapshot.error]);
|
||||
const [voiceErrorFading, setVoiceErrorFading] = useState(false);
|
||||
const [slashMenuDismissed, setSlashMenuDismissed] = useState(false);
|
||||
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
|
||||
@@ -1031,7 +1106,6 @@ export function ThreadComposer({
|
||||
const [selectedCliAppIndex, setSelectedCliAppIndex] = useState(0);
|
||||
const [cursorPosition, setCursorPosition] = useState(0);
|
||||
const [recentSlashCommands, setRecentSlashCommands] = useState<string[]>(() => readSlashRecents());
|
||||
const [queuedPrompts, setQueuedPrompts] = useState<QueuedPrompt[]>([]);
|
||||
const hasTouchPrimaryPointer = useMediaQuery("(hover: none) and (pointer: coarse)");
|
||||
// Coarser than hasTouchPrimaryPointer on purpose: tablets with a physical
|
||||
// keyboard still get the newline-on-Enter behavior.
|
||||
@@ -1068,20 +1142,14 @@ export function ThreadComposer({
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
|
||||
const queuedPromptCounterRef = useRef(0);
|
||||
// Only the prompt queued by the immediately preceding Enter can use the second-Enter shortcut.
|
||||
// A fresh queue submission arms Enter for the complete pending message.
|
||||
const secondEnterPromptIdRef = useRef<string | null>(null);
|
||||
const draggedQueuedPromptIdRef = useRef<string | null>(null);
|
||||
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
|
||||
const previousQueueRunRef = useRef({ key: pendingQueueKey, isStreaming });
|
||||
const skipQueuedPromptPersistRef = useRef(false);
|
||||
const voiceShortcutDownRef = useRef(false);
|
||||
const voiceErrorFadeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const isHero = variant === "hero";
|
||||
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
|
||||
const queuedPromptStorageKey = useMemo(
|
||||
() => queuedPromptsStorageKey(pendingQueueKey),
|
||||
[pendingQueueKey],
|
||||
);
|
||||
const projectPickerAvailable =
|
||||
isHero
|
||||
&& !!workspaceDefaultScope
|
||||
@@ -1095,32 +1163,16 @@ export function ThreadComposer({
|
||||
|
||||
useEffect(() => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
skipQueuedPromptPersistRef.current = true;
|
||||
setQueuedPrompts(queuedPromptStorageKey ? readQueuedPrompts(queuedPromptStorageKey) : []);
|
||||
}, [pendingQueueKey, queuedPromptStorageKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming || !activeTurnId) return;
|
||||
// The next lifecycle owner, not a guidance input, releases the remaining queue.
|
||||
setQueuedPrompts((items) => {
|
||||
let changed = false;
|
||||
const next = items.map((item) => {
|
||||
if (item.autoPaused || item.autoAfterTurnId === activeTurnId) return item;
|
||||
changed = true;
|
||||
return { ...item, autoAfterTurnId: activeTurnId };
|
||||
});
|
||||
return changed ? next : items;
|
||||
});
|
||||
}, [activeTurnId, isStreaming, pendingQueueKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!queuedPromptStorageKey) return;
|
||||
if (skipQueuedPromptPersistRef.current) {
|
||||
skipQueuedPromptPersistRef.current = false;
|
||||
return;
|
||||
}
|
||||
storeQueuedPrompts(queuedPromptStorageKey, queuedPrompts);
|
||||
}, [queuedPromptStorageKey, queuedPrompts]);
|
||||
setQueuedPrompt((prompt) => (
|
||||
!prompt || prompt.autoPaused || prompt.autoAfterTurnId === activeTurnId
|
||||
? prompt
|
||||
: { ...prompt, autoAfterTurnId: activeTurnId }
|
||||
));
|
||||
}, [activeTurnId, isStreaming, pendingQueueKey, setQueuedPrompt]);
|
||||
|
||||
const resolvedPlaceholder = isStreaming
|
||||
? t("thread.composer.placeholderStreaming")
|
||||
@@ -1136,7 +1188,7 @@ export function ThreadComposer({
|
||||
useLayoutEffect(() => {
|
||||
if (restoredDraftAttachments.current) return;
|
||||
restoredDraftAttachments.current = true;
|
||||
if (initialDraft?.files.length) enqueue(initialDraft.files);
|
||||
if (initialDraft?.files.length) enqueue(initialDraft.files, { restoringDraft: true });
|
||||
setDraftAttachmentsReady(true);
|
||||
}, [enqueue, initialDraft]);
|
||||
|
||||
@@ -1208,7 +1260,7 @@ export function ThreadComposer({
|
||||
return () => cancelAnimationFrame(id);
|
||||
}, [focusRequest, interactionDisabled]);
|
||||
|
||||
const normalizedQuotedContext = quotedContext?.trim().slice(0, QUEUED_PROMPT_MAX_CHARS) || null;
|
||||
const normalizedQuotedContext = quotedContext?.trim() || null;
|
||||
|
||||
const readyImages = useMemo(
|
||||
() => images.filter((img): img is AttachedImage & { dataUrl: string } =>
|
||||
@@ -1468,7 +1520,7 @@ export function ThreadComposer({
|
||||
if (segment.kind !== "session" || seen.has(segment.mention.session_key)) return [];
|
||||
seen.add(segment.mention.session_key);
|
||||
return [segment.mention];
|
||||
}).slice(0, SESSION_MENTIONS_LIMIT);
|
||||
});
|
||||
}, [mentionSegments]);
|
||||
const filteredMentionCandidates = useMemo<MentionCandidate[]>(() => {
|
||||
if (!cliAppMention) return [];
|
||||
@@ -1787,11 +1839,9 @@ export function ThreadComposer({
|
||||
|
||||
const handleStop = useCallback(() => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
if (queuedPrompts.length > 0) {
|
||||
setQueuedPrompts((items) => items.map(pauseQueuedPrompt));
|
||||
}
|
||||
setQueuedPrompt((prompt) => prompt ? pauseQueuedPrompt(prompt) : null);
|
||||
onStop?.();
|
||||
}, [onStop, queuedPrompts.length]);
|
||||
}, [onStop, setQueuedPrompt]);
|
||||
|
||||
const chooseSlashCommand = useCallback(
|
||||
(command: SlashPaletteCommand) => {
|
||||
@@ -1948,56 +1998,63 @@ export function ThreadComposer({
|
||||
resizeTextarea(restoreFocus);
|
||||
}, [resizeTextarea]);
|
||||
|
||||
const queuedPromptError = useCallback((prompt: QueuedPrompt): string | null => {
|
||||
if (utf8Bytes(formatQuotedUserMessage(prompt.text, prompt.quotedContext)) > maxTextBytes) {
|
||||
return textTooLargeMessage();
|
||||
}
|
||||
const attachments = prompt.images ?? [];
|
||||
if (attachments.length > maxAttachments) return formatRejection("too_many_attachments");
|
||||
const sizes = attachments.map(queuedAttachmentBytes);
|
||||
if (sizes.some((size) => size > (ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES))) {
|
||||
return formatRejection("too_large");
|
||||
}
|
||||
if (sizes.reduce((sum, size) => sum + size, 0) > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) {
|
||||
return formatRejection("total_too_large");
|
||||
}
|
||||
if ((prompt.sessionMentions?.length ?? 0) > SESSION_MENTIONS_LIMIT) {
|
||||
return t("thread.composer.queued.tooManyMentions", { max: SESSION_MENTIONS_LIMIT });
|
||||
}
|
||||
return null;
|
||||
}, [formatRejection, ingressLimits, maxAttachments, maxTextBytes, t, textTooLargeMessage]);
|
||||
|
||||
const collectGuidancePrompt = useCallback((): QueuedPrompt => {
|
||||
queuedPromptCounterRef.current += 1;
|
||||
const prompt: QueuedPrompt = {
|
||||
id: `queued-prompt-${Date.now()}-${queuedPromptCounterRef.current}`,
|
||||
text: value.trim(),
|
||||
images: readyImagesToQueuedImages(readyImages),
|
||||
...(activeTurnId ? { autoAfterTurnId: activeTurnId } : {}),
|
||||
...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}),
|
||||
sessionMentions: activeSessionMentions,
|
||||
};
|
||||
return queuedPrompt ? mergeQueuedPrompt(queuedPrompt, prompt) : prompt;
|
||||
}, [activeSessionMentions, activeTurnId, normalizedQuotedContext, queuedPrompt, readyImages, value]);
|
||||
|
||||
const queueGuidancePrompt = useCallback(() => {
|
||||
const text = value.trim();
|
||||
if (!canQueueGuidance || (!text && readyImages.length === 0)) return;
|
||||
if (utf8Bytes(formatQuotedUserMessage(text, normalizedQuotedContext)) > maxTextBytes) {
|
||||
setInlineError(textTooLargeMessage());
|
||||
if (!canQueueGuidance) return;
|
||||
const prompt = collectGuidancePrompt();
|
||||
const error = queuedPromptError(prompt);
|
||||
if (error) {
|
||||
setInlineError(error);
|
||||
return;
|
||||
}
|
||||
const queuedImages = readyImagesToQueuedImages(readyImages);
|
||||
queuedPromptCounterRef.current += 1;
|
||||
const id = `queued-prompt-${Date.now()}-${queuedPromptCounterRef.current}`;
|
||||
secondEnterPromptIdRef.current = id;
|
||||
setQueuedPrompts((items) => [
|
||||
...items,
|
||||
{
|
||||
id,
|
||||
text,
|
||||
...(activeTurnId ? { autoAfterTurnId: activeTurnId } : {}),
|
||||
...(queuedImages.length > 0 ? { images: queuedImages } : {}),
|
||||
...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}),
|
||||
...(activeSessionMentions.length > 0
|
||||
? { sessionMentions: activeSessionMentions }
|
||||
: {}),
|
||||
},
|
||||
]);
|
||||
secondEnterPromptIdRef.current = prompt.id;
|
||||
setQueuedPrompt(prompt);
|
||||
clear();
|
||||
clearComposerText();
|
||||
onQuotedContextChange?.(null);
|
||||
}, [
|
||||
activeSessionMentions,
|
||||
activeTurnId,
|
||||
canQueueGuidance,
|
||||
clear,
|
||||
clearComposerText,
|
||||
maxTextBytes,
|
||||
normalizedQuotedContext,
|
||||
onQuotedContextChange,
|
||||
readyImages,
|
||||
textTooLargeMessage,
|
||||
value,
|
||||
]);
|
||||
}, [canQueueGuidance, clear, clearComposerText, collectGuidancePrompt, onQuotedContextChange, queuedPromptError, setQueuedPrompt]);
|
||||
|
||||
const removeQueuedPrompt = useCallback((id: string) => {
|
||||
const removeQueuedPrompt = useCallback(() => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setQueuedPrompts((items) => items.filter((item) => item.id !== id));
|
||||
setQueuedPrompt(null);
|
||||
requestAnimationFrame(() => textareaRef.current?.focus());
|
||||
}, []);
|
||||
}, [setQueuedPrompt]);
|
||||
|
||||
const editQueuedPrompt = useCallback((prompt: QueuedPrompt) => {
|
||||
const editQueuedPrompt = useCallback((pending: QueuedPrompt) => {
|
||||
const prompt = hasComposerContent || normalizedQuotedContext ? collectGuidancePrompt() : pending;
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setQueuedPrompts((items) => items.filter((item) => item.id !== prompt.id));
|
||||
setQueuedPrompt(null);
|
||||
replaceMentionInput(prompt.text, prompt.text.length);
|
||||
setSelectedSessionMentions(prompt.sessionMentions ?? []);
|
||||
setInlineError(null);
|
||||
@@ -2010,105 +2067,53 @@ export function ThreadComposer({
|
||||
clear();
|
||||
}
|
||||
resizeTextarea();
|
||||
}, [clear, onQuotedContextChange, replaceMentionInput, resizeTextarea, restoreReadyImages]);
|
||||
|
||||
const moveQueuedPrompt = useCallback((dragId: string, targetId: string) => {
|
||||
if (dragId === targetId) return;
|
||||
secondEnterPromptIdRef.current = null;
|
||||
setQueuedPrompts((items) => {
|
||||
const from = items.findIndex((item) => item.id === dragId);
|
||||
const to = items.findIndex((item) => item.id === targetId);
|
||||
if (from === -1 || to === -1) return items;
|
||||
const next = [...items];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const observeQueuedSend = useCallback((prompt: QueuedPrompt, result: void | boolean | Promise<void | boolean>) => {
|
||||
const restore = (error?: unknown) => {
|
||||
setQueuedPrompts((items) => (items.some((item) => item.id === prompt.id)
|
||||
? items
|
||||
: [prompt, ...items]).map(pauseQueuedPrompt));
|
||||
setInlineError(error instanceof Error ? error.message : "Message not sent; queued draft retained");
|
||||
};
|
||||
if (result instanceof Promise) void result.then((accepted) => { if (accepted === false) restore(); }).catch(restore);
|
||||
else if (result === false) restore();
|
||||
}, []);
|
||||
}, [clear, collectGuidancePrompt, hasComposerContent, normalizedQuotedContext, onQuotedContextChange, replaceMentionInput, resizeTextarea, restoreReadyImages, setQueuedPrompt]);
|
||||
|
||||
const sendQueuedPrompt = useCallback(
|
||||
(prompt: QueuedPrompt) => {
|
||||
(prompt: QueuedPrompt, extraOptions?: SendOptions) => {
|
||||
if (interactionDisabled) return;
|
||||
secondEnterPromptIdRef.current = null;
|
||||
const error = queuedPromptError(prompt);
|
||||
if (error) {
|
||||
setQueuedPrompt(pauseQueuedPrompt(prompt));
|
||||
setInlineError(error);
|
||||
return;
|
||||
}
|
||||
const text = prompt.text.trim();
|
||||
const queuedImages = queuedImagesToSendImages(prompt.images);
|
||||
setQueuedPrompts((items) => {
|
||||
const remaining = items.filter((item) => item.id !== prompt.id);
|
||||
return isStreaming ? remaining : remaining.map(waitForNextQueuedTurn);
|
||||
});
|
||||
if (text || queuedImages?.length) {
|
||||
const options: SendOptions | undefined = (
|
||||
prompt.quotedContext
|
||||
|| prompt.sessionMentions?.length
|
||||
|| isStreaming
|
||||
)
|
||||
? {
|
||||
...(prompt.quotedContext ? { quotedContext: prompt.quotedContext } : {}),
|
||||
...(prompt.sessionMentions?.length
|
||||
? { sessionMentions: prompt.sessionMentions }
|
||||
: {}),
|
||||
...(isStreaming ? { continueActiveTurn: true } : {}),
|
||||
}
|
||||
: undefined;
|
||||
observeQueuedSend(prompt, onSend(text, queuedImages, options));
|
||||
}
|
||||
const options: SendOptions | undefined = (
|
||||
extraOptions || prompt.quotedContext || prompt.sessionMentions?.length || isStreaming
|
||||
)
|
||||
? {
|
||||
...extraOptions,
|
||||
...(prompt.quotedContext ? { quotedContext: prompt.quotedContext } : {}),
|
||||
...(prompt.sessionMentions?.length ? { sessionMentions: prompt.sessionMentions } : {}),
|
||||
...(isStreaming ? { continueActiveTurn: true } : {}),
|
||||
}
|
||||
: undefined;
|
||||
queuedPromptStore.send(prompt, () => (
|
||||
options ? onSend(text, queuedImages, options)
|
||||
: queuedImages?.length ? onSend(text, queuedImages)
|
||||
: onSend(text)
|
||||
));
|
||||
requestAnimationFrame(() => textareaRef.current?.focus());
|
||||
},
|
||||
[isStreaming, onSend, observeQueuedSend],
|
||||
[interactionDisabled, isStreaming, onSend, queuedPromptStore, queuedPromptError, setQueuedPrompt],
|
||||
);
|
||||
|
||||
const sendNextQueuedPrompt = useCallback(() => {
|
||||
if (queuedPrompts.length === 0) return;
|
||||
const nextPrompt = queuedPrompts.find((prompt) => prompt.text.trim());
|
||||
if (!nextPrompt) {
|
||||
setQueuedPrompts([]);
|
||||
return;
|
||||
}
|
||||
setQueuedPrompts((items) => items.filter((item) => item.id !== nextPrompt.id).map(waitForNextQueuedTurn));
|
||||
const queuedImages = queuedImagesToSendImages(nextPrompt.images);
|
||||
const options: SendOptions | undefined = (
|
||||
nextPrompt.quotedContext || nextPrompt.sessionMentions?.length
|
||||
)
|
||||
? {
|
||||
...(nextPrompt.quotedContext ? { quotedContext: nextPrompt.quotedContext } : {}),
|
||||
...(nextPrompt.sessionMentions?.length
|
||||
? { sessionMentions: nextPrompt.sessionMentions }
|
||||
: {}),
|
||||
}
|
||||
: undefined;
|
||||
const result = queuedImages?.length && options ? onSend(nextPrompt.text.trim(), queuedImages, options)
|
||||
: queuedImages?.length ? onSend(nextPrompt.text.trim(), queuedImages)
|
||||
: options ? onSend(nextPrompt.text.trim(), undefined, options)
|
||||
: onSend(nextPrompt.text.trim());
|
||||
observeQueuedSend(nextPrompt, result);
|
||||
requestAnimationFrame(() => textareaRef.current?.focus());
|
||||
}, [onSend, queuedPrompts, observeQueuedSend]);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousQueueRunRef.current;
|
||||
previousQueueRunRef.current = { key: pendingQueueKey, isStreaming };
|
||||
if (!isStreaming) secondEnterPromptIdRef.current = null;
|
||||
// Switching to an idle session is not completion of the previous session's run.
|
||||
if (previous.key !== pendingQueueKey) return;
|
||||
if (isStreaming || interactionDisabled || queuedPrompts.length === 0) return;
|
||||
const first = queuedPrompts[0];
|
||||
if (first.autoPaused) return;
|
||||
const waitingTurnCompleted = queuedPromptStorageKey !== null && first.autoAfterTurnId !== undefined
|
||||
? completedTurnIds.includes(first.autoAfterTurnId)
|
||||
if (isStreaming || interactionDisabled || !queuedPrompt || queuedPrompt.autoPaused) return;
|
||||
const waitingTurnCompleted = queuedPromptStorageKey !== null && queuedPrompt.autoAfterTurnId !== undefined
|
||||
? completedTurnIds.includes(queuedPrompt.autoAfterTurnId)
|
||||
: previous.isStreaming;
|
||||
if (!waitingTurnCompleted) return;
|
||||
sendNextQueuedPrompt();
|
||||
}, [completedTurnIds, interactionDisabled, sendNextQueuedPrompt, isStreaming, pendingQueueKey, queuedPrompts, queuedPromptStorageKey]);
|
||||
sendQueuedPrompt(queuedPrompt);
|
||||
}, [completedTurnIds, interactionDisabled, sendQueuedPrompt, isStreaming, pendingQueueKey, queuedPrompt, queuedPromptStorageKey]);
|
||||
|
||||
const submit = useCallback(() => {
|
||||
if (modelNeedsSetup) {
|
||||
@@ -2166,7 +2171,6 @@ export function ThreadComposer({
|
||||
&& onStop
|
||||
) {
|
||||
handleStop();
|
||||
setQueuedPrompts([]);
|
||||
clear();
|
||||
clearComposerText();
|
||||
onQuotedContextChange?.(null);
|
||||
@@ -2175,14 +2179,29 @@ export function ThreadComposer({
|
||||
const isSlashSideChannel = isSideChannelLifecycle(slashLifecycle);
|
||||
const finalizeActiveTurn =
|
||||
slashLifecycle === "finalize_active_turn";
|
||||
if (!slashLifecycle) {
|
||||
const prompt = collectGuidancePrompt();
|
||||
const error = queuedPromptError(prompt);
|
||||
if (error) {
|
||||
setInlineError(error);
|
||||
return;
|
||||
}
|
||||
if (queuedPrompt) {
|
||||
sendQueuedPrompt(prompt, options);
|
||||
if (draftKey) draftStore?.delete(draftKey);
|
||||
clear();
|
||||
clearComposerText(!hasTouchPrimaryPointer);
|
||||
onQuotedContextChange?.(null);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const submittedDraft = draftKey ? draftStore?.get(draftKey) : undefined;
|
||||
const finishSend = () => {
|
||||
// A pending send can finish after this composer unmounts and a newer draft is started.
|
||||
if (draftKey && draftStore && draftStore.get(draftKey) !== submittedDraft) return;
|
||||
if (draftKey) draftStore?.delete(draftKey);
|
||||
if (hasTouchPrimaryPointer) textareaRef.current?.blur();
|
||||
// Sending new guidance must not discard other messages still waiting.
|
||||
if (!isStreaming || finalizeActiveTurn) setQueuedPrompts([]);
|
||||
if (!isStreaming || finalizeActiveTurn) setQueuedPrompt(null);
|
||||
// Bubble owns the data URL copy; safe to revoke every staged blob
|
||||
// preview here without affecting the rendered message.
|
||||
clear();
|
||||
@@ -2222,6 +2241,11 @@ export function ThreadComposer({
|
||||
draftStore,
|
||||
clear,
|
||||
clearComposerText,
|
||||
collectGuidancePrompt,
|
||||
queuedPrompt,
|
||||
queuedPromptError,
|
||||
sendQueuedPrompt,
|
||||
setQueuedPrompt,
|
||||
hasTouchPrimaryPointer,
|
||||
hasComposerContent,
|
||||
handleStop,
|
||||
@@ -2308,9 +2332,7 @@ export function ThreadComposer({
|
||||
if (!e.repeat) queueGuidancePrompt();
|
||||
return;
|
||||
}
|
||||
const secondEnterPrompt = queuedPrompts.find(
|
||||
(prompt) => prompt.id === secondEnterPromptIdRef.current,
|
||||
);
|
||||
const secondEnterPrompt = queuedPrompt?.id === secondEnterPromptIdRef.current ? queuedPrompt : null;
|
||||
if (
|
||||
isStreaming
|
||||
&& value.length === 0
|
||||
@@ -2398,7 +2420,7 @@ export function ThreadComposer({
|
||||
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
|
||||
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
|
||||
&& value.length === 0 && images.length === 0 && !inlineError
|
||||
&& !normalizedQuotedContext && !queuedPrompts.length && !goalState?.active
|
||||
&& !normalizedQuotedContext && !queuedPrompt && !goalState?.active
|
||||
&& !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker;
|
||||
useLayoutEffect(() => {
|
||||
if (!compactWhenIdle || compactControls) return;
|
||||
@@ -2566,29 +2588,18 @@ export function ThreadComposer({
|
||||
"goal-shell-glow ring-1 ring-sky-400/35 motion-reduce:ring-sky-400/25 dark:ring-sky-400/45",
|
||||
)}
|
||||
>
|
||||
{queuedPrompts.length > 0 ? (
|
||||
<QueuedPromptStack
|
||||
prompts={queuedPrompts}
|
||||
isHero={isHero}
|
||||
{queuedPrompt ? (
|
||||
<QueuedPromptPreview
|
||||
prompt={queuedPrompt}
|
||||
disabled={interactionDisabled}
|
||||
editDisabled={encoding || hasErrors}
|
||||
label={t("thread.composer.queued.label")}
|
||||
guideLabel={t("thread.composer.queued.guide")}
|
||||
deleteLabel={t("thread.composer.queued.delete")}
|
||||
dragLabel={t("thread.composer.queued.drag")}
|
||||
editLabel={t("thread.composer.queued.edit")}
|
||||
onGuide={sendQueuedPrompt}
|
||||
onGuide={() => sendQueuedPrompt(queuedPrompt)}
|
||||
onDelete={removeQueuedPrompt}
|
||||
onEdit={editQueuedPrompt}
|
||||
onDragStart={(id) => {
|
||||
secondEnterPromptIdRef.current = null;
|
||||
draggedQueuedPromptIdRef.current = id;
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
draggedQueuedPromptIdRef.current = null;
|
||||
}}
|
||||
onDrop={(targetId) => {
|
||||
const dragId = draggedQueuedPromptIdRef.current;
|
||||
if (dragId) moveQueuedPrompt(dragId, targetId);
|
||||
}}
|
||||
onEdit={() => editQueuedPrompt(queuedPrompt)}
|
||||
/>
|
||||
) : null}
|
||||
{images.length > 0 ? (
|
||||
@@ -2866,40 +2877,29 @@ export function ThreadComposer({
|
||||
);
|
||||
}
|
||||
|
||||
function QueuedPromptStack({
|
||||
prompts,
|
||||
isHero,
|
||||
function QueuedPromptPreview({
|
||||
prompt,
|
||||
disabled,
|
||||
editDisabled,
|
||||
label,
|
||||
guideLabel,
|
||||
deleteLabel,
|
||||
dragLabel,
|
||||
editLabel,
|
||||
onGuide,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
onDrop,
|
||||
}: {
|
||||
prompts: QueuedPrompt[];
|
||||
isHero: boolean;
|
||||
prompt: QueuedPrompt;
|
||||
disabled: boolean;
|
||||
editDisabled: boolean;
|
||||
label: string;
|
||||
guideLabel: string;
|
||||
deleteLabel: string;
|
||||
dragLabel: string;
|
||||
editLabel: string;
|
||||
onGuide: (prompt: QueuedPrompt) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onEdit: (prompt: QueuedPrompt) => void;
|
||||
onDragStart: (id: string) => void;
|
||||
onDragEnd: () => void;
|
||||
onDrop: (targetId: string) => void;
|
||||
onGuide: () => void;
|
||||
onDelete: () => void;
|
||||
onEdit: () => void;
|
||||
}) {
|
||||
const stripMaxHeight = Math.min(
|
||||
320,
|
||||
96 + prompts.length * 34 + Math.max(0, prompts.length - 1) * 4,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
@@ -2909,150 +2909,57 @@ function QueuedPromptStack({
|
||||
"border border-black/[0.05] bg-popover/90 p-1.5",
|
||||
"shadow-[0_10px_28px_rgba(15,23,42,0.07)] backdrop-blur-md",
|
||||
"dark:border-white/[0.08] dark:bg-popover/90 dark:shadow-[0_14px_34px_rgba(0,0,0,0.30)]",
|
||||
isHero ? "max-w-none" : "max-w-none",
|
||||
)}
|
||||
style={{ "--composer-strip-max-height": `${stripMaxHeight}px` } as CSSProperties}
|
||||
style={{ "--composer-strip-max-height": "224px" } as CSSProperties}
|
||||
aria-label={label}
|
||||
>
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5 px-2 pb-1">
|
||||
<span className="text-[11.5px] font-semibold text-foreground/75">{label}</span>
|
||||
</div>
|
||||
<div className="flex max-h-[216px] flex-col gap-1 overflow-y-auto">
|
||||
{prompts.map((prompt) => (
|
||||
<QueuedPromptRow
|
||||
key={prompt.id}
|
||||
prompt={prompt}
|
||||
isHero={isHero}
|
||||
guideLabel={guideLabel}
|
||||
deleteLabel={deleteLabel}
|
||||
dragLabel={dragLabel}
|
||||
editLabel={editLabel}
|
||||
onGuide={onGuide}
|
||||
onDelete={onDelete}
|
||||
onEdit={onEdit}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnd={onDragEnd}
|
||||
onDrop={onDrop}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QueuedPromptRow({
|
||||
prompt,
|
||||
isHero,
|
||||
guideLabel,
|
||||
deleteLabel,
|
||||
dragLabel,
|
||||
editLabel,
|
||||
onGuide,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
onDrop,
|
||||
}: {
|
||||
prompt: QueuedPrompt;
|
||||
isHero: boolean;
|
||||
guideLabel: string;
|
||||
deleteLabel: string;
|
||||
dragLabel: string;
|
||||
editLabel: string;
|
||||
onGuide: (prompt: QueuedPrompt) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onEdit: (prompt: QueuedPrompt) => void;
|
||||
onDragStart: (id: string) => void;
|
||||
onDragEnd: () => void;
|
||||
onDrop: (targetId: string) => void;
|
||||
}) {
|
||||
const displayLabel = queuedPromptLabel(prompt);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-queued-prompt-row="true"
|
||||
onDragEnter={(event) => {
|
||||
event.preventDefault();
|
||||
onDrop(prompt.id);
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "move";
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
onDrop(prompt.id);
|
||||
}}
|
||||
onDragEnd={onDragEnd}
|
||||
className={cn(
|
||||
"queued-prompt-row group/queued flex min-h-8 items-center gap-1.5 rounded-control px-2 py-0.5",
|
||||
"text-[13px] transition-colors hover:bg-muted/55 dark:hover:bg-white/[0.055]",
|
||||
isHero && "text-[13.5px]",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
draggable
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={dragLabel}
|
||||
onDragStart={(event) => {
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
event.dataTransfer.setData("text/plain", prompt.id);
|
||||
suppressNativeDragPreview(event.dataTransfer);
|
||||
onDragStart(prompt.id);
|
||||
}}
|
||||
onDragEnd={onDragEnd}
|
||||
className={cn(
|
||||
"inline-flex h-7 w-7 shrink-0 cursor-grab items-center justify-center rounded-lg",
|
||||
"text-muted-foreground/45 transition-colors hover:text-muted-foreground",
|
||||
"active:cursor-grabbing",
|
||||
)}
|
||||
>
|
||||
<GripVertical className="pointer-events-none h-3.5 w-3.5" aria-hidden />
|
||||
</span>
|
||||
<div className="flex min-h-7 min-w-0 flex-1 items-center">
|
||||
<p
|
||||
title={displayLabel}
|
||||
className={cn(
|
||||
"line-clamp-3 whitespace-pre-wrap break-words font-medium leading-[1.28] text-foreground/88",
|
||||
isHero && "text-[13.5px]",
|
||||
)}
|
||||
<div className="flex min-w-0 items-center gap-1 px-1 pb-1">
|
||||
<span className="min-w-0 flex-1 truncate text-[11.5px] font-semibold text-foreground/75">{label}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={disabled}
|
||||
className="h-7 shrink-0 rounded-full px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:hover:bg-white/[0.07]"
|
||||
onClick={onGuide}
|
||||
>
|
||||
{displayLabel}
|
||||
<CornerDownRight className="mr-1 h-3 w-3" aria-hidden />
|
||||
{guideLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled || editDisabled}
|
||||
aria-label={editLabel}
|
||||
title={editLabel}
|
||||
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-foreground"
|
||||
onClick={onEdit}
|
||||
>
|
||||
<EditIcon className="h-3.5 w-3.5" aria-hidden />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={disabled}
|
||||
aria-label={deleteLabel}
|
||||
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-destructive"
|
||||
onClick={onDelete}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-40 overflow-y-auto px-2 pb-1 text-[13px]">
|
||||
<p className="whitespace-pre-wrap break-words font-medium leading-relaxed text-foreground/88">
|
||||
{queuedPromptLabel(prompt)}
|
||||
</p>
|
||||
{prompt.text && prompt.images?.length ? (
|
||||
<p className="mt-1 break-words text-xs text-muted-foreground">
|
||||
{prompt.images.map((image) => image.name).filter(Boolean).join(", ")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 shrink-0 rounded-full px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-muted/70 hover:text-foreground dark:hover:bg-white/[0.07]"
|
||||
onClick={() => onGuide(prompt)}
|
||||
>
|
||||
<CornerDownRight className="mr-1 h-3 w-3" aria-hidden />
|
||||
{guideLabel}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={editLabel}
|
||||
title={editLabel}
|
||||
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onEdit(prompt)}
|
||||
>
|
||||
<EditIcon className="h-3.5 w-3.5" aria-hidden />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
aria-label={deleteLabel}
|
||||
className="h-7 w-7 shrink-0 rounded-full text-muted-foreground hover:text-destructive"
|
||||
onClick={() => onDelete(prompt.id)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ export type AttachmentError =
|
||||
| "io"; // file read failed at the browser layer
|
||||
|
||||
export const MAX_ATTACHMENTS_PER_MESSAGE = 4;
|
||||
const MAX_ATTACHMENT_BYTES = 6 * 1024 * 1024;
|
||||
const MAX_TOTAL_ATTACHMENT_BYTES = 24 * 1024 * 1024;
|
||||
export const MAX_ATTACHMENT_BYTES = 6 * 1024 * 1024;
|
||||
export const MAX_TOTAL_ATTACHMENT_BYTES = 24 * 1024 * 1024;
|
||||
|
||||
/** MIME whitelist — mirrors the server's and the ``<input accept>`` attr. */
|
||||
const ACCEPTED_IMAGE_MIMES: ReadonlySet<string> = new Set([
|
||||
@@ -207,8 +207,9 @@ export interface UseAttachedImagesApi {
|
||||
/** Enqueue new files. Returns the list of rejected files so the caller can
|
||||
* surface inline errors. Files rejected client-side (wrong MIME, limit) are
|
||||
* *not* added to ``images`` — only recoverable read/encoding failures show
|
||||
* up as error chips. */
|
||||
enqueue: (files: Iterable<File>) => {
|
||||
* up as error chips. Restoring an existing draft preserves overflow so users
|
||||
* can remove files themselves; send validation still enforces ingress limits. */
|
||||
enqueue: (files: Iterable<File>, options?: { restoringDraft: boolean }) => {
|
||||
rejected: Array<{ file: File; reason: AttachmentError }>;
|
||||
};
|
||||
remove: (id: string) => { nextFocusId: string | null };
|
||||
@@ -269,7 +270,7 @@ export function useAttachedImages({
|
||||
}, []);
|
||||
|
||||
const enqueue = useCallback(
|
||||
(files: Iterable<File>) => {
|
||||
(files: Iterable<File>, { restoringDraft = false } = {}) => {
|
||||
const rejected: Array<{ file: File; reason: AttachmentError }> = [];
|
||||
const toAdd: AttachedAttachment[] = [];
|
||||
let slot = maxAttachments - imagesRef.current.length;
|
||||
@@ -291,16 +292,16 @@ export function useAttachedImages({
|
||||
rejected.push({ file, reason: "empty_file" });
|
||||
continue;
|
||||
}
|
||||
if (kind === "file" && file.size > maxFileBytes) {
|
||||
if (!restoringDraft && kind === "file" && file.size > maxFileBytes) {
|
||||
rejected.push({ file, reason: "too_large" });
|
||||
continue;
|
||||
}
|
||||
if (slot <= 0) {
|
||||
if (!restoringDraft && slot <= 0) {
|
||||
rejected.push({ file, reason: "too_many_attachments" });
|
||||
continue;
|
||||
}
|
||||
const nextDecodedBytes = kind === "image" ? Math.min(file.size, maxFileBytes) : file.size;
|
||||
if (projectedDecodedBytes + nextDecodedBytes > maxTotalBytes) {
|
||||
if (!restoringDraft && projectedDecodedBytes + nextDecodedBytes > maxTotalBytes) {
|
||||
rejected.push({ file, reason: "total_too_large" });
|
||||
continue;
|
||||
}
|
||||
@@ -400,7 +401,6 @@ export function useAttachedImages({
|
||||
const restoreReadyImages = useCallback((restored: RestoredReadyAttachment[]) => {
|
||||
const toRestore = restored
|
||||
.filter((img) => acceptedAttachmentKind(dataUrlToFile(img.dataUrl, img.name)))
|
||||
.slice(0, maxAttachments)
|
||||
.map((img): AttachedAttachment => {
|
||||
const file = dataUrlToFile(img.dataUrl, img.name);
|
||||
const kind = img.kind ?? kindFromDataUrl(img.dataUrl);
|
||||
@@ -427,7 +427,7 @@ export function useAttachedImages({
|
||||
imagesRef.current = toRestore;
|
||||
return toRestore;
|
||||
});
|
||||
}, [maxAttachments]);
|
||||
}, []);
|
||||
|
||||
// Final safety net: revoke any outstanding blob URLs on unmount. Safe
|
||||
// under StrictMode double-invoke because revoked blob URLs are only
|
||||
|
||||
@@ -1996,7 +1996,7 @@
|
||||
"guide": "Send now",
|
||||
"delete": "Delete message",
|
||||
"edit": "Edit message",
|
||||
"drag": "Drag to reorder"
|
||||
"tooManyMentions": "A message can mention up to {{max}} chats"
|
||||
},
|
||||
"attachImage": "Attach files",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1797,7 +1797,7 @@
|
||||
"guide": "Enviar ahora",
|
||||
"delete": "Eliminar mensaje",
|
||||
"edit": "Editar mensaje",
|
||||
"drag": "Arrastrar para reordenar"
|
||||
"tooManyMentions": "Un mensaje puede mencionar hasta {{max}} conversaciones"
|
||||
},
|
||||
"attachImage": "Adjuntar archivos",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "Envoyer",
|
||||
"delete": "Supprimer le message",
|
||||
"edit": "Modifier le message",
|
||||
"drag": "Faire glisser pour réordonner"
|
||||
"tooManyMentions": "Un message peut mentionner jusqu’à {{max}} conversations"
|
||||
},
|
||||
"attachImage": "Joindre des fichiers",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "Kirim sekarang",
|
||||
"delete": "Hapus pesan",
|
||||
"edit": "Ubah pesan",
|
||||
"drag": "Seret untuk mengurutkan"
|
||||
"tooManyMentions": "Satu pesan dapat menyebut hingga {{max}} percakapan"
|
||||
},
|
||||
"attachImage": "Lampirkan file",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "今すぐ送信",
|
||||
"delete": "メッセージを削除",
|
||||
"edit": "メッセージを編集",
|
||||
"drag": "ドラッグして並べ替え"
|
||||
"tooManyMentions": "1つのメッセージでメンションできる会話は{{max}}件までです"
|
||||
},
|
||||
"attachImage": "ファイルを添付",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "지금 보내기",
|
||||
"delete": "메시지 삭제",
|
||||
"edit": "메시지 편집",
|
||||
"drag": "드래그하여 순서 변경"
|
||||
"tooManyMentions": "메시지 하나에서 최대 {{max}}개의 대화를 멘션할 수 있습니다"
|
||||
},
|
||||
"attachImage": "파일 첨부",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1810,7 +1810,7 @@
|
||||
"guide": "Enviar agora",
|
||||
"delete": "Excluir mensagem",
|
||||
"edit": "Editar mensagem",
|
||||
"drag": "Arraste para reordenar"
|
||||
"tooManyMentions": "Uma mensagem pode mencionar até {{max}} conversas"
|
||||
},
|
||||
"attachImage": "Anexar imagem",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "Gửi ngay",
|
||||
"delete": "Xóa tin nhắn",
|
||||
"edit": "Sửa tin nhắn",
|
||||
"drag": "Kéo để sắp xếp"
|
||||
"tooManyMentions": "Mỗi tin nhắn có thể nhắc đến tối đa {{max}} cuộc trò chuyện"
|
||||
},
|
||||
"attachImage": "Đính kèm tệp",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1995,7 +1995,7 @@
|
||||
"guide": "立即发送",
|
||||
"delete": "删除消息",
|
||||
"edit": "编辑消息",
|
||||
"drag": "拖动排序"
|
||||
"tooManyMentions": "每条消息最多提及 {{max}} 个会话"
|
||||
},
|
||||
"attachImage": "添加文件",
|
||||
"imageMode": {
|
||||
|
||||
@@ -1796,7 +1796,7 @@
|
||||
"guide": "立即傳送",
|
||||
"delete": "刪除訊息",
|
||||
"edit": "編輯訊息",
|
||||
"drag": "拖曳排序"
|
||||
"tooManyMentions": "每則訊息最多提及 {{max}} 個對話"
|
||||
},
|
||||
"attachImage": "附加檔案",
|
||||
"imageMode": {
|
||||
|
||||
@@ -33,7 +33,7 @@ function readDraft(raw: string): ComposerDraft | undefined {
|
||||
...(typeof item.id === "string" && /^handle_[a-f0-9]{32}$/i.test(item.id)
|
||||
? { id: item.id } : {}),
|
||||
}];
|
||||
}).slice(0, 8);
|
||||
});
|
||||
return { text: value.text, quotedContext: value.quotedContext, sessionMentions, files: [] };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
import type { SessionMention, SlashCommand, WebUIIngressLimits } from "@/lib/types";
|
||||
import { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
|
||||
|
||||
vi.mock("@/lib/imageEncode", () => ({
|
||||
encodeImage: vi.fn(async () => ({
|
||||
ok: true,
|
||||
dataUrl: "data:image/png;base64,aW1hZ2U=",
|
||||
bytes: 5,
|
||||
normalized: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
const STORAGE_KEY = "nanobot.webui.composerQueuedGuidance.v1:chat-a";
|
||||
const PNG = { dataUrl: "data:image/png;base64,aW1hZ2U=", kind: "image", name: "first.png" };
|
||||
const DOCUMENT = { dataUrl: "data:text/plain;base64,aGVsbG8=", kind: "file", name: "second.txt" };
|
||||
|
||||
function limits(attachments: Partial<WebUIIngressLimits["attachments"]> = {}, maxTextBytes = 65536): WebUIIngressLimits {
|
||||
return {
|
||||
transport: { max_frame_bytes: 1024 * 1024, envelope_reserve_bytes: 1024 },
|
||||
message: { max_text_bytes: maxTextBytes },
|
||||
attachments: { max_count: 4, max_file_bytes: 6 * 1024 * 1024, max_total_bytes: 24 * 1024 * 1024, ...attachments },
|
||||
};
|
||||
}
|
||||
|
||||
function enter(text: string): void {
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: text } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
}
|
||||
|
||||
function mention(name: string): SessionMention {
|
||||
return { name, session_key: `websocket:${name}`, title: name };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("merged waiting messages", () => {
|
||||
it("restores legacy entries as one message with all attachments, quotes and stable session targets", () => {
|
||||
const alpha = mention("alpha");
|
||||
const beta = mention("beta");
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "1 @alpha", images: [PNG], quotedContext: "first quote", sessionMentions: [alpha] },
|
||||
{ id: "second", text: "2 @alpha @beta", images: [DOCUMENT], quotedContext: "second quote", sessionMentions: [alpha, beta] },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
|
||||
const pending = screen.getByRole("group", { name: "Waiting to send" });
|
||||
expect(within(pending).getAllByRole("button", { name: "Send now" })).toHaveLength(1);
|
||||
expect(pending).toHaveTextContent("first.png, second.txt");
|
||||
fireEvent.click(within(pending).getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(onSend).toHaveBeenCalledWith("1 @alpha\n2 @alpha @beta", [
|
||||
expect.objectContaining({ media: { data_url: PNG.dataUrl, name: PNG.name }, preview: expect.objectContaining({ kind: "image" }) }),
|
||||
expect.objectContaining({ media: { data_url: DOCUMENT.dataUrl, name: DOCUMENT.name }, preview: expect.objectContaining({ kind: "file" }) }),
|
||||
], {
|
||||
continueActiveTurn: true,
|
||||
quotedContext: "first quote\n\nsecond quote",
|
||||
sessionMentions: [alpha, beta],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves merged text longer than the former per-entry storage truncation across remounts", () => {
|
||||
const onSend = vi.fn();
|
||||
const first = render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
|
||||
const texts = ["a".repeat(3000), "b".repeat(3000)];
|
||||
texts.forEach(enter);
|
||||
first.unmount();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledWith(texts.join("\n"), undefined, { continueActiveTurn: true });
|
||||
});
|
||||
|
||||
it("leaves an over-limit UTF-8 append in the input without changing the pending content", () => {
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} isStreaming ingressLimits={limits({}, 6)} />);
|
||||
enter("一");
|
||||
enter("二");
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("二");
|
||||
expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("一");
|
||||
expect(screen.getByText(/Message text is too large/)).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("counts the combined formatted quotes and separators against the text limit", () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "1", quotedContext: "first quote" },
|
||||
]));
|
||||
const bytes = new TextEncoder().encode(formatQuotedUserMessage("1\n2", "first quote\n\nsecond quote")).length;
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming quotedContext="second quote" ingressLimits={limits({}, bytes - 1)} />);
|
||||
enter("2");
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("2");
|
||||
expect(JSON.parse(localStorage.getItem(STORAGE_KEY)!)[0]).toMatchObject({ text: "1", quotedContext: "first quote" });
|
||||
expect(screen.getByText(/Message text is too large/)).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ policy: { max_count: 1 }, error: "Max 1 attachments per message" },
|
||||
{ policy: { max_total_bytes: 9 }, error: "Attachments are too large together" },
|
||||
])("retains both pending and current attachments when merging exceeds $policy", async ({ policy, error }) => {
|
||||
Object.defineProperty(URL, "createObjectURL", { configurable: true, value: vi.fn(() => "blob:queued-test") });
|
||||
Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: vi.fn() });
|
||||
const onSend = vi.fn();
|
||||
const view = render(<ThreadComposer onSend={onSend} isStreaming ingressLimits={limits(policy)} />);
|
||||
const picker = view.container.querySelector<HTMLInputElement>('input[type="file"]')!;
|
||||
for (const [index, name] of ["first.png", "second.png"].entries()) {
|
||||
fireEvent.change(picker, { target: { files: [new File(["image"], name, { type: "image/png" })] } });
|
||||
await waitFor(() => expect(screen.queryByLabelText("Encoding…")).not.toBeInTheDocument());
|
||||
enter(String(index + 1));
|
||||
}
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("2");
|
||||
expect(screen.getByTestId("composer-chip")).toHaveTextContent("second.png");
|
||||
expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("first.png");
|
||||
expect(screen.getByText(error, { exact: false })).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lets users edit an oversized legacy aggregate without dropping excess attachments", () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "1", images: [PNG] },
|
||||
{ id: "second", text: "2", images: [DOCUMENT] },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" ingressLimits={limits({ max_count: 1 })} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
expect(screen.getByText("Max 1 attachments per message")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("1\n2");
|
||||
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
|
||||
fireEvent.click(within(screen.getAllByTestId("composer-chip")[0]).getByRole("button", { name: "Remove attachment" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onSend).toHaveBeenCalledWith("1\n2", [expect.objectContaining({ media: expect.objectContaining({ name: "second.txt" }) })], undefined);
|
||||
});
|
||||
|
||||
it("keeps all edited legacy attachments through a topic round trip", async () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "1", images: [PNG] },
|
||||
{ id: "second", text: "2", images: [DOCUMENT] },
|
||||
]));
|
||||
const draftStore = new ComposerDraftStore();
|
||||
const props = { onSend: vi.fn(), pendingQueueKey: "chat-a", draftKey: "chat-a", draftStore, ingressLimits: limits({ max_count: 1 }) };
|
||||
const view = render(<ThreadComposer {...props} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
view.unmount();
|
||||
render(<ThreadComposer {...props} />);
|
||||
await waitFor(() => expect(screen.queryByLabelText("Encoding…")).not.toBeInTheDocument());
|
||||
expect(screen.getAllByTestId("composer-chip")).toHaveLength(2);
|
||||
expect(draftStore.get("chat-a")?.files.map((file) => file.name)).toEqual(["first.png", "second.txt"]);
|
||||
});
|
||||
|
||||
it("retains a merged rejected send after leaving the topic during upload", async () => {
|
||||
let reject!: (reason: Error) => void;
|
||||
const onSend = vi.fn(() => new Promise<boolean>((_, no) => { reject = no; }));
|
||||
const props = { onSend, pendingQueueKey: "chat-a", isStreaming: true };
|
||||
const view = render(<ThreadComposer {...props} />);
|
||||
enter("1");
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "2" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
view.unmount();
|
||||
await act(async () => { reject(new Error("Upload failed")); });
|
||||
render(<ThreadComposer {...props} />);
|
||||
expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("1 2");
|
||||
expect(JSON.parse(localStorage.getItem(STORAGE_KEY)!)[0]).toMatchObject({ text: "1\n2", autoPaused: true });
|
||||
});
|
||||
|
||||
it("shares pending acceptance across remounts and clears only the accepted message", async () => {
|
||||
let accept!: (accepted: boolean) => void;
|
||||
const onSend = vi.fn(() => new Promise<boolean>((yes) => { accept = yes; }));
|
||||
const props = { onSend, pendingQueueKey: "chat-a", isStreaming: true };
|
||||
const view = render(<ThreadComposer {...props} />);
|
||||
enter("1"); enter("2");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
view.unmount();
|
||||
render(<ThreadComposer {...props} />);
|
||||
expect(screen.getByRole("button", { name: "Send now" })).toBeDisabled();
|
||||
await act(async () => { accept(true); });
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves the paused pending message when /stop is submitted with the send button", () => {
|
||||
const onStop = vi.fn();
|
||||
const onSend = vi.fn();
|
||||
const slashCommands: SlashCommand[] = [{ command: "/stop", title: "Stop", description: "Stop", icon: "square", lifecycle: "stop_active_turn", acceptsArgs: false }];
|
||||
const props = { onSend, onStop, pendingQueueKey: "chat-a", isStreaming: true, activeTurnId: "turn-a", slashCommands };
|
||||
const view = render(<ThreadComposer {...props} />);
|
||||
enter("1"); enter("2");
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "/stop" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(onStop).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("1 2");
|
||||
view.rerender(<ThreadComposer {...props} isStreaming={false} completedTurnIds={["turn-a"]} />);
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a new quote-only selection when editing the complete pending message", () => {
|
||||
const onQuotedContextChange = vi.fn();
|
||||
const props = { onSend: vi.fn(), isStreaming: true, onQuotedContextChange };
|
||||
const view = render(<ThreadComposer {...props} />);
|
||||
enter("1");
|
||||
view.rerender(<ThreadComposer {...props} quotedContext="new selection" />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("1");
|
||||
expect(onQuotedContextChange).toHaveBeenLastCalledWith("new selection");
|
||||
});
|
||||
|
||||
it("auto-sends attachment-only guidance after completion", async () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "", images: [PNG], autoAfterTurnId: "turn-a" },
|
||||
{ id: "second", text: "", images: [DOCUMENT], autoAfterTurnId: "turn-a" },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />);
|
||||
await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
|
||||
expect(onSend).toHaveBeenCalledWith("", [
|
||||
expect.objectContaining({ media: expect.objectContaining({ name: "first.png" }) }),
|
||||
expect.objectContaining({ media: expect.objectContaining({ name: "second.txt" }) }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains a ninth session target in the input instead of silently dropping its reference", () => {
|
||||
const mentions = Array.from({ length: 8 }, (_, index) => mention(`target${index}`));
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: mentions.map((item) => `@${item.name}`).join(" "), sessionMentions: mentions },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming sessions={[{
|
||||
key: "websocket:target8", channel: "websocket", chatId: "target8", title: "Ninth chat", preview: "",
|
||||
createdAt: null, updatedAt: null, handle: { id: `handle_${"a".repeat(32)}`, name: "target8" },
|
||||
}]} />);
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "@target8" } });
|
||||
fireEvent.mouseDown(screen.getByRole("option", { name: /target8/i }));
|
||||
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
|
||||
expect(screen.getByLabelText("Message input")).toHaveValue("@target8 ");
|
||||
expect(screen.getByText("A message can mention up to 8 chats")).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps all legacy session targets after editing and refreshing an over-limit draft", () => {
|
||||
const targets = Array.from({ length: 9 }, (_, index) => mention(`target${index}`));
|
||||
const text = targets.map((item) => `@${item.name}`).join(" ");
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: text.slice(0, text.lastIndexOf(" ")), sessionMentions: targets.slice(0, 8) },
|
||||
{ id: "second", text: "@target8", sessionMentions: targets.slice(8) },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
const props = { onSend, pendingQueueKey: "chat-a", draftKey: "chat-a", persistDraft: true };
|
||||
const view = render(<ThreadComposer {...props} draftStore={new ComposerDraftStore()} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
view.unmount();
|
||||
const refreshed = new ComposerDraftStore();
|
||||
expect(refreshed.get("chat-a", true)?.sessionMentions).toEqual(targets);
|
||||
render(<ThreadComposer {...props} draftStore={refreshed} />);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
expect(screen.getByText("A message can mention up to 8 chats")).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains the whole message after a rejected immediate send", () => {
|
||||
const onSend = vi.fn(() => false);
|
||||
const view = render(<ThreadComposer onSend={onSend} isStreaming activeTurnId="turn-a" pendingQueueKey="chat-a" />);
|
||||
enter("1"); enter("2");
|
||||
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByRole("group", { name: "Waiting to send" })).toHaveTextContent("1 2");
|
||||
view.rerender(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />);
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not automatically re-arm stopped content when another input is appended", () => {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify([
|
||||
{ id: "first", text: "stopped", autoPaused: true },
|
||||
]));
|
||||
const onSend = vi.fn();
|
||||
const view = render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming activeTurnId="turn-a" />);
|
||||
enter("new input");
|
||||
view.rerender(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />);
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledWith("stopped\nnew input");
|
||||
});
|
||||
});
|
||||
@@ -3163,7 +3163,7 @@ describe("ThreadComposer", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves waiting guidance when the send button submits a newer draft", () => {
|
||||
it("includes waiting guidance when the send button submits a newer draft", () => {
|
||||
const onSend = vi.fn();
|
||||
render(<ThreadComposer onSend={onSend} onStop={vi.fn()} isStreaming />);
|
||||
const input = screen.getByLabelText("Message input");
|
||||
@@ -3172,10 +3172,9 @@ describe("ThreadComposer", () => {
|
||||
fireEvent.change(input, { target: { value: "send this now" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send message" }));
|
||||
|
||||
expect(onSend).toHaveBeenCalledWith("send this now", undefined, { continueActiveTurn: true });
|
||||
expect(screen.getByText("waiting guidance")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenLastCalledWith("waiting guidance", undefined, { continueActiveTurn: true });
|
||||
expect(onSend).toHaveBeenCalledWith("waiting guidance\nsend this now", undefined, { continueActiveTurn: true });
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not mark side-channel commands as guidance during an active turn", () => {
|
||||
@@ -3402,7 +3401,7 @@ describe("ThreadComposer", () => {
|
||||
expect(screen.getByText("leave this queued")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("guides the newly queued prompt when older guidance is still waiting", () => {
|
||||
it("merges consecutive queued inputs and interjects the whole message on a second Enter", () => {
|
||||
const onSend = vi.fn();
|
||||
render(
|
||||
<ThreadComposer
|
||||
@@ -3421,16 +3420,15 @@ describe("ThreadComposer", () => {
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
expect(onSend).toHaveBeenCalledWith(
|
||||
"guide this one now",
|
||||
"older guidance\nguide this one now",
|
||||
undefined,
|
||||
{ continueActiveTurn: true },
|
||||
);
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText("older guidance")).toBeInTheDocument();
|
||||
expect(screen.queryByText("guide this one now")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps queued guidance attached to the composer and sends it one item at a time", async () => {
|
||||
it("shows one pending message and sends all consecutive inputs once after completion", async () => {
|
||||
const onSend = vi.fn();
|
||||
const { rerender } = render(
|
||||
<ThreadComposer
|
||||
@@ -3451,10 +3449,9 @@ describe("ThreadComposer", () => {
|
||||
expect(queue).toHaveClass("composer-status-strip");
|
||||
expect(queue).toHaveClass("mx-3");
|
||||
expect(queue.parentElement?.className).toContain("group/composer");
|
||||
expect(within(queue).getByText("first follow-up")).toBeInTheDocument();
|
||||
expect(within(queue).getByText("second follow-up")).toBeInTheDocument();
|
||||
expect(within(queue).getAllByRole("button", { name: "Edit message" })).toHaveLength(2);
|
||||
expect(within(queue).getAllByRole("button", { name: "Send now" })).toHaveLength(2);
|
||||
expect(within(queue).getByText("first follow-up second follow-up")).toHaveTextContent("first follow-up second follow-up");
|
||||
expect(within(queue).getAllByRole("button", { name: "Edit message" })).toHaveLength(1);
|
||||
expect(within(queue).getAllByRole("button", { name: "Send now" })).toHaveLength(1);
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
@@ -3466,11 +3463,10 @@ describe("ThreadComposer", () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenCalledWith("first follow-up");
|
||||
expect(onSend).toHaveBeenCalledWith("first follow-up\nsecond follow-up");
|
||||
});
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByText("first follow-up")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("second follow-up")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
@@ -3489,10 +3485,7 @@ describe("ThreadComposer", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenLastCalledWith("second follow-up");
|
||||
});
|
||||
expect(onSend).toHaveBeenCalledTimes(2);
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -3544,65 +3537,23 @@ describe("ThreadComposer", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("requeues edited guidance at the end of the pending list", async () => {
|
||||
it("edits the complete pending message without overwriting a newer draft", () => {
|
||||
const onSend = vi.fn();
|
||||
const { rerender } = render(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
const { rerender } = render(<ThreadComposer onSend={onSend} isStreaming />);
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "first follow-up" } });
|
||||
for (const text of ["first follow-up", "second follow-up"]) {
|
||||
fireEvent.change(input, { target: { value: text } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
}
|
||||
fireEvent.change(input, { target: { value: "third follow-up" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit message" }));
|
||||
expect(input).toHaveValue("first follow-up\nsecond follow-up\nthird follow-up");
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
fireEvent.change(input, { target: { value: "edited complete message" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
fireEvent.change(input, { target: { value: "second follow-up" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
fireEvent.click(screen.getAllByRole("button", { name: "Edit message" })[0]);
|
||||
await waitFor(() => {
|
||||
expect(input).toHaveValue("first follow-up");
|
||||
});
|
||||
fireEvent.change(input, { target: { value: "first follow-up edited" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming={false}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenCalledWith("second follow-up");
|
||||
});
|
||||
rerender(<ThreadComposer onSend={onSend} />);
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming={false}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenLastCalledWith("first follow-up edited");
|
||||
});
|
||||
expect(onSend).toHaveBeenCalledTimes(2);
|
||||
expect(onSend).toHaveBeenCalledWith("edited complete message");
|
||||
});
|
||||
|
||||
it("queues image guidance while running and restores it for editing", async () => {
|
||||
@@ -3660,98 +3611,19 @@ describe("ThreadComposer", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reorders queued guidance while dragging over another row", async () => {
|
||||
it("deletes the complete pending message across remounts", () => {
|
||||
const onSend = vi.fn();
|
||||
const { rerender } = render(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
const first = render(<ThreadComposer onSend={onSend} isStreaming pendingQueueKey="chat-a" />);
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "first follow-up" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
fireEvent.change(input, { target: { value: "second follow-up" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
const handles = screen.getAllByLabelText("Drag to reorder");
|
||||
const secondRow = screen
|
||||
.getByText("second follow-up")
|
||||
.closest("[data-queued-prompt-row='true']");
|
||||
expect(secondRow).toBeTruthy();
|
||||
|
||||
const dataTransfer = {
|
||||
effectAllowed: "",
|
||||
dropEffect: "",
|
||||
setData: vi.fn(),
|
||||
getData: vi.fn(),
|
||||
};
|
||||
fireEvent.dragStart(handles[0], { dataTransfer });
|
||||
fireEvent.dragEnter(secondRow!, { dataTransfer });
|
||||
fireEvent.dragEnd(handles[0], { dataTransfer });
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming={false}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenCalledWith("second follow-up");
|
||||
});
|
||||
});
|
||||
|
||||
it("moves later queued guidance before an earlier item while dragging", async () => {
|
||||
const onSend = vi.fn();
|
||||
const { rerender } = render(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
const input = screen.getByLabelText("Message input");
|
||||
fireEvent.change(input, { target: { value: "first follow-up" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
fireEvent.change(input, { target: { value: "second follow-up" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
const handles = screen.getAllByLabelText("Drag to reorder");
|
||||
const firstRow = screen
|
||||
.getByText("first follow-up")
|
||||
.closest("[data-queued-prompt-row='true']");
|
||||
expect(firstRow).toBeTruthy();
|
||||
|
||||
const dataTransfer = {
|
||||
effectAllowed: "",
|
||||
dropEffect: "",
|
||||
setData: vi.fn(),
|
||||
getData: vi.fn(),
|
||||
};
|
||||
fireEvent.dragStart(handles[1], { dataTransfer });
|
||||
fireEvent.dragEnter(firstRow!, { dataTransfer });
|
||||
fireEvent.dragEnd(handles[1], { dataTransfer });
|
||||
|
||||
rerender(
|
||||
<ThreadComposer
|
||||
onSend={onSend}
|
||||
onStop={vi.fn()}
|
||||
isStreaming={false}
|
||||
placeholder="Type your message..."
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSend).toHaveBeenCalledWith("second follow-up");
|
||||
});
|
||||
for (const text of ["1", "2"]) {
|
||||
fireEvent.change(input, { target: { value: text } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
}
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete message" }));
|
||||
first.unmount();
|
||||
render(<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" />);
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps queued guidance in its session when switching from running to idle", () => {
|
||||
@@ -3887,13 +3759,13 @@ describe("ThreadComposer", () => {
|
||||
<ThreadComposer onSend={otherSend} pendingQueueKey="chat-b" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
expect(otherSend).not.toHaveBeenCalled();
|
||||
expect(screen.queryByText("first follow-up")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
other.unmount();
|
||||
|
||||
const returned = render(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={[]} />,
|
||||
);
|
||||
expect(screen.getByText("first follow-up")).toBeInTheDocument();
|
||||
expect(screen.getByText("first follow-up second follow-up")).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
returned.rerender(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-other"]} />,
|
||||
@@ -3902,15 +3774,16 @@ describe("ThreadComposer", () => {
|
||||
returned.rerender(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
await waitFor(() => expect(onSend).toHaveBeenCalledWith("first follow-up"));
|
||||
await waitFor(() => expect(onSend).toHaveBeenCalledWith("first follow-up\nsecond follow-up"));
|
||||
for (let update = 0; update < 3; update += 1) {
|
||||
returned.rerender(
|
||||
<ThreadComposer onSend={(...args) => onSend(...args)} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
}
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText("second follow-up")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Send now" })).toBeDisabled();
|
||||
await act(async () => { acceptDelivery(true); await delivery; });
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
returned.rerender(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" isStreaming activeTurnId="turn-next" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
@@ -3922,8 +3795,7 @@ describe("ThreadComposer", () => {
|
||||
render(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a", "turn-next"]} />,
|
||||
);
|
||||
await waitFor(() => expect(onSend).toHaveBeenLastCalledWith("second follow-up"));
|
||||
expect(onSend).toHaveBeenCalledTimes(2);
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -3958,7 +3830,7 @@ describe("ThreadComposer", () => {
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(onSend).toHaveBeenCalledWith("keep for later", undefined, undefined);
|
||||
expect(onSend).toHaveBeenCalledWith("keep for later");
|
||||
});
|
||||
|
||||
it("retains a rejected queued attachment for manual retry after remounting", async () => {
|
||||
@@ -3973,25 +3845,28 @@ describe("ThreadComposer", () => {
|
||||
target: { files: [new File(["image"], "queued.png", { type: "image/png" })] },
|
||||
});
|
||||
await screen.findByText("queued.png");
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: "queued attachment" } });
|
||||
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
|
||||
for (const text of ["queued attachment", "more guidance"]) {
|
||||
fireEvent.change(screen.getByLabelText("Message input"), { target: { value: text } });
|
||||
fireEvent.keyDown(screen.getByLabelText("Message input"), { key: "Enter" });
|
||||
}
|
||||
first.unmount();
|
||||
const returned = render(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
|
||||
await act(async () => { rejectDelivery(new Error("Attachment upload interrupted")); });
|
||||
expect(screen.getByText("queued attachment")).toBeInTheDocument();
|
||||
expect(screen.getByText("queued attachment more guidance")).toBeInTheDocument();
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
returned.unmount();
|
||||
render(
|
||||
<ThreadComposer onSend={onSend} pendingQueueKey="chat-a" completedTurnIds={["turn-a"]} />,
|
||||
);
|
||||
expect(screen.getByText("queued attachment")).toBeInTheDocument();
|
||||
expect(screen.getByText("queued attachment more guidance")).toBeInTheDocument();
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
onSend.mockReturnValue(true);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledTimes(2);
|
||||
expect(onSend.mock.calls[1][0]).toBe("queued attachment\nmore guidance");
|
||||
expect(onSend.mock.calls[1][1]).toEqual([expect.objectContaining({ media: expect.objectContaining({ name: "queued.png" }) })]);
|
||||
});
|
||||
|
||||
@@ -4004,7 +3879,7 @@ describe("ThreadComposer", () => {
|
||||
expect(screen.getByText("legacy follow-up")).toBeInTheDocument();
|
||||
expect(onSend).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Send now" }));
|
||||
expect(onSend).toHaveBeenCalledWith("legacy follow-up", undefined, undefined);
|
||||
expect(onSend).toHaveBeenCalledWith("legacy follow-up");
|
||||
});
|
||||
|
||||
it("keeps temporary chat guidance in memory only", async () => {
|
||||
|
||||
@@ -1727,7 +1727,7 @@ describe("ThreadShell", () => {
|
||||
expect(screen.getByText("persist me across tabs")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([false, true])("drains persisted follow-ups before history refresh resolves (pending tools=%s)", async (pendingTools) => {
|
||||
it.each([false, true])("sends the merged pending message before history refresh resolves (pending tools=%s)", async (pendingTools) => {
|
||||
const client = makeClient();
|
||||
const chatId = "queued-live-completion";
|
||||
const owner = "queued-owner";
|
||||
@@ -1766,7 +1766,8 @@ describe("ThreadShell", () => {
|
||||
await waitFor(() => expect(refreshStarted).toBe(true));
|
||||
try {
|
||||
act(() => client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: owner }));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first persisted follow-up"));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first persisted follow-up\nsecond persisted follow-up"));
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
const nextTurnId = client.sendMessage.mock.calls[0][3]!.turnId!;
|
||||
act(() => client._emitChat(chatId, {
|
||||
@@ -1775,14 +1776,13 @@ describe("ThreadShell", () => {
|
||||
}));
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
act(() => client._emitChat(chatId, { event: "turn_end", chat_id: chatId, turn_id: nextTurnId }));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "second persisted follow-up"));
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(2);
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await act(async () => { finishRefresh(initialHistory as Response); });
|
||||
}
|
||||
});
|
||||
|
||||
it("drains temporary follow-ups once per live completed turn without persisted history", async () => {
|
||||
it("sends the complete temporary pending message once without persisted history", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "temporary-queued-follow-ups";
|
||||
render(wrap(client, <ThreadShell
|
||||
@@ -1803,9 +1803,9 @@ describe("ThreadShell", () => {
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "turn_end", chat_id: chatId, turn_id: "temporary-owner",
|
||||
}));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first temporary follow-up"));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "first temporary follow-up\nsecond temporary follow-up"));
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByText("second temporary follow-up")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
const nextTurnId = client.sendMessage.mock.calls[0][3]!.turnId!;
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "goal_status", chat_id: chatId, turn_id: nextTurnId,
|
||||
@@ -1816,8 +1816,7 @@ describe("ThreadShell", () => {
|
||||
act(() => client._emitChat(chatId, {
|
||||
event: "turn_end", chat_id: chatId, turn_id: nextTurnId,
|
||||
}));
|
||||
await waitFor(() => expectSendMessageWithTurn(client, chatId, "second temporary follow-up"));
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(2);
|
||||
expect(client.sendMessage).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole("group", { name: "Waiting to send" })).not.toBeInTheDocument();
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/webui-thread"))).toBe(false);
|
||||
expect(window.localStorage.getItem(`nanobot.webui.composerQueuedGuidance.v1:${chatId}`)).toBeNull();
|
||||
|
||||
Reference in new issue
Block a user