diff --git a/webui/browser/inline-references-fixture.tsx b/webui/browser/inline-references-fixture.tsx index aa39c80a5..4579f9fcb 100644 --- a/webui/browser/inline-references-fixture.tsx +++ b/webui/browser/inline-references-fixture.tsx @@ -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 |deny |revoke ]", + 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
{[answer, ...sent].map(message => )} - setSent(current => [...current, { id: `sent-${current.length}`, role: "user", content: text, createdAt: current.length + 2, }, ...(options?.userShell ? [{ diff --git a/webui/browser/inline-references.spec.ts b/webui/browser/inline-references.spec.ts index 246532c42..b50ced205 100644 --- a/webui/browser/inline-references.spec.ts +++ b/webui/browser/inline-references.spec.ts @@ -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"]); diff --git a/webui/src/components/thread/ComposerPalette.tsx b/webui/src/components/thread/ComposerPalette.tsx new file mode 100644 index 000000000..0d66c0d95 --- /dev/null +++ b/webui/src/components/thread/ComposerPalette.tsx @@ -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 = { + 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 = { + "/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 = { + 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)} + + {text.slice(index, index + query.length)} + + {text.slice(index + query.length)} + + ); +} + +function SelectionChevron({ selected, className }: { selected: boolean; className?: string }) { + return ( + + ); +} + +function PaletteKeyHint({ text }: { text: string }) { + const separator = text.indexOf(" "); + if (separator < 0) return {text}; + return ( + + + {text.slice(0, separator)} + + {text.slice(separator + 1)} + + ); +} + +function PalettePreviewShell({ + itemKey, + icon, + header, + alignIcon = "center", + children, +}: { + itemKey: string; + icon: ReactNode; + header: ReactNode; + alignIcon?: "center" | "start"; + children: ReactNode; +}) { + const { t } = useTranslation(); + return ( + <> +
+
+ + {icon} + +
{header}
+
+ {children} +
+
+ + + +
+ + ); +} + +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 ( + + ); +} + +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(null); + const surfaceRef = useOverlaySurfaceRef("overlay"); + + useLayoutEffect(() => { + const option = listRef.current?.querySelector(`[data-palette-index="${selectedIndex}"]`); + if (typeof option?.scrollIntoView === "function") option.scrollIntoView({ block: "nearest" }); + }, [selectedIndex]); + + return ( +
+
+ {children} +
+ {showSplitPreview ? ( +
+ {preview} +
+ ) : null} +
+ ); +} + +interface SharedPaletteProps { + 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 & { 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 ? ( + } + header={
{active.title}
} + > +
+ + + +
+ {active.description ? ( +

+ +

+ ) : null} + {active.hasLiveDetail ? ( +
+ + + {active.command.detail} + +
+ ) : null} +
+ ) : null; + + return ( + +
+
{groupLabel}
+ {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 ( + onChoose(command)} + className="min-h-[40px] items-start gap-2.5 py-2 sm:min-h-[38px] sm:items-center sm:py-1.5" + > + + + + + + + + + + + + + {showDetail ? ( + + + + ) : null} + + {badgeLabel ? ( + {badgeLabel} + ) : ( + + )} + + ); + })} +
+
+ ); +} + +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 & { skills: SkillPaletteItem[] }) { + const { t } = useTranslation(); + const ariaLabel = t("settings.skills.featured", { defaultValue: "Skills" }); + const activeSkill = skills[selectedIndex] ?? skills[0]; + + const groups = useMemo(() => { + 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 ? ( + } + header={ +
+
+ $ + +
+ + {skillBucketText(activeSkill.source, "sourceKey", t)} + +
+ } + > + {activeSkill.description && activeSkill.description !== activeSkill.name ? ( +

+ +

+ ) : null} +
+ ) : null; + + return ( + + {groups.map((group) => ( +
+
{group.label}
+ {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 ( + onChoose(skill)} + className="min-h-[40px] flex-col items-stretch gap-0.5 py-2 sm:min-h-[36px] sm:py-1.5" + > + + + $ + + + + + {recentLabel ? ( + {recentLabel} + ) : sourceText ? ( + {sourceText} + ) : ( + + )} + + {showDescription ? ( + + + + ) : null} + + ); + })} +
+ ))} +
+ ); +} + +export function CliAppMentionPalette({ + candidates, + query, + selectedIndex, + layout, + isHero, + onHover, + onChoose, +}: SharedPaletteProps & { 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 ( + + {groupedCandidates.map((group) => ( +
+
{group.label}
+ {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 ( + onChoose(candidate)} + className="touch-target min-h-10 flex-wrap items-center gap-x-2.5 gap-y-1 py-1.5" + > + + @ + + + {kind !== "session" ? : null} + + + + {kind !== "session" ? ( + + {typeLabel} + + ) : null} + + + ); + })} +
+ ))} +
+ ); +} + +function MentionCandidateLogo({ + candidate, + selected, +}: { + candidate: Extract; + selected: boolean; +}) { + const logoUrls = useMemo(() => logoFallbackUrls(candidate.logoUrl), [candidate.logoUrl]); + const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls); + + if (logoUrl) { + return ( + + + + ); + } + return ( + + {candidate.initials} + + ); +} diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsx index 0253c0c61..01d37b991 100644 --- a/webui/src/components/thread/ThreadComposer.tsx +++ b/webui/src/components/thread/ThreadComposer.tsx @@ -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 = { - 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 = { - "/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(() => { - 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(() => { + 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(() => { + 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(() => { 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 ? ( + + ) : showSlashMenu ? ( ); } -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(null); - - useLayoutEffect(() => { - const container = containerRef.current; - if (!container) return; - const option = container.querySelector( - `[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("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 ( -
-
- {groupedCandidates.map((group) => ( -
-
- {group.label} -
- {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 ( - - ); - })} -
- ))} -
-
- ); -} - -function MentionCandidateLogo({ - candidate, - selected, -}: { - candidate: Extract; - 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 ( - - - - ); - } - return ( - - {candidate.initials} - - ); -} - -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("overlay"); - return ( -
-
- {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 ( - - ); - })} -
-
- ); -} interface AttachmentChipProps { image: AttachedImage; diff --git a/webui/src/dev/gallery/conversation.tsx b/webui/src/dev/gallery/conversation.tsx index 71c4fe7f1..a150ec530 100644 --- a/webui/src/dev/gallery/conversation.tsx +++ b/webui/src/dev/gallery/conversation.tsx @@ -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: '' }, - { 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: '' }, { title: "previews.modelPreset.title", files: ["thread/ModelPresetBadge"], Preview: ModelPresetPreview, diff --git a/webui/src/globals.css b/webui/src/globals.css index 14aaf6234..126bd7e2a 100644 --- a/webui/src/globals.css +++ b/webui/src/globals.css @@ -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"]) { diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsx index f40716eef..50d41ab34 100644 --- a/webui/src/tests/i18n.test.tsx +++ b/webui/src/tests/i18n.test.tsx @@ -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", () => { diff --git a/webui/src/tests/skills-marketplace.test.tsx b/webui/src/tests/skills-marketplace.test.tsx index 3a718344f..881b6860a 100644 --- a/webui/src/tests/skills-marketplace.test.tsx +++ b/webui/src/tests/skills-marketplace.test.tsx @@ -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 () => { diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index 55adabfed..8a45d1472 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -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( { ); 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", () => {