feat(webui): refine composer slash, skill, and mention palettes (#6738)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-20 18:24:19 +08:00
1 parent cd75dbfaac
commit 16e573fe18
9 files changed
+993 -534

No files matched your search

+42 -6
View File
@@ -4,7 +4,7 @@ import { MessageBubble } from "@/components/MessageBubble";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import type { ChatSummary, CliAppInfo, McpPresetInfo, SlashCommand, UIMessage } from "@/lib/types";
import type { ChatSummary, CliAppInfo, McpPresetInfo, SkillSummary, SlashCommand, UIMessage } from "@/lib/types";
const session: ChatSummary = {
key: "websocket:typography", channel: "websocket", chatId: "typography",
@@ -28,10 +28,46 @@ const linearPreset: McpPresetInfo = {
connection_summary: "", logo_url: logo,
};
const mcpPresets = [linearPreset, { ...linearPreset, name: "adobe-express-docs", display_name: "Adobe Express Developer" }];
const commands: SlashCommand[] = [{
command: "/goal", title: "Start a goal", description: "Start a sustained goal.",
icon: "activity", lifecycle: "agent_turn_with_args", acceptsArgs: true,
}];
const commands: SlashCommand[] = [
{
command: "/goal", title: "Start a goal", description: "Start a sustained goal.",
icon: "activity", lifecycle: "agent_turn_with_args", acceptsArgs: true,
},
{
command: "/compact", title: "Compact context", description: "Compact context and continue chatting.",
icon: "archive", lifecycle: "finalize_active_turn", acceptsArgs: false,
},
{
command: "/model", title: "Model", description: "View or switch the current model preset.",
icon: "brain", argHint: "[preset]", lifecycle: "side_channel", acceptsArgs: true,
},
{
command: "/status", title: "Show status", description: "Check runtime, provider, and channel status.",
icon: "activity", lifecycle: "side_channel", acceptsArgs: false,
},
{
command: "/pairing", title: "Pairing", description: "Manage pairing requests.",
icon: "shield", argHint: "[list|approve <code>|deny <code>|revoke <user_id>]",
lifecycle: "side_channel", acceptsArgs: true,
},
];
const skills: SkillSummary[] = [
{
name: "frontend-design",
description: "Build polished interfaces with balanced typography, motion, and responsive layout across light and dark themes.",
source: "workspace", enabled: true, available: true,
},
{
name: "nanobot-document",
description: "Look up nanobot configuration, architecture, and troubleshooting guides.",
source: "builtin", enabled: true, available: true,
},
{
name: "skill-creator",
description: "Create or update reusable AgentSkills in the workspace.",
source: "builtin", enabled: true, available: true,
},
];
const answer: UIMessage = {
id: "reference-answer", role: "assistant", createdAt: 1,
content: "[相关会话](#session/websocket%3Atypography) · [外部文档](https://example.com/reference)",
@@ -44,7 +80,7 @@ export function InlineReferencesFixture() {
return <ThemeProvider theme={theme}>
<main className="mx-auto h-full max-w-[var(--content-column-width)] space-y-6 overflow-y-auto p-4">
{[answer, ...sent].map(message => <MessageBubble key={message.id} message={message} slashCommands={commands} />)}
<ThreadComposer compactWhenIdle sessions={[session, longSession]} cliApps={cliApps} mcpPresets={mcpPresets} modelLabel="Fixture" persistDraft={false} slashCommands={commands}
<ThreadComposer compactWhenIdle sessions={[session, longSession]} cliApps={cliApps} mcpPresets={mcpPresets} modelLabel="Fixture" persistDraft={false} slashCommands={commands} skills={skills}
onSend={(text, _media, options) => setSent(current => [...current, {
id: `sent-${current.length}`, role: "user", content: text, createdAt: current.length + 2,
}, ...(options?.userShell ? [{
+46
View File
@@ -157,6 +157,52 @@ for (const narrow of [false, true]) {
await expectMatchingInputLayers(input);
});
test(`slash and skill palettes match composer width with split preview on desktop: ${narrow ? "narrow" : "desktop"}, ${theme}`, async ({ page }, info) => {
await page.setViewportSize(narrow ? { width: 320, height: 844 } : { width: 1440, height: 1000 });
await page.addInitScript(theme => {
localStorage.setItem("nanobot.locale", "en");
localStorage.setItem("nanobot-webui.theme", theme);
}, theme);
await page.goto("/browser/fixture.html?case=inline-references");
const input = page.getByRole("textbox", { name: "Message input", exact: true });
const surface = page.locator(".thread-composer-surface");
const settledBox = async (locator: Locator) => {
await locator.evaluate(async (node) => {
await Promise.all(node.getAnimations().map((animation) => animation.finished.catch(() => {})));
});
return (await locator.boundingBox())!;
};
await input.fill("/");
const slashPalette = page.getByRole("listbox", { name: "Slash commands" });
await expect(slashPalette).toBeVisible();
const slashBox = await settledBox(slashPalette);
const surfaceBox = (await surface.boundingBox())!;
expect(Math.abs(slashBox.x - surfaceBox.x)).toBeLessThanOrEqual(2);
expect(Math.abs(slashBox.width - surfaceBox.width)).toBeLessThanOrEqual(2);
const slashPreview = slashPalette.locator("[data-palette-preview]");
if (narrow) await expect(slashPreview).toBeHidden();
else await expect(slashPreview).toBeVisible();
expect(await slashPalette.evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true);
expect(await slashPalette.locator(":scope > div").first().evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true);
await page.screenshot({ path: info.outputPath("slash-palette.png") });
await input.fill("$");
const skillPalette = page.getByRole("listbox", { name: "Skills" });
await expect(skillPalette).toBeVisible();
await expect(skillPalette.getByRole("group", { name: "Custom" })).toBeVisible();
await expect(skillPalette.getByRole("group", { name: "Built-in" })).toBeVisible();
const skillBox = await settledBox(skillPalette);
expect(Math.abs(skillBox.x - surfaceBox.x)).toBeLessThanOrEqual(2);
expect(Math.abs(skillBox.width - surfaceBox.width)).toBeLessThanOrEqual(2);
const skillPreview = skillPalette.locator("[data-palette-preview]");
if (narrow) await expect(skillPreview).toBeHidden();
else await expect(skillPreview).toBeVisible();
expect(await skillPalette.evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true);
expect(await skillPalette.locator(":scope > div").first().evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true);
await page.screenshot({ path: info.outputPath("skill-palette.png") });
});
test(`inline references preserve native editing: ${narrow ? "narrow" : "desktop"}, ${theme}`, async ({ page }, info) => {
await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1440, height: 1000 });
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
@@ -0,0 +1,646 @@
import { useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import type { TFunction } from "i18next";
import { ChevronRight, type LucideIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
ActivityIcon, ArchiveIcon, CompactIcon, DreamIcon, DreamLogIcon, EditIcon,
GoalIcon, HelpIcon, HistoryIcon, MemoryIcon, ModelsIcon, NewChatIcon,
PairingIcon, PromptTemplateIcon, RestartIcon, RestoreMemoryIcon,
RestrictedAccessIcon, SkillsIcon, StatusIcon, StopIcon, ToolRunIcon, TriggerIcon,
} from "@/components/icons/product-icons";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
import {
floatingItemClassName,
floatingItemFocusClassName,
floatingSurfaceElevationClassName,
} from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { logoFallbackUrls } from "@/lib/provider-brand";
import { sessionHandleColor } from "@/lib/session-handle";
import type { SessionMention } from "@/lib/types";
import { cn } from "@/lib/utils";
const PALETTE_CHROME_PX = 12;
const COMMAND_ICONS: Record<string, LucideIcon> = {
activity: ActivityIcon, archive: ArchiveIcon, "book-open": SkillsIcon,
brain: MemoryIcon, "circle-help": HelpIcon, history: HistoryIcon,
"rotate-cw": RestartIcon, shield: RestrictedAccessIcon, sparkles: DreamIcon,
square: StopIcon, "square-pen": EditIcon, "undo-2": RestoreMemoryIcon,
zap: TriggerIcon, "file-text": PromptTemplateIcon, wrench: ToolRunIcon,
};
const BUILTIN_COMMAND_ICONS: Record<string, LucideIcon> = {
"/new": NewChatIcon, "/compact": CompactIcon, "/stop": StopIcon,
"/restart": RestartIcon, "/status": StatusIcon, "/model": ModelsIcon,
"/goal": GoalIcon, "/trigger": TriggerIcon,
"/dream": DreamIcon, "/dream-log": DreamLogIcon, "/dream-restore": RestoreMemoryIcon,
"/dream-prompt": PromptTemplateIcon, "/evaluator-prompt": PromptTemplateIcon,
"/skill": SkillsIcon, "/help": HelpIcon, "/pairing": PairingIcon,
};
export type SlashPalettePlacement = "above" | "below" | "beside";
export interface SlashPaletteLayout { placement: SlashPalettePlacement; maxHeight: number; }
export type SkillSourceBucket = "workspace" | "builtin" | "other";
export interface SlashPaletteCommand {
command: string;
title: string;
description: string;
icon: string;
argHint?: string;
detail: string;
badge?: string;
recent: boolean;
}
export interface SkillPaletteItem {
name: string;
command: string;
description: string;
source: string;
recent: boolean;
}
export type MentionCandidate = { name: string; displayName: string } & (
| { kind: "session"; mention: SessionMention }
| { kind: "cli" | "mcp"; brandColor: string | null; logoUrl: string | null; initials: string }
);
const SKILL_SOURCE_META: Record<SkillSourceBucket, { sourceKey: string; groupKey: string; fallback: string }> = {
workspace: { sourceKey: "settings.skills.sourceWorkspace", groupKey: "settings.skills.customGroup", fallback: "Custom" },
builtin: { sourceKey: "settings.skills.sourceBuiltin", groupKey: "settings.skills.builtinGroup", fallback: "Built-in" },
other: { sourceKey: "settings.skills.otherGroup", groupKey: "settings.skills.otherGroup", fallback: "Other" },
};
const groupHeaderClass = "px-2.5 pb-1 pt-1 text-[11px] font-medium tracking-normal text-muted-foreground/75";
const badgeClass =
"inline-flex shrink-0 items-center rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[10.5px] font-medium leading-none text-muted-foreground dark:bg-white/[0.08]";
export function slashCommandI18nKey(command: string): string {
return command.replace(/^\//, "").replace(/-/g, "_");
}
export function skillSourceBucket(source: string): SkillSourceBucket {
return source === "workspace" || source === "builtin" ? source : "other";
}
function skillBucketText(sourceOrBucket: string, kind: "sourceKey" | "groupKey", t: TFunction): string {
const meta = SKILL_SOURCE_META[skillSourceBucket(sourceOrBucket)];
return t(meta[kind], { defaultValue: meta.fallback });
}
function resolveSlashCommand(command: SlashPaletteCommand, t: TFunction) {
const key = slashCommandI18nKey(command.command);
const title = t(`thread.composer.slash.commands.${key}.title`, { defaultValue: command.title });
const description = t(`thread.composer.slash.commands.${key}.description`, { defaultValue: command.description });
const detail = command.detail || description;
return {
Icon: BUILTIN_COMMAND_ICONS[command.command] ?? COMMAND_ICONS[command.icon] ?? HelpIcon,
title,
description,
detail,
showDetail: Boolean(detail && detail !== title),
hasLiveDetail: Boolean(command.detail && command.detail !== description),
badgeLabel: command.badge ?? (command.recent ? t("thread.composer.slash.badges.recent") : null),
commandLabel: command.argHint ? `${command.command} ${command.argHint}` : command.command,
};
}
function HighlightedText({ text, query }: { text: string; query: string }) {
if (!query) return text;
const index = text.toLowerCase().indexOf(query);
if (index < 0) return text;
return (
<>
{text.slice(0, index)}
<mark className="rounded-[3px] bg-foreground/[0.09] text-inherit dark:bg-white/[0.15]">
{text.slice(index, index + query.length)}
</mark>
{text.slice(index + query.length)}
</>
);
}
function SelectionChevron({ selected, className }: { selected: boolean; className?: string }) {
return (
<ChevronRight
aria-hidden
className={cn(
"hidden h-3.5 w-3.5 shrink-0 text-muted-foreground/50 transition-opacity duration-100 sm:block",
selected ? "opacity-100" : "opacity-0",
className,
)}
/>
);
}
function PaletteKeyHint({ text }: { text: string }) {
const separator = text.indexOf(" ");
if (separator < 0) return <span className="text-[11px] text-muted-foreground/70">{text}</span>;
return (
<span className="inline-flex items-center gap-1.5 text-[11px] text-muted-foreground/70">
<kbd className="rounded-[5px] border border-border/75 bg-background/90 px-1.5 py-[1px] font-sans text-[10px] font-medium leading-4 text-foreground/75 shadow-[0_1px_0_rgba(15,23,42,0.06)] dark:border-white/[0.10] dark:bg-white/[0.06] dark:shadow-none">
{text.slice(0, separator)}
</kbd>
<span>{text.slice(separator + 1)}</span>
</span>
);
}
function PalettePreviewShell({
itemKey,
icon,
header,
alignIcon = "center",
children,
}: {
itemKey: string;
icon: ReactNode;
header: ReactNode;
alignIcon?: "center" | "start";
children: ReactNode;
}) {
const { t } = useTranslation();
return (
<>
<div
key={itemKey}
className="composer-palette-preview-body inset-scrollbar min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain px-5 py-4"
>
<div className={cn("flex gap-3", alignIcon === "start" ? "items-start" : "items-center")}>
<span className={cn(
"flex h-9 w-9 shrink-0 items-center justify-center rounded-control bg-background text-foreground ring-1 ring-border/70 shadow-[0_1px_2px_rgba(15,23,42,0.05)] dark:bg-white/[0.06] dark:ring-white/[0.09] dark:shadow-none",
alignIcon === "start" && "mt-0.5",
)}>
{icon}
</span>
<div className="min-w-0 flex-1">{header}</div>
</div>
{children}
</div>
<div className="flex shrink-0 flex-wrap items-center gap-x-4 gap-y-1 border-t border-border/45 px-5 py-2.5 dark:border-white/[0.06]">
<PaletteKeyHint text={t("thread.composer.slash.navigateHint")} />
<PaletteKeyHint text={t("thread.composer.slash.selectHint")} />
<PaletteKeyHint text={t("thread.composer.slash.closeHint")} />
</div>
</>
);
}
function PaletteOption({
index,
selected,
ariaLabel,
className,
onHover,
onChoose,
children,
}: {
index: number;
selected: boolean;
ariaLabel: string;
className: string;
onHover: (index: number) => void;
onChoose: () => void;
children: ReactNode;
}) {
return (
<button
type="button"
role="option"
data-palette-index={index}
aria-selected={selected}
aria-label={ariaLabel}
onMouseEnter={() => onHover(index)}
onMouseDown={(e) => {
e.preventDefault();
onChoose();
}}
className={cn(
floatingItemClassName,
floatingItemFocusClassName,
"flex w-full min-w-0 overflow-hidden px-2.5 text-left transition-colors duration-100",
selected
? "bg-foreground/[0.06] text-foreground dark:bg-black/[0.16]"
: "text-foreground/90 hover:bg-foreground/[0.04] dark:hover:bg-black/[0.10]",
className,
)}
>
{children}
</button>
);
}
function ComposerPaletteSurface({
ariaLabel,
layout,
isHero,
selectedIndex,
preview,
children,
}: {
ariaLabel: string;
layout: SlashPaletteLayout;
isHero: boolean;
selectedIndex: number;
preview?: ReactNode;
children: ReactNode;
}) {
const showSplitPreview = Boolean(preview) && layout.placement !== "beside";
const listMaxHeight = Math.max(0, showSplitPreview ? layout.maxHeight : layout.maxHeight - PALETTE_CHROME_PX);
const listRef = useRef<HTMLDivElement | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
useLayoutEffect(() => {
const option = listRef.current?.querySelector<HTMLElement>(`[data-palette-index="${selectedIndex}"]`);
if (typeof option?.scrollIntoView === "function") option.scrollIntoView({ block: "nearest" });
}, [selectedIndex]);
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={ariaLabel}
data-placement={layout.placement}
style={{ maxHeight: layout.maxHeight }}
className={cn(
floatingSurfaceElevationClassName,
"composer-palette-surface z-30 overflow-hidden rounded-floating ring-1 ring-border/75 dark:ring-white/[0.08]",
"shadow-[0_12px_36px_-8px_rgba(15,23,42,0.12),0_2px_10px_-2px_rgba(15,23,42,0.06)] dark:shadow-[0_16px_40px_-6px_rgba(0,0,0,0.44)]",
showSplitPreview
? "grid grid-cols-1 p-0 sm:grid-cols-[minmax(0,16.5rem)_minmax(0,1fr)] md:grid-cols-[minmax(0,18.5rem)_minmax(0,1fr)]"
: "p-1.5",
layout.placement === "beside"
? "relative col-start-2 row-start-1 w-full"
: cn(
"absolute inset-x-0 mx-auto",
layout.placement === "above" ? "bottom-full mb-2" : "top-full mt-2",
isHero
? "w-full max-w-[var(--composer-content-width,58rem)]"
: "w-[calc(100%-0.5rem)] max-w-[var(--composer-content-width,49.5rem)] sm:w-full",
),
)}
>
<div
ref={listRef}
className={cn(
"inset-scrollbar min-w-0 overflow-x-hidden overflow-y-auto overscroll-contain",
showSplitPreview && "p-1.5",
)}
style={{ maxHeight: listMaxHeight }}
>
{children}
</div>
{showSplitPreview ? (
<div
aria-hidden
data-palette-preview
style={{ maxHeight: layout.maxHeight }}
className="hidden min-w-0 flex-col overflow-hidden border-l border-border/55 bg-muted/[0.32] sm:flex dark:border-white/[0.06] dark:bg-black/[0.16]"
>
{preview}
</div>
) : null}
</div>
);
}
interface SharedPaletteProps<T> {
query: string;
selectedIndex: number;
layout: SlashPaletteLayout;
isHero: boolean;
onHover: (index: number) => void;
onChoose: (item: T) => void;
}
export function SlashCommandPalette({
commands,
query,
selectedIndex,
layout,
isHero,
onHover,
onChoose,
}: SharedPaletteProps<SlashPaletteCommand> & { commands: SlashPaletteCommand[] }) {
const { t } = useTranslation();
const groupLabel = t("thread.composer.slash.ariaLabel");
const resolved = commands.map((command) => ({ command, ...resolveSlashCommand(command, t) }));
const active = resolved[selectedIndex] ?? resolved[0];
const activePreview = active ? (
<PalettePreviewShell
itemKey={active.command.command}
icon={<active.Icon className="h-[18px] w-[18px]" />}
header={<div className="truncate text-[14px] font-semibold leading-snug text-foreground">{active.title}</div>}
>
<div className="mt-3">
<code className="inline-block max-w-full break-words rounded-compact bg-foreground/[0.045] px-2.5 py-1.5 font-mono text-[12px] font-medium leading-relaxed text-foreground/90 dark:bg-white/[0.065]">
<HighlightedText text={active.commandLabel} query={query} />
</code>
</div>
{active.description ? (
<p className="mt-2.5 break-words text-[13px] leading-[1.6] text-muted-foreground">
<HighlightedText text={active.description} query={query} />
</p>
) : null}
{active.hasLiveDetail ? (
<div className="mt-3 flex min-w-0 items-center gap-2 rounded-compact bg-background/85 px-3 py-2 ring-1 ring-border/60 dark:bg-white/[0.045] dark:ring-white/[0.08]">
<span
className={cn(
"h-1.5 w-1.5 shrink-0 rounded-full",
active.command.command === "/stop"
? "bg-amber-500"
: active.command.command === "/model" || active.command.badge
? "bg-emerald-500"
: "bg-foreground/45",
)}
/>
<span className="min-w-0 break-words font-mono text-[12px] font-medium text-foreground/90">
{active.command.detail}
</span>
</div>
) : null}
</PalettePreviewShell>
) : null;
return (
<ComposerPaletteSurface
ariaLabel={groupLabel}
layout={layout}
isHero={isHero}
selectedIndex={selectedIndex}
preview={activePreview}
>
<div role="group" aria-label={groupLabel}>
<div className={groupHeaderClass}>{groupLabel}</div>
{resolved.map(({ command, Icon, title, detail, showDetail, badgeLabel, commandLabel }, index) => {
const selected = index === selectedIndex;
const ariaLabel = [commandLabel, title, showDetail ? detail : null, badgeLabel].filter(Boolean).join(" ");
return (
<PaletteOption
key={command.command}
index={index}
selected={selected}
ariaLabel={ariaLabel}
onHover={onHover}
onChoose={() => onChoose(command)}
className="min-h-[40px] items-start gap-2.5 py-2 sm:min-h-[38px] sm:items-center sm:py-1.5"
>
<span
aria-hidden
className={cn(
"mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors sm:mt-0",
selected
? "bg-foreground/[0.08] text-foreground dark:bg-white/[0.11]"
: "bg-foreground/[0.04] text-muted-foreground dark:bg-white/[0.055]",
)}
>
<Icon className="h-3.5 w-3.5" />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="flex min-w-0 items-baseline gap-2">
<span className={cn("min-w-0 truncate font-mono text-[13px] tracking-tight text-foreground", selected ? "font-semibold" : "font-medium")}>
<HighlightedText text={command.command} query={query} />
</span>
<span className="max-w-[46%] shrink-0 truncate text-[12px] text-muted-foreground/80">
<HighlightedText text={title} query={query} />
</span>
</span>
{showDetail ? (
<span className="min-w-0 truncate text-[12px] leading-[1.4] text-muted-foreground sm:hidden">
<HighlightedText text={detail} query={query} />
</span>
) : null}
</span>
{badgeLabel ? (
<span className={cn(badgeClass, "ml-auto mt-0.5 sm:mt-0")}>{badgeLabel}</span>
) : (
<SelectionChevron selected={selected} className="ml-auto" />
)}
</PaletteOption>
);
})}
</div>
</ComposerPaletteSurface>
);
}
interface SkillGroup {
key: string;
label: string;
showRecentPill: boolean;
showSourceLabel: boolean;
items: Array<{ skill: SkillPaletteItem; index: number }>;
}
export function SkillPalette({
skills,
query,
selectedIndex,
layout,
isHero,
onHover,
onChoose,
}: SharedPaletteProps<SkillPaletteItem> & { skills: SkillPaletteItem[] }) {
const { t } = useTranslation();
const ariaLabel = t("settings.skills.featured", { defaultValue: "Skills" });
const activeSkill = skills[selectedIndex] ?? skills[0];
const groups = useMemo<SkillGroup[]>(() => {
const indexed = skills.map((skill, index) => ({ skill, index }));
const hasMultipleSources = new Set(skills.map((skill) => skillSourceBucket(skill.source))).size > 1;
if (query !== "" || !hasMultipleSources) {
return [{ key: "skills", label: ariaLabel, showRecentPill: true, showSourceLabel: hasMultipleSources, items: indexed }];
}
const recentItems = indexed.filter(({ skill }) => skill.recent);
const remaining = indexed.filter(({ skill }) => !skill.recent);
return [
...(recentItems.length
? [{ key: "recent", label: t("thread.composer.slash.badges.recent"), showRecentPill: false, showSourceLabel: true, items: recentItems }]
: []),
...(["workspace", "builtin", "other"] as const).flatMap((bucket) => {
const items = remaining.filter(({ skill }) => skillSourceBucket(skill.source) === bucket);
return items.length
? [{ key: bucket, label: skillBucketText(bucket, "groupKey", t), showRecentPill: false, showSourceLabel: false, items }]
: [];
}),
];
}, [ariaLabel, query, skills, t]);
const activePreview = activeSkill ? (
<PalettePreviewShell
itemKey={activeSkill.command}
alignIcon="start"
icon={<SkillsIcon className="h-[18px] w-[18px]" style={{ color: INLINE_REFERENCE_HIGHLIGHT_COLOR }} />}
header={
<div className="flex flex-col gap-1.5">
<div className="break-words font-mono text-[14px] font-semibold leading-snug tracking-tight text-foreground [overflow-wrap:anywhere]">
<span className="select-none font-normal opacity-90" style={{ color: INLINE_REFERENCE_HIGHLIGHT_COLOR }}>$</span>
<HighlightedText text={activeSkill.name} query={query} />
</div>
<span className="inline-flex w-fit items-center rounded-full bg-foreground/[0.055] px-2 py-0.5 text-[11px] font-medium leading-none text-muted-foreground dark:bg-white/[0.08]">
{skillBucketText(activeSkill.source, "sourceKey", t)}
</span>
</div>
}
>
{activeSkill.description && activeSkill.description !== activeSkill.name ? (
<p className="mt-3.5 break-words text-[13px] leading-[1.65] text-foreground/80">
<HighlightedText text={activeSkill.description} query={query} />
</p>
) : null}
</PalettePreviewShell>
) : null;
return (
<ComposerPaletteSurface
ariaLabel={ariaLabel}
layout={layout}
isHero={isHero}
selectedIndex={selectedIndex}
preview={activePreview}
>
{groups.map((group) => (
<div key={group.key} role="group" aria-label={group.label} className="mt-1.5 first:mt-0">
<div className={groupHeaderClass}>{group.label}</div>
{group.items.map(({ skill, index }) => {
const selected = index === selectedIndex;
const showDescription = Boolean(skill.description && skill.description !== skill.name);
const recentLabel = group.showRecentPill && skill.recent ? t("thread.composer.slash.badges.recent") : null;
const sourceText = group.showSourceLabel ? skillBucketText(skill.source, "sourceKey", t) : null;
const optionAriaLabel = [skill.name, showDescription ? skill.description : null, recentLabel ?? sourceText].filter(Boolean).join(" ");
return (
<PaletteOption
key={skill.command}
index={index}
selected={selected}
ariaLabel={optionAriaLabel}
onHover={onHover}
onChoose={() => onChoose(skill)}
className="min-h-[40px] flex-col items-stretch gap-0.5 py-2 sm:min-h-[36px] sm:py-1.5"
>
<span className="flex w-full min-w-0 items-center gap-2">
<span className={cn("flex min-w-0 flex-1 items-baseline font-mono text-[13px] tracking-tight text-foreground", selected ? "font-semibold" : "font-medium")}>
<span aria-hidden className="select-none font-normal opacity-90" style={{ color: INLINE_REFERENCE_HIGHLIGHT_COLOR }}>$</span>
<span data-palette-skill-name className="min-w-0 break-words [overflow-wrap:anywhere]">
<HighlightedText text={skill.name} query={query} />
</span>
</span>
{recentLabel ? (
<span className={badgeClass}>{recentLabel}</span>
) : sourceText ? (
<span className="shrink-0 text-[11px] font-normal text-muted-foreground/70">{sourceText}</span>
) : (
<SelectionChevron selected={selected} />
)}
</span>
{showDescription ? (
<span className="line-clamp-2 w-full break-words text-[12px] leading-[1.45] text-muted-foreground sm:hidden">
<HighlightedText text={skill.description} query={query} />
</span>
) : null}
</PaletteOption>
);
})}
</div>
))}
</ComposerPaletteSurface>
);
}
export function CliAppMentionPalette({
candidates,
query,
selectedIndex,
layout,
isHero,
onHover,
onChoose,
}: SharedPaletteProps<MentionCandidate> & { candidates: MentionCandidate[] }) {
const { t } = useTranslation();
const groupedCandidates = (["session", "cli", "mcp"] as const)
.map((kind) => ({
kind,
label: t(`thread.composer.mentions.${kind}Group`),
items: candidates.map((candidate, index) => ({ candidate, index })).filter(({ candidate }) => candidate.kind === kind),
}))
.filter((group) => group.items.length > 0);
return (
<ComposerPaletteSurface
ariaLabel={t("thread.composer.mentions.ariaLabel")}
layout={layout}
isHero={isHero}
selectedIndex={selectedIndex}
>
{groupedCandidates.map((group) => (
<div key={group.kind} role="group" aria-label={group.label} className="mt-1.5 first:mt-0">
<div className={groupHeaderClass}>{group.label}</div>
{group.items.map(({ candidate, index }) => {
const selected = index === selectedIndex;
const { name, kind } = candidate;
const handleColor = kind === "session"
? candidate.mention.id ? sessionHandleColor(candidate.mention.id) : INLINE_TOKEN_HIGHLIGHT_COLOR
: undefined;
const typeLabel = t(`thread.composer.mentions.${kind}Badge`);
const ariaDescription = t(`thread.composer.mentions.${kind}Description`, { name });
return (
<PaletteOption
key={`${kind}-${name}`}
index={index}
selected={selected}
ariaLabel={`@${name} ${candidate.displayName} ${ariaDescription} ${typeLabel}`}
onHover={onHover}
onChoose={() => onChoose(candidate)}
className="touch-target min-h-10 flex-wrap items-center gap-x-2.5 gap-y-1 py-1.5"
>
<span className="max-w-full shrink-0 truncate text-[13.5px] font-normal tracking-normal text-muted-foreground/75" style={{ color: handleColor }}>
@<HighlightedText text={name} query={query} />
</span>
<span className={cn("flex max-w-full flex-1 flex-wrap items-center gap-x-2 gap-y-1", kind === "session" ? "min-w-[min(4rem,100%)]" : "min-w-[min(8rem,100%)]")}>
{kind !== "session" ? <MentionCandidateLogo candidate={candidate} selected={selected} /> : null}
<span className="min-w-[min(4rem,100%)] flex-1 truncate text-[13.5px] font-medium tracking-normal text-foreground">
<HighlightedText text={candidate.displayName} query={query} />
</span>
{kind !== "session" ? (
<span className={cn("ml-auto shrink-0 rounded-full px-1.5 py-0.5 text-[10.5px] font-semibold leading-none tracking-normal", kind === "cli" ? "bg-orange-500/10 text-orange-600 dark:text-orange-300" : "bg-sky-500/10 text-sky-600 dark:text-sky-300")}>
{typeLabel}
</span>
) : null}
</span>
</PaletteOption>
);
})}
</div>
))}
</ComposerPaletteSurface>
);
}
function MentionCandidateLogo({
candidate,
selected,
}: {
candidate: Extract<MentionCandidate, { kind: "cli" | "mcp" }>;
selected: boolean;
}) {
const logoUrls = useMemo(() => logoFallbackUrls(candidate.logoUrl), [candidate.logoUrl]);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
if (logoUrl) {
return (
<span className={cn("flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-compact", selected ? "bg-background/55" : "bg-transparent")}>
<img src={logoUrl} alt="" decoding="async" loading="lazy" className="h-5 w-5 object-contain" onLoad={onLogoLoad} onError={onLogoError} />
</span>
);
}
return (
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-compact text-[7.5px] font-semibold text-white" style={{ backgroundColor: candidate.brandColor || INLINE_TOKEN_HIGHLIGHT_COLOR }}>
{candidate.initials}
</span>
);
}
+167 -497
View File
@@ -1,29 +1,9 @@
import type { ModelOptionsControlProps } from "@/components/thread/ModelOptionsControl";
import { pastedFilePath, PastedPathRange, type LocalAttachment } from "../../../../packages/client-events/attachments";
import {
NewChatIcon,
CompactIcon,
StatusIcon,
ModelsIcon,
TriggerIcon,
DreamLogIcon,
PromptTemplateIcon,
PairingIcon,
ToolRunIcon,
ActivityIcon,
ArchiveIcon,
SkillsIcon,
MemoryIcon,
HelpIcon,
HistoryIcon,
AttachIcon,
RestartIcon,
RestrictedAccessIcon,
DreamIcon,
StopIcon,
EditIcon,
GoalIcon,
RestoreMemoryIcon,
} from "@/components/icons/product-icons";
import {
useCallback,
@@ -54,7 +34,7 @@ import {
isCapabilityMentionStart,
type CapabilityMentionSegment,
} from "@/lib/composer-mention-text";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, INLINE_TOKEN_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { SlashCommandText } from "@/components/SlashCommandText";
import {
CornerDownRight,
@@ -64,7 +44,6 @@ import {
Quote,
Trash2,
X,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -73,10 +52,17 @@ import { useToast } from "@/components/ui/toast";
import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard";
import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon";
import {
floatingItemClassName,
floatingItemFocusClassName,
floatingSurfaceVisualClassName,
} from "@/components/ui/floating-surface";
CliAppMentionPalette,
SkillPalette,
SlashCommandPalette,
skillSourceBucket,
slashCommandI18nKey,
type MentionCandidate,
type SkillPaletteItem,
type SlashPaletteCommand,
type SlashPaletteLayout,
type SlashPalettePlacement,
} from "@/components/thread/ComposerPalette";
import {
Tooltip,
TooltipContent,
@@ -107,7 +93,6 @@ import {
} from "@/hooks/useAttachedImages";
import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop";
import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput";
@@ -127,10 +112,6 @@ import type {
ProjectDirectory,
WorkspaceDirectoriesPayload,
} from "@/lib/types";
import {
logoFallbackUrls,
} from "@/lib/provider-brand";
import { sessionHandleColor } from "@/lib/session-handle";
import { requestSkillsRefresh } from "@/lib/skill-events";
import {
isRegisteredSlashCommand,
@@ -144,7 +125,6 @@ import {
readDraggedSession,
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
@@ -232,37 +212,9 @@ interface ThreadComposerProps {
onQuotedContextChange?: (text: string | null) => void;
}
const COMMAND_ICONS: Record<string, LucideIcon> = {
activity: ActivityIcon,
archive: ArchiveIcon,
"book-open": SkillsIcon,
brain: MemoryIcon,
"circle-help": HelpIcon,
history: HistoryIcon,
"rotate-cw": RestartIcon,
shield: RestrictedAccessIcon,
sparkles: DreamIcon,
square: StopIcon,
"square-pen": EditIcon,
"undo-2": RestoreMemoryIcon,
zap: TriggerIcon,
"file-text": PromptTemplateIcon,
wrench: ToolRunIcon,
};
const BUILTIN_COMMAND_ICONS: Record<string, LucideIcon> = {
"/new": NewChatIcon, "/compact": CompactIcon, "/stop": StopIcon,
"/restart": RestartIcon, "/status": StatusIcon, "/model": ModelsIcon,
"/goal": GoalIcon, "/trigger": TriggerIcon,
"/dream": DreamIcon, "/dream-log": DreamLogIcon, "/dream-restore": RestoreMemoryIcon,
"/dream-prompt": PromptTemplateIcon, "/evaluator-prompt": PromptTemplateIcon,
"/skill": SkillsIcon, "/help": HelpIcon, "/pairing": PairingIcon,
};
const SLASH_PALETTE_GAP_PX = 8;
const SLASH_PALETTE_MAX_HEIGHT_PX = 288;
const SLASH_PALETTE_MIN_HEIGHT_PX = 144;
const SLASH_PALETTE_CHROME_PX = 12;
const SLASH_RECENTS_STORAGE_KEY = "nanobot.webui.slashCommandRecents";
const SLASH_RECENTS_LIMIT = 5;
const SESSION_MENTIONS_LIMIT = 8;
@@ -306,32 +258,12 @@ function VoiceRecordingMeter({
);
}
type SlashPalettePlacement = "above" | "below" | "beside";
interface SlashPaletteLayout {
placement: SlashPalettePlacement;
maxHeight: number;
}
interface CliAppMentionQuery {
query: string;
start: number;
end: number;
}
type MentionCandidate = {
name: string;
displayName: string;
} & (
| { kind: "session"; mention: SessionMention }
| {
kind: "cli" | "mcp";
brandColor: string | null;
logoUrl: string | null;
initials: string;
}
);
interface MentionInsertion {
value: string;
cursor: number;
@@ -373,18 +305,6 @@ function sessionMentionOptions(sessions: ChatSummary[]): SessionMention[] {
});
}
interface SlashPaletteCommand {
command: string;
title: string;
description: string;
icon: string;
kind?: "skill";
argHint?: string;
detail: string;
badge?: string;
recent: boolean;
}
function skillMatchRank(skill: SkillSummary, query: string): number | null {
if (!query) return 0;
const name = skill.name.toLowerCase();
@@ -395,8 +315,29 @@ function skillMatchRank(skill: SkillSummary, query: string): number | null {
return null;
}
function slashCommandI18nKey(command: string): string {
return command.replace(/^\//, "").replace(/-/g, "_");
function skillSourceOrder(source: string): number {
const bucket = skillSourceBucket(source);
if (bucket === "workspace") return 0;
if (bucket === "builtin") return 1;
return 2;
}
function slashCommandMatchRank(
command: SlashCommand,
title: string,
description: string,
query: string,
): number | null {
if (!query) return 0;
const name = command.command.replace(/^\//, "").toLowerCase();
if (name === query) return 0;
if (name.startsWith(query)) return 1;
if (name.includes(query)) return 2;
if (title.toLowerCase().includes(query) || command.title.toLowerCase().includes(query)) return 3;
const haystack = [command.command, command.description, command.argHint ?? "", description]
.join(" ")
.toLowerCase();
return haystack.includes(query) ? 4 : null;
}
function readSlashRecents(): string[] {
@@ -919,48 +860,46 @@ export function ThreadComposer({
];
}, [isStreaming, onStop, slashCommands]);
const filteredSlashCommands = useMemo<SlashPaletteCommand[]>(() => {
if (skillQuery !== null) {
const query = skillQuery.text;
return skills
.filter((skill) => skill.enabled !== false && skill.available)
.flatMap((skill) => {
const matchRank = skillMatchRank(skill, query);
return matchRank === null
? []
: [{
command: `$${skill.name}`,
matchRank,
skill,
}];
})
.sort((a, b) => {
if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank;
if (query !== "") return 0;
const aRecent = recentSlashCommands.indexOf(a.command);
const bRecent = recentSlashCommands.indexOf(b.command);
if (aRecent === -1 && bRecent === -1) return 0;
const filteredSkills = useMemo<SkillPaletteItem[]>(() => {
if (skillQuery === null) return [];
const query = skillQuery.text;
return skills
.filter((skill) => skill.enabled !== false && skill.available)
.flatMap((skill) => {
const matchRank = skillMatchRank(skill, query);
return matchRank === null
? []
: [{
command: `$${skill.name}`,
matchRank,
skill,
}];
})
.sort((a, b) => {
if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank;
if (query !== "") return 0;
const aRecent = recentSlashCommands.indexOf(a.command);
const bRecent = recentSlashCommands.indexOf(b.command);
if (aRecent !== -1 || bRecent !== -1) {
if (aRecent === -1) return 1;
if (bRecent === -1) return -1;
return aRecent - bRecent;
})
.slice(0, 8)
.map(({ command, skill }) => {
const description = skill.description || skill.name;
return {
command,
title: skill.name,
description,
detail: description,
icon: "brain",
kind: "skill" as const,
recent: recentSlashCommands.includes(command),
};
});
}
if (slashQuery === null) return [];
const withDetails = visibleSlashCommands
.filter((command) => {
}
return skillSourceOrder(a.skill.source) - skillSourceOrder(b.skill.source);
})
.map(({ command, skill }) => ({
name: skill.name,
command,
description: skill.description || skill.name,
source: skill.source,
recent: recentSlashCommands.includes(command),
}));
}, [recentSlashCommands, skills, skillQuery]);
const filteredSlashCommands = useMemo<SlashPaletteCommand[]>(() => {
if (skillQuery !== null || slashQuery === null) return [];
return visibleSlashCommands
.flatMap((command) => {
if (
slashQuery === ""
&& (
@@ -968,7 +907,7 @@ export function ThreadComposer({
|| (command.command === "/stop" && !(isStreaming && onStop))
)
) {
return false;
return [];
}
const commandKey = slashCommandI18nKey(command.command);
const title = t(`thread.composer.slash.commands.${commandKey}.title`, {
@@ -977,21 +916,8 @@ export function ThreadComposer({
const description = t(`thread.composer.slash.commands.${commandKey}.description`, {
defaultValue: command.description,
});
const haystack = [
command.command,
command.title,
command.description,
command.argHint ?? "",
title,
description,
].join(" ").toLowerCase();
return haystack.includes(slashQuery);
})
.map((command) => {
const commandKey = slashCommandI18nKey(command.command);
const description = t(`thread.composer.slash.commands.${commandKey}.description`, {
defaultValue: command.description,
});
const matchRank = slashCommandMatchRank(command, title, description, slashQuery);
if (matchRank === null) return [];
let detail = description;
let badge: string | undefined;
if (command.command === "/model" && modelLabel) {
@@ -1004,34 +930,37 @@ export function ThreadComposer({
} else if (command.command === "/stop" && isStreaming) {
detail = t("thread.composer.slash.details.stopRunning");
}
return {
...command,
detail,
badge,
recent: recentSlashCommands.includes(command.command),
};
return [{
matchRank,
item: {
...command,
detail,
badge,
recent: recentSlashCommands.includes(command.command),
},
}];
})
.sort((a, b) => {
if (isStreaming) {
if (a.command === "/stop") return -1;
if (b.command === "/stop") return 1;
if (a.item.command === "/stop") return -1;
if (b.item.command === "/stop") return 1;
}
if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank;
if (slashQuery !== "") return 0;
const aRecent = recentSlashCommands.indexOf(a.command);
const bRecent = recentSlashCommands.indexOf(b.command);
const aRecent = recentSlashCommands.indexOf(a.item.command);
const bRecent = recentSlashCommands.indexOf(b.item.command);
if (aRecent !== -1 || bRecent !== -1) {
if (aRecent === -1) return 1;
if (bRecent === -1) return -1;
return aRecent - bRecent;
}
return 0;
});
})
.map(({ item }) => item);
}, [goalState?.active, isStreaming, modelLabel, onStop, recentSlashCommands, skillQuery, slashQuery, t, visibleSlashCommands]);
return withDetails
.slice(0, 8);
}, [goalState?.active, isStreaming, modelLabel, recentSlashCommands, skills, skillQuery, slashQuery, t, visibleSlashCommands]);
const showSlashMenu = filteredSlashCommands.length > 0;
const showSkillMenu = filteredSkills.length > 0;
const showSlashMenu = !showSkillMenu && filteredSlashCommands.length > 0;
const cliAppMention = useMemo<CliAppMentionQuery | null>(() => {
if (interactionDisabled || isUserShell || cliAppMenuDismissed) return null;
const caret = Math.min(Math.max(cursorPosition, 0), value.length);
@@ -1249,7 +1178,7 @@ export function ThreadComposer({
}, [cliAppMention, cliApps, insertableSessionMentions, mcpPresets, sessionMentionCatalog]);
const showCliAppMenu = filteredMentionCandidates.length > 0;
const showAnyPalette = showSlashMenu || showCliAppMenu;
const showAnyPalette = showSlashMenu || showSkillMenu || showCliAppMenu;
const inlineSegments = useMemo(
() => isUserShell ? displayMentionSegments : withSkillReferences(displayMentionSegments),
[displayMentionSegments, isUserShell],
@@ -1277,19 +1206,21 @@ export function ThreadComposer({
maxHeight: SLASH_PALETTE_MAX_HEIGHT_PX,
});
const activeCommandCount = showSkillMenu ? filteredSkills.length : filteredSlashCommands.length;
useEffect(() => {
setSelectedCommandIndex(0);
}, [slashQuery]);
}, [skillQuery?.text, slashQuery]);
useEffect(() => {
setSelectedCliAppIndex(0);
}, [cliAppMention?.query]);
useEffect(() => {
if (selectedCommandIndex >= filteredSlashCommands.length) {
if (selectedCommandIndex >= activeCommandCount) {
setSelectedCommandIndex(0);
}
}, [filteredSlashCommands.length, selectedCommandIndex]);
}, [activeCommandCount, selectedCommandIndex]);
useEffect(() => {
if (selectedCliAppIndex >= filteredMentionCandidates.length) {
@@ -1361,7 +1292,7 @@ export function ThreadComposer({
window.removeEventListener("resize", updateLayout);
document.removeEventListener("scroll", updateLayout, true);
};
}, [filteredMentionCandidates.length, filteredSlashCommands.length, showAnyPalette]);
}, [filteredMentionCandidates.length, filteredSkills.length, filteredSlashCommands.length, showAnyPalette]);
useLayoutEffect(() => {
if (mentionInput.isComposing) return;
@@ -1413,6 +1344,32 @@ export function ThreadComposer({
onStop?.();
}, [onStop, pauseQueue]);
const recordSlashRecent = useCallback((command: string) => {
const nextRecents = [
command,
...recentSlashCommands.filter((item) => item !== command),
].slice(0, SLASH_RECENTS_LIMIT);
setRecentSlashCommands(nextRecents);
storeSlashRecents(nextRecents);
}, [recentSlashCommands]);
const chooseSkill = useCallback(
(skill: SkillPaletteItem) => {
if (skillQuery === null) return;
recordSlashRecent(skill.command);
const suffix = value.slice(skillQuery.end);
const inserted = `${skill.command}${suffix.startsWith(" ") ? "" : " "}`;
const next = `${value.slice(0, skillQuery.start)}${inserted}${suffix}`;
const nextCursor = skillQuery.start + inserted.length;
replaceMentionInput(next, nextCursor);
setSlashMenuDismissed(true);
setCliAppMenuDismissed(false);
setInlineError(null);
focusTextarea();
},
[focusTextarea, recordSlashRecent, replaceMentionInput, skillQuery, value],
);
const chooseSlashCommand = useCallback(
(command: SlashPaletteCommand) => {
if (command.command === "/stop" && isStreaming && onStop) {
@@ -1425,28 +1382,14 @@ export function ThreadComposer({
return;
}
const nextRecents = [
command.command,
...recentSlashCommands.filter((item) => item !== command.command),
].slice(0, SLASH_RECENTS_LIMIT);
setRecentSlashCommands(nextRecents);
storeSlashRecents(nextRecents);
if (skillQuery !== null) {
const suffix = value.slice(skillQuery.end);
const inserted = `${command.command}${suffix.startsWith(" ") ? "" : " "}`;
const next = `${value.slice(0, skillQuery.start)}${inserted}${suffix}`;
const nextCursor = skillQuery.start + inserted.length;
replaceMentionInput(next, nextCursor);
} else {
setValue(command.argHint ? `${command.command} ` : command.command);
}
recordSlashRecent(command.command);
setValue(command.argHint ? `${command.command} ` : command.command);
setSlashMenuDismissed(true);
setCliAppMenuDismissed(false);
setInlineError(null);
focusTextarea();
},
[handleStop, isStreaming, onStop, recentSlashCommands, replaceMentionInput, focusTextarea, skillQuery, value],
[focusTextarea, handleStop, isStreaming, onStop, recordSlashRecent],
);
const insertMention = useCallback(
@@ -1741,6 +1684,30 @@ export function ThreadComposer({
return;
}
}
if (showSkillMenu) {
if (e.key === "ArrowDown") {
e.preventDefault();
setSelectedCommandIndex((idx) => (idx + 1) % filteredSkills.length);
return;
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSelectedCommandIndex(
(idx) => (idx - 1 + filteredSkills.length) % filteredSkills.length,
);
return;
}
if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
e.preventDefault();
chooseSkill(filteredSkills[selectedCommandIndex]);
return;
}
if (e.key === "Escape") {
e.preventDefault();
setSlashMenuDismissed(true);
return;
}
}
if (showSlashMenu) {
if (e.key === "ArrowDown") {
e.preventDefault();
@@ -2011,9 +1978,20 @@ export function ThreadComposer({
paletteBeside && "grid grid-cols-2 items-start gap-2 p-0",
)}
>
{showSlashMenu ? (
{showSkillMenu ? (
<SkillPalette
skills={filteredSkills}
query={skillQuery?.text ?? ""}
selectedIndex={selectedCommandIndex}
layout={slashPaletteLayout}
isHero={isHero}
onHover={setSelectedCommandIndex}
onChoose={chooseSkill}
/>
) : showSlashMenu ? (
<SlashCommandPalette
commands={filteredSlashCommands}
query={slashQuery ?? ""}
selectedIndex={selectedCommandIndex}
layout={slashPaletteLayout}
isHero={isHero}
@@ -2024,6 +2002,7 @@ export function ThreadComposer({
{showCliAppMenu ? (
<CliAppMentionPalette
candidates={filteredMentionCandidates}
query={cliAppMention?.query ?? ""}
selectedIndex={selectedCliAppIndex}
layout={slashPaletteLayout}
isHero={isHero}
@@ -2507,315 +2486,6 @@ function ComposerInlineReferenceOverlay({
</div>
);
}
interface SlashCommandPaletteProps {
commands: SlashPaletteCommand[];
selectedIndex: number;
layout: SlashPaletteLayout;
isHero: boolean;
onHover: (index: number) => void;
onChoose: (command: SlashPaletteCommand) => void;
}
interface CliAppMentionPaletteProps {
candidates: MentionCandidate[];
selectedIndex: number;
layout: SlashPaletteLayout;
isHero: boolean;
onHover: (index: number) => void;
onChoose: (candidate: MentionCandidate) => void;
}
function useSelectedOptionScroll(selectedIndex: number) {
const containerRef = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const option = container.querySelector<HTMLElement>(
`[data-palette-index="${selectedIndex}"]`,
);
if (typeof option?.scrollIntoView === "function") {
option.scrollIntoView({ block: "nearest" });
}
}, [selectedIndex]);
return containerRef;
}
function CliAppMentionPalette({
candidates,
selectedIndex,
layout,
isHero,
onHover,
onChoose,
}: CliAppMentionPaletteProps) {
const { t } = useTranslation();
const listMaxHeight = Math.max(
0,
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const groupedCandidates = (["session", "cli", "mcp"] as const)
.map((kind) => ({
kind,
label: kind === "session"
? t("thread.composer.mentions.sessionGroup")
: kind === "cli"
? t("thread.composer.mentions.cliGroup")
: t("thread.composer.mentions.mcpGroup"),
items: candidates
.map((candidate, index) => ({ candidate, index }))
.filter(({ candidate }) => candidate.kind === kind),
}))
.filter((group) => group.items.length > 0);
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.mentions.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
className={cn(
floatingSurfaceVisualClassName,
"z-30 overflow-hidden",
layout.placement === "beside"
? "relative col-start-2 row-start-1 w-full"
: cn("absolute left-1/2 w-[calc(100%-0.5rem)] -translate-x-1/2",
layout.placement === "above" ? "bottom-full mb-2" : "top-full mt-2"),
isHero ? "max-w-[58rem]" : "max-w-[49.5rem]",
)}
>
<div ref={listRef} className="overflow-y-auto" style={{ maxHeight: listMaxHeight }}>
{groupedCandidates.map((group) => (
<div key={group.kind} role="group" aria-label={group.label} className="mt-1.5 first:mt-0">
<div className="px-2 pb-1 pt-1 text-[12px] font-medium text-muted-foreground/72">
{group.label}
</div>
{group.items.map(({ candidate, index }) => {
const selected = index === selectedIndex;
const name = candidate.name;
const handleColor = candidate.kind === "session"
? candidate.mention.id ? sessionHandleColor(candidate.mention.id) : INLINE_TOKEN_HIGHLIGHT_COLOR
: undefined;
const typeLabel = candidate.kind === "cli"
? t("thread.composer.mentions.cliBadge")
: candidate.kind === "mcp"
? t("thread.composer.mentions.mcpBadge")
: t("thread.composer.mentions.sessionBadge");
const ariaDescription = candidate.kind === "cli"
? t("thread.composer.mentions.cliDescription", { name })
: candidate.kind === "mcp"
? t("thread.composer.mentions.mcpDescription", { name })
: t("thread.composer.mentions.sessionDescription", { name });
return (
<button
key={`${candidate.kind}-${name}`}
type="button"
role="option"
data-palette-index={index}
aria-selected={selected}
aria-label={`@${name} ${candidate.displayName} ${ariaDescription} ${typeLabel}`}
onMouseEnter={() => onHover(index)}
onMouseDown={(e) => {
e.preventDefault();
onChoose(candidate);
}}
className={cn(
floatingItemClassName,
floatingItemFocusClassName,
"touch-target flex min-h-10 w-full flex-wrap items-center gap-x-2.5 gap-y-1 px-2.5 py-1.5 text-left transition-colors",
selected
? "bg-foreground/[0.055] text-foreground dark:bg-black/[0.12]"
: "text-foreground/90 hover:bg-foreground/[0.04]",
)}
>
<span
className="max-w-full shrink-0 truncate text-[15px] font-normal tracking-normal text-muted-foreground/72"
style={{ color: handleColor }}
>
@{name}
</span>
<span className={cn(
"flex max-w-full flex-1 flex-wrap items-center gap-x-2.5 gap-y-1",
candidate.kind === "session" ? "min-w-[min(4rem,100%)]" : "min-w-[min(8rem,100%)]",
)}>
{candidate.kind !== "session" ? <MentionCandidateLogo candidate={candidate} selected={selected} /> : null}
<span className="min-w-[min(4rem,100%)] flex-1 truncate text-[15px] font-medium tracking-normal text-foreground">
{candidate.displayName}
</span>
{candidate.kind !== "session" ? (
<span
className={cn(
"ml-2 shrink-0 rounded-full px-2 py-0.5 text-[11px] font-semibold tracking-normal",
candidate.kind === "cli"
? "bg-orange-500/10 text-orange-600 dark:text-orange-300"
: "bg-sky-500/10 text-sky-600 dark:text-sky-300",
)}
>
{typeLabel}
</span>
) : null}
</span>
</button>
);
})}
</div>
))}
</div>
</div>
);
}
function MentionCandidateLogo({
candidate,
selected,
}: {
candidate: Extract<MentionCandidate, { kind: "cli" | "mcp" }>;
selected: boolean;
}) {
const color = candidate.brandColor || INLINE_TOKEN_HIGHLIGHT_COLOR;
const logoUrls = useMemo(() => logoFallbackUrls(candidate.logoUrl), [candidate.logoUrl]);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
if (logoUrl) {
return (
<span
className={cn(
"flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-compact",
selected ? "bg-background/55" : "bg-transparent",
)}
>
<img
src={logoUrl}
alt=""
decoding="async"
loading="lazy"
className="h-5 w-5 object-contain"
onLoad={onLogoLoad}
onError={onLogoError}
/>
</span>
);
}
return (
<span
className="flex h-5 w-5 shrink-0 items-center justify-center rounded-compact text-[7.5px] font-semibold text-white"
style={{ backgroundColor: color }}
>
{candidate.initials}
</span>
);
}
function SlashCommandPalette({
commands,
selectedIndex,
layout,
isHero,
onHover,
onChoose,
}: SlashCommandPaletteProps) {
const { t } = useTranslation();
const listMaxHeight = Math.max(
0,
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.slash.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
className={cn(
floatingSurfaceVisualClassName,
"z-30 overflow-hidden",
layout.placement === "beside"
? "relative col-start-2 row-start-1 w-full"
: cn("absolute left-1/2 w-[calc(100%-0.5rem)] -translate-x-1/2",
layout.placement === "above" ? "bottom-full mb-2" : "top-full mt-2"),
isHero ? "max-w-[58rem]" : "max-w-[49.5rem]",
)}
>
<div ref={listRef} className="overflow-y-auto pr-0.5" style={{ maxHeight: listMaxHeight }}>
{commands.map((command, index) => {
const Icon = command.kind === "skill" ? SkillsIcon : BUILTIN_COMMAND_ICONS[command.command] ?? COMMAND_ICONS[command.icon] ?? HelpIcon;
const selected = index === selectedIndex;
const isSkill = command.kind === "skill";
const commandKey = slashCommandI18nKey(command.command);
const title = t(`thread.composer.slash.commands.${commandKey}.title`, {
defaultValue: command.title,
});
const description = t(`thread.composer.slash.commands.${commandKey}.description`, {
defaultValue: command.description,
});
return (
<button
key={command.command}
type="button"
role="option"
data-palette-index={index}
aria-selected={selected}
onMouseEnter={() => onHover(index)}
onMouseDown={(e) => {
e.preventDefault();
onChoose(command);
}}
className={cn(
floatingItemClassName,
floatingItemFocusClassName,
"flex min-h-[44px] w-full items-center gap-3 px-3 py-2 text-left transition-colors",
selected
? "bg-foreground/[0.065] text-foreground dark:bg-white/[0.09]"
: "text-foreground/86 hover:bg-foreground/[0.045] dark:hover:bg-white/[0.065]",
)}
>
<span
className={cn(
"flex h-7 w-7 shrink-0 items-center justify-center text-muted-foreground transition-colors",
selected && "text-foreground",
)}
>
<Icon className="h-4 w-4" />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-0.5 sm:flex-row sm:items-baseline sm:gap-2">
<span
className={cn(
"text-[13.5px] font-semibold tracking-normal text-foreground",
isSkill
? "max-w-full shrink-0 break-all sm:max-w-[55%]"
: "min-w-0 truncate",
)}
>
{title}
</span>
<span className="min-w-0 truncate text-[13px] text-muted-foreground">
{command.detail || description}
</span>
</span>
{!isSkill || command.badge || command.recent ? (
<span className="ml-2 flex max-w-[42%] shrink-0 items-center gap-1.5 sm:max-w-none">
{command.badge || command.recent ? (
<span className="hidden rounded-full bg-foreground/[0.055] px-2 py-1 text-[11px] font-medium text-muted-foreground sm:inline-flex">
{command.badge ?? t("thread.composer.slash.badges.recent")}
</span>
) : null}
{!isSkill ? (
<span className="font-mono text-[12px] text-muted-foreground/60">
{command.argHint ? `${command.command} ${command.argHint}` : command.command}
</span>
) : null}
</span>
) : null}
</button>
);
})}
</div>
</div>
);
}
interface AttachmentChipProps {
image: AttachedImage;
+8 -2
View File
@@ -23,7 +23,7 @@ import { WebSearchRun } from "@/components/thread/activity/WebSearchRun";
import { Button } from "@/components/ui/button";
import type { StreamError } from "@/lib/nanobot-client";
import { formatToolCallTrace } from "@/lib/tool-traces";
import type { RecoveryState, SlashCommand, ToolProgressEvent, UIContextCompaction, UIMessage, WorkspaceScopePayload, WorkspacesPayload } from "@/lib/types";
import type { RecoveryState, SkillSummary, SlashCommand, ToolProgressEvent, UIContextCompaction, UIMessage, WorkspaceScopePayload, WorkspacesPayload } from "@/lib/types";
import { Sample, StatePicker, type ComponentExample } from "./example";
import { useGalleryTranslation } from "./i18n";
@@ -42,6 +42,11 @@ const commands: SlashCommand[] = [
{ command: "/compact", title: "previews.composer.compactCommand", description: "previews.composer.compactDescription", icon: "archive", lifecycle: "finalize_active_turn", acceptsArgs: false },
{ command: "/help", title: "previews.composer.helpCommand", description: "previews.composer.helpDescription", icon: "circle-help", lifecycle: "side_channel", acceptsArgs: false },
];
const gallerySkills: SkillSummary[] = [
{ name: "frontend-design", description: "Build refined interfaces with balanced typography, motion, and responsive layout.", source: "workspace", enabled: true, available: true },
{ name: "nanobot-document", description: "Look up nanobot configuration, architecture, and troubleshooting guides.", source: "builtin", enabled: true, available: true },
{ name: "skill-creator", description: "Create or update reusable AgentSkills in the workspace.", source: "builtin", enabled: true, available: true },
];
const projectScope: WorkspaceScopePayload = { project_path: "D:\\Projects\\nanobot", project_name: "nanobot", access_mode: "restricted" };
const workspaceCatalog: WorkspacesPayload = {
schema_version: 1, default_access_mode: "default", default_scope: projectScope,
@@ -79,6 +84,7 @@ function ComposerPreview() {
inputAriaLabel={t("previews.composer.input")} placeholder={t("previews.composer.placeholder")}
modelLabel={selected.name} modelDetail={selected.model} modelProvider={selected.provider} modelPreset={preset}
modelPresets={presets} onModelPresetChange={setPreset} slashCommands={commands.map((command) => ({ ...command, title: t(command.title), description: t(command.description) }))}
skills={gallerySkills}
renderContextUsage={renderContextUsage}
workspaceScope={projectScope} workspaceControlsHidden quotedContext={quoted} onQuotedContextChange={setQuoted}
onStop={() => { setMode("thread"); setSent({ kind: "stopped" }); }}
@@ -360,7 +366,7 @@ export const conversationExamples: ComponentExample[] = [
{ title: "previews.goal.title", files: ["thread/GoalIsland"], Preview: GoalPreview,
description: "previews.goal.description", options: "previews.goal.options",
code: '<GoalIsland goal={{ active: true, status: "active", ui_summary: summary, objective }} />' },
{ title: "previews.composer.title", files: ["thread/ThreadComposer"], Preview: ComposerPreview,
{ title: "previews.composer.title", files: ["thread/ThreadComposer", "thread/ComposerPalette"], Preview: ComposerPreview,
description: "previews.composer.description", options: "previews.composer.options",
code: '<ThreadComposer onSend={send} modelPresets={presets} onModelPresetChange={setPreset} slashCommands={commands} />' },
{ title: "previews.modelPreset.title", files: ["thread/ModelPresetBadge"], Preview: ModelPresetPreview,
+44 -1
View File
@@ -1384,6 +1384,48 @@
container-type: inline-size;
}
@keyframes composer-palette-enter {
from {
opacity: 0;
transform: translateY(var(--palette-enter-y, 4px)) scale(0.985);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}
@keyframes composer-palette-preview-in {
from {
opacity: 0.55;
transform: translateY(2px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.composer-palette-surface {
--palette-enter-y: 4px;
transform-origin: bottom center;
animation: composer-palette-enter 130ms cubic-bezier(0.16, 1, 0.3, 1);
}
.composer-palette-surface[data-placement="below"] {
--palette-enter-y: -4px;
transform-origin: top center;
}
.composer-palette-surface[data-placement="beside"] {
--palette-enter-y: 0px;
transform-origin: left center;
}
.composer-palette-preview-body {
animation: composer-palette-preview-in 110ms ease-out;
}
.dark .thread-composer-surface,
.dark .context-inspector-surface,
.dark .user-message-surface,
@@ -1393,6 +1435,7 @@
@media (prefers-reduced-motion: reduce) {
.thread-composer-surface { transition: var(--theme-paint-transition, none); }
.composer-palette-surface, .composer-palette-preview-body { animation: none; }
.pending-edge-overlay[data-pending-edge-overlay="pending"] .pending-edge-layer-dashed {
border-color: hsl(var(--muted-foreground) / 0.30);
animation: none;
@@ -1412,7 +1455,7 @@
}
@media (forced-colors: active) {
.thread-composer-surface, .context-inspector-surface, .user-message-surface, .side-panel-surface { outline: 1px solid CanvasText; }
.thread-composer-surface, .composer-palette-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"]) {
+4 -3
View File
@@ -576,9 +576,10 @@ describe("webui i18n", () => {
});
expect(screen.getByRole("listbox", { name: "斜杠命令" })).toBeInTheDocument();
expect(screen.getByText("压缩上下文")).toBeInTheDocument();
expect(screen.getByText("压缩上下文后继续对话")).toBeInTheDocument();
expect(screen.getByText("/compact")).toBeInTheDocument();
const option = screen.getByRole("option", { name: /\/compact/ });
expect(option).toHaveTextContent("/compact");
expect(option).toHaveTextContent("压缩上下文");
expect(option).toHaveTextContent("压缩上下文后继续对话");
});
it("keeps empty landing resources localized for every registered locale", () => {
+1 -1
View File
@@ -141,7 +141,7 @@ describe("useSkills", () => {
fireEvent.change(input, { target: { value: "$", selectionStart: 1 } });
await act(async () => {});
expect(fetchSkills).toHaveBeenCalledTimes(3);
expect(screen.queryByRole("listbox", { name: "Slash commands" })).not.toBeInTheDocument();
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
});
it("coalesces opens during an older fetch into one trailing refresh", async () => {
+35 -24
View File
@@ -2546,15 +2546,15 @@ describe("ThreadComposer", () => {
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "/git", selectionStart: 4 } });
expect(screen.queryByRole("listbox", { name: "Slash commands" })).not.toBeInTheDocument();
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
fireEvent.change(input, { target: { value: "please use $arxiv", selectionStart: 17 } });
const palette = screen.getByRole("listbox", { name: "Slash commands" });
const palette = screen.getByRole("listbox", { name: "Skills" });
const option = within(palette).getByRole("option", { name: new RegExp(skillName, "i") });
const name = within(option).getByText(skillName);
const name = option.querySelector("[data-palette-skill-name]");
expect(name).toHaveTextContent(skillName);
expect(name).not.toHaveClass("truncate");
expect(within(option).queryByText(`$${skillName}`)).not.toBeInTheDocument();
expect(within(palette).queryByText("arxiv-disabled")).not.toBeInTheDocument();
expect(within(palette).queryByText("arxiv-unavailable")).not.toBeInTheDocument();
expect(within(palette).queryByText("/model")).not.toBeInTheDocument();
@@ -2603,23 +2603,31 @@ describe("ThreadComposer", () => {
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "$up", selectionStart: 3 } });
const options = within(screen.getByRole("listbox", { name: "Slash commands" }))
const options = within(screen.getByRole("listbox", { name: "Skills" }))
.getAllByRole("option");
expect(options.map((option) => option.textContent)).toEqual([
"upExact match",
"upload-filesTransfer local files",
"setup-updateConfigure upgrades",
"skill-creatorCreate or update AgentSkills",
]);
expect(options).toHaveLength(4);
expect(options[0]).toHaveTextContent("$up");
expect(options[0]).toHaveTextContent("Custom");
expect(options[1]).toHaveTextContent("$upload-files");
expect(options[2]).toHaveTextContent("$setup-update");
expect(options[3]).toHaveTextContent("$skill-creator");
});
it("keeps a recently selected skill visible at the top of the blank skill menu", () => {
const skills = Array.from({ length: 9 }, (_, index) => ({
name: `skill-${index}`,
description: `Skill ${index}`,
source: "builtin",
available: true,
}));
it("groups mixed-source skills and keeps a recently selected skill at the top of the blank menu", () => {
const skills = [
...Array.from({ length: 8 }, (_, index) => ({
name: `skill-${index}`,
description: `Skill ${index}`,
source: "builtin",
available: true,
})),
{
name: "workspace-deploy",
description: "Deploy workspace build",
source: "workspace",
available: true,
},
];
render(
<ThreadComposer
onSend={vi.fn()}
@@ -2629,15 +2637,18 @@ describe("ThreadComposer", () => {
);
const input = screen.getByLabelText("Message input");
fireEvent.change(input, { target: { value: "$skill-8", selectionStart: 8 } });
fireEvent.change(input, { target: { value: "$skill-7", selectionStart: 8 } });
fireEvent.keyDown(input, { key: "Tab" });
fireEvent.change(input, { target: { value: "$", selectionStart: 1 } });
const options = within(screen.getByRole("listbox", { name: "Slash commands" }))
.getAllByRole("option");
expect(options).toHaveLength(8);
expect(options[0]).toHaveTextContent("skill-8");
expect(options[0]).toHaveTextContent("Recent");
const palette = screen.getByRole("listbox", { name: "Skills" });
expect(within(palette).getByRole("group", { name: "Recent" })).toBeInTheDocument();
expect(within(palette).getByRole("group", { name: "Custom" })).toBeInTheDocument();
expect(within(palette).getByRole("group", { name: "Built-in" })).toBeInTheDocument();
const options = within(palette).getAllByRole("option");
expect(options).toHaveLength(9);
expect(options[0]).toHaveTextContent("$skill-7");
expect(options[1]).toHaveTextContent("$workspace-deploy");
});
it("shows session handles without an icon and preserves app icons after their identifiers", () => {