refactor(webui): use native link actions and remove website previews (#6391)

* refactor(webui): remove website previews and custom link menus

* docs(webui): focus guide on product-specific usage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-22 16:34:54 +08:00
1 parent bc5c58d239
commit 08ca3b4525
42 files changed
+179 -1493

No files matched your search

+1 -1
View File
@@ -23,7 +23,7 @@ Change state selectors to inspect streaming, completion, disabled, missing-media
Feature screens that own gateway requests, session state, or host connections are indexed with their source and callers. Exercise their complete workflows in the running WebUI. The gallery does not emulate those services.
Runtime adapters and presentation views have separate responsibilities. Adapters subscribe to clients, load data, enforce browser restrictions, and perform service actions. Their views receive display data and operation callbacks. Production screens and gallery examples mount the same views, including host menus, pairing, file/web previews, session tasks, automation results, version information, and notification preferences. Connected source entries link to the corresponding view examples.
Runtime adapters and presentation views have separate responsibilities. Adapters subscribe to clients, load data, enforce browser restrictions, and perform service actions. Their views receive display data and operation callbacks. Production screens and gallery examples mount the same views, including host menus, pairing, file previews, session tasks, automation results, version information, and notification preferences. Connected source entries link to the corresponding view examples.
Every channel registration has a preview. Channels with shared configuration forms use their production setup view; Linear, Feishu, Weixin, and WhatsApp use their channel-owned views, including authorization, verification, assistant management, and connection reset. The source inventory includes channel `webui/index.ts` registrations as well as `.tsx` components. Connected adapters link to the views they own.
+1 -7
View File
@@ -7,7 +7,7 @@ import {
useState,
type ReactNode,
} from "react";
import { Activity, Check, ChevronRight, CircleAlert, Clock3, Copy, Link2, Quote, Wrench } from "lucide-react";
import { Activity, Check, ChevronRight, CircleAlert, Clock3, Copy, Quote, Wrench } from "lucide-react";
import { useTranslation } from "react-i18next";
import { DisclosureContent } from "@/components/ui/disclosure";
@@ -145,7 +145,6 @@ interface MessageBlockMenuActionsProps {
isTurnStreaming?: boolean;
onForkFromHere?: () => void;
activity?: MessageBlockMenuActivity;
onViewLinks?: () => void;
sheet?: boolean;
}
@@ -155,7 +154,6 @@ export function MessageBlockMenuActions({
isTurnStreaming = false,
onForkFromHere,
activity,
onViewLinks,
sheet = false,
}: MessageBlockMenuActionsProps) {
const { t } = useTranslation();
@@ -248,10 +246,6 @@ export function MessageBlockMenuActions({
) : null}
</div>
) : null}
{onViewLinks ? <button type="button" data-message-links-trigger onClick={onViewLinks}
className="flex min-h-[var(--message-block-control-size)] w-full items-center gap-2 rounded-control px-2 py-1.5 text-[13px] text-muted-foreground hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Link2 className="h-3.5 w-3.5" aria-hidden />{t("webPreview.viewLinks")}
</button> : null}
<FallbackResponseSources
sources={message.role === "assistant" ? message.responseSources : undefined}
className="min-h-[var(--message-block-control-size)] gap-1"
-94
View File
@@ -1,94 +0,0 @@
import { useContext, useLayoutEffect, useRef, useState, type RefObject } from "react";
import { ArrowLeft, ChevronRight, Link2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { WebPreviewContext } from "@/components/WebLink";
import { floatingItemClassName, floatingItemFocusClassName } from "@/components/ui/floating-surface";
import { copyTextToClipboard } from "@/lib/clipboard";
import { currentWebPreviewRestriction, parseWebLink } from "@/lib/web-preview";
interface MessageWebLink { href: string; title: string }
/** Read only links actually rendered in this message, not code samples or file references. */
export function useMessageWebLinks(root: RefObject<HTMLElement>, open: boolean) {
const [links, setLinks] = useState<MessageWebLink[]>([]);
useLayoutEffect(() => {
const element = root.current;
if (!open || !element) return;
const collect = () => {
const unique = new Map<string, MessageWebLink>();
element.querySelectorAll<HTMLAnchorElement>("[data-assistant-selectable] a[data-web-link]").forEach((anchor) => {
const href = anchor.getAttribute("href") ?? "";
const url = parseWebLink(href);
if (url && !unique.has(url.href)) {
unique.set(url.href, { href, title: anchor.textContent?.trim() || href });
}
});
setLinks(Array.from(unique.values()));
};
collect();
// Markdown is lazy-loaded; collect again when its real links appear/change.
const observer = new MutationObserver(collect);
observer.observe(element, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["href"] });
return () => observer.disconnect();
}, [root, open]);
return links;
}
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} w-full min-h-11 text-start hover:bg-muted/70`;
/** A drill-in inside the message's action surface, not another floating layer. */
export function MessageLinksMenu({ links, onBack, onClose, expanded = false }: {
links: MessageWebLink[];
onBack: () => void;
onClose: () => void;
expanded?: boolean;
}) {
const { t } = useTranslation();
const openPreview = useContext(WebPreviewContext);
const [selected, setSelected] = useState<string | null>(links.length === 1 ? links[0].href : null);
const active = links.find((link) => link.href === selected);
const backRef = useRef<HTMLButtonElement>(null);
useLayoutEffect(() => { backRef.current?.focus({ preventScroll: true }); }, [selected]);
return <div className={expanded ? "w-full" : "w-60 max-w-full"}>
<button ref={backRef} type="button" className={itemClassName} aria-label={t("webPreview.back")}
onClick={() => active && links.length > 1 ? setSelected(null) : onBack()}>
<ArrowLeft aria-hidden /><span>{t("webPreview.viewLinks")}</span>
</button>
{active ? <MessageLinkActions key={active.href} link={active} onClose={onClose}
onPreview={openPreview ? () => { onClose(); openPreview(active.href); } : undefined} />
: <div className="border-t border-border/45 pt-1">
{links.map((link) => <button type="button" key={link.href} className={itemClassName} onClick={() => setSelected(link.href)}>
<Link2 className="text-muted-foreground" aria-hidden />
<span className="min-w-0 flex-1 truncate">{link.title}</span><ChevronRight className="text-muted-foreground" aria-hidden />
</button>)}
</div>}
</div>;
}
function MessageLinkActions({ link, onClose, onPreview }: {
link: MessageWebLink;
onClose: () => void;
onPreview?: () => void;
}) {
const { t } = useTranslation();
const restriction = onPreview ? currentWebPreviewRestriction(parseWebLink(link.href)) : null;
const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
const mounted = useRef(false);
useLayoutEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
const copy = async () => {
const success = await copyTextToClipboard(link.href);
if (mounted.current) setFeedback(success ? "copied" : "copyFailed");
};
return <div className="border-t border-border/45 pt-1">
<p className="max-h-24 overflow-y-auto px-2.5 py-2 text-xs text-muted-foreground [overflow-wrap:anywhere]" dir="auto">{link.href}</p>
{onPreview && !restriction ? <button type="button" className={itemClassName} onClick={onPreview}>{t("webPreview.open")}</button> : null}
<a className={itemClassName} href={link.href} target="_blank" rel="noreferrer noopener" onClick={onClose}>{t("webPreview.external")}</a>
<button type="button" className={itemClassName} onClick={() => { void copy(); }}>{t("webPreview.copy")}</button>
{restriction ? <p className="px-2.5 py-1.5 text-xs leading-relaxed text-muted-foreground">{t(`webPreview.${restriction}`)}</p> : null}
{feedback ? <p role="status" className="px-2.5 py-1.5 text-xs text-muted-foreground">{t(`webPreview.${feedback}`)}</p> : null}
</div>;
}
+4 -9
View File
@@ -1,5 +1,5 @@
import { useEffect, useId, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import { Globe2, PanelRightClose, X } from "lucide-react";
import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { FileReferenceIcon, fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
import { FileActions } from "@/components/FileActions";
@@ -7,10 +7,6 @@ import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/compo
import type { PreviewTab } from "@/hooks/useFilePreviewState";
import { cn } from "@/lib/utils";
function tabName(tab: PreviewTab) {
return tab.kind === "web" ? new URL(tab.value).host : splitFilePath(tab.value).name;
}
/** One stable sidebar shell: switching targets never replays its opening animation. */
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
tabs: PreviewTab[];
@@ -72,7 +68,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
highlightClassName="rounded-compact">
{tabs.map((tab, index) => {
const selected = tab.id === activeId;
const name = tabName(tab);
const name = splitFilePath(tab.value).name;
const item = <div key={tab.id} role="presentation" data-preview-tab-active={selected ? "" : undefined}
className={cn(SIDEBAR_SELECTION_ITEM_CLASS, "group flex min-h-8 max-w-56 shrink-0 items-center rounded-compact", selected ? "text-foreground" : "text-muted-foreground hover:bg-muted/50 hover:text-foreground")}>
<button type="button" role="tab" id={`${id}-tab-${index}`} aria-selected={selected} aria-controls={`${id}-panel`}
@@ -93,8 +89,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
}}
className="touch-target flex h-8 min-w-0 items-center gap-1.5 rounded-compact pl-2.5 pr-1.5 text-[12.5px] font-medium leading-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
<span aria-hidden className="flex size-3.5 shrink-0 items-center justify-center text-muted-foreground">
{tab.kind === "web" ? <Globe2 className="size-3.5" />
: <FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" />}
<FileReferenceIcon kind={fileKindForPath(tab.value)} className="size-3.5" />
</span>
<span className="truncate">{name}</span>
</button>
@@ -104,7 +99,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
<X className="size-3" aria-hidden />
</button>
</div>;
return tab.kind === "file" ? <FileActions key={tab.id} path={tab.value} className="shrink-0">{item}</FileActions> : item;
return <FileActions key={tab.id} path={tab.value} className="shrink-0">{item}</FileActions>;
})}
</SidebarSelectionHighlight>
</div>
+12 -99
View File
@@ -1,108 +1,21 @@
import { createContext, useContext, useEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import * as Menu from "@radix-ui/react-menu";
import { useTranslation } from "react-i18next";
import type { ComponentPropsWithoutRef } from "react";
import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface";
import { useFloatingPortal } from "@/components/ui/floating-portal";
import { copyTextToClipboard } from "@/lib/clipboard";
import { currentWebPreviewRestriction, parseWebLink } from "@/lib/web-preview";
import { cn } from "@/lib/utils";
export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} cursor-default`;
function parseWebLink(value: string): URL | null {
if (value.length > 8192 || value.includes("\\")
|| Array.from(value).some((char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127)) return null;
try {
const url = new URL(value);
return /^https?:$/.test(url.protocol) && !url.username && !url.password ? url : null;
} catch {
return null;
}
}
export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutRef<"a">) {
const url = parseWebLink(href);
if (url) return <WebsiteLink key={href} {...props} href={href}>{children}</WebsiteLink>;
// Keep the renderer's relative media/document and mail links unchanged.
const relative = !/^[a-z][a-z\d+.-]*:/i.test(href)
&& !href.includes("\\") && !Array.from(href).some((char) => char.charCodeAt(0) < 32);
return relative || /^(mailto:|tel:|#)/i.test(href)
return url || relative || /^(mailto:|tel:|#)/i.test(href)
? <a {...props} href={href} target="_blank" rel="noreferrer noopener">{children}</a> : <>{children}</>;
}
/** Keep links as links; secondary actions share the compact file-reference surface. */
function WebsiteLink({ href, children, className, ...props }: ComponentPropsWithoutRef<"a"> & { href: string }) {
const { t } = useTranslation();
const openPreview = useContext(WebPreviewContext);
const portal = useFloatingPortal();
const [open, setOpen] = useState(false);
const restriction = open && openPreview ? currentWebPreviewRestriction(parseWebLink(href)) : null;
const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
const link = useRef<HTMLAnchorElement>(null);
const point = useRef({ x: 0, y: 0 });
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
const interactedOutside = useRef(false);
const generation = useRef(0);
const pointerType = useRef("");
useEffect(() => () => {
generation.current += 1;
}, []);
const changeOpen = (next: boolean) => {
generation.current += 1;
setOpen(next);
};
const openAt = (x: number, y: number) => {
point.current = { x, y };
interactedOutside.current = false;
setFeedback(null);
changeOpen(true);
};
const copy = async () => {
const current = generation.current;
const copied = await copyTextToClipboard(href);
// Late clipboard results must not dismiss a new menu or report another URL.
if (current !== generation.current) return;
setFeedback(copied ? "copied" : "copyFailed");
if (copied) changeOpen(false);
};
return <Menu.Root open={open} onOpenChange={changeOpen}>
<Menu.Anchor virtualRef={anchor} />
<span className="inline max-w-full"
onContextMenu={(event) => {
event.stopPropagation();
// Touch keeps the browser's native link preview/copy/share menu. Older
// WebKit exposes contextmenu as a MouseEvent, so remember the last pointer.
const type = (event.nativeEvent as PointerEvent).pointerType || pointerType.current;
if (type === "touch" || (!type && window.matchMedia("(pointer: coarse)").matches)) return;
event.preventDefault();
openAt(event.clientX, event.clientY);
}}
onKeyDown={(event) => {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
const bounds = link.current!.getBoundingClientRect();
openAt(bounds.left, bounds.bottom);
}}
onPointerDown={(event) => {
pointerType.current = event.pointerType;
}}>
<a {...props} ref={link} data-web-link href={href} target="_blank" rel="noreferrer noopener"
className={className}>{children}</a>
</span>
{feedback === "copied" ? <span role="status" className="sr-only">{t("webPreview.copied")}</span> : null}
<Menu.Portal container={portal ?? undefined}>
<Menu.Content aria-label={t("webPreview.actions")} align="start" sideOffset={4} collisionPadding={12}
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 rounded-control p-1 [&_[role=menuitem]]:py-1.5 [@media(pointer:coarse)]:[&_[role=menuitem]]:min-h-11")}
onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); }}
onClick={(event) => event.stopPropagation()}
onInteractOutside={() => { interactedOutside.current = true; }}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (!interactedOutside.current) link.current?.focus();
}}>
{openPreview && !restriction ? <Menu.Item className={itemClassName} onSelect={() => openPreview(href)}>{t("webPreview.open")}</Menu.Item> : null}
<Menu.Item asChild className={itemClassName}>
<a href={href} target="_blank" rel="noreferrer noopener">{t("webPreview.external")}</a>
</Menu.Item>
<Menu.Item className={itemClassName} onSelect={(event) => { event.preventDefault(); void copy(); }}>{t("webPreview.copy")}</Menu.Item>
{restriction ? <p className="max-w-64 px-2.5 py-1.5 text-xs leading-relaxed text-muted-foreground">{t(`webPreview.${restriction}`)}</p> : null}
{feedback === "copyFailed" ? <div role="status" className="max-w-64 px-2.5 py-1.5 text-xs text-muted-foreground">{t("webPreview.copyFailed")}</div> : null}
</Menu.Content>
</Menu.Portal>
</Menu.Root>;
}
-24
View File
@@ -1,24 +0,0 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { WebPreviewPanelView } from "@/components/WebPreviewPanelView";
import { isLoopbackHost } from "@/lib/network";
import { currentWebPreviewRestriction, parseWebLink } from "@/lib/web-preview";
interface WebPreviewPanelProps {
url: string;
}
export function WebPreviewPanel({ url: value }: WebPreviewPanelProps) {
const { t } = useTranslation();
const [revision, setRevision] = useState(0);
const url = parseWebLink(value);
const restriction = currentWebPreviewRestriction(url);
return <WebPreviewPanelView url={url} restriction={restriction} loopback={!!url && isLoopbackHost(url.hostname)}
onRefresh={() => setRevision((n) => n + 1)}>
{!restriction ? <iframe key={`${value}:${revision}`} title={t("webPreview.frame", { host: url!.host })}
{...{ credentialless: "" }} sandbox="allow-scripts" referrerPolicy="no-referrer"
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; payment 'none'; fullscreen 'none'; display-capture 'none'; usb 'none'; serial 'none'; hid 'none'"
src={url!.href} className="min-h-0 w-full flex-1 border-0 bg-white" /> : null}
</WebPreviewPanelView>;
}
@@ -1,41 +0,0 @@
import type { ReactNode } from "react";
import { ExternalLink, Info, RotateCw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { currentWebPreviewRestriction } from "@/lib/web-preview";
export function WebPreviewPanelView({ url, restriction, loopback, onRefresh, children }: {
url: URL | null;
restriction: ReturnType<typeof currentWebPreviewRestriction>;
loopback: boolean;
onRefresh: () => void;
children?: ReactNode;
}) {
const { t } = useTranslation();
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return (
<section aria-label={t("webPreview.title")} data-testid="web-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div className="flex h-9 shrink-0 items-center gap-1 border-b border-border/40 px-2">
<p className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
<Popover>
<PopoverTrigger asChild><button type="button" className={buttonClass} aria-label={t("previewTabs.websiteInfo")} title={t("previewTabs.websiteInfo")}><Info className="size-3.5" aria-hidden /></button></PopoverTrigger>
<PopoverContent align="end" className="w-72 space-y-2 rounded-control p-3 text-xs leading-relaxed text-muted-foreground">
<p>{t("webPreview.isolated")}</p>
<p>{t("webPreview.blockedHint")}</p>
{loopback ? <p>{t("webPreview.loopback")}</p> : null}
</PopoverContent>
</Popover>
{!restriction ? <button type="button" className={buttonClass} onClick={onRefresh} title={t("webPreview.refresh")} aria-label={t("webPreview.refresh")}>
<RotateCw className="h-4 w-4" aria-hidden />
</button> : null}
{url ? <a className={buttonClass} href={url.href} target="_blank" rel="noreferrer noopener" title={t("webPreview.external")} aria-label={t("webPreview.external")}>
<ExternalLink className="h-4 w-4" aria-hidden />
</a> : null}
</div>
{restriction ? <div role="status" className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6 text-center text-sm text-muted-foreground">
{t(`webPreview.${restriction}`)}
</div> : children}
</section>
);
}
+2 -13
View File
@@ -1,8 +1,7 @@
import { Fragment, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { Fragment, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { MoreHorizontal } from "lucide-react";
import { useTranslation } from "react-i18next";
import { MessageBlockMenuActions, MessageBubble, MessageCopyButton } from "@/components/MessageBubble";
import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import {
AgentActivityCluster,
@@ -395,7 +394,6 @@ interface ThreadDisplayUnitProps {
interface MessageBlockMenuProps {
mobileActions: boolean;
messageRoot: RefObject<HTMLElement>;
message: UIMessage;
isTurnStreaming: boolean;
contextBlockKey: string;
@@ -414,7 +412,6 @@ interface MessageBlockMenuProps {
function MessageBlockMenu({
mobileActions,
messageRoot,
message,
isTurnStreaming,
contextBlockKey,
@@ -428,9 +425,6 @@ function MessageBlockMenu({
const { t } = useTranslation();
const contentRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const links = useMessageWebLinks(messageRoot, open);
const [linksShown, setLinksShown] = useState(false);
useEffect(() => { if (!open) setLinksShown(false); }, [open]);
const [triggerHeight, setTriggerHeight] = useState(28);
useLayoutEffect(() => {
const trigger = triggerRef.current;
@@ -451,16 +445,12 @@ function MessageBlockMenu({
// Re-evaluated when this message becomes active, including after an overnight idle.
const shortTime = mobileActions ? "" : formatMessageHoverTime(timestamp);
const fullTime = shortTime ? fmtDateTime(timestamp) : "";
const actions = linksShown && links.length > 0 ? <MessageLinksMenu links={links}
expanded={mobileActions}
onBack={() => { setLinksShown(false); contentRef.current?.focus({ preventScroll: true }); }}
onClose={() => onOpenChange(false)} /> : <MessageBlockMenuActions
const actions = <MessageBlockMenuActions
message={message}
isTurnStreaming={isTurnStreaming}
onForkFromHere={onForkFromHere ? () => { if (mobileActions) onOpenChange(false); onForkFromHere(); } : undefined}
activity={activity}
sheet={mobileActions}
onViewLinks={links.length > 0 ? () => setLinksShown(true) : undefined}
/>;
if (mobileActions) {
return <div data-message-mobile-actions className={cn("mt-1 flex items-center", message.role === "user" ? "me-2 justify-end" : "-ms-2")}>
@@ -665,7 +655,6 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? (
<MessageBlockMenu
mobileActions={mobileActions}
messageRoot={elementRef}
message={unit.message}
isTurnStreaming={isTurnStreaming}
contextBlockKey={contextBlockKey}
+11 -25
View File
@@ -7,9 +7,6 @@ import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailab
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { PreviewPane } from "@/components/PreviewPane";
import { FileActionsProvider } from "@/components/FileActions";
import { WebPreviewContext } from "@/components/WebLink";
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
import { parseWebLink } from "@/lib/web-preview";
import { createFilePreviewResource } from "@/lib/file-preview-resource";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
@@ -538,7 +535,7 @@ export function ThreadShell({
} | null>(null);
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, openFile, resolveFile, openWeb, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
const { state: previewState, openFile, resolveFile, selectTab, closeTab, close: closePreview, setWidth: setFilePreviewWidth } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -1127,13 +1124,6 @@ export function ThreadShell({
loadPreview: filePreviews.load,
}), [resolveFileMetadata, filePreviews]);
const openWebPreview = useCallback((url: string) => {
const parsed = parseWebLink(url);
if (!parsed) return;
cancelPreviewClose();
openWeb(parsed.href);
}, [cancelPreviewClose, openWeb]);
useEffect(() => {
if (!previewOpen || !headerActive) return;
const onKeyDown = (event: KeyboardEvent) => {
@@ -1452,7 +1442,6 @@ export function ThreadShell({
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
>
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
<WebPreviewContext.Provider value={previewSessionKey ? openWebPreview : undefined}>
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
@@ -1485,7 +1474,6 @@ export function ThreadShell({
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
/>
</WebPreviewContext.Provider>
</FileActionsProvider>
</FilePreviewAvailabilityProvider>
</div>
@@ -1515,18 +1503,16 @@ export function ThreadShell({
onClose={handleCloseFilePreview}
onResizeStart={handleFilePreviewResizeStart}
>
{activePreview.kind === "file" ? (
<FilePreviewPanel
key={activePreview.id}
sessionKey={previewSessionKey}
path={activePreview.value}
token={token}
loadPreview={filePreviews.load}
initialPreview={filePreviews.peek(activePreview.value)}
onOpenFilePreview={openFilePreview}
onResolvePath={resolveFile}
/>
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
<FilePreviewPanel
key={activePreview.id}
sessionKey={previewSessionKey}
path={activePreview.value}
token={token}
loadPreview={filePreviews.load}
initialPreview={filePreviews.peek(activePreview.value)}
onOpenFilePreview={openFilePreview}
onResolvePath={resolveFile}
/>
</PreviewPane>
</FileActionsProvider>
) : null}
-24
View File
@@ -1,7 +1,6 @@
import { useState } from "react";
import { FilePreviewPanelView, type FilePreviewPanelState } from "@/components/FilePreviewPanelView";
import { WebPreviewPanelView } from "@/components/WebPreviewPanelView";
import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverView";
import { SubagentThreadView } from "@/components/thread/SubagentThreadView";
import type { AutomationUpdatePayload, SessionAutomationJob, UIMessage } from "@/lib/types";
@@ -31,26 +30,6 @@ function FilePreview() {
</div>;
}
const localDocument = '<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font-family:system-ui;padding:32px;color:#252525}h1{font-size:24px}p{line-height:1.7}code{background:#f2f2f2;padding:4px 8px;border-radius:6px}</style><h1>网页预览</h1><p>这段内容来自当前示例的本地文档。</p><p>点击顶部 <code>刷新</code> 按钮,重新显示文档;打开信息按钮查看隔离说明。</p></html>';
function WebsitePreview() {
const { t } = useGalleryTranslation();
const [mode, setMode] = useState<"available" | "native" | "unsupported" | "sameOrigin" | "mixedContent" | "invalid">("available");
const [revision, setRevision] = useState(0);
const url = mode === "invalid" ? null : new URL(mode === "sameOrigin" ? window.location.href : "https://example.com/preview");
return <div className="space-y-4">
<StatePicker label={t("previews.webPreview.state")} value={mode} options={["available", "native", "unsupported", "sameOrigin", "mixedContent", "invalid"]} onChange={setMode} />
<div className="flex h-80 flex-col overflow-hidden rounded-control border">
<WebPreviewPanelView url={url} restriction={mode === "available" ? null : mode} loopback={mode === "sameOrigin"}
onRefresh={() => setRevision((value) => value + 1)}>
<iframe key={revision} title={t("previews.webPreview.frame")} sandbox="" referrerPolicy="no-referrer" srcDoc={localDocument}
className="min-h-0 w-full flex-1 border-0 bg-white" />
</WebPreviewPanelView>
</div>
<p role="status" className="text-xs text-muted-foreground">{t("previews.webPreview.refreshes", { amount: revision })}</p>
</div>;
}
function exampleJobs(now: number): SessionAutomationJob[] {
return [
{ id: "gallery-daily-summary", name: "项目摘要", enabled: true, schedule: { kind: "every", every_ms: 3_600_000 },
@@ -125,9 +104,6 @@ export const contentExamples: ComponentExample[] = [
{ title: "previews.filePreview.title", files: ["webui/src/components/FilePreviewPanelView.tsx"], Preview: FilePreview,
description: "previews.filePreview.description", options: "previews.filePreview.options",
code: '<FilePreviewPanelView path={path} state={previewState} imageOpen={imageOpen} onImageOpenChange={setImageOpen} onImageError={reportImageError} />' },
{ title: "previews.webPreview.title", files: ["webui/src/components/WebPreviewPanelView.tsx"], Preview: WebsitePreview,
description: "previews.webPreview.description", options: "previews.webPreview.options",
code: '<WebPreviewPanelView url={url} restriction={restriction} loopback={loopback} onRefresh={refresh}>{frame}</WebPreviewPanelView>' },
{ title: "previews.session.title", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview,
description: "previews.session.description", options: "previews.session.options",
code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },
@@ -61,16 +61,6 @@
"scope": "File scope",
"hint": "Right-click for the copy menu, or focus the file and press Shift+F10."
},
"webLinks": {
"title": "Web links · Link menu",
"description": "Open the real link menu to select message links and copy addresses.",
"options": "WebLink accepts link attributes. useMessageWebLinks collects rendered message links. MessageLinksMenu takes entries and back/close callbacks; expanded controls width. All example links point to local Gallery resources.",
"width": "Link menu width",
"message": "View the <gallery>component Gallery</gallery> and <brand>brand image</brand>.",
"close": "Close link menu",
"open": "View message links",
"hint": "Right-click a link to copy its address. The message menu collects links from the rendered message."
},
"workbench": {
"title": "PaneWorkbench · Multiple panes",
"description": "Switch layouts, activate or add panes, and adjust their position and size.",
@@ -235,14 +225,6 @@
"options": "state supplies a display snapshot; path determines the file type and name. Image open and error callbacks update the preview.",
"state": "File preview state"
},
"webPreview": {
"title": "WebPreviewPanelView · Web content",
"description": "Explore the web title bar, isolation notes and restrictions; refresh a local document.",
"options": "The runtime chooses restriction before supplying content. children provides content; onRefresh requests a refresh. This iframe uses local srcDoc.",
"state": "Web preview state",
"frame": "Local example webpage",
"refreshes": "Refreshes: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Session automations",
"description": "View, edit, disable and delete jobs, with loading and error states.",
@@ -61,16 +61,6 @@
"scope": "Ámbito del archivo",
"hint": "Haz clic derecho para abrir el menú de copia, o enfoca el archivo y pulsa Mayús+F10."
},
"webLinks": {
"title": "Web links · Menú de enlaces",
"description": "Abre el menú real de enlaces para elegir enlaces del mensaje y copiar direcciones.",
"options": "WebLink recibe atributos de enlace. useMessageWebLinks recoge los enlaces renderizados. MessageLinksMenu recibe entradas y funciones de volver y cerrar; expanded controla el ancho. Todos los enlaces apuntan a recursos locales de la galería.",
"width": "Ancho del menú de enlaces",
"message": "Consulta la <gallery>galería de componentes</gallery> y la <brand>imagen de marca</brand>.",
"close": "Cerrar menú de enlaces",
"open": "Ver enlaces del mensaje",
"hint": "Haz clic derecho en un enlace para copiar su dirección. El menú recoge los enlaces del mensaje renderizado."
},
"workbench": {
"title": "PaneWorkbench · Paneles múltiples",
"description": "Cambia la disposición, activa o añade paneles y ajusta su posición y tamaño.",
@@ -235,14 +225,6 @@
"options": "state aporta la instantánea visual; path determina el tipo y nombre del archivo. Las funciones de apertura y error de imagen actualizan la vista previa.",
"state": "Estado de la vista previa del archivo"
},
"webPreview": {
"title": "WebPreviewPanelView · Contenido web",
"description": "Explora la barra de título, el aislamiento y las restricciones; actualiza un documento local.",
"options": "El entorno de ejecución elige restriction antes de aportar el contenido. children lo contiene y onRefresh solicita una actualización. Este iframe usa un srcDoc local.",
"state": "Estado de la vista previa web",
"frame": "Página web local de ejemplo",
"refreshes": "Actualizaciones: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Automatizaciones de sesión",
"description": "Consulta, edita, desactiva y elimina tareas con estados de carga y error.",
@@ -61,16 +61,6 @@
"scope": "Emplacement du fichier",
"hint": "Ouvrez le menu de copie par clic droit, ou placez le focus sur le fichier et appuyez sur Maj+F10."
},
"webLinks": {
"title": "Web links · Menu des liens",
"description": "Ouvrez le véritable menu des liens pour sélectionner un lien et copier son adresse.",
"options": "WebLink reçoit les attributs du lien. useMessageWebLinks collecte les liens affichés. MessageLinksMenu reçoit les entrées et les rappels de retour et de fermeture ; expanded contrôle la largeur. Les liens pointent vers des ressources locales de la galerie.",
"width": "Largeur du menu des liens",
"message": "Consultez la <gallery>galerie de composants</gallery> et l’<brand>image de marque</brand>.",
"close": "Fermer le menu des liens",
"open": "Voir les liens du message",
"hint": "Un clic droit permet de copier l’adresse d’un lien. Le menu collecte les liens du message affiché."
},
"workbench": {
"title": "PaneWorkbench · Volets multiples",
"description": "Changez la disposition, activez ou ajoutez des volets et ajustez leur position et leur taille.",
@@ -235,14 +225,6 @@
"options": "state fournit l’état d’affichage ; path détermine le type et le nom du fichier. Les rappels d’ouverture et d’erreur d’image actualisent l’aperçu.",
"state": "État de l’aperçu du fichier"
},
"webPreview": {
"title": "WebPreviewPanelView · Contenu web",
"description": "Explorez le titre, l’isolation et les restrictions ; actualisez un document local.",
"options": "Le runtime choisit restriction avant de fournir le contenu. children fournit le contenu ; onRefresh demande une actualisation. Cet iframe utilise un srcDoc local.",
"state": "État de l’aperçu web",
"frame": "Page web d’exemple locale",
"refreshes": "Actualisations : {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Automatisations de session",
"description": "Consultez, modifiez, désactivez et supprimez des tâches, avec chargement et erreurs.",
@@ -61,16 +61,6 @@
"scope": "Cakupan berkas",
"hint": "Klik kanan untuk membuka menu salin, atau fokuskan berkas lalu tekan Shift+F10."
},
"webLinks": {
"title": "Web links · Menu tautan",
"description": "Buka menu tautan asli untuk memilih tautan pesan dan menyalin alamatnya.",
"options": "WebLink menerima atribut tautan. useMessageWebLinks mengumpulkan tautan yang dirender. MessageLinksMenu menerima entri serta callback kembali dan tutup; expanded mengatur lebar. Semua tautan menuju sumber daya galeri lokal.",
"width": "Lebar menu tautan",
"message": "Lihat <gallery>galeri komponen</gallery> dan <brand>gambar merek</brand>.",
"close": "Tutup menu tautan",
"open": "Lihat tautan pesan",
"hint": "Klik kanan tautan untuk menyalin alamatnya. Menu mengumpulkan tautan dari pesan yang dirender."
},
"workbench": {
"title": "PaneWorkbench · Beberapa panel",
"description": "Ganti tata letak, aktifkan atau tambahkan panel, lalu atur posisi dan ukurannya.",
@@ -235,14 +225,6 @@
"options": "state menyediakan snapshot tampilan; path menentukan jenis dan nama berkas. Callback pembukaan dan kesalahan gambar memperbarui pratinjau.",
"state": "Status pratinjau berkas"
},
"webPreview": {
"title": "WebPreviewPanelView · Konten web",
"description": "Jelajahi bilah judul, keterangan isolasi, dan pembatasan; segarkan dokumen lokal.",
"options": "Runtime menentukan restriction sebelum menyediakan konten. children menyediakan konten; onRefresh meminta penyegaran. iframe ini memakai srcDoc lokal.",
"state": "Status pratinjau web",
"frame": "Halaman web contoh lokal",
"refreshes": "Penyegaran: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Otomatisasi sesi",
"description": "Lihat, edit, nonaktifkan, dan hapus tugas dengan status pemuatan dan kesalahan.",
@@ -61,16 +61,6 @@
"scope": "ファイルの範囲",
"hint": "右クリックでコピーメニューを開くか、ファイルにフォーカスして Shift+F10 を押してください。"
},
"webLinks": {
"title": "Web links · リンクメニュー",
"description": "実際のリンクメニューでメッセージのリンクを選び、アドレスをコピーできます。",
"options": "WebLink はリンク属性を受け取ります。useMessageWebLinks は表示済みのリンクを収集します。MessageLinksMenu は項目と戻る・閉じるコールバックを受け取り、expanded が幅を制御します。リンク先はすべてローカルのギャラリー素材です。",
"width": "リンクメニューの幅",
"message": "<gallery>コンポーネントギャラリー</gallery>と<brand>ブランド画像</brand>を表示します。",
"close": "リンクメニューを閉じる",
"open": "メッセージのリンクを見る",
"hint": "リンクを右クリックするとアドレスをコピーできます。メニューは表示済みメッセージからリンクを収集します。"
},
"workbench": {
"title": "PaneWorkbench · 複数ペイン",
"description": "レイアウトの切り替え、ペインの選択・追加、移動やサイズ変更を試せます。",
@@ -235,14 +225,6 @@
"options": "state は表示状態を提供し、path はファイルの種類と名前を決定します。画像の表示・エラーコールバックがプレビューを更新します。",
"state": "ファイルプレビューの状態"
},
"webPreview": {
"title": "WebPreviewPanelView · ウェブ内容",
"description": "タイトルバー、隔離の説明、各種制限を確認し、ローカル文書を更新できます。",
"options": "ランタイムが restriction を決めてから内容を渡します。children が内容を提供し、onRefresh が更新を要求します。この iframe はローカルの srcDoc を使います。",
"state": "ウェブプレビューの状態",
"frame": "ローカルのサンプルページ",
"refreshes": "更新回数:{{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · セッションの自動化",
"description": "タスクの表示、編集、無効化、削除と読み込み・エラー状態を試せます。",
@@ -61,16 +61,6 @@
"scope": "파일 범위",
"hint": "오른쪽 클릭으로 복사 메뉴를 열거나 파일에 초점을 두고 Shift+F10을 누르세요."
},
"webLinks": {
"title": "Web links · 링크 메뉴",
"description": "실제 링크 메뉴에서 메시지의 링크를 선택하고 주소를 복사합니다.",
"options": "WebLink는 링크 속성을 받습니다. useMessageWebLinks는 렌더링된 링크를 수집합니다. MessageLinksMenu는 항목과 뒤로 가기·닫기 콜백을 받고 expanded로 너비를 정합니다. 예제 링크는 모두 로컬 갤러리 리소스로 연결됩니다.",
"width": "링크 메뉴 너비",
"message": "<gallery>컴포넌트 갤러리</gallery>와 <brand>브랜드 이미지</brand>를 확인하세요.",
"close": "링크 메뉴 닫기",
"open": "메시지 링크 보기",
"hint": "링크를 오른쪽 클릭하면 주소를 복사할 수 있습니다. 메시지 메뉴는 실제 표시된 링크를 수집합니다."
},
"workbench": {
"title": "PaneWorkbench · 여러 창",
"description": "레이아웃을 바꾸고 창을 선택하거나 추가하며 위치와 크기를 조절합니다.",
@@ -235,14 +225,6 @@
"options": "state가 표시 스냅샷을 제공하고 path가 파일 형식과 이름을 정합니다. 이미지 열기와 오류 콜백이 미리보기를 갱신합니다.",
"state": "파일 미리보기 상태"
},
"webPreview": {
"title": "WebPreviewPanelView · 웹 콘텐츠",
"description": "웹 제목 표시줄, 격리 안내, 제한을 확인하고 로컬 문서를 새로 고칩니다.",
"options": "런타임이 restriction을 정한 후 내용을 전달합니다. children이 내용을 제공하고 onRefresh가 새로고침을 요청합니다. 이 iframe은 로컬 srcDoc을 사용합니다.",
"state": "웹 미리보기 상태",
"frame": "로컬 예제 웹페이지",
"refreshes": "새로고침 횟수: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · 세션 자동화",
"description": "작업 조회, 편집, 비활성화, 삭제와 로딩·오류 상태를 시험합니다.",
@@ -61,16 +61,6 @@
"scope": "Escopo do arquivo",
"hint": "Clique com o botão direito para abrir o menu de cópia, ou foque o arquivo e pressione Shift+F10."
},
"webLinks": {
"title": "Web links · Menu de links",
"description": "Abra o menu real de links para selecionar links da mensagem e copiar endereços.",
"options": "WebLink recebe atributos de link. useMessageWebLinks coleta os links renderizados. MessageLinksMenu recebe entradas e callbacks de voltar e fechar; expanded controla a largura. Todos os links apontam para recursos locais da galeria.",
"width": "Largura do menu de links",
"message": "Veja a <gallery>galeria de componentes</gallery> e a <brand>imagem de marca</brand>.",
"close": "Fechar menu de links",
"open": "Ver links da mensagem",
"hint": "Clique com o botão direito em um link para copiar o endereço. O menu coleta os links da mensagem renderizada."
},
"workbench": {
"title": "PaneWorkbench · Múltiplos painéis",
"description": "Mude o layout, ative ou adicione painéis e ajuste a posição e o tamanho.",
@@ -235,14 +225,6 @@
"options": "state fornece o estado visual; path determina o tipo e o nome do arquivo. Os callbacks de abertura e erro de imagem atualizam a prévia.",
"state": "Estado da prévia do arquivo"
},
"webPreview": {
"title": "WebPreviewPanelView · Conteúdo web",
"description": "Explore a barra de título, o isolamento e as restrições; atualize um documento local.",
"options": "O runtime escolhe restriction antes de fornecer o conteúdo. children fornece o conteúdo; onRefresh solicita a atualização. Este iframe usa um srcDoc local.",
"state": "Estado da prévia web",
"frame": "Página web local de exemplo",
"refreshes": "Atualizações: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Automações da sessão",
"description": "Veja, edite, desative e exclua tarefas com estados de carregamento e erro.",
@@ -61,16 +61,6 @@
"scope": "Phạm vi tệp",
"hint": "Nhấp chuột phải để mở menu sao chép, hoặc đưa tiêu điểm vào tệp rồi nhấn Shift+F10."
},
"webLinks": {
"title": "Web links · Menu liên kết",
"description": "Mở menu liên kết thực để chọn liên kết trong tin nhắn và sao chép địa chỉ.",
"options": "WebLink nhận thuộc tính liên kết. useMessageWebLinks thu thập liên kết đã hiển thị. MessageLinksMenu nhận các mục và hàm gọi lại để quay lại, đóng; expanded điều khiển chiều rộng. Mọi liên kết đều trỏ đến tài nguyên thư viện cục bộ.",
"width": "Chiều rộng menu liên kết",
"message": "Xem <gallery>thư viện thành phần</gallery> và <brand>ảnh thương hiệu</brand>.",
"close": "Đóng menu liên kết",
"open": "Xem liên kết trong tin nhắn",
"hint": "Nhấp chuột phải vào liên kết để sao chép địa chỉ. Menu thu thập liên kết từ tin nhắn đã hiển thị."
},
"workbench": {
"title": "PaneWorkbench · Nhiều ngăn",
"description": "Đổi bố cục, kích hoạt hoặc thêm ngăn, điều chỉnh vị trí và kích thước.",
@@ -235,14 +225,6 @@
"options": "state cung cấp trạng thái hiển thị; path xác định loại và tên tệp. Hàm gọi lại mở ảnh và lỗi ảnh cập nhật bản xem trước.",
"state": "Trạng thái xem trước tệp"
},
"webPreview": {
"title": "WebPreviewPanelView · Nội dung web",
"description": "Khám phá thanh tiêu đề, thông tin cách ly và giới hạn; làm mới tài liệu cục bộ.",
"options": "Runtime chọn restriction trước khi cung cấp nội dung. children cung cấp nội dung; onRefresh yêu cầu làm mới. iframe này dùng srcDoc cục bộ.",
"state": "Trạng thái xem trước web",
"frame": "Trang web ví dụ cục bộ",
"refreshes": "Số lần làm mới: {{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · Tác vụ tự động của phiên",
"description": "Xem, sửa, tắt và xóa tác vụ với trạng thái đang tải và lỗi.",
@@ -61,16 +61,6 @@
"scope": "文件范围",
"hint": "右键打开复制菜单,也可聚焦文件后按 Shift+F10。"
},
"webLinks": {
"title": "Web links · 链接菜单",
"description": "选择消息链接并复制地址。",
"options": "WebLink 接收链接属性;useMessageWebLinks 收集实际渲染的消息链接。MessageLinksMenu 接收条目、返回与关闭回调,expanded 控制宽度。示例链接均指向本地画廊资源。",
"width": "链接菜单宽度",
"message": "查看<gallery>组件画廊</gallery>和<brand>品牌图片</brand>。",
"close": "关闭链接菜单",
"open": "查看消息链接",
"hint": "右键链接可复制地址;消息菜单从实际渲染的链接中收集条目。"
},
"workbench": {
"title": "PaneWorkbench · 多窗格",
"description": "切换布局、激活或添加窗格并调整尺寸。",
@@ -235,14 +225,6 @@
"options": "state 为显示快照;path 决定文件类型和名称;图片打开与失败回调更新当前预览。",
"state": "文件预览状态"
},
"webPreview": {
"title": "WebPreviewPanelView · 网页内容",
"description": "查看隔离与限制提示,试用刷新本地文档。",
"options": "运行时先决定 restriction,再提供内容。children 接收内容,onRefresh 请求刷新;此示例的 iframe 使用本地 srcDoc。",
"state": "网页预览状态",
"frame": "本地示例网页",
"refreshes": "刷新次数:{{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · 会话任务",
"description": "查看、编辑、停用和删除会话任务。",
@@ -61,16 +61,6 @@
"scope": "檔案範圍",
"hint": "按右鍵開啟複製選單,或聚焦檔案後按 Shift+F10。"
},
"webLinks": {
"title": "Web links · 連結選單",
"description": "選擇訊息連結並複製網址。",
"options": "WebLink 接收連結屬性;useMessageWebLinks 收集實際呈現的訊息連結。MessageLinksMenu 接收項目、返回與關閉回呼,expanded 控制寬度。範例連結皆指向本機元件庫資源。",
"width": "連結選單寬度",
"message": "查看<gallery>元件庫</gallery>與<brand>品牌圖片</brand>。",
"close": "關閉連結選單",
"open": "查看訊息連結",
"hint": "在連結上按右鍵可複製網址;訊息選單從實際呈現的連結收集項目。"
},
"workbench": {
"title": "PaneWorkbench · 多窗格",
"description": "切換版面、啟用或新增窗格並調整尺寸。",
@@ -235,14 +225,6 @@
"options": "state 為顯示快照;path 決定檔案類型與名稱;圖片開啟與失敗回呼更新目前預覽。",
"state": "檔案預覽狀態"
},
"webPreview": {
"title": "WebPreviewPanelView · 網頁內容",
"description": "查看隔離與限制提示,試用重新整理。",
"options": "執行階段先決定 restriction,再提供內容。children 接收內容,onRefresh 請求重新整理;此範例的 iframe 使用本機 srcDoc。",
"state": "網頁預覽狀態",
"frame": "本機範例網頁",
"refreshes": "重新整理次數:{{amount}}"
},
"session": {
"title": "SessionInfoPopoverView · 對話任務",
"description": "查看、編輯、停用與刪除對話任務。",
+1 -28
View File
@@ -1,4 +1,4 @@
import { useRef, useState, type ReactNode } from "react";
import { useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Trans, useTranslation } from "react-i18next";
@@ -7,13 +7,11 @@ import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";
import { DeleteConfirm } from "@/components/DeleteConfirm";
import { FileActions } from "@/components/FileActions";
import { InlineTokenHighlight, INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";
import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu";
import { RenameDialog } from "@/components/RenameDialog";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { SlashCommandText } from "@/components/SlashCommandText";
import { StartupShell } from "@/components/StartupShell";
import { UserMessageText } from "@/components/UserMessageText";
import { WebLink } from "@/components/WebLink";
import * as ProductIcons from "@/components/icons/product-icons";
import { HostCompatibilityDialog } from "@/components/remote/HostCompatibilityDialog";
import { HostConnectionStatus } from "@/components/remote/HostConnectionStatus";
@@ -174,28 +172,6 @@ function FileActionsPreview() {
</>;
}
function WebLinksPreview() {
const { t } = useGalleryTranslation();
const [open, setOpen] = useState(false);
const [display, setDisplay] = useState<"compact" | "expanded">("compact");
const message = useRef<HTMLDivElement>(null);
const links = useMessageWebLinks(message, open);
return <div className="space-y-4">
<StatePicker label={t("previews.webLinks.width")} value={display} options={["compact", "expanded"]} onChange={setDisplay} />
<div ref={message} className="text-sm leading-7"><p data-assistant-selectable>
<Trans t={t} i18nKey="previews.webLinks.message" components={{
gallery: <WebLink href={`${window.location.origin}/gallery.html`} className="underline underline-offset-4" />,
brand: <WebLink href={`${window.location.origin}/brand/nanobot_icon_512.png`} className="underline underline-offset-4" />,
}} />
</p></div>
<Button variant="outline" onClick={() => setOpen((value) => !value)}>{t(open ? "previews.webLinks.close" : "previews.webLinks.open")}</Button>
{open && links.length > 0 ? <div className="rounded-control border p-1">
<MessageLinksMenu links={links} onBack={() => setOpen(false)} onClose={() => setOpen(false)} expanded={display === "expanded"} />
</div> : null}
<p className="text-xs text-muted-foreground">{t("previews.webLinks.hint")}</p>
</div>;
}
const initialPanes: WorkbenchPane[] = [
{ key: "pane-1", title: "组件设计" }, { key: "pane-2", title: "实现" }, { key: "pane-3", title: "验证" },
];
@@ -289,9 +265,6 @@ export const shellExamples: ComponentExample[] = [
{ title: "previews.fileActions.title", files: ["FileActions"], Preview: FileActionsPreview,
description: "previews.fileActions.description", options: "previews.fileActions.options",
code: '<FileActions path="src/app.tsx" metadata={{ path: "D:/workspace/src/app.tsx", relative_path: "src/app.tsx" }}><Button>app.tsx</Button></FileActions>' },
{ title: "previews.webLinks.title", files: ["WebLink", "MessageLinksMenu"], Preview: WebLinksPreview,
description: "previews.webLinks.description", options: "previews.webLinks.options",
code: '<WebLink href={url}>组件画廊</WebLink>\nconst links = useMessageWebLinks(messageRef, open);\n<MessageLinksMenu links={links} onBack={close} onClose={close} expanded />' },
{ title: "previews.workbench.title", files: ["workbench/PaneWorkbench"], Preview: WorkbenchPreview,
description: "previews.workbench.description", options: "previews.workbench.options",
code: '<PaneWorkbench panes={panes} activePaneKey={active} layout={layout} showLayoutControl onActivatePane={setActive} onAddPane={addPane} onLayoutChange={setLayout} onPaneOrderChange={reorder} renderPane={renderPane} />' },
+6 -11
View File
@@ -2,7 +2,6 @@ import { useCallback, useState, useSyncExternalStore } from "react";
export interface PreviewTab {
id: string;
kind: "file" | "web";
value: string;
canonicalPath?: string;
}
@@ -37,11 +36,11 @@ export class FilePreviewStore {
this.listeners.forEach((listener) => listener());
}
open(key: string, kind: PreviewTab["kind"], value: string) {
open(key: string, value: string) {
const previous = this.get(key);
const id = `${kind}:${value}`;
const id = `file:${value}`;
const tabs = previous.tabs.some((tab) => tab.id === id)
? previous.tabs : [...previous.tabs, { id, kind, value }];
? previous.tabs : [...previous.tabs, { id, value }];
this.update(key, { tabs, activeId: id });
}
@@ -51,8 +50,7 @@ export class FilePreviewStore {
const id = `file:${path}`;
const current = previous.tabs.find(tab => tab.id === id);
if (!current || current.canonicalPath === canonicalPath) return;
const existing = previous.tabs.find(tab => tab.id !== id && tab.kind === "file"
&& tab.canonicalPath === canonicalPath);
const existing = previous.tabs.find(tab => tab.id !== id && tab.canonicalPath === canonicalPath);
const tabs = existing
? previous.tabs.filter(tab => tab.id !== id)
: previous.tabs.map(tab => tab.id === id ? { ...tab, canonicalPath } : tab);
@@ -94,7 +92,7 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const snapshot = useCallback(() => store.get(key), [key, store]);
const state = useSyncExternalStore(store.subscribe, snapshot, snapshot);
const openFile = useCallback((path: string) => {
if (key) store.open(key, "file", path);
if (key) store.open(key, path);
}, [key, store]);
const resolveFile = useCallback((path: string, canonicalPath: string) => {
if (key) store.resolveFile(key, path, canonicalPath);
@@ -102,9 +100,6 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const setWidth = useCallback((width: number) => {
if (key) store.update(key, { width });
}, [key, store]);
const openWeb = useCallback((url: string) => {
if (key) store.open(key, "web", url);
}, [key, store]);
const selectTab = useCallback((id: string) => {
if (key) store.select(key, id);
}, [key, store]);
@@ -114,5 +109,5 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const close = useCallback(() => {
if (key) store.close(key);
}, [key, store]);
return { state, openFile, resolveFile, openWeb, selectTab, closeTab, close, setWidth };
return { state, openFile, resolveFile, selectTab, closeTab, close, setWidth };
}
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Preview",
"closeTab": "Close {{name}}",
"closeAll": "Close preview pane",
"websiteInfo": "About website previews"
},
"webPreview": {
"viewLinks": "View links",
"back": "Back",
"original": "Original link",
"actions": "Link actions",
"open": "Preview website",
"external": "Open in browser",
"copy": "Copy link",
"copied": "Link copied",
"copyFailed": "Could not copy link",
"title": "Website preview",
"resize": "Resize website preview",
"refresh": "Refresh website",
"close": "Close preview",
"isolated": "Restricted, isolated preview. Sign-in and interactive features may not work.",
"blockedHint": "Some sites block embedding. If this view stays blank or fails, open it in your browser.",
"loopback": "Localhost points to this browser’s device, not a remote gateway. No ports are forwarded.",
"native": "Embedded previews are unavailable in the native host. Open this link in your browser.",
"unsupported": "This browser does not support credential-isolated previews. Open this link in a new tab.",
"sameOrigin": "The nanobot application itself cannot be embedded here. Open it in a new tab.",
"mixedContent": "An HTTPS page cannot preview an HTTP website here. Open it in a new tab.",
"invalid": "This address cannot be previewed.",
"frame": "Website preview: {{host}}"
"closeAll": "Close preview pane"
},
"starPrompt": {
"footerAction": "Star nanobot on GitHub",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Vista previa",
"closeTab": "Cerrar {{name}}",
"closeAll": "Cerrar panel de vista previa",
"websiteInfo": "Acerca de las vistas previas web"
},
"webPreview": {
"viewLinks": "Ver enlaces",
"back": "Atrás",
"original": "Enlace original",
"actions": "Acciones del enlace",
"open": "Vista previa del sitio",
"external": "Abrir en navegador",
"copy": "Copiar enlace",
"copied": "Enlace copiado",
"copyFailed": "No se pudo copiar el enlace",
"title": "Vista previa web",
"resize": "Cambiar ancho de la vista previa",
"refresh": "Actualizar sitio",
"close": "Cerrar vista previa",
"isolated": "Vista previa aislada y limitada. El inicio de sesión y algunas funciones pueden no funcionar.",
"blockedHint": "Algunos sitios bloquean la inserción. Si la vista está vacía o falla, ábrela en el navegador.",
"loopback": "Localhost apunta al dispositivo de este navegador, no a una pasarela remota. No se reenvían puertos.",
"native": "La aplicación nativa no admite vistas previas incrustadas. Abre el enlace en el navegador.",
"unsupported": "Este navegador no admite vistas previas con credenciales aisladas. Abre el enlace en una pestaña nueva.",
"sameOrigin": "No se puede incrustar la propia aplicación nanobot. Ábrela en una pestaña nueva.",
"mixedContent": "Una página HTTPS no puede previsualizar un sitio HTTP aquí. Ábrelo en una pestaña nueva.",
"invalid": "No se puede previsualizar esta dirección.",
"frame": "Vista previa web: {{host}}"
"closeAll": "Cerrar panel de vista previa"
},
"starPrompt": {
"footerAction": "Dale una estrella a nanobot",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Aperçu",
"closeTab": "Fermer {{name}}",
"closeAll": "Fermer le panneau d’aperçu",
"websiteInfo": "À propos des aperçus web"
},
"webPreview": {
"viewLinks": "Voir les liens",
"back": "Retour",
"original": "Lien d’origine",
"actions": "Actions du lien",
"open": "Aperçu du site",
"external": "Ouvrir dans le navigateur",
"copy": "Copier le lien",
"copied": "Lien copié",
"copyFailed": "Impossible de copier le lien",
"title": "Aperçu web",
"resize": "Redimensionner l’aperçu web",
"refresh": "Actualiser le site",
"close": "Fermer l’aperçu",
"isolated": "Aperçu isolé et limité. La connexion et certaines interactions peuvent ne pas fonctionner.",
"blockedHint": "Certains sites bloquent l’intégration. Si la vue reste vide ou échoue, ouvrez-la dans le navigateur.",
"loopback": "Localhost désigne l’appareil de ce navigateur, pas une passerelle distante. Aucun port n’est redirigé.",
"native": "L’application native ne prend pas en charge les aperçus intégrés. Ouvrez ce lien dans le navigateur.",
"unsupported": "Ce navigateur ne prend pas en charge les aperçus aux identifiants isolés. Ouvrez un nouvel onglet.",
"sameOrigin": "L’application nanobot elle-même ne peut pas être intégrée ici. Ouvrez un nouvel onglet.",
"mixedContent": "Une page HTTPS ne peut pas afficher un site HTTP ici. Ouvrez un nouvel onglet.",
"invalid": "Cette adresse ne peut pas être prévisualisée.",
"frame": "Aperçu web : {{host}}"
"closeAll": "Fermer le panneau d’aperçu"
},
"starPrompt": {
"footerAction": "Ajouter une étoile à nanobot",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Pratinjau",
"closeTab": "Tutup {{name}}",
"closeAll": "Tutup panel pratinjau",
"websiteInfo": "Tentang pratinjau situs"
},
"webPreview": {
"viewLinks": "Lihat tautan",
"back": "Kembali",
"original": "Tautan asli",
"actions": "Tindakan tautan",
"open": "Pratinjau situs",
"external": "Buka di browser",
"copy": "Salin tautan",
"copied": "Tautan disalin",
"copyFailed": "Tidak dapat menyalin tautan",
"title": "Pratinjau situs",
"resize": "Ubah lebar pratinjau",
"refresh": "Muat ulang situs",
"close": "Tutup pratinjau",
"isolated": "Pratinjau terisolasi dan terbatas. Login dan beberapa interaksi mungkin tidak berfungsi.",
"blockedHint": "Beberapa situs memblokir penyematan. Jika kosong atau gagal, buka di browser.",
"loopback": "Localhost merujuk ke perangkat browser ini, bukan gateway jarak jauh. Port tidak diteruskan.",
"native": "Aplikasi native tidak mendukung pratinjau tertanam. Buka tautan ini di browser.",
"unsupported": "Browser ini tidak mendukung pratinjau dengan kredensial terisolasi. Buka di tab baru.",
"sameOrigin": "Aplikasi nanobot sendiri tidak dapat disematkan di sini. Buka di tab baru.",
"mixedContent": "Halaman HTTPS tidak dapat menampilkan situs HTTP di sini. Buka di tab baru.",
"invalid": "Alamat ini tidak dapat dipratinjau.",
"frame": "Pratinjau situs: {{host}}"
"closeAll": "Tutup panel pratinjau"
},
"starPrompt": {
"footerAction": "Beri bintang untuk nanobot",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "プレビュー",
"closeTab": "{{name}} を閉じる",
"closeAll": "プレビューパネルを閉じる",
"websiteInfo": "ウェブプレビューについて"
},
"webPreview": {
"viewLinks": "リンクを表示",
"back": "戻る",
"original": "元のリンク",
"actions": "リンク操作",
"open": "ウェブサイトをプレビュー",
"external": "ブラウザーで開く",
"copy": "リンクをコピー",
"copied": "リンクをコピーしました",
"copyFailed": "リンクをコピーできませんでした",
"title": "ウェブプレビュー",
"resize": "プレビューの幅を変更",
"refresh": "ウェブサイトを再読み込み",
"close": "プレビューを閉じる",
"isolated": "制限付きの分離プレビューです。ログインや一部の操作は利用できない場合があります。",
"blockedHint": "埋め込みを許可しないサイトもあります。空白やエラーの場合はブラウザーで開いてください。",
"loopback": "localhost はリモートゲートウェイではなく、このブラウザーの端末を指します。ポート転送は行いません。",
"native": "ネイティブホストでは埋め込みプレビューを利用できません。ブラウザーで開いてください。",
"unsupported": "このブラウザーは認証情報を分離したプレビューに対応していません。新しいタブで開いてください。",
"sameOrigin": "nanobot 自体は埋め込めません。新しいタブで開いてください。",
"mixedContent": "HTTPS ページでは HTTP サイトをプレビューできません。新しいタブで開いてください。",
"invalid": "このアドレスはプレビューできません。",
"frame": "ウェブプレビュー:{{host}}"
"closeAll": "プレビューパネルを閉じる"
},
"starPrompt": {
"footerAction": "nanobot にスターを付ける",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "미리보기",
"closeTab": "{{name}} 닫기",
"closeAll": "미리보기 패널 닫기",
"websiteInfo": "웹 미리보기 정보"
},
"webPreview": {
"viewLinks": "링크 보기",
"back": "뒤로",
"original": "원본 링크",
"actions": "링크 작업",
"open": "웹사이트 미리보기",
"external": "브라우저에서 열기",
"copy": "링크 복사",
"copied": "링크를 복사했습니다",
"copyFailed": "링크를 복사하지 못했습니다",
"title": "웹사이트 미리보기",
"resize": "웹 미리보기 너비 조절",
"refresh": "웹사이트 새로고침",
"close": "미리 보기 닫기",
"isolated": "제한된 격리 미리보기입니다. 로그인 및 일부 상호작용이 작동하지 않을 수 있습니다.",
"blockedHint": "일부 사이트는 삽입을 차단합니다. 비어 있거나 실패하면 브라우저에서 여세요.",
"loopback": "localhost는 원격 게이트웨이가 아닌 이 브라우저의 기기를 가리킵니다. 포트는 전달되지 않습니다.",
"native": "네이티브 호스트에서는 삽입 미리보기를 지원하지 않습니다. 브라우저에서 여세요.",
"unsupported": "이 브라우저는 인증 정보 격리 미리보기를 지원하지 않습니다. 새 탭에서 여세요.",
"sameOrigin": "nanobot 앱 자체는 여기에 삽입할 수 없습니다. 새 탭에서 여세요.",
"mixedContent": "HTTPS 페이지에서 HTTP 사이트를 미리 볼 수 없습니다. 새 탭에서 여세요.",
"invalid": "이 주소를 미리 볼 수 없습니다.",
"frame": "웹 미리보기: {{host}}"
"closeAll": "미리보기 패널 닫기"
},
"starPrompt": {
"footerAction": "nanobot에 스타 남기기",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Prévia",
"closeTab": "Fechar {{name}}",
"closeAll": "Fechar painel de prévia",
"websiteInfo": "Sobre as prévias de sites"
},
"webPreview": {
"viewLinks": "Ver links",
"back": "Voltar",
"original": "Link original",
"actions": "Ações do link",
"open": "Pré-visualizar site",
"external": "Abrir no navegador",
"copy": "Copiar link",
"copied": "Link copiado",
"copyFailed": "Não foi possível copiar o link",
"title": "Prévia do site",
"resize": "Redimensionar prévia",
"refresh": "Atualizar site",
"close": "Fechar prévia",
"isolated": "Prévia isolada e limitada. O login e algumas interações podem não funcionar.",
"blockedHint": "Alguns sites bloqueiam a incorporação. Se a prévia ficar vazia ou falhar, abra no navegador.",
"loopback": "Localhost aponta para o dispositivo deste navegador, não para um gateway remoto. Nenhuma porta é encaminhada.",
"native": "O aplicativo nativo não permite prévias incorporadas. Abra o link no navegador.",
"unsupported": "Este navegador não permite prévias com credenciais isoladas. Abra em uma nova aba.",
"sameOrigin": "O próprio aplicativo nanobot não pode ser incorporado aqui. Abra em uma nova aba.",
"mixedContent": "Uma página HTTPS não pode exibir um site HTTP aqui. Abra em uma nova aba.",
"invalid": "Não é possível pré-visualizar este endereço.",
"frame": "Prévia do site: {{host}}"
"closeAll": "Fechar painel de prévia"
},
"starPrompt": {
"footerAction": "Dê uma estrela ao nanobot",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "Xem trước",
"closeTab": "Đóng {{name}}",
"closeAll": "Đóng khung xem trước",
"websiteInfo": "Giới thiệu về xem trước trang web"
},
"webPreview": {
"viewLinks": "Xem liên kết",
"back": "Quay lại",
"original": "Liên kết gốc",
"actions": "Thao tác liên kết",
"open": "Xem trước trang web",
"external": "Mở trong trình duyệt",
"copy": "Sao chép liên kết",
"copied": "Đã sao chép liên kết",
"copyFailed": "Không thể sao chép liên kết",
"title": "Xem trước trang web",
"resize": "Đổi chiều rộng bản xem trước",
"refresh": "Tải lại trang web",
"close": "Đóng bản xem trước",
"isolated": "Bản xem trước cách ly và hạn chế. Đăng nhập và một số tương tác có thể không hoạt động.",
"blockedHint": "Một số trang chặn nhúng. Nếu nội dung trống hoặc bị lỗi, hãy mở trong trình duyệt.",
"loopback": "Localhost trỏ đến thiết bị của trình duyệt này, không phải gateway từ xa. Không có chuyển tiếp cổng.",
"native": "Ứng dụng gốc không hỗ trợ xem trước nhúng. Hãy mở liên kết trong trình duyệt.",
"unsupported": "Trình duyệt này không hỗ trợ xem trước cách ly thông tin xác thực. Hãy mở trong tab mới.",
"sameOrigin": "Không thể nhúng chính ứng dụng nanobot tại đây. Hãy mở trong tab mới.",
"mixedContent": "Trang HTTPS không thể xem trước trang HTTP tại đây. Hãy mở trong tab mới.",
"invalid": "Không thể xem trước địa chỉ này.",
"frame": "Xem trước trang web: {{host}}"
"closeAll": "Đóng khung xem trước"
},
"starPrompt": {
"footerAction": "Tặng nanobot một sao",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "预览",
"closeTab": "关闭 {{name}}",
"closeAll": "关闭预览栏",
"websiteInfo": "关于网页预览"
},
"webPreview": {
"viewLinks": "查看链接",
"back": "返回",
"original": "原链接",
"actions": "链接操作",
"open": "预览网页",
"external": "浏览器打开",
"copy": "复制链接",
"copied": "链接已复制",
"copyFailed": "无法复制链接",
"title": "网页预览",
"resize": "调整网页预览宽度",
"refresh": "刷新网页",
"close": "关闭预览",
"isolated": "受限的隔离预览,登录及部分交互功能可能无法使用。",
"blockedHint": "部分网站禁止嵌入。如果页面空白或加载失败,请在浏览器中打开。",
"loopback": "localhost 指向当前浏览器所在设备,而非远程网关。不会自动转发端口。",
"native": "原生客户端暂不支持嵌入预览,请在浏览器中打开此链接。",
"unsupported": "此浏览器不支持凭据隔离预览,请在新标签页中打开。",
"sameOrigin": "不能在此嵌入 nanobot 应用自身,请在新标签页中打开。",
"mixedContent": "HTTPS 页面不能在此预览 HTTP 网站,请在新标签页中打开。",
"invalid": "无法预览此地址。",
"frame": "网页预览:{{host}}"
"closeAll": "关闭预览栏"
},
"starPrompt": {
"footerAction": "给 nanobot 点个 Star",
+1 -26
View File
@@ -355,32 +355,7 @@
"previewTabs": {
"title": "預覽",
"closeTab": "關閉 {{name}}",
"closeAll": "關閉預覽欄",
"websiteInfo": "關於網頁預覽"
},
"webPreview": {
"viewLinks": "查看連結",
"back": "返回",
"original": "原連結",
"actions": "連結操作",
"open": "預覽網頁",
"external": "瀏覽器開啟",
"copy": "複製連結",
"copied": "已複製連結",
"copyFailed": "無法複製連結",
"title": "網頁預覽",
"resize": "調整網頁預覽寬度",
"refresh": "重新整理網頁",
"close": "關閉預覽",
"isolated": "受限的隔離預覽,登入及部分互動功能可能無法使用。",
"blockedHint": "部分網站禁止嵌入。若頁面空白或載入失敗,請在瀏覽器中開啟。",
"loopback": "localhost 指向目前瀏覽器所在裝置,而非遠端閘道。不會轉送任何連接埠。",
"native": "原生用戶端暫不支援嵌入預覽,請在瀏覽器中開啟此連結。",
"unsupported": "此瀏覽器不支援憑證隔離預覽,請在新分頁中開啟。",
"sameOrigin": "無法在此嵌入 nanobot 應用程式本身,請在新分頁中開啟。",
"mixedContent": "HTTPS 頁面無法在此預覽 HTTP 網站,請在新分頁中開啟。",
"invalid": "無法預覽此位址。",
"frame": "網頁預覽:{{host}}"
"closeAll": "關閉預覽欄"
},
"starPrompt": {
"footerAction": "給 nanobot 一顆 Star",
-32
View File
@@ -1,32 +0,0 @@
import { isNativeRuntime } from "@/lib/runtime";
/** Only explicit web URLs belong in the web-link menu; file/session links have other owners. */
export function parseWebLink(value: string): URL | null {
if (value.length > 8192 || value.includes("\\")
|| Array.from(value).some((char) => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127)) return null;
try {
const url = new URL(value);
return /^https?:$/.test(url.protocol) && !url.username && !url.password ? url : null;
} catch {
return null;
}
}
export function webPreviewRestriction(
url: URL,
pageUrl: URL,
native: boolean,
credentialless: boolean,
): "native" | "unsupported" | "sameOrigin" | "mixedContent" | null {
if (native) return "native";
if (!credentialless) return "unsupported";
if (url.origin === pageUrl.origin) return "sameOrigin";
if (pageUrl.protocol === "https:" && url.protocol === "http:") return "mixedContent";
return null;
}
/** Menus and restored preview tabs must agree on the current browser's boundary. */
export function currentWebPreviewRestriction(url: URL | null) {
return url ? webPreviewRestriction(url, new URL(window.location.href), isNativeRuntime(),
"credentialless" in HTMLIFrameElement.prototype) : "invalid";
}
+1 -1
View File
@@ -92,7 +92,7 @@ describe("FilePreviewPanel", () => {
});
const store = new FilePreviewStore();
const resource = createFilePreviewResource(path => fetchFilePreview("test", "a", path));
store.open("a", "file", "reports/REPORT.md");
store.open("a", "reports/REPORT.md");
function View() {
const { state, openFile, resolveFile, selectTab, closeTab, close } = useFilePreviewState("a", store);
const active = state.tabs.find(tab => tab.id === state.activeId)!;
+1 -1
View File
@@ -41,7 +41,7 @@ describe("shared file icons", () => {
const open = vi.fn();
render(<>
<FileReferenceChip path={path} onOpen={open} />
<PreviewPane tabs={[{ id: path, kind: "file", value: path }]} activeId={path}
<PreviewPane tabs={[{ id: path, value: path }]} activeId={path}
width={544} isClosing={false} onSelect={() => {}} onCloseTab={() => {}}
onClose={() => {}} onResizeStart={() => {}}><p>Preview</p></PreviewPane>
<AttachmentTile attachment={{ kind: "file", name: path, url: `/download/${path}` }} />
-209
View File
@@ -1,209 +0,0 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useRef } from "react";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { WebLink, WebPreviewContext } from "@/components/WebLink";
import { useMessageWebLinks } from "@/components/MessageLinksMenu";
import { copyTextToClipboard } from "@/lib/clipboard";
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn(async () => true) }));
const credentialless = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, "credentialless");
beforeEach(() => {
Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", { configurable: true, value: false });
});
afterEach(() => {
cleanup(); vi.unstubAllGlobals(); vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true);
if (credentialless) Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", credentialless);
else Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
});
function view(content: string, openPreview?: (url: string) => void) {
return <WebPreviewContext.Provider value={openPreview}>
<ThreadMessages messages={[{ id: "links", role: "assistant", content, createdAt: 1 }]} />
</WebPreviewContext.Provider>;
}
async function openLinks() {
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
fireEvent.click(await screen.findByRole("button", { name: "View links" }));
return screen.getByRole("dialog", { name: "Message actions" });
}
describe("message link actions", () => {
beforeAll(preloadMarkdownText);
function mobileViewport() {
const listeners = new Set<() => void>();
let narrow = true;
vi.stubGlobal("matchMedia", vi.fn((query: string) => ({
get matches() { return query === "(max-width: 767px)" && narrow; },
media: query,
addEventListener: (_event: string, listener: () => void) => listeners.add(listener),
removeEventListener: (_event: string, listener: () => void) => listeners.delete(listener),
})));
return (value: boolean) => act(() => { narrow = value; listeners.forEach(listener => listener()); });
}
it("puts mobile actions after the reply and opens one bottom sheet with working back, copy and preview", async () => {
mobileViewport();
const preview = vi.fn();
const content = "[Website](https://example.com/demo)";
const { container } = render(view(content, preview));
const link = await screen.findByRole("link", { name: /Website/ });
const footer = container.querySelector("[data-message-mobile-actions]")!;
expect(link.compareDocumentPosition(footer) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(container.querySelector(".message-block-menu-trigger")).not.toBeInTheDocument();
expect(container.querySelector("[data-message-hover-time]")).not.toBeInTheDocument();
fireEvent.click(within(footer as HTMLElement).getByRole("button", { name: "Copy" }));
await waitFor(() => expect(copyTextToClipboard).toHaveBeenCalledWith(content));
const menu = await openLinks();
expect(menu).toHaveAttribute("data-message-mobile-sheet");
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
fireEvent.click(within(menu).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Message actions" })).toHaveFocus();
await openLinks();
fireEvent.click(screen.getByRole("button", { name: "Preview website" }));
expect(preview).toHaveBeenCalledWith("https://example.com/demo");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("restores the desktop menu on resize without duplicating actions", async () => {
const resize = mobileViewport();
const { container } = render(view("[Website](https://example.com/demo)"));
await screen.findByRole("link", { name: /Website/ });
await openLinks();
resize(false);
await waitFor(() => expect(container.querySelector("[data-message-mobile-actions]")).not.toBeInTheDocument());
expect(screen.queryByRole("dialog")).not.toHaveAttribute("data-message-mobile-sheet");
expect(screen.getAllByRole("button", { name: "Message actions" })).toHaveLength(1);
// Resizing may close the modal as focus is returned; either way its trigger stays usable.
if (!screen.queryByRole("dialog")) fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.getAllByRole("dialog")).toHaveLength(1);
});
it("keeps mobile users in the link sheet when isolated previews are unsupported", async () => {
mobileViewport();
Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
const preview = vi.fn();
render(view("[Website](https://example.com/demo)", preview));
await screen.findByRole("link", { name: /Website/ });
const menu = await openLinks();
expect(within(menu).queryByRole("button", { name: "Preview website" })).not.toBeInTheDocument();
expect(within(menu).getByText(/does not support credential-isolated/)).toBeVisible();
const external = within(menu).getByRole("link", { name: "Open in browser" });
expect(external).toHaveAttribute("href", "https://example.com/demo");
expect(external).toHaveAttribute("rel", "noreferrer noopener");
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
await waitFor(() => expect(copyTextToClipboard).toHaveBeenLastCalledWith("https://example.com/demo"));
expect(preview).not.toHaveBeenCalled();
expect(screen.getByRole("dialog")).toBe(menu);
});
it("keeps user actions outside the bubble and exposes a labelled mobile fork action", async () => {
mobileViewport();
const fork = vi.fn();
const { container } = render(<ThreadMessages onForkFromMessage={fork} messages={[
{ id: "user", role: "user", content: "A prompt", createdAt: 1 },
{ id: "reply", role: "assistant", content: "A reply", createdAt: 2 },
]} />);
await screen.findByText("A reply");
expect(container.querySelector("[data-user-text-bubble] [data-message-block-menu-trigger]")).toBeNull();
expect(container.querySelectorAll("[data-message-mobile-actions]")).toHaveLength(2);
fireEvent.click(screen.getAllByRole("button", { name: "Message actions" })[1]);
const menu = screen.getByRole("dialog");
expect(within(menu).getByRole("button", { name: "New chat from here" })).toHaveTextContent("New chat from here");
fireEvent.click(within(menu).getByRole("button", { name: "New chat from here" }));
expect(fork).toHaveBeenCalledWith(1);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("collects rendered links, deduplicates destinations and ignores code, images and file references", async () => {
render(view("[First](https://example.com/) and [Again](https://example.com).\n\n[Second](https://example.org/demo)\n\nhttps://example.net/plain\n\n`https://code.invalid/inline`\n\n```text\nhttps://code.invalid/block\n```\n\n![Image](https://image.invalid/pic.png)\n\n[notes.txt](notes.txt)"));
await screen.findByRole("link", { name: "First" });
const menu = await openLinks();
expect(within(menu).getAllByRole("button").map(button => button.textContent)).toEqual(["View links", "First", "Second", "https://example.net/plain"]);
expect(within(menu).queryByRole("button", { name: "Again" })).not.toBeInTheDocument();
expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible();
expect(within(menu).getByRole("button", { name: "https://example.net/plain" })).toBeVisible();
fireEvent.click(within(menu).getByRole("button", { name: "First" }));
expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("href", "https://example.com/");
expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener");
expect(within(menu).queryByRole("button", { name: "Preview website" })).not.toBeInTheDocument();
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible();
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible();
});
it("does not show an entry for a message without a rendered web link", async () => {
render(view("No links here. `https://example.com/code` [Mail](mailto:test@example.com) [Unsafe](javascript:alert)"));
await screen.findByText(/No links here/);
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.queryByRole("button", { name: "View links" })).not.toBeInTheDocument();
});
it("opens the single link's actions directly and closes the message menu on preview", async () => {
const preview = vi.fn();
render(view("[Website](https://example.com/demo?q=one#two)", preview));
await screen.findByRole("link", { name: /Website/ });
const menu = await openLinks();
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.click(within(menu).getByRole("button", { name: "Preview website" }));
expect(preview).toHaveBeenCalledWith("https://example.com/demo?q=one#two");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.getByRole("button", { name: "View links" })).toBeVisible();
});
it("provides copy feedback and retry without losing the selected link", async () => {
vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
render(view("[Website](https://example.com/demo)"));
await screen.findByRole("link", { name: /Website/ });
const menu = await openLinks();
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
expect(await screen.findByRole("status")).toHaveTextContent("Could not copy link");
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied"));
expect(copyTextToClipboard).toHaveBeenLastCalledWith("https://example.com/demo");
fireEvent.keyDown(menu, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Message actions" })).toHaveFocus();
});
it("ignores late copy feedback after going back", async () => {
let finish!: (result: boolean) => void;
vi.mocked(copyTextToClipboard).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(view("[Old](https://example.com/old)"));
await screen.findByRole("link", { name: /Old/ });
const menu = await openLinks();
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
await act(async () => finish(true));
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible();
});
it("tracks newly rendered or changed links only within the owning message", async () => {
function LiveMessage({ href }: { href: string | null }) {
const root = useRef<HTMLDivElement>(null);
const links = useMessageWebLinks(root, true);
return <><WebLink href="https://elsewhere.invalid/">Another message</WebLink>
<div ref={root}>
<WebLink href="https://activity.invalid/">An activity link, not part of the reply</WebLink>
<div data-assistant-selectable>{href ? <WebLink href={href}>Current link</WebLink> : null}</div>
</div>
<output>{links.map(link => link.href).join(",")}</output></>;
}
const { rerender } = render(<LiveMessage href={null} />);
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender(<LiveMessage href="https://example.com/old" />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/old$/));
rerender(<LiveMessage href="https://example.com/new" />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/new$/));
rerender(<LiveMessage href={null} />);
await waitFor(() => expect(screen.getByRole("status")).toBeEmptyDOMElement());
});
});
+16 -16
View File
@@ -6,20 +6,20 @@ import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewSta
describe("preview tabs", () => {
it("reuses a gateway-resolved file without merging same-named files or sessions", () => {
const store = new FilePreviewStore();
store.open("a", "file", "reports/REPORT.md");
store.open("a", "reports/REPORT.md");
store.resolveFile("a", "reports/REPORT.md", "/workspace/reports/REPORT.md");
store.open("a", "file", "/workspace/reports/./details.md");
store.open("a", "/workspace/reports/./details.md");
store.resolveFile("a", "/workspace/reports/./details.md", "/workspace/reports/details.md");
store.update("a", { width: 620 });
store.open("a", "file", "/workspace/reports/./REPORT.md");
store.open("a", "/workspace/reports/./REPORT.md");
store.resolveFile("a", "/workspace/reports/./REPORT.md", "/workspace/reports/REPORT.md");
expect(store.get("a").tabs.map(tab => tab.value)).toEqual([
"reports/REPORT.md", "/workspace/reports/./details.md",
]);
expect(store.get("a")).toMatchObject({ activeId: "file:reports/REPORT.md", width: 620 });
store.open("a", "file", "archive/REPORT.md");
store.open("a", "archive/REPORT.md");
store.resolveFile("a", "archive/REPORT.md", "/workspace/archive/REPORT.md");
store.open("b", "file", "reports/REPORT.md");
store.open("b", "reports/REPORT.md");
store.resolveFile("b", "reports/REPORT.md", "/workspace/reports/REPORT.md");
expect(store.get("a").tabs).toHaveLength(3);
expect(store.get("b").tabs).toHaveLength(1);
@@ -28,11 +28,11 @@ describe("preview tabs", () => {
it("deduplicates targets, keeps selection and width per session, and closes neighboring tabs", () => {
const store = new FilePreviewStore();
const storage = vi.spyOn(Storage.prototype, "setItem");
store.open("a", "file", "chart.png");
store.open("a", "file", "index.html");
store.open("a", "file", "data.json");
store.open("a", "chart.png");
store.open("a", "index.html");
store.open("a", "data.json");
store.update("a", { width: 620 });
store.open("a", "file", "index.html");
store.open("a", "index.html");
expect(store.get("a").tabs).toHaveLength(3);
expect(store.get("a").activeId).toBe("file:index.html");
store.closeTab("a", "file:chart.png");
@@ -42,12 +42,12 @@ describe("preview tabs", () => {
store.select("a", "missing");
store.closeTab("a", "missing");
expect(store.get("a").activeId).toBe("file:data.json");
store.open("b", "web", "https://example.com");
store.open("b", "other.txt");
expect(store.get("a").width).toBe(620);
store.closeTab("a", "file:data.json");
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
expect(store.get("b").tabs).toHaveLength(1);
store.open("a", "file", "chart.png");
store.open("a", "chart.png");
store.close("a");
expect(store.get("a")).toMatchObject({ tabs: [], activeId: null, width: 620 });
store.delete("b");
@@ -60,9 +60,9 @@ describe("preview tabs", () => {
it("keeps one shell, supports keyboard tabs and close buttons, and never reloads the same tab", async () => {
const store = new FilePreviewStore();
store.open("a", "file", "chart.png");
store.open("a", "file", "index.html");
store.open("a", "file", "data.json");
store.open("a", "chart.png");
store.open("a", "index.html");
store.open("a", "data.json");
function View() {
const { state, selectTab, closeTab, close } = useFilePreviewState("a", store);
return state.activeId ? <PreviewPane tabs={state.tabs} activeId={state.activeId} width={544}
@@ -86,7 +86,7 @@ describe("preview tabs", () => {
fireEvent.keyDown(screen.getByRole("tab", { name: "chart.png" }), { key: "ArrowRight" });
expect(screen.getByRole("tab", { name: "index.html" })).toHaveFocus();
expect(screen.getByRole("tab", { name: "index.html" })).toHaveAttribute("aria-selected", "true");
act(() => store.open("a", "file", "index.html"));
act(() => store.open("a", "index.html"));
expect(screen.getAllByRole("tab")).toHaveLength(3);
fireEvent.keyDown(screen.getByRole("tab", { name: "index.html" }), { key: "Delete" });
expect(screen.queryByRole("tab", { name: "index.html" })).not.toBeInTheDocument();
@@ -108,7 +108,7 @@ describe("preview tabs", () => {
disconnect = disconnect;
});
try {
const tab = { id: "file:chart.png", kind: "file" as const, value: "chart.png" };
const tab = { id: "file:chart.png", value: "chart.png" };
const view = render(<PreviewPane tabs={[tab]} activeId={tab.id} width={544} isClosing={false}
onSelect={() => {}} onCloseTab={() => {}} onClose={() => {}} onResizeStart={() => {}}>
<p>Preview</p>
@@ -1,4 +1,3 @@
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -11,7 +10,6 @@ import { canonicalThreadPayload } from "./thread-test-payload";
let groupedTopics = false;
let withFiles = false;
const credentialless = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, "credentialless");
const previewFile = (path: string) => ({
path: `/workspace/${path}`, display_path: path, project_path: "/workspace",
language: "text", content: `Preview of ${path}`, size: 20, truncated: false,
@@ -151,8 +149,6 @@ describe("temporary chat navigation", () => {
afterEach(() => {
cleanup();
if (credentialless) Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", credentialless);
else Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
if (vi.isFakeTimers()) vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
@@ -323,53 +319,6 @@ describe("temporary chat navigation", () => {
}
});
it("restores website targets per session, switches to files, and closes below menus", async () => {
// Exercise the working embed path; unsupported browsers do not offer it.
Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", { configurable: true, value: false });
withFiles = true;
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
await startTemporaryChat("Synthetic separate session");
await selectTopic("Regular topic");
const website = await screen.findByRole("link", { name: "Website" });
const storedWebsiteValues = () => [localStorage, sessionStorage].map((storage) =>
Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!))
.filter((value) => value?.includes("https://example.com/demo")));
const beforePreview = storedWebsiteValues();
fireEvent.contextMenu(website);
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
await screen.findByTestId("web-preview-panel");
await selectTopic("Synthetic separate session");
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
await selectTopic("Regular topic");
await screen.findByTestId("web-preview-panel");
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
await screen.findByRole("menu");
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
expect(screen.getByTestId("web-preview-panel")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
fireEvent.keyDown(window, { key: "Escape" });
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
// The same pane is reachable with taps only, without intercepting a native
// touch context menu or adding a button next to every rendered link.
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
fireEvent.click(await screen.findByRole("button", { name: "View links" }));
fireEvent.click(await screen.findByRole("button", { name: "Preview website" }));
await screen.findByTestId("web-preview-panel");
expect(screen.queryByRole("dialog", { name: "Message actions" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
await screen.findByText("Preview of notes.txt");
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Close preview pane" }));
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
// The transcript may cache its link; preview targets must not add persisted state.
expect(storedWebsiteValues()).toEqual(beforePreview);
});
it("keeps the sidebar mounted across tabs, deduplicates repeated opens, and handles Escape below dialogs", async () => {
withFiles = true;
render(<App />);
@@ -418,7 +367,7 @@ describe("temporary chat navigation", () => {
expect(store.get(`websocket:${chatId}`).activeId).toBe("file:notes.txt");
await selectTopic("Close temporary chat: Show example files");
expect(store.get(`websocket:${chatId}`).tabs).toEqual([]);
act(() => store.open("websocket:regular", "file", "notes.txt"));
act(() => store.open("websocket:regular", "notes.txt"));
vi.useFakeTimers();
act(() => TestSocket.current.close());
expect(store.get("websocket:regular").tabs).toEqual([]);
+13
View File
@@ -52,6 +52,19 @@ function openMessageBlockMenu(root: ParentNode): {
}
describe("ThreadMessages", () => {
it("preserves native context menus and navigation on rendered reply links", async () => {
await preloadMarkdownText();
render(<ThreadMessages messages={[
{ id: "reply", role: "assistant", content: "[**Website**](https://example.com/?q=one#two)", createdAt: 1 },
]} />);
const link = await screen.findByRole("link", { name: "Website" });
expect(fireEvent.contextMenu(within(link).getByText("Website"))).toBe(true);
link.focus();
expect(fireEvent.keyDown(link, { key: "F10", shiftKey: true })).toBe(true);
expect(link).toHaveFocus();
expect(fireEvent.click(link, { ctrlKey: true })).toBe(true);
});
it.each(["diff", "collapsed_diff"] as const)(
"keeps completed %s edits visible when answer activity is toggled",
(fileEditDisplayMode) => {
+56
View File
@@ -0,0 +1,56 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { WebLink } from "@/components/WebLink";
const href = "https://example.com/?q=one#two";
describe("browser-owned web links", () => {
it("keeps the address, anchor attributes and caller styling", () => {
render(<WebLink href={href} className="underline" title="Full title">Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
expect(link).toHaveAttribute("href", href);
expect(link).toHaveAttribute("target", "_blank");
expect(link).toHaveAttribute("rel", "noreferrer noopener");
expect(link).toHaveClass("underline");
expect(link).toHaveAttribute("title", "Full title");
});
it.each(["mouse", "touch"])("leaves %s context menus to the browser", (pointerType) => {
render(<WebLink href={href}>Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.pointerDown(link, { pointerType, button: 2 });
expect(fireEvent.contextMenu(link)).toBe(true);
});
it.each([{ key: "ContextMenu" }, { key: "F10", shiftKey: true }])(
"leaves the $key keyboard menu to the browser", (event) => {
render(<WebLink href={href}>Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
link.focus();
expect(fireEvent.keyDown(link, event)).toBe(true);
expect(link).toHaveFocus();
},
);
it.each([{}, { ctrlKey: true }, { metaKey: true }, { shiftKey: true }])(
"preserves native navigation for click modifiers %j", (modifiers) => {
render(<WebLink href={href}>Example</WebLink>);
expect(fireEvent.click(screen.getByRole("link", { name: "Example" }), modifiers)).toBe(true);
},
);
it.each(["http://127.1:4173/page?q=one#two", "/api/media/report.pdf", "./notes.html", "mailto:test@example.com", "tel:+1234567", "#section"])(
"preserves supported link %s", (value) => {
render(<WebLink href={value}>Example</WebLink>);
expect(screen.getByRole("link", { name: "Example" })).toHaveAttribute("href", value);
},
);
it.each(["javascript:alert(1)", "data:text/html,hello", "file:///etc/passwd", "https://user:password@example.com/", "https://example.com/\n", "https:\\example.com", "https://example.com/" + "x".repeat(8192)])(
"keeps unsafe or malformed addresses as text (%#)", (value) => {
render(<WebLink href={value}>Example</WebLink>);
expect(screen.getByText("Example")).toBeVisible();
expect(screen.queryByRole("link")).not.toBeInTheDocument();
},
);
});
-239
View File
@@ -1,239 +0,0 @@
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WebLink, WebPreviewContext } from "@/components/WebLink";
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
import { FilePreviewStore, useFilePreviewState } from "@/hooks/useFilePreviewState";
import { copyTextToClipboard } from "@/lib/clipboard";
import { isNativeRuntime } from "@/lib/runtime";
import { parseWebLink, webPreviewRestriction } from "@/lib/web-preview";
vi.mock("@/lib/runtime", () => ({ isNativeRuntime: vi.fn(() => false) }));
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn(async () => true) }));
const credentialless = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, "credentialless");
beforeEach(() => {
vi.mocked(isNativeRuntime).mockReturnValue(false);
vi.mocked(copyTextToClipboard).mockResolvedValue(true);
Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", { configurable: true, value: false });
});
afterEach(() => {
cleanup();
vi.useRealTimers();
if (credentialless) Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", credentialless);
else Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
});
describe("web preview boundaries", () => {
it.each(["javascript:alert(1)", "data:text/html,hello", "file:///etc/passwd", "https://user:password@example.com/", "https://example.com/\n", "https:\\example.com", "/api/settings", "https://example.com/" + "x".repeat(8192)])("rejects %s", (url) => {
expect(parseWebLink(url)).toBeNull();
});
it("keeps URL query/hash and accepts loopback without treating it as a server-side fetch", () => {
expect(parseWebLink("http://127.1:4173/page?q=one#two")?.href).toBe("http://127.0.0.1:4173/page?q=one#two");
});
it("gates native, unsupported, same-origin and mixed-content embeds", () => {
const page = new URL("https://nanobot.example");
const external = new URL("https://example.com");
expect(webPreviewRestriction(external, page, true, true)).toBe("native");
expect(webPreviewRestriction(external, page, false, false)).toBe("unsupported");
expect(webPreviewRestriction(page, page, false, true)).toBe("sameOrigin");
expect(webPreviewRestriction(new URL("http://example.com"), page, false, true)).toBe("mixedContent");
expect(webPreviewRestriction(external, page, false, true)).toBeNull();
});
it("embeds only on mount, without credentials/referrer/host permissions, and refreshes with a new frame", async () => {
const { container } = render(<WebPreviewPanel url="https://example.com/demo" />);
const frame = container.querySelector("iframe")!;
expect(frame).toHaveAttribute("src", "https://example.com/demo");
expect(frame).toHaveAttribute("sandbox", "allow-scripts");
expect(frame).toHaveAttribute("credentialless", "");
expect(frame).toHaveAttribute("referrerpolicy", "no-referrer");
expect(frame.getAttribute("allow")).toContain("clipboard-read 'none'");
// A frame load event is not evidence that CSP/X-Frame-Options allowed embedding.
fireEvent.load(frame);
expect(screen.queryByText(/Some sites block embedding/)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
expect(await screen.findByText(/Some sites block embedding/)).toBeInTheDocument();
await userEvent.setup().keyboard("{Escape}");
fireEvent.click(screen.getByRole("button", { name: "Refresh website" }));
expect(container.querySelector("iframe")).not.toBe(frame);
expect(screen.getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener");
});
it("does not load an iframe in native or unsupported browsers", () => {
vi.mocked(isNativeRuntime).mockReturnValue(true);
const { container, rerender } = render(<WebPreviewPanel url="https://example.com" />);
expect(container.querySelector("iframe")).toBeNull();
expect(screen.getByRole("status")).toHaveTextContent(/native host/);
vi.mocked(isNativeRuntime).mockReturnValue(false);
Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
rerender(<WebPreviewPanel url="https://example.com" />);
expect(container.querySelector("iframe")).toBeNull();
expect(screen.getByRole("status")).toHaveTextContent(/does not support/);
});
it("explains that loopback belongs to the browsing device on request", async () => {
render(<WebPreviewPanel url="http://127.0.0.1:4173" />);
fireEvent.click(screen.getByRole("button", { name: "About website previews" }));
expect(await screen.findByText(/not a remote gateway/)).toBeInTheDocument();
});
});
describe("web link actions", () => {
it("keeps the primary link without a persistent action button or extra tab stop", () => {
render(<WebLink href="https://example.com/">Long website title</WebLink>);
const link = screen.getByRole("link", { name: "Long website title" });
expect(link).toHaveAttribute("href", "https://example.com/");
expect(link).toHaveAttribute("target", "_blank");
expect(link).toHaveAttribute("rel", "noreferrer noopener");
expect(screen.queryByRole("button")).not.toBeInTheDocument();
expect(fireEvent.click(link)).toBe(true);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
});
it("opens a shared right-click menu without loading any website beforehand", async () => {
const open = vi.fn();
const { container } = render(<WebPreviewContext.Provider value={open}><WebLink href="https://example.com/?a=b#c">Example</WebLink></WebPreviewContext.Provider>);
expect(container.querySelector("iframe")).toBeNull();
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
expect(screen.getAllByRole("menuitem")).toHaveLength(3);
expect(screen.queryByText("example.com")).not.toBeInTheDocument();
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
expect(open).toHaveBeenCalledWith("https://example.com/?a=b#c");
});
it("supports keyboard menus and reports copy success or failure", async () => {
render(<WebLink href="https://example.com/?q=one#two">Example</WebLink>);
fireEvent.keyDown(screen.getByRole("link", { name: "Example" }), { key: "F10", shiftKey: true });
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied"));
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(screen.getByRole("link", { name: "Example" })).toHaveFocus();
expect(copyTextToClipboard).toHaveBeenCalledWith("https://example.com/?q=one#two");
expect(screen.queryByRole("menuitem", { name: "Preview website" })).not.toBeInTheDocument();
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
fireEvent.keyDown(screen.getByRole("link", { name: "Example" }), { key: "ContextMenu" });
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Could not copy link"));
expect(screen.getByRole("menu")).toBeInTheDocument();
vi.mocked(copyTextToClipboard).mockResolvedValue(true);
fireEvent.click(screen.getByRole("menuitem", { name: "Copy link" }));
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
});
it.each(["unsupported", "native", "sameOrigin"])("omits unusable preview actions for %s links while keeping external open and copy", async (reason) => {
if (reason === "unsupported") Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
if (reason === "native") vi.mocked(isNativeRuntime).mockReturnValue(true);
const href = reason === "sameOrigin" ? `${window.location.origin}/settings` : "https://example.com/demo";
const open = vi.fn();
render(<WebPreviewContext.Provider value={open}><WebLink href={href}>Example</WebLink></WebPreviewContext.Provider>);
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
expect(screen.queryByRole("menuitem", { name: "Preview website" })).not.toBeInTheDocument();
expect(screen.getByRole("menuitem", { name: "Open in browser" })).toHaveAttribute("href", href);
const explanation = reason === "unsupported" ? /does not support credential-isolated/ : reason === "native" ? /native host/ : /application itself cannot be embedded/;
expect(screen.getByText(explanation)).toBeVisible();
fireEvent.click(screen.getByRole("menuitem", { name: "Copy link" }));
await waitFor(() => expect(copyTextToClipboard).toHaveBeenLastCalledWith(href));
expect(open).not.toHaveBeenCalled();
});
it("ignores a late copy completion after the user reopens the menu", async () => {
let finish!: (result: boolean) => void;
vi.mocked(copyTextToClipboard).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(<WebLink href="https://example.com/">Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.contextMenu(link);
fireEvent.click(screen.getByRole("menuitem", { name: "Copy link" }));
await userEvent.setup().keyboard("{Escape}");
fireEvent.contextMenu(link);
await act(async () => finish(true));
expect(screen.getByRole("menu")).toBeInTheDocument();
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});
it("closes with Escape and restores focus, without stealing an outside click", async () => {
const user = userEvent.setup();
render(<><WebLink href="https://example.com/">Example</WebLink><button>Elsewhere</button></>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.keyDown(link, { key: "F10", shiftKey: true });
await user.keyboard("{Escape}");
await waitFor(() => expect(link).toHaveFocus());
fireEvent.contextMenu(link);
// Radix's modal menu disables hit testing on underlying controls. A real
// outside pointer first dismisses the menu rather than activating that control.
// Its document listener is deferred until the opening pointer event finishes.
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
fireEvent.pointerDown(document.body, { pointerType: "mouse", button: 0 });
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(link).not.toHaveFocus();
});
it("leaves touch holds, native context menus and subsequent taps to the browser", async () => {
vi.useFakeTimers();
const onClick = vi.fn();
render(<WebLink href="https://example.com/" onClick={onClick}>Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 150 });
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
expect(fireEvent.contextMenu(link)).toBe(true);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
expect(link.className).not.toContain("touch-callout");
fireEvent.pointerUp(link, { pointerId: 1, pointerType: "touch" });
expect(fireEvent.click(link)).toBe(true);
expect(onClick).toHaveBeenCalledTimes(1);
});
it("still supports a mouse and keyboard after touch on a hybrid device", () => {
render(<WebLink href="https://example.com/">Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.pointerDown(link, { pointerType: "touch" });
fireEvent.pointerDown(link, { pointerType: "mouse", button: 2 });
expect(fireEvent.contextMenu(link)).toBe(false);
expect(screen.getByRole("menu")).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
fireEvent.pointerDown(link, { pointerType: "touch" });
fireEvent.keyDown(link, { key: "F10", shiftKey: true });
expect(screen.getByRole("menu")).toBeInTheDocument();
});
it("leaves a coarse-pointer context menu native even without a preceding pointer event", () => {
const original = window.matchMedia;
const media = vi.spyOn(window, "matchMedia").mockImplementation(query => ({ ...original(query), matches: query === "(pointer: coarse)" }));
render(<WebLink href="https://example.com/">Example</WebLink>);
expect(fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }))).toBe(true);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
media.mockRestore();
});
it("discards an open menu when its URL changes", () => {
const view = (href: string) => <WebLink href={href}>Example</WebLink>;
const { rerender } = render(view("https://example.com/old"));
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
expect(screen.getByRole("menu")).toBeInTheDocument();
rerender(view("https://example.com/third"));
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
});
it("does not add web actions for mail, files or executable addresses", () => {
render(<><WebLink href="mailto:test@example.com">Mail</WebLink><WebLink href="javascript:alert(1)">Unsafe</WebLink><WebLink href="file:///notes">File</WebLink></>);
expect(screen.getByRole("link", { name: "Mail" })).toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Unsafe" })).not.toBeInTheDocument();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
});
});
it("keeps file and website tabs per session, clears them on deletion, and never persists URLs", () => {
const store = new FilePreviewStore();
const local = vi.spyOn(Storage.prototype, "setItem");
function View({ session }: { session: string }) {
const { state, openWeb, openFile } = useFilePreviewState(session, store);
return <><output>{state.tabs.find((tab) => tab.id === state.activeId)?.value ?? "closed"}</output><button onClick={() => openWeb("https://example.com/preview")}>Web</button><button onClick={() => openFile("notes.txt")}>File</button></>;
}
const { rerender } = render(<View session="a" />);
fireEvent.click(screen.getByText("Web"));
rerender(<View session="b" />);
expect(screen.getByRole("status")).toHaveTextContent("closed");
fireEvent.click(screen.getByText("File"));
rerender(<View session="a" />);
expect(screen.getByRole("status")).toHaveTextContent("https://example.com/preview");
fireEvent.click(screen.getByText("File"));
expect(store.get("a").activeId).toBe("file:notes.txt");
expect(store.get("a").tabs).toHaveLength(2);
fireEvent.click(screen.getByText("Web"));
expect(store.get("a").activeId).toBe("web:https://example.com/preview");
expect(store.get("a").tabs).toHaveLength(2);
act(() => store.delete("a"));
expect(screen.getByRole("status")).toHaveTextContent("closed");
act(() => store.clear());
expect(store.get("b").tabs).toEqual([]);
expect(local).not.toHaveBeenCalled();
});