feat(webui): show when the agent picks up queued messages (#6719)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 16:03:16 +08:00
1 parent 3025a01cf0
commit b453de9cf6
26 files changed
+642 -29

No files matched your search

+2
View File
@@ -231,6 +231,8 @@ During a response, desktop Enter appends input to one waiting message, preservin
Automatic sending continues across topic switches and short reconnects while the page stays live. Reloading, reopening, leaving the page, or the browser freezing it restores waiting content for manual sending; choose **Send now** or edit and send it when ready. Automatic sending continues across topic switches and short reconnects while the page stays live. Reloading, reopening, leaving the page, or the browser freezing it restores waiting content for manual sending; choose **Send now** or edit and send it when ready.
When you send a follow-up while the agent is busy, a dashed edge shows that the message is waiting for the model. The usual edge returns when the request that answers that message begins. This live hint is cleared on Stop or disconnect and is not restored from history.
For image generation, configure an image provider first and then use the WebUI image mode from the composer. See [`image-generation.md`](./image-generation.md) for provider setup and output behavior. For image generation, configure an image provider first and then use the WebUI image mode from the composer. See [`image-generation.md`](./image-generation.md) for provider setup and output behavior.
## Channels ## Channels
@@ -5434,6 +5434,7 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
"chat_id": "shared-chat", "chat_id": "shared-chat",
"text": "one more detail", "text": "one more detail",
"starts_turn": False, "starts_turn": False,
"waiting_for_model": True,
"turn_id": "steer-a", "turn_id": "steer-a",
"input_id": "user:steer-a", "input_id": "user:steer-a",
"active_turn_id": "turn-a", "active_turn_id": "turn-a",
@@ -5446,12 +5447,13 @@ async def test_user_messages_fan_out_to_other_clients_on_the_same_chat(
payload["turn_id"], payload["turn_id"],
payload["starts_turn"], payload["starts_turn"],
payload["active_turn_id"], payload["active_turn_id"],
payload.get("waiting_for_model"),
) )
for payload in origin_payloads for payload in origin_payloads
if payload["event"] == "message_accepted" if payload["event"] == "message_accepted"
] == [ ] == [
("message_accepted", "turn-a", True, "turn-a"), ("message_accepted", "turn-a", True, "turn-a", None),
("message_accepted", "steer-a", False, "turn-a"), ("message_accepted", "steer-a", False, "turn-a", True),
] ]
outsider.send.assert_not_awaited() outsider.send.assert_not_awaited()
assert bus.publish_inbound.await_count == 2 assert bus.publish_inbound.await_count == 2
+11
View File
@@ -248,6 +248,7 @@ class WebUICommandRouter:
*, *,
turn_id: str | None, turn_id: str | None,
starts_turn: bool, starts_turn: bool,
waiting_for_model: bool,
media: list[dict[str, Any]], media: list[dict[str, Any]],
cli_apps: list[dict[str, Any]], cli_apps: list[dict[str, Any]],
mcp_presets: list[dict[str, Any]], mcp_presets: list[dict[str, Any]],
@@ -262,6 +263,8 @@ class WebUICommandRouter:
if turn_id is not None: if turn_id is not None:
body["turn_id"] = turn_id body["turn_id"] = turn_id
body["input_id"] = f"user:{turn_id}" body["input_id"] = f"user:{turn_id}"
if waiting_for_model:
body["waiting_for_model"] = True
if media: if media:
body["media_urls"] = media body["media_urls"] = media
if cli_apps: if cli_apps:
@@ -812,6 +815,12 @@ class WebUICommandRouter:
if queued_owner is not None: if queued_owner is not None:
metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner metadata[WEBSOCKET_TURN_OWNER_METADATA_KEY] = queued_owner
# Live presentation only: a follow-up accepted while another turn owns the chat.
waiting_for_model = (
is_webui and temporary_policy is None and turn_id is not None
and not restart_control and not is_user_shell and not content.lstrip().startswith("/")
and queued_owner is None and websocket_turn_id(chat_id) is not None
)
accepted = False accepted = False
session_generation: str | None = None session_generation: str | None = None
session_created = False session_created = False
@@ -905,6 +914,7 @@ class WebUICommandRouter:
content, content,
turn_id=turn_id, turn_id=turn_id,
starts_turn=queued_owner is not None, starts_turn=queued_owner is not None,
waiting_for_model=waiting_for_model,
media=media, media=media,
cli_apps=cli_apps, cli_apps=cli_apps,
mcp_presets=mcp_presets, mcp_presets=mcp_presets,
@@ -919,6 +929,7 @@ class WebUICommandRouter:
chat_id=chat_id, chat_id=chat_id,
turn_id=turn_id, turn_id=turn_id,
starts_turn=queued_owner is not None, starts_turn=queued_owner is not None,
**({"waiting_for_model": True} if waiting_for_model else {}),
**({"media_urls": media} if media else {}), **({"media_urls": media} if media else {}),
**( **(
{"active_turn_id": active_turn_id} {"active_turn_id": active_turn_id}
+5 -5
View File
@@ -102,11 +102,11 @@ async def test_session_message_text_is_not_dispatched_as_a_slash_command(
loop: AgentLoop, loop: AgentLoop,
) -> None: ) -> None:
loop.sessions.save(loop.sessions.get_or_create("telegram:target")) loop.sessions.save(loop.sessions.get_or_create("telegram:target"))
await loop._dispatch_inbound(_message("/stop")) # Bound hangs without imposing a tight deadline on SQLite checkpoint writes.
await asyncio.wait_for( async with asyncio.timeout(10):
asyncio.gather(*loop._active_tasks["telegram:target"]), timeout=2, await loop._dispatch_inbound(_message("/stop"))
) await asyncio.gather(*loop._active_tasks["telegram:target"])
response = await asyncio.wait_for(loop.bus.consume_outbound(), timeout=2) response = loop.bus.outbound.get_nowait()
assert response.content == "Reviewed" assert response.content == "Reviewed"
loop.provider.chat_stream_with_retry.assert_awaited_once() loop.provider.chat_stream_with_retry.assert_awaited_once()
+9 -1
View File
@@ -59,8 +59,16 @@ const samples: { label: string; message: UIMessage }[] = [
]; ];
export function AttachmentLayoutFixture() { export function AttachmentLayoutFixture() {
const processingSamples: typeof samples = (["pending", "consumed"] as const).map((status) => ({
label: `Attachments: ${status}`,
message: {
id: `attachments-${status}`, role: "user", content: "", createdAt: 8, processingStatus: status,
media: [archive, image("Study.svg", "#83a9d8"), { kind: "video", name: "sample.webm", url: sampleVideo }],
},
}));
const messages = new URLSearchParams(window.location.search).has("processing") ? processingSamples : samples;
return <main className="space-y-8 px-4 py-6"> return <main className="space-y-8 px-4 py-6">
{samples.map(({ label, message }) => <section key={message.id} aria-label={label}> {messages.map(({ label, message }) => <section key={message.id} aria-label={label}>
<h2 className="mb-3 text-xs font-medium text-muted-foreground">{label}</h2> <h2 className="mb-3 text-xs font-medium text-muted-foreground">{label}</h2>
<MessageBubble message={message} /> <MessageBubble message={message} />
</section>)} </section>)}
+25
View File
@@ -150,6 +150,31 @@ for (const width of [1024, 360]) {
} }
} }
test("attachment-only pending messages keep static dashed edges in forced colors", async ({ page }) => {
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
await page.emulateMedia({ forcedColors: "active", reducedMotion: "no-preference", colorScheme: "dark" });
await page.goto("/browser/fixture.html?case=attachments&processing");
const solid = page.getByRole("region", { name: "Attachments: consumed" });
const fileSurface = "[data-file-attachment] > span";
await expect(solid.locator(fileSurface)).toHaveCSS("border-top-style", "solid");
await expect(solid.locator("[data-pending-edge-overlay]")).toHaveCount(0);
const region = page.getByRole("region", { name: "Attachments: pending" });
const card = region.locator(fileSurface);
await expect(card).toHaveCSS("border-top-style", "dashed");
await expect(card.locator("[data-pending-edge-overlay]")).toBeHidden();
const box = await bounds(card);
expect({ width: box.width, height: box.height }).toEqual({ width: 96, height: 96 });
const mediaEdges = region.locator('[data-solid-tone="media"] > .pending-edge-layer-dashed');
await expect(mediaEdges).toHaveCount(2);
for (const edge of await mediaEdges.all()) {
await expect(edge).toBeVisible();
await expect(edge).toHaveCSS("border-top-style", "dashed");
await expect(edge).toHaveCSS("animation-name", "none");
}
});
test("image lightbox and file download remain keyboard accessible", async ({ page }, testInfo) => { test("image lightbox and file download remain keyboard accessible", async ({ page }, testInfo) => {
await page.route("**/fixture/retry.webm", (route) => route.fulfill({ status: 503, body: "Temporarily unavailable" })); await page.route("**/fixture/retry.webm", (route) => route.fulfill({ status: 503, body: "Temporarily unavailable" }));
await openAttachments(page); await openAttachments(page);
+6 -1
View File
@@ -2,6 +2,7 @@ import { useState, type ReactNode } from "react";
import { FileText, ImageIcon, Video } from "lucide-react"; import { FileText, ImageIcon, Video } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { PendingEdgeOverlay, type PendingEdgeState } from "@/components/PendingEdgeOverlay";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { UIMediaKind } from "@/lib/types"; import type { UIMediaKind } from "@/lib/types";
@@ -10,12 +11,14 @@ import { cn } from "@/lib/utils";
export const attachmentCardActionClassName = "absolute right-0 top-0 grid h-11 w-11 place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"; export const attachmentCardActionClassName = "absolute right-0 top-0 grid h-11 w-11 place-items-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring";
/** The card owns only its information surface; callers own removal, download, and status. */ /** The card owns only its information surface; callers own removal, download, and status. */
export function AttachmentCard({ name, description, children, action, invalid = false }: { export function AttachmentCard({ name, description, children, action, invalid = false, edgeState = "solid", onSealEnd }: {
name: string; name: string;
description?: string; description?: string;
children: ReactNode; children: ReactNode;
action?: ReactNode; action?: ReactNode;
invalid?: boolean; invalid?: boolean;
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
}) { }) {
const [detailsOpen, setDetailsOpen] = useState(false); const [detailsOpen, setDetailsOpen] = useState(false);
const [hintOpen, setHintOpen] = useState(false); const [hintOpen, setHintOpen] = useState(false);
@@ -28,7 +31,9 @@ export function AttachmentCard({ name, description, children, action, invalid =
return <span className={cn( return <span className={cn(
"relative block h-24 w-24 max-w-full shrink-0 rounded-control border transition-colors motion-reduce:transition-none", "relative block h-24 w-24 max-w-full shrink-0 rounded-control border transition-colors motion-reduce:transition-none",
invalid ? "border-destructive/40 bg-destructive/5 text-destructive" : "border-border/70 bg-muted/35", invalid ? "border-destructive/40 bg-destructive/5 text-destructive" : "border-border/70 bg-muted/35",
edgeState !== "solid" && "border-transparent",
)}> )}>
<PendingEdgeOverlay state={edgeState} solidTone="card" inset="-inset-px" onSealEnd={onSealEnd} />
<TooltipProvider> <TooltipProvider>
<Tooltip open={hintOpen && !detailsOpen} onOpenChange={setHintOpen}> <Tooltip open={hintOpen && !detailsOpen} onOpenChange={setHintOpen}>
<Popover open={detailsOpen} onOpenChange={changeDetailsOpen}> <Popover open={detailsOpen} onOpenChange={changeDetailsOpen}>
+18 -5
View File
@@ -8,6 +8,7 @@ import { ImageThumbnail } from "@/components/ImageGallery";
import { ImageLightbox } from "@/components/ImageLightbox"; import { ImageLightbox } from "@/components/ImageLightbox";
import { useRegisterInlineImage } from "@/components/InlineImageContext"; import { useRegisterInlineImage } from "@/components/InlineImageContext";
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard"; import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
import { PendingEdgeOverlay, type PendingEdgeState } from "@/components/PendingEdgeOverlay";
interface AttachmentTileProps { interface AttachmentTileProps {
attachment: UIMediaAttachment; attachment: UIMediaAttachment;
@@ -15,9 +16,11 @@ interface AttachmentTileProps {
inline?: boolean; inline?: boolean;
variant?: "default" | "compact"; variant?: "default" | "compact";
pending?: boolean; pending?: boolean;
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
} }
export function AttachmentTile({ attachment, className, inline = false, variant = "default", pending = false }: AttachmentTileProps) { export function AttachmentTile({ attachment, className, inline = false, variant = "default", pending = false, edgeState = "solid", onSealEnd }: AttachmentTileProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const videoUrl = attachment.url; const videoUrl = attachment.url;
const [failedUrl, setFailedUrl] = useState<string | undefined>(undefined); const [failedUrl, setFailedUrl] = useState<string | undefined>(undefined);
@@ -31,7 +34,7 @@ export function AttachmentTile({ attachment, className, inline = false, variant
return ( return (
<span className={cn("not-prose my-3 block max-w-full", className)}> <span className={cn("not-prose my-3 block max-w-full", className)}>
<ImageThumbnail key={attachment.url} image={attachment} <ImageThumbnail key={attachment.url} image={attachment}
size={variant === "compact" ? "compact" : "large"} size={variant === "compact" ? "compact" : "large"} edgeState={edgeState} onSealEnd={onSealEnd}
onOpen={() => setImageOpen(true)} onError={() => setFailedUrl(attachment.url)} /> onOpen={() => setImageOpen(true)} onError={() => setFailedUrl(attachment.url)} />
<ImageLightbox images={[attachment]} index={imageOpen ? 0 : null} <ImageLightbox images={[attachment]} index={imageOpen ? 0 : null}
onIndexChange={() => {}} onOpenChange={setImageOpen} /> onIndexChange={() => {}} onOpenChange={setImageOpen} />
@@ -46,6 +49,8 @@ export function AttachmentTile({ attachment, className, inline = false, variant
className={className} className={className}
inline={inline} inline={inline}
variant={variant} variant={variant}
edgeState={edgeState}
onSealEnd={onSealEnd}
> >
<video <video
src={videoUrl} src={videoUrl}
@@ -73,7 +78,7 @@ export function AttachmentTile({ attachment, className, inline = false, variant
</a> : undefined; </a> : undefined;
return <span data-file-attachment className={cn("not-prose inline-flex w-24 max-w-full shrink-0 flex-col gap-1 align-top", className)}> return <span data-file-attachment className={cn("not-prose inline-flex w-24 max-w-full shrink-0 flex-col gap-1 align-top", className)}>
<AttachmentCard name={name} description={status} action={download}> <AttachmentCard name={name} description={status} action={download} edgeState={edgeState} onSealEnd={onSealEnd}>
<AttachmentTypeFace name={filePath} kind={attachment.kind} /> <AttachmentTypeFace name={filePath} kind={attachment.kind} />
</AttachmentCard> </AttachmentCard>
{status ? <span className="break-words text-center text-[11px] leading-4 text-muted-foreground">{status}</span> : null} {status ? <span className="break-words text-center text-[11px] leading-4 text-muted-foreground">{status}</span> : null}
@@ -92,16 +97,21 @@ function AttachmentFrame({
className, className,
inline = false, inline = false,
variant = "default", variant = "default",
edgeState = "solid",
onSealEnd,
}: { }: {
attachment: UIMediaAttachment; attachment: UIMediaAttachment;
children: ReactNode; children: ReactNode;
className?: string; className?: string;
inline?: boolean; inline?: boolean;
variant?: "default" | "compact"; variant?: "default" | "compact";
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
}) { }) {
const frameClassName = cn( const frameClassName = cn(
"not-prose my-3 block w-fit max-w-full overflow-hidden rounded-control", "not-prose relative my-3 block w-fit max-w-full overflow-hidden rounded-control",
"border border-border/60 bg-muted/40", edgeState === "solid" && "ring-1 ring-inset ring-border/60",
"bg-muted/40",
attachment.kind === "image" && "bg-background/85", attachment.kind === "image" && "bg-background/85",
attachment.kind === "video" ? "w-[min(100%,32rem)]" : "", attachment.kind === "video" ? "w-[min(100%,32rem)]" : "",
variant === "compact" && "my-1 rounded-xl shadow-none", variant === "compact" && "my-1 rounded-xl shadow-none",
@@ -114,13 +124,16 @@ function AttachmentFrame({
) : ( ) : (
<div className={bodyClassName}>{children}</div> <div className={bodyClassName}>{children}</div>
); );
const edgeOverlay = <PendingEdgeOverlay state={edgeState} solidTone="media" onSealEnd={onSealEnd} />;
return inline ? ( return inline ? (
<span className={frameClassName}> <span className={frameClassName}>
{body} {body}
{edgeOverlay}
</span> </span>
) : ( ) : (
<figure className={frameClassName}> <figure className={frameClassName}>
{body} {body}
{edgeOverlay}
</figure> </figure>
); );
} }
+14 -5
View File
@@ -3,15 +3,18 @@ import { ImageIcon } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ImageLightbox } from "@/components/ImageLightbox"; import { ImageLightbox } from "@/components/ImageLightbox";
import { PendingEdgeOverlay, type PendingEdgeState } from "@/components/PendingEdgeOverlay";
import { IMAGE_GAP, imageFrameRatio, layoutImageRows, type ImageDimensions } from "@/lib/image-gallery-layout"; import { IMAGE_GAP, imageFrameRatio, layoutImageRows, type ImageDimensions } from "@/lib/image-gallery-layout";
import type { UIImage } from "@/lib/types"; import type { UIImage } from "@/lib/types";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
/** A bounded, quiet preview; the viewer still contains every delivered image. */ /** A bounded, quiet preview; the viewer still contains every delivered image. */
export function ImageGallery({ images, align = "left", size = "large" }: { export function ImageGallery({ images, align = "left", size = "large", edgeState = "solid", onSealEnd }: {
images: UIImage[]; images: UIImage[];
align?: "left" | "right"; align?: "left" | "right";
size?: "compact" | "large"; size?: "compact" | "large";
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [index, setIndex] = useState<number | null>(null); const [index, setIndex] = useState<number | null>(null);
@@ -70,7 +73,8 @@ export function ImageGallery({ images, align = "left", size = "large" }: {
const remaining = images.length - visible.length; const remaining = images.length - visible.length;
const overflow = position === visible.length - 1 && remaining > 0; const overflow = position === visible.length - 1 && remaining > 0;
return <ImageThumbnail key={`${image.url ?? image.name}-${position}`} return <ImageThumbnail key={`${image.url ?? image.name}-${position}`}
image={image} size={size} frame={frame} image={image} size={size} frame={frame} edgeState={edgeState}
onSealEnd={position === 0 ? onSealEnd : undefined}
onLoad={(value) => { if (image.url) remember(image.url, value); }} onLoad={(value) => { if (image.url) remember(image.url, value); }}
onError={() => { if (image.url) remember(image.url, null); }} onError={() => { if (image.url) remember(image.url, null); }}
label={overflow ? t("lightbox.viewAll", { count: images.length }) : undefined} label={overflow ? t("lightbox.viewAll", { count: images.length }) : undefined}
@@ -83,9 +87,11 @@ export function ImageGallery({ images, align = "left", size = "large" }: {
</>; </>;
} }
export function ImageThumbnail({ image, size = "large", frame, onOpen, label, overlay, onLoad, onError }: { export function ImageThumbnail({ image, size = "large", frame, onOpen, label, overlay, onLoad, onError, edgeState = "solid", onSealEnd }: {
image: UIImage; image: UIImage;
size?: "compact" | "large"; size?: "compact" | "large";
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
frame?: ImageDimensions & { left: number; top: number }; frame?: ImageDimensions & { left: number; top: number };
onOpen?: () => void; onOpen?: () => void;
label?: string; label?: string;
@@ -96,11 +102,13 @@ export function ImageThumbnail({ image, size = "large", frame, onOpen, label, ov
const { t } = useTranslation(); const { t } = useTranslation();
const [failed, setFailed] = useState(false); const [failed, setFailed] = useState(false);
const classes = cn( const classes = cn(
"relative block max-w-full shrink-0 overflow-hidden rounded-control bg-muted/25 ring-1 ring-inset ring-border/60", "relative block max-w-full shrink-0 overflow-hidden rounded-control bg-muted/25",
edgeState === "solid" && "ring-1 ring-inset ring-border/60",
!frame && (size === "large" ? "w-[min(100%,28rem)]" : "w-48"), !frame && (size === "large" ? "w-[min(100%,28rem)]" : "w-48"),
); );
const style: CSSProperties | undefined = frame ? { ...frame, position: "absolute" } : undefined; const style: CSSProperties | undefined = frame ? { ...frame, position: "absolute" } : undefined;
const unavailable = t("message.attachmentUnavailable"); const unavailable = t("message.attachmentUnavailable");
const edgeOverlay = <PendingEdgeOverlay state={edgeState} solidTone="media" onSealEnd={onSealEnd} />;
const content = image.url && !failed ? <img src={image.url} alt={image.name ?? ""} const content = image.url && !failed ? <img src={image.url} alt={image.name ?? ""}
loading="lazy" decoding="async" draggable={false} loading="lazy" decoding="async" draggable={false}
onLoad={(event) => { onLoad={(event) => {
@@ -114,11 +122,12 @@ export function ImageThumbnail({ image, size = "large", frame, onOpen, label, ov
<ImageIcon className="h-4 w-4 shrink-0" aria-hidden /> <ImageIcon className="h-4 w-4 shrink-0" aria-hidden />
<span className="min-w-0 truncate">{unavailable}</span> <span className="min-w-0 truncate">{unavailable}</span>
</span>; </span>;
if (!onOpen || ((!image.url || failed) && !overlay)) return <span className={classes} style={style}>{content}</span>; if (!onOpen || ((!image.url || failed) && !overlay)) return <span className={classes} style={style}>{content}{edgeOverlay}</span>;
return <button type="button" onClick={onOpen} style={style} return <button type="button" onClick={onOpen} style={style}
aria-label={label ?? (image.name ? `${t("lightbox.open")}: ${image.name}` : t("lightbox.open"))} aria-label={label ?? (image.name ? `${t("lightbox.open")}: ${image.name}` : t("lightbox.open"))}
className={cn(classes, "cursor-zoom-in p-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background")}> className={cn(classes, "cursor-zoom-in p-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background")}>
{content} {content}
{overlay ? <span className="absolute inset-0 flex items-center justify-center bg-black/45 text-xl font-medium text-white" aria-hidden>{overlay}</span> : null} {overlay ? <span className="absolute inset-0 flex items-center justify-center bg-black/45 text-xl font-medium text-white" aria-hidden>{overlay}</span> : null}
{edgeOverlay}
</button>; </button>;
} }
+54 -8
View File
@@ -19,6 +19,7 @@ import { ImageGallery } from "@/components/ImageGallery";
import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext"; import { InlineImageProvider, useInlineImages } from "@/components/InlineImageContext";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight"; import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { MarkdownText } from "@/components/MarkdownText"; import { MarkdownText } from "@/components/MarkdownText";
import { PendingEdgeOverlay, usePendingEdgeState, type PendingEdgeState } from "@/components/PendingEdgeOverlay";
import { SlashCommandText } from "@/components/SlashCommandText"; import { SlashCommandText } from "@/components/SlashCommandText";
import { ReasoningRow } from "@/components/thread/activity/ReasoningRow"; import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";
import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen"; import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";
@@ -424,6 +425,11 @@ export function MessageBubble({
() => mergeMcpMentionPresets(mcpPresets, message.mcpPresets), () => mergeMcpMentionPresets(mcpPresets, message.mcpPresets),
[mcpPresets, message.mcpPresets], [mcpPresets, message.mcpPresets],
); );
const { edgeState, completeSeal } = usePendingEdgeState(
message.id,
message.role === "user" ? message.processingStatus : undefined,
temporary || message.role !== "user",
);
if (message.kind === "compaction" && message.compaction) { if (message.kind === "compaction" && message.compaction) {
return <ContextCompactionNotice compaction={message.compaction} />; return <ContextCompactionNotice compaction={message.compaction} />;
@@ -453,6 +459,15 @@ export function MessageBubble({
const hasText = userContent.trim().length > 0; const hasText = userContent.trim().length > 0;
const showDeliveryStatus = const showDeliveryStatus =
message.deliveryStatus === "sending" || message.deliveryStatus === "failed"; message.deliveryStatus === "sending" || message.deliveryStatus === "failed";
const processingStatus = message.processingStatus;
const showProcessingStatus = !temporary && processingStatus === "pending";
const mediaEdgeState: PendingEdgeState = !hasText ? edgeState : "solid";
const mediaSealEnd = !hasText ? completeSeal : undefined;
const userMedia = hasImages
? <ImageGallery images={images} align="right" size="compact" edgeState={mediaEdgeState} onSealEnd={mediaSealEnd} />
: hasMedia
? <MessageMedia media={media} align="right" pending={message.deliveryStatus === "sending"} edgeState={mediaEdgeState} onSealEnd={mediaSealEnd} />
: null;
const quotedContext = parsedMessage.quotedContext; const quotedContext = parsedMessage.quotedContext;
const slashCommand = matchingSlashCommand(userContent, slashCommands); const slashCommand = matchingSlashCommand(userContent, slashCommands);
const bangPrefix = /^(\s*)!/.exec(userContent); const bangPrefix = /^(\s*)!/.exec(userContent);
@@ -487,10 +502,7 @@ export function MessageBubble({
className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5" className="group relative ml-auto flex w-fit max-w-[min(85%,36rem)] flex-col items-end gap-1.5"
> >
{!hasText ? contextMenu : null} {!hasText ? contextMenu : null}
{hasImages ? <ImageGallery images={images} align="right" size="compact" /> : null} {userMedia}
{!hasImages && hasMedia ? (
<MessageMedia media={media} align="right" pending={message.deliveryStatus === "sending"} />
) : null}
{quotedContext ? ( {quotedContext ? (
<UserQuotedContext <UserQuotedContext
text={quotedContext} text={quotedContext}
@@ -503,18 +515,26 @@ export function MessageBubble({
<p <p
data-theme-surface data-theme-surface
data-temporary-message={temporary ? "true" : undefined} data-temporary-message={temporary ? "true" : undefined}
data-pending-edge={edgeState !== "solid" ? edgeState : undefined}
className={cn( className={cn(
"ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2", "relative ml-auto w-fit max-w-full min-w-0 rounded-floating px-4 py-2",
"text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]", "text-left text-reading whitespace-pre-wrap [overflow-wrap:anywhere]",
temporary temporary
? "border border-dashed border-muted-foreground/40 bg-transparent" ? "border border-dashed border-muted-foreground/40 bg-transparent"
: "user-message-surface bg-secondary/70", : "user-message-surface bg-secondary/70",
showProcessingStatus && "user-message-surface-dashed",
)} )}
> >
<PendingEdgeOverlay state={edgeState} onSealEnd={completeSeal} />
{messageText} {messageText}
</p> </p>
</div> </div>
) : null} ) : null}
{!showDeliveryStatus && showProcessingStatus ? (
<span role="status" className="sr-only">
{t("message.delivery.waiting")}
</span>
) : null}
{showDeliveryStatus ? ( {showDeliveryStatus ? (
<div className="flex min-h-8 items-center justify-end gap-1.5 text-muted-foreground"> <div className="flex min-h-8 items-center justify-end gap-1.5 text-muted-foreground">
<UserDeliveryStatus <UserDeliveryStatus
@@ -657,10 +677,14 @@ function MessageMedia({
media, media,
align, align,
pending = false, pending = false,
edgeState = "solid",
onSealEnd,
}: { }: {
media: UIMediaAttachment[]; media: UIMediaAttachment[];
align: "left" | "right"; align: "left" | "right";
pending?: boolean; pending?: boolean;
edgeState?: PendingEdgeState;
onSealEnd?: () => void;
}) { }) {
const inlineImages = useInlineImages(); const inlineImages = useInlineImages();
if (media.length === 0) return null; if (media.length === 0) return null;
@@ -681,6 +705,9 @@ function MessageMedia({
} }
} }
if (images.length === 0 && videos.length === 0 && files.length === 0) return null; if (images.length === 0 && videos.length === 0 && files.length === 0) return null;
const attachSealToImages = images.length > 0;
const attachSealToVideos = !attachSealToImages && videos.length > 0;
const attachSealToFiles = !attachSealToImages && !attachSealToVideos;
return ( return (
<div <div
@@ -690,15 +717,34 @@ function MessageMedia({
)} )}
> >
{images.length > 0 ? ( {images.length > 0 ? (
<ImageGallery images={images} align={align} size={align === "left" ? "large" : "compact"} /> <ImageGallery
images={images}
align={align}
size={align === "left" ? "large" : "compact"}
edgeState={edgeState}
onSealEnd={attachSealToImages ? onSealEnd : undefined}
/>
) : null} ) : null}
{videos.map((item, i) => ( {videos.map((item, i) => (
<AttachmentTile key={`video-${i}`} attachment={item} pending={pending} className="my-0" /> <AttachmentTile
key={`video-${i}`}
attachment={item}
pending={pending}
edgeState={edgeState}
onSealEnd={attachSealToVideos && i === 0 ? onSealEnd : undefined}
className="my-0"
/>
))} ))}
{files.length > 0 ? ( {files.length > 0 ? (
<div className={cn("flex w-full min-w-0 flex-wrap items-start gap-2", align === "right" && "justify-end")}> <div className={cn("flex w-full min-w-0 flex-wrap items-start gap-2", align === "right" && "justify-end")}>
{files.map((item, i) => ( {files.map((item, i) => (
<AttachmentTile key={`file-${i}`} attachment={item} pending={pending} /> <AttachmentTile
key={`file-${i}`}
attachment={item}
pending={pending}
edgeState={edgeState}
onSealEnd={attachSealToFiles && i === 0 ? onSealEnd : undefined}
/>
))} ))}
</div> </div>
) : null} ) : null}
+103
View File
@@ -0,0 +1,103 @@
import { useCallback, useEffect, useState } from "react";
import type { InputProcessingStatus } from "@/lib/types";
import { cn } from "@/lib/utils";
export type PendingEdgeState = "solid" | "pending" | "sealing";
const SEAL_FALLBACK_MS = 560;
/**
* Tracks the visual edge lifecycle for queued user messages:
* - "pending" while waiting in queue (dashed with subtle breathing)
* - "cancelled" when stopped before consumption (static dashed)
* - "sealing" for a single transition when a live message moves pending -> consumed
* - "solid" at rest (including historical messages loaded as consumed)
*/
export function usePendingEdgeState(
messageId: string,
processingStatus: InputProcessingStatus | undefined,
disabled: boolean,
): { edgeState: PendingEdgeState; completeSeal: () => void } {
const [tracked, setTracked] = useState<{
id: string;
status: InputProcessingStatus | undefined;
sealing: boolean;
}>({
id: messageId,
status: processingStatus,
sealing: false,
});
if (tracked.id !== messageId || tracked.status !== processingStatus) {
const shouldSeal =
!disabled &&
tracked.id === messageId &&
((tracked.status === "pending" && processingStatus === "consumed") ||
(tracked.sealing && processingStatus === undefined));
setTracked({
id: messageId,
status: processingStatus,
sealing: shouldSeal,
});
}
const edgeState: PendingEdgeState = disabled
? "solid"
: processingStatus === "pending"
? "pending"
: tracked.sealing
? "sealing"
: "solid";
const completeSeal = useCallback(() => {
setTracked((prev) => (prev.sealing ? { ...prev, sealing: false } : prev));
}, []);
useEffect(() => {
if (edgeState !== "sealing") return;
const timer = window.setTimeout(completeSeal, SEAL_FALLBACK_MS);
return () => window.clearTimeout(timer);
}, [edgeState, completeSeal]);
return { edgeState, completeSeal };
}
export function PendingEdgeOverlay({
state,
solidTone = "bubble",
inset = "inset-0",
onSealEnd,
}: {
state: PendingEdgeState;
solidTone?: "bubble" | "card" | "media";
inset?: string;
onSealEnd?: () => void;
}) {
if (state === "solid") return null;
return (
<span
aria-hidden="true"
data-pending-edge-overlay={state}
data-solid-tone={solidTone}
className={cn("pending-edge-overlay", inset)}
onAnimationEnd={(event) => {
if (
state === "sealing" &&
(event.animationName === "pending-edge-seal" ||
event.animationName === "pending-edge-fade-out")
) {
onSealEnd?.();
}
}}
>
<span className="pending-edge-layer pending-edge-layer-dashed" />
{state === "sealing" ? (
<>
<span className="pending-edge-layer pending-edge-layer-solid" />
<span className="pending-edge-layer pending-edge-layer-sheen" />
</>
) : null}
</span>
);
}
+192 -1
View File
@@ -84,6 +84,11 @@
inherits: false; inherits: false;
initial-value: transparent; initial-value: transparent;
} }
@property --pending-edge-progress {
syntax: "<percentage>";
inherits: true;
initial-value: -20%;
}
/* Design tokens — HSL form, sourced from shadcn/ui's "neutral" palette. */ /* Design tokens — HSL form, sourced from shadcn/ui's "neutral" palette. */
@layer base { @layer base {
@@ -1237,10 +1242,167 @@
.user-message-surface, .user-message-surface,
.side-panel-surface { .side-panel-surface {
--composer-shadow-color: 240 10% 16%; --composer-shadow-color: 240 10% 16%;
--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12); --surface-depth-shadow: 0 4px 18px -8px hsl(var(--composer-shadow-color) / 0.12);
--tw-shadow: inset 0 0 0 1px hsl(var(--border) / 0.75), var(--surface-depth-shadow);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
} }
.user-message-surface-dashed,
.user-message-surface[data-pending-edge="sealing"] {
--tw-shadow: var(--surface-depth-shadow);
}
.pending-edge-overlay {
--pending-edge-progress: -20%;
--pending-edge-solid-color: hsl(var(--border) / 0.75);
--pending-edge-sheen-color: hsl(var(--foreground) / 0.34);
position: absolute;
z-index: 1;
pointer-events: none;
border-radius: inherit;
corner-shape: inherit;
}
.dark .pending-edge-overlay {
--pending-edge-sheen-color: hsl(var(--foreground) / 0.42);
}
.pending-edge-overlay[data-solid-tone="card"] {
--pending-edge-solid-color: hsl(var(--border) / 0.70);
}
.pending-edge-overlay[data-solid-tone="media"] {
--pending-edge-solid-color: hsl(var(--border) / 0.60);
}
.pending-edge-overlay[data-pending-edge-overlay="sealing"] {
animation: pending-edge-seal 460ms cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
.pending-edge-layer {
position: absolute;
inset: 0;
border-radius: inherit;
corner-shape: inherit;
}
.pending-edge-layer-dashed {
border: 1px dashed hsl(var(--muted-foreground) / 0.30);
}
.pending-edge-overlay[data-pending-edge-overlay="pending"] .pending-edge-layer-dashed {
border-color: hsl(var(--muted-foreground) / 0.58);
animation: pending-edge-breathe 2s ease-in-out infinite;
}
.dark .pending-edge-overlay[data-pending-edge-overlay="pending"] .pending-edge-layer-dashed {
border-color: hsl(var(--muted-foreground) / 0.62);
}
.pending-edge-overlay[data-pending-edge-overlay="sealing"] .pending-edge-layer-dashed {
-webkit-mask-image: linear-gradient(
105deg,
transparent 0%,
transparent calc(var(--pending-edge-progress) - 8%),
#000 calc(var(--pending-edge-progress) + 8%),
#000 100%
);
mask-image: linear-gradient(
105deg,
transparent 0%,
transparent calc(var(--pending-edge-progress) - 8%),
#000 calc(var(--pending-edge-progress) + 8%),
#000 100%
);
}
.pending-edge-layer-solid {
border: 1px solid var(--pending-edge-solid-color);
-webkit-mask-image: linear-gradient(
105deg,
#000 0%,
#000 calc(var(--pending-edge-progress) - 8%),
transparent calc(var(--pending-edge-progress) + 8%),
transparent 100%
);
mask-image: linear-gradient(
105deg,
#000 0%,
#000 calc(var(--pending-edge-progress) - 8%),
transparent calc(var(--pending-edge-progress) + 8%),
transparent 100%
);
}
.pending-edge-layer-sheen {
border: 1px solid var(--pending-edge-sheen-color);
-webkit-mask-image: linear-gradient(
105deg,
transparent calc(var(--pending-edge-progress) - 18%),
#000 var(--pending-edge-progress),
transparent calc(var(--pending-edge-progress) + 18%)
);
mask-image: linear-gradient(
105deg,
transparent calc(var(--pending-edge-progress) - 18%),
#000 var(--pending-edge-progress),
transparent calc(var(--pending-edge-progress) + 18%)
);
animation: pending-edge-sheen-opacity 460ms ease-out forwards;
}
@keyframes pending-edge-breathe {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
@keyframes pending-edge-seal {
from {
--pending-edge-progress: -20%;
}
to {
--pending-edge-progress: 120%;
}
}
@keyframes pending-edge-sheen-opacity {
0% {
opacity: 0;
}
18% {
opacity: 1;
}
78% {
opacity: 0.9;
}
100% {
opacity: 0;
}
}
@keyframes pending-edge-fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@keyframes pending-edge-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.thread-composer-surface { .thread-composer-surface {
transition: var(--theme-paint-transition, background-color 160ms ease-out, box-shadow 160ms ease-out), opacity 160ms ease-out; transition: var(--theme-paint-transition, background-color 160ms ease-out, box-shadow 160ms ease-out), opacity 160ms ease-out;
container-name: thread-composer; container-name: thread-composer;
@@ -1256,10 +1418,39 @@
@media (prefers-reduced-motion: reduce) { @media (prefers-reduced-motion: reduce) {
.thread-composer-surface { transition: var(--theme-paint-transition, none); } .thread-composer-surface { transition: var(--theme-paint-transition, none); }
.pending-edge-overlay[data-pending-edge-overlay="pending"] .pending-edge-layer-dashed {
border-color: hsl(var(--muted-foreground) / 0.30);
animation: none;
}
.pending-edge-overlay[data-pending-edge-overlay="sealing"] { animation: none; }
.pending-edge-overlay[data-pending-edge-overlay="sealing"] .pending-edge-layer-dashed {
-webkit-mask-image: none;
mask-image: none;
animation: pending-edge-fade-out 160ms ease-out forwards;
}
.pending-edge-layer-solid {
-webkit-mask-image: none;
mask-image: none;
animation: pending-edge-fade-in 160ms ease-out forwards;
}
.pending-edge-layer-sheen { display: none; }
} }
@media (forced-colors: active) { @media (forced-colors: active) {
.thread-composer-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; } .thread-composer-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; }
.user-message-surface-dashed { outline-style: dashed; }
.pending-edge-overlay { display: none; }
:has(> .pending-edge-overlay[data-solid-tone="card"][data-pending-edge-overlay="pending"]) {
border-color: CanvasText;
border-style: dashed;
}
.pending-edge-overlay[data-solid-tone="media"][data-pending-edge-overlay="pending"] {
display: block;
& .pending-edge-layer-dashed {
border-color: CanvasText;
animation: none;
}
}
.thread-composer-surface:focus-within { outline: 2px solid Highlight; } .thread-composer-surface:focus-within { outline: 2px solid Highlight; }
[data-keyboard-focus] { outline: 2px solid Highlight; outline-offset: -2px; } [data-keyboard-focus] { outline: 2px solid Highlight; outline-offset: -2px; }
} }
+48 -1
View File
@@ -183,6 +183,12 @@ export function useNanobotStream(
historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 }; historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 };
} }
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialTranscript.messages); const [messages, setRenderedMessages] = useState<UIMessage[]>(initialTranscript.messages);
const [liveInputs, setLiveInputs] = useState<{
chatId: string;
client: typeof client;
waiting: ReadonlySet<string>;
consumed: ReadonlySet<string>;
} | null>(null);
const [execSourceMessages, setExecSourceMessages] = useState<UIMessage[]>(initialTranscript.messages); const [execSourceMessages, setExecSourceMessages] = useState<UIMessage[]>(initialTranscript.messages);
const [modelRequests, setModelRequests] = useState(initialTranscript.modelRequests); const [modelRequests, setModelRequests] = useState(initialTranscript.modelRequests);
const messagesRef = useRef(messages); const messagesRef = useRef(messages);
@@ -686,6 +692,8 @@ export function useNanobotStream(
useEffect(() => { useEffect(() => {
if (!chatId) return; if (!chatId) return;
// A request may start before its acceptance frame reaches this tab.
const startedInputs = new Set<string>();
const handle = (ev: InboundEvent) => { const handle = (ev: InboundEvent) => {
if (ev.event === "error") { if (ev.event === "error") {
if (ev.detail === "message_too_big") { if (ev.detail === "message_too_big") {
@@ -716,6 +724,15 @@ export function useNanobotStream(
if (turnId) { if (turnId) {
setMessages((prev) => transitionTurnDelivery(prev, turnId, "accepted")); setMessages((prev) => transitionTurnDelivery(prev, turnId, "accepted"));
} }
if ((ev.event === "message_accepted" || ev.event === "user_message") && ev.waiting_for_model === true) {
const id = ev.event === "user_message" ? ev.input_id : `user:${ev.turn_id}`;
if (id && !startedInputs.has(id)) {
setLiveInputs((prev) => {
const current = prev?.chatId === chatId && prev.client === client ? prev : null;
return { chatId, client, waiting: new Set([...(current?.waiting ?? []), id]), consumed: new Set() };
});
}
}
if (ev.event === "message_accepted") { if (ev.event === "message_accepted") {
if (ev.media_urls?.length) { if (ev.media_urls?.length) {
setMessages((prev) => prev.map((message) => ( setMessages((prev) => prev.map((message) => (
@@ -732,6 +749,16 @@ export function useNanobotStream(
return; return;
} }
if (ev.event === "model_request") { if (ev.event === "model_request") {
if (ev.phase === "started" && Array.isArray(ev.response_input_ids)) {
const ids = ev.response_input_ids;
ids.forEach((id) => startedInputs.add(id));
setLiveInputs((prev) => {
if (prev?.chatId !== chatId || prev.client !== client) return prev;
const consumed = new Set(ids.filter((id) => prev.waiting.has(id)));
if (!consumed.size) return prev;
return { ...prev, waiting: new Set([...prev.waiting].filter((id) => !consumed.has(id))), consumed };
});
}
flushPendingStreamEvents(); flushPendingStreamEvents();
applyProjectionEvent(ev); applyProjectionEvent(ev);
return; return;
@@ -844,6 +871,9 @@ export function useNanobotStream(
} }
if (ev.event === "turn_end") { if (ev.event === "turn_end") {
if (!sideChannelEvent && (ev.outcome === "cancelled" || ev.outcome === "failed" || ev.outcome === "interrupted")) {
setLiveInputs(null);
}
if (typeof ev.turn_id === "string") transcriptRef.current.sideChannelTurnIds.delete(ev.turn_id); if (typeof ev.turn_id === "string") transcriptRef.current.sideChannelTurnIds.delete(ev.turn_id);
if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") { if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") {
setGoalState(ev.goal_state); setGoalState(ev.goal_state);
@@ -939,9 +969,14 @@ export function useNanobotStream(
} }
}; };
const unsubStatus = client.onStatus((status) => {
if (status !== "open") setLiveInputs(null);
});
const unsub = client.onTranscript(chatId, handle); const unsub = client.onTranscript(chatId, handle);
return () => { return () => {
unsubStatus();
unsub(); unsub();
setLiveInputs(null);
// Navigation may happen before the throttled paint. Snapshot the pending // Navigation may happen before the throttled paint. Snapshot the pending
// deltas synchronously while they still belong to this subscription. // deltas synchronously while they still belong to this subscription.
const pending = pendingStreamEventsRef.current; const pending = pendingStreamEventsRef.current;
@@ -1061,6 +1096,7 @@ export function useNanobotStream(
const stop = useCallback(() => { const stop = useCallback(() => {
if (!chatId) return; if (!chatId) return;
flushPendingStreamEvents(); flushPendingStreamEvents();
setLiveInputs(null);
setRetryStatus(null); setRetryStatus(null);
setMessages((prev) => { setMessages((prev) => {
const settled = prev.map((m) => ({ ...m, isStreaming: false })); const settled = prev.map((m) => ({ ...m, isStreaming: false }));
@@ -1097,8 +1133,19 @@ export function useNanobotStream(
[recoveryAction], [recoveryAction],
); );
const visibleMessages = useMemo(() => {
if (!liveInputs || liveInputs.chatId !== messageScope.chatId || liveInputs.client !== messageScope.client
|| (!liveInputs.waiting.size && !liveInputs.consumed.size)) return messages;
return messages.map((row): UIMessage => {
if (row.role !== "user" || !row.inputId) return row;
if (liveInputs.waiting.has(row.inputId)) return { ...row, processingStatus: "pending" };
if (liveInputs.consumed.has(row.inputId)) return { ...row, processingStatus: "consumed" };
return row;
});
}, [liveInputs, messageScope, messages]);
return { return {
messages, messages: visibleMessages,
execSourceMessages, execSourceMessages,
modelRequests, modelRequests,
messagesKey: messageScope.historyKey ?? messageScope.chatId, messagesKey: messageScope.historyKey ?? messageScope.chatId,
+1
View File
@@ -2364,6 +2364,7 @@
"actions": "Message actions", "actions": "Message actions",
"streaming": "streaming", "streaming": "streaming",
"delivery": { "delivery": {
"waiting": "Waiting to be processed",
"sending": "Sending", "sending": "Sending",
"failed": "Not sent" "failed": "Not sent"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "Acciones del mensaje", "actions": "Acciones del mensaje",
"streaming": "transmitiendo", "streaming": "transmitiendo",
"delivery": { "delivery": {
"waiting": "Pendiente de procesar",
"sending": "Enviando", "sending": "Enviando",
"failed": "No enviado" "failed": "No enviado"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "Actions du message", "actions": "Actions du message",
"streaming": "en cours de génération", "streaming": "en cours de génération",
"delivery": { "delivery": {
"waiting": "En attente de traitement",
"sending": "Envoi", "sending": "Envoi",
"failed": "Non envoyé" "failed": "Non envoyé"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "Tindakan pesan", "actions": "Tindakan pesan",
"streaming": "sedang mengalir", "streaming": "sedang mengalir",
"delivery": { "delivery": {
"waiting": "Menunggu diproses",
"sending": "Mengirim", "sending": "Mengirim",
"failed": "Belum terkirim" "failed": "Belum terkirim"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "メッセージ操作", "actions": "メッセージ操作",
"streaming": "生成中", "streaming": "生成中",
"delivery": { "delivery": {
"waiting": "処理待ち",
"sending": "送信中", "sending": "送信中",
"failed": "未送信" "failed": "未送信"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "메시지 작업", "actions": "메시지 작업",
"streaming": "생성 중", "streaming": "생성 중",
"delivery": { "delivery": {
"waiting": "처리 대기 중",
"sending": "전송 중", "sending": "전송 중",
"failed": "전송되지 않음" "failed": "전송되지 않음"
}, },
+1
View File
@@ -2184,6 +2184,7 @@
"actions": "Ações da mensagem", "actions": "Ações da mensagem",
"streaming": "transmitindo", "streaming": "transmitindo",
"delivery": { "delivery": {
"waiting": "Aguardando processamento",
"sending": "Enviando", "sending": "Enviando",
"failed": "Não enviada" "failed": "Não enviada"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "Thao tác tin nhắn", "actions": "Thao tác tin nhắn",
"streaming": "đang truyền", "streaming": "đang truyền",
"delivery": { "delivery": {
"waiting": "Đang chờ xử lý",
"sending": "Đang gửi", "sending": "Đang gửi",
"failed": "Chưa gửi" "failed": "Chưa gửi"
}, },
+1
View File
@@ -2364,6 +2364,7 @@
"actions": "消息操作", "actions": "消息操作",
"streaming": "流式输出中", "streaming": "流式输出中",
"delivery": { "delivery": {
"waiting": "等待处理",
"sending": "发送中", "sending": "发送中",
"failed": "未发送" "failed": "未发送"
}, },
+1
View File
@@ -2182,6 +2182,7 @@
"actions": "訊息操作", "actions": "訊息操作",
"streaming": "串流輸出中", "streaming": "串流輸出中",
"delivery": { "delivery": {
"waiting": "等待處理",
"sending": "傳送中", "sending": "傳送中",
"failed": "未傳送" "failed": "未傳送"
}, },
+5
View File
@@ -17,6 +17,7 @@ export interface UIContextCompaction extends ContextCompaction {
export type UITurnPhase = "user" | "reasoning" | "activity" | "answer" | "complete"; export type UITurnPhase = "user" | "reasoning" | "activity" | "answer" | "complete";
export type MessageDeliveryStatus = "sending" | "accepted" | "failed"; export type MessageDeliveryStatus = "sending" | "accepted" | "failed";
export type InputProcessingStatus = "pending" | "consumed";
export type MessageDeliveryErrorKind = export type MessageDeliveryErrorKind =
| "message_too_big" | "message_too_big"
| "workspace_scope_rejected" | "workspace_scope_rejected"
@@ -184,6 +185,8 @@ export interface UIMessage {
reasoningStreamId?: string; reasoningStreamId?: string;
/** Ephemeral delivery lifecycle for optimistic user messages. */ /** Ephemeral delivery lifecycle for optimistic user messages. */
deliveryStatus?: MessageDeliveryStatus; deliveryStatus?: MessageDeliveryStatus;
/** Live UI hint; not part of the persisted transcript. */
processingStatus?: InputProcessingStatus;
deliveryErrorKind?: MessageDeliveryErrorKind; deliveryErrorKind?: MessageDeliveryErrorKind;
} }
@@ -1569,6 +1572,7 @@ export type InboundEvent =
event: "message_accepted"; event: "message_accepted";
chat_id: string; chat_id: string;
turn_id: string; turn_id: string;
waiting_for_model?: true;
media_urls?: UIMediaAttachment[]; media_urls?: UIMediaAttachment[];
starts_turn?: boolean; starts_turn?: boolean;
active_turn_id?: string; active_turn_id?: string;
@@ -1578,6 +1582,7 @@ export type InboundEvent =
event: "user_message"; event: "user_message";
chat_id: string; chat_id: string;
text: string; text: string;
waiting_for_model?: true;
turn_id?: string; turn_id?: string;
active_turn_id?: string; active_turn_id?: string;
starts_turn: boolean; starts_turn: boolean;
+85
View File
@@ -376,6 +376,91 @@ describe("MessageBubble", () => {
expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70"); expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70");
}); });
it("seals the dashed edge into a solid border when the agent picks up a waiting message", () => {
const message: UIMessage = {
id: "u-pending",
role: "user",
content: "One more detail",
createdAt: Date.now(),
deliveryStatus: "accepted",
};
const { rerender } = render(<MessageBubble message={message} />);
const bubble = screen.getByText(message.content);
const originalClasses = bubble.className;
rerender(<MessageBubble message={{ ...message, processingStatus: "pending" }} />);
expect(bubble).toHaveClass("user-message-surface-dashed");
expect(bubble).toHaveAttribute("data-pending-edge", "pending");
expect(bubble.querySelector("[data-pending-edge-overlay='pending']")).toBeInTheDocument();
const waitingStatus = screen.getByRole("status");
expect(waitingStatus).toHaveClass("sr-only");
expect(waitingStatus).toHaveTextContent("Waiting to be processed");
rerender(<MessageBubble message={{ ...message, processingStatus: "consumed" }} />);
expect(bubble.className).toBe(originalClasses);
expect(bubble).toHaveAttribute("data-pending-edge", "sealing");
const sealingOverlay = bubble.querySelector("[data-pending-edge-overlay='sealing']");
expect(sealingOverlay).toBeInTheDocument();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
const endEvent = new Event("animationend", { bubbles: true });
Object.defineProperty(endEvent, "animationName", { value: "pending-edge-seal" });
fireEvent(sealingOverlay!, endEvent);
expect(bubble).not.toHaveAttribute("data-pending-edge");
expect(bubble.querySelector("[data-pending-edge-overlay]")).not.toBeInTheDocument();
});
it("does not play the seal transition for already-consumed or cancelled user messages", () => {
const { container, rerender } = render(
<MessageBubble
message={{
id: "u-history-consumed",
role: "user",
content: "Already consumed",
createdAt: Date.now(),
processingStatus: "consumed",
}}
/>,
);
expect(container.querySelector("[data-pending-edge-overlay]")).not.toBeInTheDocument();
const pending: UIMessage = {
id: "u-waiting",
role: "user",
content: "Never picked up",
createdAt: Date.now(),
processingStatus: "pending",
};
rerender(<MessageBubble message={pending} />);
expect(container.querySelector("[data-pending-edge-overlay='pending']")).toBeInTheDocument();
rerender(<MessageBubble message={{ ...pending, processingStatus: undefined }} />);
expect(container.querySelector("[data-pending-edge-overlay]")).not.toBeInTheDocument();
});
it("seals media-only waiting user messages when consumed", () => {
const mediaMessage: UIMessage = {
id: "u-media-pending",
role: "user",
content: "",
createdAt: Date.now(),
processingStatus: "pending",
media: [{ kind: "file", name: "notes.txt", url: "/api/files/notes.txt" }],
};
const { container, rerender } = render(<MessageBubble message={mediaMessage} />);
expect(container.querySelector("[data-pending-edge-overlay='pending']")).toBeInTheDocument();
rerender(<MessageBubble message={{ ...mediaMessage, processingStatus: "consumed" }} />);
const sealingOverlay = container.querySelector("[data-pending-edge-overlay='sealing']");
expect(sealingOverlay).toBeInTheDocument();
const endEvent = new Event("animationend", { bubbles: true });
Object.defineProperty(endEvent, "animationName", { value: "pending-edge-seal" });
fireEvent(sealingOverlay!, endEvent);
expect(container.querySelector("[data-pending-edge-overlay]")).not.toBeInTheDocument();
});
it("renders completed message branches with static wrapper classes", async () => { it("renders completed message branches with static wrapper classes", async () => {
const messages: UIMessage[] = [ const messages: UIMessage[] = [
{ {
+51
View File
@@ -2564,6 +2564,57 @@ describe("useNanobotStream", () => {
]); ]);
}); });
it("ends the live waiting hint only when a request starts for that input", () => {
const fake = fakeClient();
const chat = "chat-processing";
const { result } = renderHook(() => useNanobotStream(chat, EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
const peerInput = (id: string, waiting = false) => fake.emit(chat, {
event: "user_message", chat_id: chat, turn_id: id, input_id: `user:${id}`,
starts_turn: !waiting, text: "identical prompt", ...(waiting ? { waiting_for_model: true } : {}),
});
let sequence = 0;
const request = (id: string, phase: "started" | "completed" = "started") => fake.emit(chat, {
event: "model_request", chat_id: chat, turn_id: "first", request_id: id, run_id: "run",
sequence: ++sequence, phase, response_input_ids: [`user:${id}`],
});
const state = (id: string) => result.current.messages.find((row) => row.inputId === `user:${id}`)?.processingStatus;
act(() => {
peerInput("first");
peerInput("followup", true);
request("first");
request("first", "completed");
});
expect(state("first")).toBeUndefined();
expect(state("followup")).toBe("pending");
act(() => request("followup"));
expect(state("followup")).toBe("consumed");
act(() => {
request("late-echo");
peerInput("late-echo", true);
});
expect(state("late-echo")).toBeUndefined();
});
it.each(["stop", "cancelled by another tab", "disconnect"])("drops the temporary waiting hint on %s", (event) => {
const fake = fakeClient();
const chat = "chat-processing";
const { result } = renderHook(() => useNanobotStream(chat, EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
let turnId = "";
act(() => { turnId = result.current.send("follow-up")!.turnId; });
act(() => fake.emit(chat, {
event: "message_accepted", chat_id: chat, turn_id: turnId, active_turn_id: "active", waiting_for_model: true,
}));
expect(result.current.messages[0]).toMatchObject({ processingStatus: "pending", deliveryStatus: "accepted" });
act(() => {
if (event === "stop") result.current.stop();
else if (event === "disconnect") fake.emitStatus("reconnecting");
else fake.emit(chat, { event: "turn_end", chat_id: chat, turn_id: "active", outcome: "cancelled" });
});
expect(result.current.messages[0]).toMatchObject({ content: "follow-up", deliveryStatus: "accepted" });
expect(result.current.messages[0].processingStatus).toBeUndefined();
});
it("projects a user turn submitted from another attached client exactly once", () => { it("projects a user turn submitted from another attached client exactly once", () => {
const fake = fakeClient(); const fake = fakeClient();
const { result } = renderHook( const { result } = renderHook(