feat(queue): add Send Now dispatch controls (#2292)

This commit is contained in:
Carlos Florêncio
2026-08-06 13:45:55 +01:00
committed by GitHub
parent 26bc2e1269
commit 6b42e335db
50 changed files with 5456 additions and 522 deletions
@@ -44,6 +44,7 @@ const QUEUED_BY_USER = "user";
const MERGE_BUTTON_ID = "queue-entry-merge";
const EDIT_BUTTON_ID = "queue-entry-edit";
const REMOVE_BUTTON_ID = "queue-entry-remove";
const SEND_NOW_BUTTON_ID = "queue-entry-send-now";
function entry(overrides: Partial<QueuedMessage> = {}): QueuedMessage {
return {
@@ -89,6 +90,9 @@ function baseState(entries: QueuedMessage[]) {
editEntry: vi.fn(async () => {}),
removeEntry: vi.fn(async () => {}),
mergeEntry: vi.fn(async () => {}),
sendEntryNow: vi.fn(async () => {}),
sendAllNow: vi.fn(async () => {}),
cancellationPending: false,
refetch: vi.fn(async () => {}),
};
}
@@ -212,7 +216,40 @@ describe("QueueAffordance", () => {
fireEvent.click(screen.getByTestId("queue-drain-next"));
expect(state.drainNext).toHaveBeenCalledTimes(1);
});
});
describe("QueueAffordance Send Now", () => {
it("sends the whole visible queue from the header", () => {
const state = queueState([entry(), entry({ id: "q-2", content: "second" })]);
useQueueMock.mockReturnValue(state);
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
fireEvent.click(screen.getByTestId("queue-send-now"));
expect(state.sendAllNow).toHaveBeenCalledTimes(1);
});
it("sends the selected row now", () => {
const state = queueState([
entry({ id: "q-1", content: "first" }),
entry({ id: "q-2", content: "second" }),
]);
useQueueMock.mockReturnValue(state);
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
fireEvent.click(screen.getAllByTestId(SEND_NOW_BUTTON_ID)[1]);
expect(state.sendEntryNow).toHaveBeenCalledWith("q-2");
});
it("disables row and header Send Now while cancellation is pending", () => {
useQueueMock.mockReturnValue(queueState([entry()], { cancellationPending: true }));
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
expect((screen.getByTestId("queue-send-now") as HTMLButtonElement).disabled).toBe(true);
expect((screen.getByTestId(SEND_NOW_BUTTON_ID) as HTMLButtonElement).disabled).toBe(true);
});
});
describe("QueueAffordance busy controls", () => {
it("hides the run-next action while the agent is busy", () => {
useQueueMock.mockReturnValue(queueState([entry()]));
render(
@@ -2,17 +2,21 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import { IconLayoutList, IconPlayerPlay, IconTrash, IconX } from "@tabler/icons-react";
import { IconLayoutList } from "@tabler/icons-react";
import { toast } from "@/lib/toast/sonner";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui";
import { Collapsible, CollapsibleContent } from "@kandev/ui/collapsible";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import { stripSystemTags } from "@/lib/utils/system-tags";
import { MergeReferenceOverflowError, QueueEntryNotFoundError } from "@/lib/api/domains/queue-api";
import {
MergeReferenceOverflowError,
QueueEntryNotFoundError,
QueueSendNowError,
} from "@/lib/api/domains/queue-api";
import { useQueue } from "@/hooks/domains/session/use-queue";
import { canMergeWithAbove, QueuedGhostMessage } from "./queued-ghost-message";
import { QueuePanelHeader } from "./queued-ghost-panel-header";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
import type { EntityReference } from "@/lib/types/entity-reference";
@@ -83,14 +87,60 @@ type QueuePanelHandlerArgs = {
) => Promise<void>;
removeEntry: (entryId: string) => Promise<void>;
mergeEntry: (entryId: string) => Promise<void>;
sendEntryNow: (entryId: string) => Promise<void>;
sendAllNow: () => Promise<void>;
};
function useSendNowPanelHandlers(
sendEntryNow: (entryId: string) => Promise<void>,
sendAllNow: () => Promise<void>,
) {
const { t } = useTranslation();
const sendNowErrorMessage = useCallback(
(err: unknown) => {
if (err instanceof QueueEntryNotFoundError) return t("chat:sendNowEntryAlreadySent");
if (err instanceof QueueSendNowError) {
const messages: Record<string, string> = {
queue_empty: "chat:sendNowQueueEmpty",
queue_changed: "chat:sendNowQueueChanged",
send_now_conflict: "chat:sendNowConflict",
turn_changed: "chat:sendNowTurnChanged",
send_now_attachment_overflow: "chat:sendNowAttachmentOverflow",
send_now_reference_overflow: "chat:sendNowReferenceOverflow",
};
const key = messages[err.code];
if (key) return t(key);
}
return t("chat:failedToSendQueuedMessageNow");
},
[t],
);
const handleSendEntryNow = useCallback(
(entryId: string) => {
sendEntryNow(entryId).catch((err) => {
console.error("Failed to send queued message now:", err);
toast.error(sendNowErrorMessage(err));
});
},
[sendEntryNow, sendNowErrorMessage],
);
const handleSendAllNow = useCallback(() => {
sendAllNow().catch((err) => {
console.error("Failed to send queued messages now:", err);
toast.error(sendNowErrorMessage(err));
});
}, [sendAllNow, sendNowErrorMessage]);
return { handleSendEntryNow, handleSendAllNow };
}
function useQueuePanelHandlers({
clearAll,
drainNext,
editEntry,
removeEntry,
mergeEntry,
sendEntryNow,
sendAllNow,
}: QueuePanelHandlerArgs) {
// Tracks merge requests still in flight so a rapid second click on the same
// row cannot fire a second request for an entry that is already gone — the
@@ -98,6 +148,10 @@ function useQueuePanelHandlers({
// a spurious "not found" error.
const pendingMerges = useRef(new Set<string>());
const { t } = useTranslation();
const { handleSendEntryNow, handleSendAllNow } = useSendNowPanelHandlers(
sendEntryNow,
sendAllNow,
);
const handleSave = useCallback(
async (entryId: string, content: string, entityReferences: EntityReference[]) => {
await editEntry(entryId, content, undefined, entityReferences);
@@ -151,7 +205,99 @@ function useQueuePanelHandlers({
});
}, [drainNext, t]);
return { handleSave, handleRemove, handleMerge, handleClear, handleDrain };
return {
handleSave,
handleRemove,
handleMerge,
handleClear,
handleDrain,
handleSendEntryNow,
handleSendAllNow,
};
}
type QueuePanelDisclosureProps = {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
entries: QueuedMessage[];
count: number;
max: number;
isFull: boolean;
canDrain: boolean;
isLoading: boolean;
cancellationPending: boolean;
onClose: () => void;
onClear: () => void;
onDrain: () => void;
onSendNow: () => void;
onSave: (entryId: string, content: string, refs: EntityReference[]) => Promise<void>;
onRemove: (entryId: string) => Promise<void>;
onMerge: (entryId: string) => Promise<void>;
onSendEntryNow: (entryId: string) => void;
};
function QueuePanelDisclosure({
isOpen,
onOpenChange,
entries,
count,
max,
isFull,
canDrain,
isLoading,
cancellationPending,
onClose,
onClear,
onDrain,
onSendNow,
onSave,
onRemove,
onMerge,
onSendEntryNow,
}: QueuePanelDisclosureProps) {
return (
<Collapsible open={isOpen} onOpenChange={onOpenChange}>
<CollapsibleContent
className={cn(
"overflow-hidden",
"data-[state=open]:animate-queue-open data-[state=closed]:animate-queue-close",
)}
>
<QueuePanel
entries={entries}
count={count}
max={max}
isFull={isFull}
canDrain={canDrain}
isLoading={isLoading}
cancellationPending={cancellationPending}
onClose={onClose}
onClear={onClear}
onDrain={onDrain}
onSendNow={onSendNow}
onSave={onSave}
onRemove={onRemove}
onMerge={onMerge}
onSendEntryNow={onSendEntryNow}
/>
</CollapsibleContent>
</Collapsible>
);
}
function useQueuePanelOpenState(sessionId: string | null, entryCount: number) {
const [isOpen, setIsOpen] = useState(false);
const [lastSession, setLastSession] = useState(sessionId);
const [lastEntryCount, setLastEntryCount] = useState(entryCount);
if (sessionId !== lastSession) {
setLastSession(sessionId);
setIsOpen(false);
}
if (entryCount !== lastEntryCount) {
setLastEntryCount(entryCount);
if (entryCount === 0) setIsOpen(false);
}
return [isOpen, setIsOpen] as const;
}
/**
@@ -179,33 +325,33 @@ export function QueueAffordance({
editEntry,
removeEntry,
mergeEntry,
sendEntryNow,
sendAllNow,
cancellationPending,
} = useQueue(sessionId);
const [isOpen, setIsOpen] = useState(false);
const { handleSave, handleRemove, handleMerge, handleClear, handleDrain } = useQueuePanelHandlers(
{
clearAll,
drainNext,
editEntry,
removeEntry,
mergeEntry,
},
);
const entryCount = entries.length;
const [isOpen, setIsOpen] = useQueuePanelOpenState(sessionId, entryCount);
const {
handleSave,
handleRemove,
handleMerge,
handleClear,
handleDrain,
handleSendEntryNow,
handleSendAllNow,
} = useQueuePanelHandlers({
clearAll,
drainNext,
editEntry,
removeEntry,
mergeEntry,
sendEntryNow,
sendAllNow,
});
// Reset disclosure on session switch or full drain using render-phase state
// adjustment (React docs: "Adjusting some state when a prop changes"). This
// avoids the cascading-render anti-pattern of doing it inside useEffect.
const entryCount = entries.length;
const [lastSession, setLastSession] = useState(sessionId);
const [lastEntryCount, setLastEntryCount] = useState(entryCount);
if (sessionId !== lastSession) {
setLastSession(sessionId);
setIsOpen(false);
}
if (entryCount !== lastEntryCount) {
setLastEntryCount(entryCount);
if (entryCount === 0) setIsOpen(false);
}
const close = useCallback(() => setIsOpen(false), []);
useEscToClose(isOpen, close);
@@ -233,29 +379,25 @@ export function QueueAffordance({
return (
<>
{renderStatusBar?.(chipNode)}
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<CollapsibleContent
className={cn(
"overflow-hidden",
"data-[state=open]:animate-queue-open data-[state=closed]:animate-queue-close",
)}
>
<QueuePanel
entries={entries}
count={count}
max={max}
isFull={isFull}
canDrain={canDrain}
isLoading={isLoading}
onClose={close}
onClear={handleClear}
onDrain={handleDrain}
onSave={handleSave}
onRemove={handleRemove}
onMerge={handleMerge}
/>
</CollapsibleContent>
</Collapsible>
<QueuePanelDisclosure
isOpen={isOpen}
onOpenChange={setIsOpen}
entries={entries}
count={count}
max={max}
isFull={isFull}
canDrain={canDrain}
isLoading={isLoading}
cancellationPending={cancellationPending}
onClose={close}
onClear={handleClear}
onDrain={handleDrain}
onSendNow={handleSendAllNow}
onSave={handleSave}
onRemove={handleRemove}
onMerge={handleMerge}
onSendEntryNow={handleSendEntryNow}
/>
{!renderStatusBar && chipNode && (
<div className="flex items-center px-1 pb-1 animate-in fade-in-0 slide-in-from-bottom-1 duration-150 motion-reduce:animate-none">
{chipNode}
@@ -324,12 +466,15 @@ type QueuePanelProps = {
isFull: boolean;
canDrain: boolean;
isLoading: boolean;
cancellationPending: boolean;
onClose: () => void;
onClear: () => void;
onDrain: () => void;
onSendNow: () => void;
onSave: (entryId: string, content: string, entityReferences: EntityReference[]) => Promise<void>;
onRemove: (entryId: string) => Promise<void>;
onMerge: (entryId: string) => Promise<void>;
onSendEntryNow: (entryId: string) => void;
};
function QueuePanel({
@@ -339,12 +484,15 @@ function QueuePanel({
isFull,
canDrain,
isLoading,
cancellationPending,
onClose,
onClear,
onDrain,
onSendNow,
onSave,
onRemove,
onMerge,
onSendEntryNow,
}: QueuePanelProps) {
const { t } = useTranslation();
return (
@@ -365,8 +513,10 @@ function QueuePanel({
isFull={isFull}
canDrain={canDrain}
isLoading={isLoading}
cancellationPending={cancellationPending}
onClear={onClear}
onDrain={onDrain}
onSendNow={onSendNow}
onClose={onClose}
/>
<div
@@ -384,82 +534,11 @@ function QueuePanel({
onSave={(content, entityReferences) => onSave(entry.id, content, entityReferences)}
onRemove={() => onRemove(entry.id)}
onMerge={() => onMerge(entry.id)}
onSendNow={() => onSendEntryNow(entry.id)}
sendNowDisabled={isLoading || cancellationPending}
/>
))}
</div>
</div>
);
}
type QueuePanelHeaderProps = {
count: number;
max: number;
isFull: boolean;
canDrain: boolean;
isLoading: boolean;
onClear: () => void;
onDrain: () => void;
onClose: () => void;
};
function QueuePanelHeader({
count,
max,
isFull,
canDrain,
isLoading,
onClear,
onDrain,
onClose,
}: QueuePanelHeaderProps) {
const { t } = useTranslation();
const capacityText =
max > 0
? t(isFull ? "chat:queueCapacityFull" : "chat:queueCapacity", { count, max })
: t("chat:queueCount", { count });
return (
<div className="flex shrink-0 items-center justify-between gap-3 py-1">
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<IconLayoutList className="h-3.5 w-3.5" />
<span className="uppercase tracking-wide">{t("chat:queued")}</span>
<span className={cn(isFull && "text-amber-600 dark:text-amber-400")}>{capacityText}</span>
</div>
<div className="flex items-center gap-1">
{canDrain && (
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onDrain}
disabled={isLoading}
title={t("chat:runNextQueuedMessage")}
data-testid="queue-drain-next"
>
<IconPlayerPlay className="mr-1 h-3 w-3" />
{t("chat:runNext")}
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onClear}
title={t("chat:clearAllQueuedMessages")}
data-testid="queue-clear-all"
>
<IconTrash className="mr-1 h-3 w-3" />
{t("chat:clearAll")}
</Button>
<button
type="button"
onClick={onClose}
aria-label={t("chat:collapseQueuedMessages")}
data-testid="queue-close"
className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground cursor-pointer rounded p-1 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
>
<IconX className="h-3.5 w-3.5" />
</button>
</div>
</div>
);
}
@@ -9,18 +9,7 @@ import {
useRef,
useState,
} from "react";
import {
IconCheck,
IconChevronDown,
IconChevronUp,
IconEdit,
IconFile,
IconInfoCircle,
IconRobot,
IconUser,
IconX,
IconArrowMerge,
} from "@tabler/icons-react";
import { IconCheck, IconFile, IconInfoCircle, IconRobot, IconUser } from "@tabler/icons-react";
import ReactMarkdown from "react-markdown";
import { toast } from "@/lib/toast/sonner";
import { useTranslation } from "react-i18next";
@@ -47,6 +36,7 @@ import {
survivingEntityReferences,
} from "@/lib/entity-references/message-references";
import { buildEntityReferenceMarkdownComponents } from "@/components/task/chat/messages/entity-reference-chip";
import { QueuedGhostRowActions } from "@/components/task/chat/queued-ghost-row-actions";
import { t } from "@/lib/i18n";
type QueuedAttachment = NonNullable<QueuedMessage["attachments"]>[number];
@@ -302,6 +292,8 @@ type DisplayViewProps = {
onStartEdit: () => void;
onRemove: () => void;
onMerge?: () => void | Promise<void>;
onSendNow: () => void;
sendNowDisabled: boolean;
};
/** Rough threshold above which we offer a per-row expand toggle. Two lines of
@@ -310,100 +302,12 @@ type DisplayViewProps = {
* (lists, code blocks) would otherwise be silently truncated. */
const EXPAND_THRESHOLD = 80;
function shouldOfferExpand(text: string): boolean {
return text.length > EXPAND_THRESHOLD || text.includes("\n");
function queuePositionLabel(index: number | undefined, position: number | undefined): string {
return `#${index === undefined ? (position ?? 1) : index + 1}`;
}
type RowActionsProps = {
canExpand: boolean;
expanded: boolean;
canMerge: boolean;
canEdit: boolean;
canRemove: boolean;
onToggleExpand: () => void;
onMerge?: () => void | Promise<void>;
onStartEdit: () => void;
onRemove: () => void;
};
function RowActions({
canExpand,
expanded,
canMerge,
canEdit,
canRemove,
onToggleExpand,
onMerge,
onStartEdit,
onRemove,
}: RowActionsProps) {
const { t } = useTranslation();
return (
<div
className={cn(
"flex items-center gap-0.5 flex-shrink-0 transition-opacity",
// Hover-reveal on devices that support hover (desktop); always
// visible on touch surfaces where there's no hover affordance.
"opacity-0 group-hover:opacity-100 focus-within:opacity-100",
"[@media(hover:none)]:opacity-100",
"[@media(pointer:coarse)]:opacity-100",
)}
>
{canExpand && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onToggleExpand}
title={expanded ? t("chat:collapseMessage") : t("chat:expandMessage")}
data-testid="queue-entry-expand"
aria-expanded={expanded}
>
{expanded ? (
<IconChevronUp className="h-3.5 w-3.5" />
) : (
<IconChevronDown className="h-3.5 w-3.5" />
)}
</Button>
)}
{canMerge && onMerge && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onMerge}
title={t("chat:mergeWithAbove")}
data-testid="queue-entry-merge"
>
<IconArrowMerge className="h-3.5 w-3.5" />
</Button>
)}
{canEdit && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onStartEdit}
title={t("chat:editQueuedMessage")}
data-testid="queue-entry-edit"
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
)}
{canRemove && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onRemove}
title={t("chat:removeQueuedMessage")}
data-testid="queue-entry-remove"
>
<IconX className="h-4 w-4" />
</Button>
)}
</div>
);
function shouldOfferExpand(text: string): boolean {
return text.length > EXPAND_THRESHOLD || text.includes("\n");
}
function DisplayView({
@@ -416,6 +320,8 @@ function DisplayView({
onStartEdit,
onRemove,
onMerge,
onSendNow,
sendNowDisabled,
}: DisplayViewProps) {
const { t } = useTranslation();
const visible = stripSystemTags(entry.content);
@@ -460,7 +366,7 @@ function DisplayView({
)}
<AttachmentRow attachments={attachments} interactive={true} />
</div>
<RowActions
<QueuedGhostRowActions
canExpand={canExpand}
expanded={expanded}
canMerge={canMerge}
@@ -470,6 +376,8 @@ function DisplayView({
onMerge={onMerge}
onStartEdit={onStartEdit}
onRemove={onRemove}
onSendNow={onSendNow}
sendNowDisabled={sendNowDisabled}
/>
</div>
);
@@ -495,6 +403,10 @@ type QueuedGhostMessageProps = {
onRemove: () => void | Promise<void>;
/** Fold this entry into the one above it. */
onMerge?: () => void | Promise<void>;
/** Interrupt the current turn and dispatch this exact queued entry. */
onSendNow?: () => void;
/** Disable while the queue mutation or backend cancellation is in flight. */
sendNowDisabled?: boolean;
/** Called after edit save/cancel so the parent can refocus the chat input. */
onEditComplete?: () => void;
};
@@ -511,6 +423,54 @@ function useFocusQueuedEdit(
}, [editing, textareaRef]);
}
type QueuedGhostSaveArgs = {
value: string;
entryContent: string;
entityReferences: readonly EntityReference[];
onSave: QueuedGhostMessageProps["onSave"];
onEditComplete?: () => void;
setEditing: (editing: boolean) => void;
setSaving: (saving: boolean) => void;
t: (key: string) => string;
};
function useQueuedGhostSave({
value,
entryContent,
entityReferences,
onSave,
onEditComplete,
setEditing,
setSaving,
t,
}: QueuedGhostSaveArgs) {
return useCallback(async () => {
const trimmed = value.trim();
if (!trimmed || trimmed === entryContent) {
setEditing(false);
onEditComplete?.();
return;
}
setSaving(true);
try {
await onSave(trimmed, survivingEntityReferences(trimmed, entityReferences));
setEditing(false);
onEditComplete?.();
} catch (err) {
console.error("Failed to update queued entry:", err);
if (err instanceof QueueEntryNotFoundError) {
toast.error(t("chat:queueEditAlreadySent"));
} else {
toast.error(t("chat:queueEditSaveFailed"));
}
setEditing(false);
onEditComplete?.();
} finally {
setSaving(false);
}
}, [value, entryContent, onSave, onEditComplete, entityReferences, setEditing, setSaving, t]);
}
export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGhostMessageProps>(
function QueuedGhostMessage(
{
@@ -522,6 +482,8 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
onSave,
onRemove,
onMerge,
onSendNow = () => undefined,
sendNowDisabled = false,
onEditComplete,
},
ref,
@@ -537,7 +499,6 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
);
const effectiveCanMerge = canMerge && canMergeEntry(entry);
useFocusQueuedEdit(editing, textareaRef);
useEffect(() => {
if (!editing) setValue(entry.content);
}, [entry.content, editing]);
@@ -549,45 +510,24 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
}, [entry.content, canEdit]);
useImperativeHandle(ref, () => ({ startEdit }), [startEdit]);
const handleCancel = useCallback(() => {
setValue(entry.content);
setEditing(false);
onEditComplete?.();
}, [entry.content, onEditComplete]);
const handleSave = useCallback(async () => {
const trimmed = value.trim();
if (!trimmed || trimmed === entry.content) {
setEditing(false);
onEditComplete?.();
return;
}
setSaving(true);
try {
await onSave(trimmed, survivingEntityReferences(trimmed, entityReferences));
setEditing(false);
onEditComplete?.();
} catch (err) {
console.error("Failed to update queued entry:", err);
// Exit edit mode after both drain races and transient failures.
if (err instanceof QueueEntryNotFoundError) {
toast.error(t("chat:queueEditAlreadySent"));
} else {
toast.error(t("chat:queueEditSaveFailed"));
}
setEditing(false);
onEditComplete?.();
} finally {
setSaving(false);
}
}, [value, entry.content, onSave, onEditComplete, entityReferences, t]);
const handleSave = useQueuedGhostSave({
value,
entryContent: entry.content,
entityReferences,
onSave,
onEditComplete,
setEditing,
setSaving,
t,
});
// Persisted positions are durable FIFO keys and intentionally retain gaps
// after a remove or merge. The panel index is the compact user-facing
// ordinal, so prefer it whenever this row belongs to a rendered list.
const positionNumber = index === undefined ? (entry.position ?? 1) : index + 1;
const positionLabel = `#${positionNumber}`;
const positionLabel = queuePositionLabel(index, entry.position);
return (
<div
@@ -617,6 +557,8 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
onStartEdit={startEdit}
onRemove={onRemove}
onMerge={onMerge}
onSendNow={onSendNow}
sendNowDisabled={sendNowDisabled}
/>
)}
</div>
@@ -0,0 +1,93 @@
import { IconLayoutList, IconPlayerPlay, IconSend, IconTrash, IconX } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui";
import { cn } from "@/lib/utils";
export type QueuePanelHeaderProps = {
count: number;
max: number;
isFull: boolean;
canDrain: boolean;
isLoading: boolean;
cancellationPending: boolean;
onClear: () => void;
onDrain: () => void;
onSendNow: () => void;
onClose: () => void;
};
export function QueuePanelHeader({
count,
max,
isFull,
canDrain,
isLoading,
cancellationPending,
onClear,
onDrain,
onSendNow,
onClose,
}: QueuePanelHeaderProps) {
const { t } = useTranslation();
const capacityText =
max > 0
? t(isFull ? "chat:queueCapacityFull" : "chat:queueCapacity", { count, max })
: t("chat:queueCount", { count });
return (
<div className="flex shrink-0 items-center justify-between gap-3 py-1">
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<IconLayoutList className="h-3.5 w-3.5" />
<span className="uppercase tracking-wide">{t("chat:queued")}</span>
<span className={cn(isFull && "text-amber-600 dark:text-amber-400")}>{capacityText}</span>
</div>
<div className="flex flex-wrap items-center justify-end gap-1">
{canDrain && (
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onDrain}
disabled={isLoading}
title={t("chat:runNextQueuedMessage")}
data-testid="queue-drain-next"
>
<IconPlayerPlay className="mr-1 h-3 w-3" />
{t("chat:runNext")}
</Button>
)}
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onSendNow}
disabled={isLoading || cancellationPending}
title={t("chat:sendNowQueuedMessages")}
data-testid="queue-send-now"
>
<IconSend className="mr-1 h-3 w-3" />
{t("chat:sendNow")}
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 px-1.5 text-xs text-muted-foreground hover:text-foreground cursor-pointer [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:px-3"
onClick={onClear}
title={t("chat:clearAllQueuedMessages")}
data-testid="queue-clear-all"
>
<IconTrash className="mr-1 h-3 w-3" />
{t("chat:clearAll")}
</Button>
<button
type="button"
onClick={onClose}
aria-label={t("chat:collapseQueuedMessages")}
data-testid="queue-close"
className="inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground cursor-pointer rounded p-1 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
>
<IconX className="h-3.5 w-3.5" />
</button>
</div>
</div>
);
}
@@ -0,0 +1,118 @@
import {
IconArrowMerge,
IconChevronDown,
IconChevronUp,
IconEdit,
IconSend,
IconX,
} from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { Button } from "@kandev/ui";
import { cn } from "@/lib/utils";
export type QueuedGhostRowActionsProps = {
canExpand: boolean;
expanded: boolean;
canMerge: boolean;
canEdit: boolean;
canRemove: boolean;
onToggleExpand: () => void;
onMerge?: () => void | Promise<void>;
onStartEdit: () => void;
onRemove: () => void;
onSendNow?: () => void;
sendNowDisabled: boolean;
};
export function QueuedGhostRowActions({
canExpand,
expanded,
canMerge,
canEdit,
canRemove,
onToggleExpand,
onMerge,
onStartEdit,
onRemove,
onSendNow,
sendNowDisabled,
}: QueuedGhostRowActionsProps) {
const { t } = useTranslation();
return (
<div
className={cn(
"flex items-center gap-0.5 flex-shrink-0 transition-opacity",
// Hover-reveal on devices that support hover (desktop); always
// visible on touch surfaces where there's no hover affordance.
"opacity-0 group-hover:opacity-100 focus-within:opacity-100",
"[@media(hover:none)]:opacity-100",
"[@media(pointer:coarse)]:opacity-100",
)}
>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onSendNow}
disabled={sendNowDisabled}
title={t("chat:sendNowQueuedMessage")}
data-testid="queue-entry-send-now"
>
<IconSend className="h-3.5 w-3.5" />
</Button>
{canExpand && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onToggleExpand}
title={expanded ? t("chat:collapseMessage") : t("chat:expandMessage")}
data-testid="queue-entry-expand"
aria-expanded={expanded}
>
{expanded ? (
<IconChevronUp className="h-3.5 w-3.5" />
) : (
<IconChevronDown className="h-3.5 w-3.5" />
)}
</Button>
)}
{canMerge && onMerge && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onMerge}
title={t("chat:mergeWithAbove")}
data-testid="queue-entry-merge"
>
<IconArrowMerge className="h-3.5 w-3.5" />
</Button>
)}
{canEdit && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onStartEdit}
title={t("chat:editQueuedMessage")}
data-testid="queue-entry-edit"
>
<IconEdit className="h-3.5 w-3.5" />
</Button>
)}
{canRemove && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 cursor-pointer p-0 text-muted-foreground hover:text-foreground [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11"
onClick={onRemove}
title={t("chat:removeQueuedMessage")}
data-testid="queue-entry-remove"
>
<IconX className="h-4 w-4" />
</Button>
)}
</div>
);
}