feat(webui): add isolated website previews and link actions

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent 05bee21b10
commit fccf415283
19 files changed
+626 -13

No files matched your search

+36
View File
@@ -438,6 +438,42 @@ private, trusted network.
## Troubleshooting
### Links and website previews
HTTP(S) links in replies have a **Link actions** menu: right-click the link,
press Shift+F10 while it is focused, or use its ellipsis button. You can copy the
link, open it in a browser tab, or preview it beside the current conversation.
Ordinary clicks still open links in a browser tab. File and session links keep
their own behavior.
The sidebar shares space with file previews and has refresh, external-open and
close controls. Escape closes it when focus is in the nanobot page, unless a
menu or dialog handles Escape first. Once focus is inside a third-party page,
use the sidebar's close button. The opened address and width are remembered
per session for this app connection, not written to browser storage. Returning
to a session reloads the original address; it does not preserve the website's
DOM, navigation history or forms. The header shows the **original link**, not a
live address bar for navigation inside the embedded page.
This is a restricted preview, not a full browser. It requires browser support
for credentialless iframes and is disabled in the native host until a separate
untrusted-content boundary is available. Unsupported browsers can still copy
links and open new tabs. Previews use an opaque-origin sandbox with scripts
but without same-origin access, forms, popups, downloads or top navigation.
No gateway token, host bridge or parent storage is passed into the frame.
Sites may refuse embedding via CSP or X-Frame-Options, and sign-in or some
interactive features may not work. Use **Open in browser** if the frame is blank
or reports a failure. The browser does not reliably expose an embedding failure
to nanobot, so a frame load event is not presented as a success signal. Nanobot
does not proxy pages or bypass their headers. Same-origin nanobot URLs and
HTTP pages embedded from an HTTPS WebUI are not previewed.
`localhost` and loopback addresses refer to the device running your browser,
not a remote nanobot gateway. This feature does not forward remote ports.
### Connection checks
If the page does not open, check these in order:
1. `nanobot agent -m "Hello!"` works in the same Python environment.
@@ -15,6 +15,7 @@ import { Streamdown, type Components, type StreamdownProps } from "streamdown";
import { AttachmentTile } from "@/components/AttachmentTile";
import { CodeBlock } from "@/components/CodeBlock";
import { WebLink } from "@/components/WebLink";
import {
INLINE_TOKEN_HIGHLIGHT_COLOR,
InlineTokenHighlight,
@@ -451,7 +452,7 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {
: link.title;
return (
<a
<WebLink
href={link.href}
target="_blank"
rel="noreferrer noopener"
@@ -487,7 +488,7 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {
<span className="min-w-0 [overflow-wrap:anywhere] leading-normal sm:truncate">
{label}
</span>
</a>
</WebLink>
);
}
@@ -672,7 +673,7 @@ export default function MarkdownTextRenderer({
return <>{markdownChildren}</>;
}
return (
<a
<WebLink
href={href}
target="_blank"
rel="noreferrer noopener"
@@ -680,7 +681,7 @@ export default function MarkdownTextRenderer({
{...props}
>
{markdownChildren}
</a>
</WebLink>
);
},
// Streamdown decorates emphasis with spans by default. Preserve native
+66
View File
@@ -0,0 +1,66 @@
import { createContext, useContext, useEffect, useState, type ComponentPropsWithoutRef } from "react";
import { Copy, ExternalLink, MoreHorizontal, PanelRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { copyTextToClipboard } from "@/lib/clipboard";
import { parseWebLink } from "@/lib/web-preview";
export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);
export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutRef<"a">) {
const { t } = useTranslation();
const openPreview = useContext(WebPreviewContext);
const [open, setOpen] = useState(false);
const [feedback, setFeedback] = useState("");
useEffect(() => {
if (!feedback) return;
const timer = window.setTimeout(() => setFeedback(""), 4000);
return () => window.clearTimeout(timer);
}, [feedback]);
const url = parseWebLink(href);
const anchor = <a {...props} href={href} target="_blank" rel="noreferrer noopener">{children}</a>;
if (!url) {
// 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) ? anchor : <>{children}</>;
}
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
<span className="inline max-w-full" onContextMenu={(event) => {
event.preventDefault(); event.stopPropagation(); setOpen(true);
}} onKeyDown={(event) => {
if ((event.shiftKey && event.key === "F10") || event.key === "ContextMenu") {
event.preventDefault(); event.stopPropagation(); setOpen(true);
}
}}>
{anchor}
<DropdownMenuTrigger asChild>
<button type="button" aria-label={t("webPreview.actions")} title={t("webPreview.actions")}
className="ml-0.5 inline-flex h-6 w-6 items-center justify-center rounded-md align-middle text-muted-foreground/70 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<MoreHorizontal className="h-3.5 w-3.5" aria-hidden />
</button>
</DropdownMenuTrigger>
</span>
<DropdownMenuContent align="start">
<DropdownMenuLabel className="max-w-64 truncate">{url.host}</DropdownMenuLabel>
{openPreview ? <DropdownMenuItem onSelect={() => openPreview(url.href)}>
<PanelRight className="h-4 w-4" aria-hidden />{t("webPreview.open")}
</DropdownMenuItem> : null}
<DropdownMenuItem asChild>
<a href={url.href} target="_blank" rel="noreferrer noopener">
<ExternalLink className="h-4 w-4" aria-hidden />{t("webPreview.external")}
</a>
</DropdownMenuItem>
<DropdownMenuItem onSelect={(event) => {
// Keep the menu/focus alive until the clipboard fallback finishes.
event.preventDefault();
setFeedback("");
void copyTextToClipboard(url.href).then((copied) => setFeedback(t(copied ? "webPreview.copied" : "webPreview.copyFailed")));
}}><Copy className="h-4 w-4" aria-hidden />{t("webPreview.copy")}</DropdownMenuItem>
{feedback ? <div role="status" className="px-2.5 py-1.5 text-xs text-muted-foreground">{feedback}</div> : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
+56
View File
@@ -0,0 +1,56 @@
import { useState, type CSSProperties, type PointerEvent } from "react";
import { ExternalLink, RotateCw, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { isLoopbackHost } from "@/lib/network";
import { isNativeRuntime } from "@/lib/runtime";
import { parseWebLink, webPreviewRestriction } from "@/lib/web-preview";
interface WebPreviewPanelProps {
url: string;
desktopWidth?: number;
onResizeStart?: (event: PointerEvent<HTMLButtonElement>) => void;
onClose: () => void;
}
export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart, onClose }: WebPreviewPanelProps) {
const { t } = useTranslation();
const [revision, setRevision] = useState(0);
const url = parseWebLink(value);
const restriction = url ? webPreviewRestriction(url, new URL(window.location.href), isNativeRuntime(),
"credentialless" in HTMLIFrameElement.prototype) : "invalid";
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return (
<aside aria-label={t("webPreview.title")} data-testid="web-preview-panel" data-file-preview-panel
style={{ "--file-preview-width": `${desktopWidth}px`, "--file-preview-slot-width": `${desktopWidth}px` } as CSSProperties}
className="absolute inset-y-0 right-0 z-30 flex w-full flex-col border-l border-border/70 bg-background pb-[env(safe-area-inset-bottom)] shadow-2xl md:relative md:z-auto md:w-[var(--file-preview-slot-width)] md:min-w-0 md:shrink-0 md:pb-0 md:shadow-none">
{onResizeStart ? <button type="button" aria-label={t("webPreview.resize")}
className="absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none hover:bg-border/50 md:block"
onPointerDown={onResizeStart} /> : null}
<div className="flex shrink-0 items-center gap-1 border-b border-border/60 px-3 py-2">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium" title={url?.origin}>{t("webPreview.original")}</p>
<p className="truncate text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
</div>
{!restriction ? <button type="button" className={buttonClass} onClick={() => setRevision((n) => n + 1)} 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}
<button type="button" className={buttonClass} onClick={onClose} title={t("webPreview.close")} aria-label={t("webPreview.close")}><X className="h-4 w-4" aria-hidden /></button>
</div>
<div className="shrink-0 space-y-1 border-b border-border/60 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
<p>{t("webPreview.isolated")}</p>
<p>{t("webPreview.blockedHint")}</p>
{url && isLoopbackHost(url.hostname) ? <p>{t("webPreview.loopback")}</p> : 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> : <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" />}
</aside>
);
}
+42 -6
View File
@@ -6,6 +6,9 @@ import { useTranslation } from "react-i18next";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { FileActionsProvider } from "@/components/FileActions";
import { WebPreviewContext } from "@/components/WebLink";
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
import { parseWebLink } from "@/lib/web-preview";
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
@@ -713,7 +716,7 @@ export function ThreadShell({
} | null>(null);
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth } =
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth, setWebUrl } =
useFilePreviewState(previewSessionKey, filePreviewStore);
const [closingPreview, setClosingPreview] = useState<{ key: string; path: string } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -1544,18 +1547,36 @@ export function ThreadShell({
},
}), [filePreviewClosing, filePreviewPath, openFilePreview, resolveFileMetadata]);
const openWebPreview = useCallback((url: string) => {
const parsed = parseWebLink(url);
if (!parsed) return;
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
setWebUrl(parsed.href);
}, [setWebUrl]);
const closeWebPreview = useCallback(() => {
filePreviewResizeCleanupRef.current?.();
setWebUrl(null);
}, [setWebUrl]);
useEffect(() => {
if (!filePreviewPath || !headerActive) return;
if ((!filePreviewPath && !previewState.webUrl) || !headerActive) return;
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
// Let a dialog/menu above the pane consume Escape without closing this preview.
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
event.preventDefault();
handleCloseFilePreview();
if (previewState.webUrl) closeWebPreview();
else handleCloseFilePreview();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [filePreviewPath, headerActive, handleCloseFilePreview]);
}, [filePreviewPath, previewState.webUrl, headerActive, handleCloseFilePreview, closeWebPreview]);
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
filePreviewResizeCleanupRef.current?.();
@@ -1568,12 +1589,15 @@ export function ThreadShell({
const originalBodyCursor = document.body.style.cursor;
const originalBodyUserSelect = document.body.style.userSelect;
const originalPanelTransition = panel?.style.transition ?? "";
const frameElement = panel?.querySelector("iframe");
const originalFramePointerEvents = frameElement?.style.pointerEvents ?? "";
let nextWidth = filePreviewWidthRef.current;
let frame: number | null = null;
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
if (panel) panel.style.transition = "none";
if (frameElement) frameElement.style.pointerEvents = "none";
const applyWidth = (clientX: number) => {
nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth);
@@ -1597,6 +1621,7 @@ export function ThreadShell({
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
if (panel) panel.style.transition = originalPanelTransition;
if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents;
if (commit) setFilePreviewWidth(nextWidth);
document.body.style.cursor = originalBodyCursor;
document.body.style.userSelect = originalBodyUserSelect;
@@ -1615,7 +1640,7 @@ export function ThreadShell({
}, [setFilePreviewWidth]);
useEffect(() => {
if (!filePreviewPath) return;
if (!filePreviewPath && !previewState.webUrl) return;
const clampToShell = () => {
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
const maxWidth = maxFilePreviewWidth(shellWidth);
@@ -1629,7 +1654,7 @@ export function ThreadShell({
observer?.disconnect();
window.removeEventListener("resize", clampToShell);
};
}, [filePreviewPath]);
}, [filePreviewPath, previewState.webUrl]);
const handleForkFromMessage = useCallback(
async (beforeUserIndex: number) => {
@@ -1833,6 +1858,7 @@ export function ThreadShell({
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
>
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
<WebPreviewContext.Provider value={previewSessionKey ? openWebPreview : undefined}>
<ThreadViewport
ref={viewportRef}
messages={displayMessages}
@@ -1861,6 +1887,7 @@ export function ThreadShell({
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
/>
</WebPreviewContext.Provider>
</FileActionsProvider>
</FilePreviewAvailabilityProvider>
</div>
@@ -1890,6 +1917,15 @@ export function ThreadShell({
onClose={handleCloseFilePreview}
/>
) : null}
{previewState.webUrl && previewSessionKey ? (
<WebPreviewPanel
key={`${previewSessionKey}:${previewState.webUrl}`}
url={previewState.webUrl}
desktopWidth={filePreviewWidth}
onResizeStart={handleFilePreviewResizeStart}
onClose={closeWebPreview}
/>
) : null}
</section>
);
}
+8 -2
View File
@@ -2,6 +2,7 @@ import { useCallback, useState, useSyncExternalStore } from "react";
interface FilePreviewState {
path: string | null;
webUrl?: string | null;
width: number;
}
@@ -24,7 +25,9 @@ export class FilePreviewStore {
update(key: string, patch: Partial<FilePreviewState>) {
const previous = this.get(key);
const next = { ...previous, ...patch };
if (previous.path === next.path && previous.width === next.width) return;
if (patch.path) next.webUrl = null;
if (patch.webUrl) next.path = null;
if (previous.path === next.path && previous.width === next.width && previous.webUrl === next.webUrl) return;
this.states.set(key, next);
this.listeners.forEach((listener) => listener());
}
@@ -50,5 +53,8 @@ export function useFilePreviewState(key: string | null, sharedStore?: FilePrevie
const setWidth = useCallback((width: number) => {
if (key) store.update(key, { width });
}, [key, store]);
return { state, setPath, setWidth };
const setWebUrl = useCallback((webUrl: string | null) => {
if (key) store.update(key, { webUrl });
}, [key, store]);
return { state, setPath, setWidth, setWebUrl };
}
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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 website 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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"original": "Enlace original",
"actions": "Acciones del enlace",
"open": "Vista previa del sitio",
"external": "Abrir en el 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 web",
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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 web",
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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 situs",
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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 do site",
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+22
View File
@@ -1,4 +1,26 @@
{
"webPreview": {
"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}}"
},
"app": {
"brand": "nanobot",
"loading": {
+24
View File
@@ -0,0 +1,24 @@
/** 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;
}
@@ -129,7 +129,7 @@ describe("temporary chat navigation", () => {
schemaVersion: 3,
messages: [{
id: "file-reply", role: "assistant", createdAt: 1,
content: "Files: [notes.txt](notes.txt) and [second.txt](second.txt)",
content: "Files: [notes.txt](notes.txt) and [second.txt](second.txt). [Website](https://example.com/demo)",
}],
}));
}
@@ -201,6 +201,43 @@ describe("temporary chat navigation", () => {
}
});
it("restores website targets per session, switches to files, and closes below menus", async () => {
withFiles = true;
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
await startTemporaryChat("Synthetic separate session");
await selectTopic("Regular topic");
fireEvent.contextMenu(await screen.findByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
await screen.findByTestId("web-preview-panel");
await selectTopic("Synthetic separate session");
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" });
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
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 website preview" }));
expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument();
for (const storage of [localStorage, sessionStorage]) {
const values = Array.from({ length: storage.length }, (_, i) => storage.getItem(storage.key(i)!));
expect(JSON.stringify(values)).not.toContain("https://example.com/demo");
}
});
it("toggles the current file, switches files, and only handles Escape below dialogs", async () => {
withFiles = true;
render(<App />);
+131
View File
@@ -0,0 +1,131 @@
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
import { act, 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(() => {
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 close = vi.fn();
const { container } = render(<WebPreviewPanel url="https://example.com/demo" onClose={close} />);
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.getByText(/Some sites block embedding/)).toBeInTheDocument();
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");
fireEvent.click(screen.getByRole("button", { name: "Close website preview" }));
expect(close).toHaveBeenCalledOnce();
});
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" onClose={() => {}} />);
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" onClose={() => {}} />);
expect(container.querySelector("iframe")).toBeNull();
expect(screen.getByRole("status")).toHaveTextContent(/does not support/);
});
it("explains that loopback belongs to the browsing device", () => {
render(<WebPreviewPanel url="http://127.0.0.1:4173" onClose={() => {}} />);
expect(screen.getByText(/not a remote gateway/)).toBeInTheDocument();
});
});
describe("web link actions", () => {
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" }));
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"));
expect(screen.getByRole("menu")).toBeInTheDocument();
expect(copyTextToClipboard).toHaveBeenCalledWith("https://example.com/?q=one#two");
expect(screen.queryByRole("menuitem", { name: "Preview website" })).not.toBeInTheDocument();
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
await userEvent.setup().keyboard("{Escape}");
await userEvent.setup().click(screen.getByRole("button", { name: "Link actions" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Could not copy link"));
});
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 mutually exclusive preview targets 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, setWebUrl, setPath } = useFilePreviewState(session, store);
return <><output>{state.webUrl ?? state.path ?? "closed"}</output><button onClick={() => setWebUrl("https://example.com/preview")}>Web</button><button onClick={() => setPath("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")).toMatchObject({ path: "notes.txt", webUrl: null });
fireEvent.click(screen.getByText("Web"));
expect(store.get("a").path).toBeNull();
act(() => store.delete("a"));
expect(screen.getByRole("status")).toHaveTextContent("closed");
act(() => store.clear());
expect(store.get("b").path).toBeNull();
expect(local).not.toHaveBeenCalled();
});