Skip to content

Your lightweight open-source personal agent.

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

chengyongru08ca3b4525bf
diff --git a/docs/webui.md b/docs/webui.md
index f9c8942ad..6e261e734 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -2,42 +2,34 @@
<!-- Meta description: Run nanobot from a browser WebUI with persistent and temporary chats, visible tool activity, workspace controls, Apps, skill discovery, settings, and Automations. -->
-The WebUI is nanobot's browser workbench for persistent topics, grouped conversation panes, temporary chats, visible agent activity, workspace controls, Apps, skill discovery, settings, and Automations in one place. It shares the gateway and saved sessions with the native terminal client.
+The WebUI shares its gateway and saved sessions with the native terminal client and is included with `nanobot-ai`.
For a visual tour, see the [README feature gallery](../README.md#-webui). This guide follows the current source tree; some features are newer than the published release.
-The published `nanobot-ai` wheel already includes the WebUI bundle. You only need the `webui/` source directory when you are changing the frontend itself.
-
## Open the WebUI
-Use the launcher:
-
```bash
nanobot webui
```
-`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same gateway used by the native TUI and opens the browser. Fresh official-installer environments start it persistently and return control to the terminal; other installations keep the attached on-demand launch. With a fresh config, it can open before a model is configured so you can finish setup in **Settings → Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so it is not available from other devices on your LAN. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.
+On a new installation, the launcher asks for confirmation to create the config and workspace, enables the local WebUI, and opens a signed-in browser. Configure a provider and model in **Settings → Models** before sending your first message; see [Configure Your Model](./quick-start.md#2-configure-your-model). The default address is `http://127.0.0.1:8765`, accessible only from the same machine.
-Outside an installer-managed environment, use `nanobot webui --detach` to open the browser and keep the gateway running after the terminal closes. Alternatively, start or promote the same shared gateway explicitly:
+Official-installer environments start a persistent gateway by default. Other installations keep it attached to the launchers: closing the last WebUI or TUI launcher stops an on-demand gateway. Use `nanobot webui --detach` to keep it running after the terminal closes, or start it explicitly:
```bash
nanobot gateway --background
```
-`nanobot webui --background` remains deprecated and prints migration guidance. All launch routes use the same gateway lifecycle owner and state.
-
-Each foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway, but not a persistent one. Manage the persistent gateway with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`. Use the printed instance-specific commands when you selected a custom config or workspace. `--detach --dev` is unsupported; development remains attached.
+Manage a persistent gateway with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`. Use the printed instance-specific commands for a custom config or workspace. The old `nanobot webui --background` flag is deprecated; `--detach` cannot be combined with `--dev`.
-The browser signs in automatically using the generated credential in the launch URL. The terminal also prints the complete login link: if automatic opening fails, copy that link into your browser, including the fragment after `#`. In WSL, the launcher opens your Windows default browser through Windows PowerShell; an explicit `BROWSER` setting takes precedence. If Windows integration is unavailable, open the printed link in your Windows browser. The plain page address does not sign in a new browser. Treat the login link as a credential and do not share it.
+To sign in another browser, use the complete printed login link, including the fragment after `#`. Treat it as a credential. `nanobot webui --no-open` prints the link without opening a browser. In WSL, the launcher uses the Windows default browser unless `BROWSER` is set; if automatic opening fails, use the printed link.
-`nanobot webui --no-open` prints the same login link without opening a browser. Development mode uses the Vite address, normally `http://127.0.0.1:5173`, with the same gateway authentication.
-
-If no provider is configured, follow the **Next step** prompt to open **Settings → Models**. Errors for a configured provider appear with that prompt.
+The launcher displays gateway warnings and errors; use the printed logs command for full output.
<details>
<summary>Manual configuration for the local WebUI</summary>
-Manual config still works. Same-machine localhost WebUI access can run without a browser password. Set `tokenIssueSecret` when you intentionally expose the WebUI beyond localhost or want a browser password. These listener and authentication fields have no graphical editor:
+Listener and authentication fields are configured in `config.json`. Localhost access can run without a browser password; set `tokenIssueSecret` for access beyond localhost or to require a password:
```json
{
@@ -54,40 +46,24 @@ Manual config still works. Same-machine localhost WebUI access can run without a
</details>
-The WebUI is served by the WebSocket channel on port `8765` by default. The gateway health endpoint, `18790` by default, is not the browser UI.
-
### macOS Dock icon
-In a local macOS desktop session, `nanobot webui` shows the nanobot cat in the Dock. Click it to open the current local WebUI in your default browser. `--no-open` keeps the icon but does not open a page automatically. SSH, headless, Windows and Linux launches keep their existing behavior. A one-shot connection to an unmanaged gateway does not leave an icon behind.
+On a local macOS desktop, `nanobot webui` provides a Dock shortcut to the running WebUI. `--no-open` keeps the shortcut without opening a page; `--no-dock` disables it. It is unavailable in SSH/headless sessions or for non-loopback browser addresses.
-Ordinary foreground launchers for the same instance, browser address and installation share an icon. The last WebUI launcher removes it when it exits, including after a terminal crash. For `--detach` and official-installer automatic background launch, the gateway owns the icon instead: closing the terminal does not remove it. An ordinary restart, successful update or supported automatic restoration shows it again once that gateway is activated. The icon can disappear while the service is stopped for an update; it is not an update-progress indicator. `nanobot gateway stop` removes it without changing configuration or chats.
+Attached launchers share the shortcut until the last matching WebUI launcher exits. With `--detach` or official-installer background launch, it remains until the gateway stops and returns after restart or update. It is a shortcut to a running instance, not a standalone app.
-Use `--no-dock` to disable the icon for a launcher. In detached mode this also remembers the choice for that instance's later restarts; running `nanobot webui` without it enables the background icon again. The request is stored beside the runtime state as a small `.dock` file, without a URL or credentials. Choosing **Hide Dock Icon** or quitting the icon hides only this shortcut, not the gateway or its tasks. It stays hidden until another explicit launch or service restart. The icon is not a standalone launcher to keep pinned when nanobot is stopped.
-
-The helper uses the installed Python and macOS frameworks, with no Xcode, extra Python dependency, executable download or separate updater. Its temporary application wrapper is private to the OS user. The login URL stays in memory and a private socket, never in process arguments or a file. The helper holds no installation or data lease, and protected restart does not start it until activation. A missing image or unavailable desktop does not prevent WebUI startup, updates or independent recovery. Non-loopback browser addresses continue to use the normal browser launcher.
+**Hide Dock Icon** or quitting the icon hides the shortcut without stopping the gateway or its tasks, until the next explicit launch or service restart. In detached mode, `--no-dock` also disables it for later restarts; launching without that flag enables it again.
## Navigate a long conversation
-On wide screens, use the message rail on the left to browse saved prompts; click one to jump to it. You can also search prompt summaries from the header. The WebUI loads messages near the selected prompt rather than the entire conversation. Scroll backward or forward to browse, or use the bottom arrow to return to the latest messages. If loading fails, your current content stays visible and you can retry. Older compatible hosts may only support navigation among messages that are already loaded.
+The message rail on wide screens and prompt-summary search in the header jump to saved prompts, loading the surrounding messages as needed. Loading errors leave the current content available for retry. Older compatible hosts may only support navigation among already-loaded messages.
## Sharing access
-The WebUI is an administration interface for one nanobot instance. Signed-in WebUI users can work with its saved topics and manage models, channels, Apps, automations, and settings within the gateway's supported capabilities. There are no per-user roles or private topic ownership boundaries. Remote package installation has an additional restriction described under [LAN Access](#lan-access); that restriction does not turn other WebUI users into read-only users.
+The WebUI administers one nanobot instance. Signed-in users share saved topics and administrative controls; there are no per-user roles or private topic ownership boundaries. The [remote installation restriction](#lan-access) limits package installation, not other administrative access.
Share WebUI access only with people you trust to administer the same agent. To give someone chat access without the administration interface, connect a [chat platform](./chat-apps.md) and configure its access policy. Channel approval still does not create a separate agent or memory store. For separate clients or users whose data must not mix, use [separate instances](./multiple-instances.md).
-## First 10 Minutes
-
-Use the WebUI as the primary setup surface:
-
-1. Open **Settings → Models** and configure a provider, credential, and active model preset.
-2. Send `Hello!` in a new topic to prove the selected model works.
-3. Start a separate topic before project work, then choose the intended workspace and access mode.
-4. Add only one capability next: a chat channel in **Channels**, a web/voice/image provider in **Settings**, or an App/MCP integration in **Apps**.
-5. Restart when the WebUI shows a restart requirement, then test that capability with the smallest possible request.
-
-This path avoids hand-editing `config.json` for normal setup. Use the reference docs when you need an option the WebUI does not expose or when you manage config as code.
-
## What It Is For
| Area | Use it for |
@@ -105,23 +81,17 @@ This path avoids hand-editing `config.json` for normal setup. Use the reference
| Automations | Review, search, run, pause, edit, and delete scheduled and local-trigger agent turns |
| Settings | Adjust models, providers, image generation, voice, web tools, runtime, and safety options |
-### Optional GitHub invitation
-
-Returning users may see an illustrated invitation to star nanobot on GitHub. It follows the WebUI language and theme; the button's star animation also supports keyboard focus and respects reduced-motion preferences. **Maybe later**, the close button, or Escape dismisses it for now. **Don't ask again** or opening GitHub from the invitation stops future reminders for the gateway instance, including in other browsers. Starring is optional and never required to use nanobot.
-
## Topic Workspace
The sidebar is the topic switcher. Each topic keeps its own history, title, workspace selection, and linked automations. Use a new topic when you want a separate context; use fork when you want to continue from an existing point without changing the original thread.
-On touch devices, sidebar action buttons stay visible with larger touch areas for topics, conversation groups, panes, and projects. Tap a title to select it or the adjacent action button for its menu. Desktop actions still appear on hover or keyboard focus. Press Escape in an action menu to return focus to its button and continue with Tab, including from the **Move to** submenu. ArrowLeft leaves the submenu and returns to **Move to** without closing the parent menu. Choosing **Rename** for a topic moves focus into its sidebar title. Edit the name in place, then press Enter or choose the checkmark to save; press Escape or choose × to cancel. A failed save keeps the draft and an error beside it so you can retry. Project and conversation-group names still use dialogs. Clicking outside a menu keeps focus at the clicked destination.
-
-Drag a topic within its current sidebar group to keep frequently used work in your preferred order. Drag a topic from the sidebar into the composer when you want to reference it in the next message instead of switching to it.
+Drag topics within a sidebar group to reorder them. **Rename** edits a topic title in place; a failed save keeps the draft for retry.
### Conversation groups and panes
Open a topic's sidebar action menu and choose **Create group** to turn it into a conversation group. Use **Add pane** in the workbench header to start another topic alongside it. A group holds up to four panes. To bring in an existing topic, drag it onto the group or use **Move to** in its action menu.
-Use **Pane layout** to choose columns, rows, a grid, BSP, or a main pane with a stack. Drag a divider to resize panes. Each pane has its own conversation; select one to direct the shared composer to that topic. Group membership and layout persist across refreshes. Grouping topics does not merge their histories.
+**Pane layout** controls the arrangement of resizable panes. Selecting a pane directs the shared composer to that topic. Group membership and layout persist across refreshes; grouping does not merge topic histories.
To use work from another topic, mention it with `@` and tell nanobot what you need. See [Composer](#composer) for how to add a topic reference.
@@ -129,41 +99,31 @@ To use work from another topic, mention it with `@` and tell nanobot what you ne
The message timeline shows replies and agent activity. Expand the **Worked for** section to inspect the reasoning and tool activity for a completed turn.
-To load earlier messages, scroll past the oldest loaded message, or pull down far enough and release on touch devices. The muted loading indicator settles into view while the request runs. When loading succeeds, the indicator and its temporary space disappear and normal message spacing returns. If loading fails, the blocks turn red; hover for error details, then pull again or select the red blocks to retry. If there are no earlier messages, pulling at the real history boundary briefly shows **No earlier messages**.
-
-If the connection drops, the host control shows **Reconnecting**. Tasks in persistent topics can continue during the interruption. After reconnecting, task indicators and completed replies update automatically, including topics you have switched away from. Some text generated while disconnected may appear only after the task finishes. [Temporary chats](#temporary-chats) end when their connection is lost.
-
-When the agent writes or edits files, the activity item shows the target path, status, and changed line counts. Choose **Settings → Appearance → File edit display** to control the detail: **Summary** shows the change summary, **Diff** shows available unified patches inline, and **Collapsed diff** lets you expand them with **View diff**. Large diffs may hide unchanged lines or truncate the inline preview. Select the filename in the activity row to open the read-only file preview panel.
-
-Files open as tabs in one preview pane. Select another file to add or switch a tab without reopening the pane; close a tab with its **×**, or close the pane with **Escape**. Tabs and width follow each session while the WebUI remains open. They are kept only in memory and cleared when that session is deleted or the connection ends. The pane overlays the conversation on narrow screens.
-
-Markdown files open in **Preview**, with formatted headings, lists, tables and code blocks. Select **Source** to see the original Markdown with line numbers, then **Preview** to return. The control changes only the display; it does not edit or read the file again. Each newly opened or selected file starts in Preview. Images in Markdown appear as links and do not load automatically. Local links open through the same file access checks; relative paths start from the document's folder. Section-only links remain text. HTML and MDX components do not execute.
-
-Text previews include up to 384 KiB, with a notice when the file is truncated. Large source previews show readable text before adding syntax colors; very large or minified source stays plain text. All previewed text remains available for selection and browser search, and the source pane scrolls in both directions.
+Scroll past the oldest loaded message, or pull down and release on touch devices, to load earlier history. A red indicator offers error details and retry; **No earlier messages** marks the history boundary.
-PNG, JPEG, GIF and WebP files up to 8 MiB can be previewed as images. Hover or focus an image file reference for a compact quick look, or select it to open the pane. Select the preview image for the full-size viewer, which supports zoom controls, pinch-to-zoom and panning. HTML and SVG files remain read-only source previews rather than executable pages.
+Tasks in persistent topics can continue while the connection is lost. Status and completed replies update after reconnecting; some missed text may appear only when the task finishes. [Temporary chats](#temporary-chats) end on connection loss.
-A plain image file link does not automatically insert a large image into the reply. Explicit Markdown images appear inline; image attachments use a compact gallery, showing at most four thumbnails before a count of the remaining images. An image already displayed inline is not duplicated in the attachment gallery.
+The context indicator beside the model badge shows context-window usage. **Recent rounds** includes token usage, generation time and KV cache hits when reported. Provider figures may be estimated or unavailable and are not a billing statement.
-Mermaid code fences show their source while a reply is being generated, then render a diagram when the reply finishes. Choose **Source** or **Diagram** to switch views, or **Copy source** to copy the original code. **Enlarge diagram** opens a viewer with zoom buttons, pinch-to-zoom and drag-to-pan. With the viewport focused, use **+**, **−** and **0** to zoom or reset, and arrow keys to pan; **Escape** closes the viewer.
+During compaction, the model switches to a summary plus subsequent messages; the original messages remain in chat history. Use `/compact` to compact the current topic manually. See [Memory](./memory.md) for compaction and Dream consolidation.
-If a diagram cannot be rendered, its source stays available with an error message. Links, external images and executable HTML inside diagrams are disabled.
+### File and diagram previews
-Select a file reference to preview it. Right-click the reference or its preview tab to copy its absolute or project-relative path. Keyboard users can focus a reference and press **Shift+F10**. Paths are resolved on the gateway machine, which may not be the computer running your browser. Files outside the project do not have a project-relative path. If a reference cannot be resolved, you can still copy the original reference; the menu does not invent an absolute path. Finder, external editor and terminal launching are not available from this browser menu.
+File activity shows the path, status and changed line counts. **Settings → Appearance → File edit display** offers **Summary**, inline **Diff**, or **Collapsed diff** with **View diff**. Large patches may omit unchanged lines or be truncated. Select a filename to open its read-only preview.
-File previews follow the active topic's access mode. Restricted workspace access previews only files under the selected workspace. Full Access can preview files outside the workspace when that access mode is allowed by the gateway.
+Files share a tabbed preview pane. Tabs and pane width are remembered per topic until the session is deleted or the WebUI connection ends.
-Website links normally open in a new browser tab. Right-click a link (or press **Shift+F10** while it is focused) for link actions. On mobile, use the reply's **Message actions → View links** menu. **Preview website** appears only when the current browser and URL allow credential-isolated embedding; otherwise the menu explains the restriction and keeps **Open in browser** and **Copy link** available. Sites can still refuse embedding through their own security headers. nanobot does not proxy pages or bypass those restrictions; use **Open in browser** instead.
+Selecting a Markdown file opens **Preview**; **Source** shows the original text. Relative file links resolve from the document's folder and follow the same access checks. Images are not loaded automatically, section-only links remain text, and HTML/MDX components do not execute.
-On touch devices with Visual Viewport support, the app follows the visible area when the on-screen keyboard opens or pans the page. Navigation and the composer stay in view while messages scroll independently. Session search also follows the visible area: the search field stays above the keyboard and results scroll inside the dialog. In short landscape viewports, its input and results sit side by side so a result remains reachable. Taller dialogs scroll from their top instead of centering content outside the visible area. The `@` mention and `/` command menus use the visible app area above or below the composer, including when the keyboard pans the page. Scroll within a menu to reach more results. Mention rows use the app's larger touch targets on phones while retaining desktop density. In very short, wide viewports (such as landscape with the keyboard open), menus sit beside the input instead of overflowing the scrollable composer. Scroll the menu for more candidates and the input area for its controls. If the browser bars and keyboard leave no usable page area, dismiss the keyboard or return to portrait. Pinch zoom keeps the existing layout instead of resizing it to the magnified area; normal fitting resumes when you return to the default zoom. Non-touch desktop and native-host layout remain unchanged.
+Text previews are limited to 384 KiB and indicate truncation. Very large or minified source may remain plain text. Image previews support PNG, JPEG, GIF and WebP up to 8 MiB. HTML and SVG files display as read-only source.
-On touch devices, compact text fields use a readable 16px minimum baseline to avoid Safari automatically zooming the page on focus. Desktop field density and manual page zoom remain unchanged.
+Explicit Markdown images appear inline; image attachments use a gallery. Ordinary image file links open the preview instead.
-On touch devices, preview tab controls and the full-screen image viewer's close button use larger touch areas without enlarging the icons. Preview tabs remain horizontally scrollable when space is limited.
+Mermaid diagrams render after the reply finishes. The source remains available if rendering fails. Links, external images and executable HTML inside diagrams are disabled.
-Open the context indicator beside the composer model badge to see how much of the model's context window is in use. The **Recent rounds** chart shows input tokens for each logical model round, including tool-call rounds. Hover or focus a bar for input tokens, output tokens, generation time, and the KV cache hit rate when reported. Provider usage may be estimated or unavailable; these figures are not a billing statement.
+Right-click a file reference or preview tab to copy its absolute or project-relative path on the connected host. Files outside the project have no project-relative path; unresolved references can only be copied as written.
-When nanobot compacts context, the timeline shows its progress and outcome. The model continues with a summary and any messages after it; messages covered by the summary remain in your chat history but are no longer sent to the model verbatim. Use `/compact` to compact the current topic's context manually. See [Memory](./memory.md) for compaction and Dream consolidation.
+File previews follow the active topic's access mode. Restricted workspace access previews only files under the selected workspace. Full Access can preview files outside the workspace when that access mode is allowed by the gateway.
### Model failures
@@ -175,17 +135,13 @@ When nanobot delegates work to subagents, a work group appears under the request
Work groups follow the browser's **Activity details** preference: **Auto** opens running work and folds it when all tasks finish; **Expanded** keeps it open by default. You can also expand or fold a group manually to check individual outcomes, including failures and partial results.
-Select a task to open its read-only conversation on the right, or across the screen on mobile. Read its messages, tool activity, file edits, and results, including formatted Markdown. Closing the details leaves the task running; its stop button cancels only that task. Give follow-up instructions to nanobot in the main conversation.
+Select a task for its read-only conversation and tool activity. Closing the details leaves it running; its stop button cancels only that task. Give follow-up instructions to nanobot in the main conversation.
These controls appear when the connected host supports subagent tasks. See [Subagents](./concepts.md#subagents) for cancellation, saved history, and gateway restart behavior.
## Temporary Chats
-Use a temporary chat for a conversation that should not be added to nanobot's topic history or long-term memory:
-
-1. Select **New topic**.
-2. Select the **Temporary chat** control in the page header.
-3. Send the first message.
+Start **New topic → Temporary chat** for a conversation that should not be added to topic history or long-term memory.
You can keep more than one temporary chat open and switch between them under **Temporary chats** in the sidebar while the current WebUI connection remains open. Reloading or closing the page, restarting the gateway, or losing the WebSocket connection ends all of them. They cannot be recovered afterward.
@@ -197,9 +153,9 @@ Temporary does not mean consequence-free. Requests still go to the configured mo
Use the workspace picker to browse folders on the connected nanobot host, enter an absolute path, or return to recent and starred projects; favorites persist across gateway restarts. The host name appears above saved locations. Project paths refer to that machine, not the browser's filesystem.
-Use the breadcrumb nodes or Back and Forward controls to navigate. **Last visited folder** returns directly to the folder you most recently left, restoring its directory columns, selected rows, filter, and scroll positions. **Filter this folder** only filters the current directory. Click the empty area in the path bar or press **Cmd/Ctrl+Shift+G** to enter a host path; Tab completes it and Enter opens it. Click outside the input or press Escape to cancel path editing; **Confirm** confirms the edited path. Browsing does not change the workspace until you choose **Confirm**. **Cancel** leaves the current workspace unchanged. Desktop uses directory columns with Shift+wheel horizontal scrolling; narrow screens show one folder at a time, with favorites and recent projects under **Saved locations**. Directory columns settle on complete rows after scrolling.
+Browsing does not change the topic's workspace until you choose **Confirm**. **Filter this folder** searches only the current directory. **Cmd/Ctrl+Shift+G** opens host-path entry, with Tab completion; **Last visited folder** returns to the previous location.
-On a compatible host without the optional directory-browser capabilities, manual path entry remains available. Browse and favorite requests are not sent to that host. The gateway still validates the selected workspace and owns its access policy.
+Manual path entry remains available when the connected host does not support directory browsing. The host validates the selected path and access policy.
Selecting a project does not replace the configured agent workspace. The two paths have different responsibilities:
@@ -219,9 +175,7 @@ In Restricted mode, ordinary file and shell work stays inside the selected proje
## Composer
-With voice transcription configured, the idle composer uses one button for voice input when empty and Send when text or attachments are present; speech is transcribed into the draft before sending.
-
-The composer supports plain messages, image attachments, voice input when transcription is configured, slash commands, and `@` mentions for installed Apps, MCP presets, or saved topics.
+The composer supports text, image attachments, slash commands and `@` mentions. With voice transcription configured, the empty composer offers voice input; transcription is added to the draft before sending.
To reference another topic, type or paste its complete handle (such as `@luma`), choose it from the `@` menu, or drag it from the sidebar into the composer. Recognized handles are highlighted; unknown handles remain plain text. You can reference up to eight different topics in one message.
@@ -229,21 +183,13 @@ Ask nanobot to find, read, or send messages to other saved topics, including tho
On touch-primary phones and tablets, **Enter** inserts a newline; tap the send arrow to submit. This also applies when a coarse-pointer tablet has a hardware keyboard attached. On desktop, **Enter** sends and **Shift+Enter** adds a newline. An open slash-command or mention menu takes precedence: Enter selects its item.
-While a response is running, desktop Enter adds your input to one waiting message. Further inputs append in order, separated by newlines, with their attachments and references retained. The complete message is sent once the current response finishes. Press Enter again with an empty input or choose **Send now** to insert it immediately as guidance for the active turn. The send arrow also includes any waiting content when submitting a new draft. Use **Edit message** to revise the complete message or **Delete message** to discard it. If an addition would exceed the message limits, it stays in the input so you can revise it. The primary button shows **Stop** when there is no sendable draft; stopping or a failed send keeps the waiting message for manual sending.
-
-The model badge shows the current model or preset and links to model settings when setup is incomplete.
+During a response, desktop Enter appends input to one waiting message, preserving order, attachments and references. It sends when the response finishes. **Send now** or Enter on an empty input sends it immediately as guidance; the send arrow submits the waiting content together with any draft. **Edit message** and **Delete message** act on the whole waiting message. Additions that exceed limits stay in the input. Stopping a turn or a failed send preserves the waiting message for manual sending.
For image generation, configure an image provider first and then use the WebUI image mode from the composer. See [`image-generation.md`](./image-generation.md) for provider setup and output behavior.
## Channels
-Open **Channels** to connect chat apps without assembling JSON by hand. Search for a platform, open its setup panel, and follow the fields or QR flow shown for that channel. The guided setup can:
-
-- install missing optional channel support when the WebUI is running locally;
-- collect platform credentials while preserving previously saved values;
-- handle supported QR-based login flows;
-- validate the connection and show actionable setup errors;
-- tell you when the gateway needs to restart.
+**Channels** provides credential or QR-based setup, connection validation, and restart guidance. Missing channel support can be installed from a local WebUI.
The platform itself may still require you to create a bot, enable event permissions, copy a token, or configure a webhook. Use [`chat-apps.md`](./chat-apps.md) for those platform-side prerequisites and for manual JSON/reference options.
@@ -251,19 +197,17 @@ Test a new channel with a private DM. When a supported channel sends a pairing c
## Apps
-Open Apps from the sidebar to review and manage installable capabilities. The default **Ready** view shows only capabilities that can be used immediately:
+**Apps → Ready** lists capabilities available for use:
- **Agent Plugins** are local packages that can bundle skills, MCP servers, or both. A package under `<workspace>/plugins/` is installed but remains inactive until you enable it in Apps.
-- **CLI Apps** are local command-line adapters that nanobot runs on your machine. Their installer manages the executable and exposes its adapter through the same plugin activation model. Installing an adapter does not modify the native desktop or web app it connects to.
+- **CLI Apps** are command-line tool adapters on the nanobot host. Install and enable an adapter before attaching it to a turn.
- **MCP** lists Model Context Protocol servers. Presets provide known configurations, and the **Add MCP server** panel accepts stdio, HTTP, and SSE servers. Custom HTTP/SSE servers can use no authentication, OAuth, or request headers. After saving an OAuth server, choose **Connect** to open its sign-in page. Presets such as Xmind, Notion, and Linear already use OAuth. HTTPS and localhost WebUIs return automatically; a remote plain-HTTP WebUI shows one field for pasting the complete localhost callback URL.
CLI Apps run with a limited environment that excludes provider API keys. On Unix, they inherit `XDG_RUNTIME_DIR` when it is set in the gateway's environment, so desktop CLIs such as Obsidian can locate the running application. Start the gateway in the same desktop session as the app to inherit that runtime directory.
-Apps intentionally does not list nanobot runtime support packages such as `api` or `bedrock`. Those packages enable providers, servers, or channels; they are not tools that can be attached to a turn with `@`. Manage them from **System**, **Models**, or **Web**. PDF and common Office document readers are included in nanobot and activate automatically when a file is attached. The equivalent CLI for optional integrations remains `nanobot plugins`. See [`cli-reference.md`](./cli-reference.md#optional-features). That command manages nanobot runtime extras, not Agent Plugin packages.
-
-Some MCP presets connect to hosted keyless endpoints. For example, the Firecrawl preset uses Firecrawl's hosted MCP endpoint for search, scrape, crawl, and extraction tools without requiring an API key. This does not replace nanobot's built-in web search provider; mention the Firecrawl MCP preset with `@` when a turn needs Firecrawl's richer web data tools.
+Manage optional runtime support from **System**, **Models**, or **Web**, or use [`nanobot plugins`](./cli-reference.md#optional-features). That command manages runtime extras, not Agent Plugin packages. PDF and common Office attachment readers require no setup.
-The Parallel Search preset connects to the free, anonymous Parallel Search MCP endpoint and exposes `web_search` and `web_fetch` without requiring an API key. It is an optional integration and does not replace nanobot's built-in web search provider; mention `@parallel-search` when a turn should use it.
+Keyless hosted presets include **Firecrawl** for search, scraping, crawling and extraction, and **Parallel Search** for `web_search` and `web_fetch`. They are optional MCP tools and do not change the built-in web search provider.
After a CLI App or MCP server is available, mention it from the composer with `@` to attach that tool to the next message. Plugin-provided skills participate in normal skill discovery and can be invoked with `$skill-name`.
@@ -288,15 +232,7 @@ There are two user-facing automation types:
For recurring background checks that should stay quiet unless there is something useful to report, use the protected heartbeat job by editing `HEARTBEAT.md` instead of creating a chat automation.
-Use the Automations view to:
-
-- Filter by all, active, paused, needs-attention, or system jobs.
-- Search by task name, message, trigger command, linked topic, schedule, or status.
-- Sort by next run, last run, updated time, or name.
-- Run scheduled automations now.
-- Pause or resume, rename, or delete user-created automations.
-- Copy the CLI command for local triggers.
-- Inspect protected system automations without changing them.
+The Automations view manages user-created jobs and can run scheduled jobs immediately. Protected system jobs are read-only.
Search accepts plain text and field filters such as `name:backup`, `chat:WeChat`, `schedule:09:30`, `cron:"0 23 * * *"`, `trigger`, and `status:paused`.
@@ -306,13 +242,9 @@ Local triggers do not have a WebUI "Run now" action because each run needs a mes
## Settings
-Settings is the control surface for browser-local and gateway-backed runtime configuration. Use it to review or adjust model presets, providers, image generation, voice transcription, web tools, chat channels, Apps, Automations, Skills, runtime identity, and advanced safety controls.
-
-Some settings take effect immediately. Runtime settings that affect the gateway or agent process may require a restart; the WebUI shows that requirement next to the relevant control.
+Runtime settings may require a gateway restart; the WebUI marks those controls.
-Browser-only display preferences take effect immediately and persist in the current browser. In **Appearance → Local preferences**, **Reading text size** offers three A buttons: small, standard (default), and large. They adjust conversation text, Markdown and code, with a coordinated message input size; navigation and toolbars keep their interface size. Browser zoom remains available. These preferences, including file edit display mode, do not change gateway configuration.
-
-To add a model, follow [Configure Your Model](./quick-start.md#2-configure-your-model).
+**Appearance → Local preferences** applies immediately to the current browser without changing gateway configuration. **Reading text size** adjusts conversation text, Markdown, code and the input, but not navigation or toolbars; standard is the default.
## LAN Access
@@ -349,26 +281,12 @@ Remote WebUI clients with a valid token can view and use Apps and installed skil
</details>
-Use this only for a private deployment where every authenticated WebUI user is trusted to change nanobot's Python environment and install workspace skill instructions or scripts. If you publish the WebUI through Nginx, Caddy, Cloudflare Tunnel, or a similar service, treat it as remote access and leave package and skill installs disabled unless that is intentional.
+Enable remote installation only for a private deployment whose users are trusted to change the Python environment and install skill instructions or scripts. Reverse-proxy and tunnel deployments count as remote access.
Optional feature installs use pip's configured package index, including `PIP_INDEX_URL`. skills.sh marketplace installs use `npx` instead.
-Leave remote package installs disabled when the WebUI is exposed beyond a private, trusted network.
-
## Troubleshooting
-### Links and website previews
-
-HTTP(S) links in replies have a **Link actions** menu: right-click the link or press Shift+F10 while it is focused. Touch and hold keeps the browser's native link menu. For in-app actions on touch devices, open the message's existing **Message actions → View links** entry. It lists only the web links rendered in that message, not URLs inside code blocks or file references. Choose a link to copy it, open it externally, or preview it beside the current conversation. On phone-sized screens, Copy and Message actions sit below the message, leaving the full text width available. Message actions opens a bottom sheet; close it with its close button, by tapping outside, or with Escape. Desktop keeps the hover-triggered message popover. On desktop, hovering or focusing a message also reveals a short timestamp below its actions: a 24-hour clock for today, or month/day for every other date. Hover or focus that label for the full local date and time, including the year. Replies use their completion timestamp when available, otherwise their creation timestamp. There is no persistent action button beside each link and no custom long-press gesture to interfere with scrolling or text selection. 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:
@@ -376,9 +294,7 @@ If the page does not open, check these in order:
1. `nanobot agent -m "Hello!"` works in the same Python environment.
2. `~/.nanobot/config.json` does not explicitly set `channels.websocket.enabled` to `false`.
3. `nanobot gateway` is still running.
-4. You are opening port `8765`, not the gateway health port.
+4. You are using the WebUI port (`8765` by default), not the health port (`18790` by default).
5. LAN access uses `host: "0.0.0.0"` and a token or token issue secret.
-If voice input asks for a secure connection, use HTTPS with a certificate the device trusts. Browsers do not expose microphone capture to `http://<your-ip>` origins.
-
For detailed diagnostics, see [`troubleshooting.md#webui-problems`](./troubleshooting.md#webui-problems). For frontend development, see [`../webui/README.md`](../webui/README.md).
diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.md
index b9f3f3a13..ce2ab7790 100644
--- a/webui/COMPONENTS.md
+++ b/webui/COMPONENTS.md
@@ -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.
diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx
index 9315bb77e..bfb768578 100644
--- a/webui/src/components/MessageBubble.tsx
+++ b/webui/src/components/MessageBubble.tsx
@@ -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"
diff --git a/webui/src/components/MessageLinksMenu.tsx b/webui/src/components/MessageLinksMenu.tsx
deleted file mode 100644
index 3bf332b60..000000000
--- a/webui/src/components/MessageLinksMenu.tsx
+++ /dev/null
@@ -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>;
-}
diff --git a/webui/src/components/PreviewPane.tsx b/webui/src/components/PreviewPane.tsx
index 4dc3459eb..add566d98 100644
--- a/webui/src/components/PreviewPane.tsx
+++ b/webui/src/components/PreviewPane.tsx
@@ -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>
diff --git a/webui/src/components/WebLink.tsx b/webui/src/components/WebLink.tsx
index d1389bb8e..fdb802ade 100644
--- a/webui/src/components/WebLink.tsx
+++ b/webui/src/components/WebLink.tsx
@@ -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 { 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`;
+import type { ComponentPropsWithoutRef } from "react";
+
+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>;
-}
diff --git a/webui/src/components/WebPreviewPanel.tsx b/webui/src/components/WebPreviewPanel.tsx
deleted file mode 100644
index 50a0e8feb..000000000
--- a/webui/src/components/WebPreviewPanel.tsx
+++ /dev/null
@@ -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>;
-}
diff --git a/webui/src/components/WebPreviewPanelView.tsx b/webui/src/components/WebPreviewPanelView.tsx
deleted file mode 100644
index 64b1a34a5..000000000
--- a/webui/src/components/WebPreviewPanelView.tsx
+++ /dev/null
@@ -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>
- );
-}
diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx
index edc127c2c..717a6166f 100644
--- a/webui/src/components/thread/ThreadMessages.tsx
+++ b/webui/src/components/thread/ThreadMessages.tsx
@@ -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}
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index dac7e9c9d..19bc934a5 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -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}
diff --git a/webui/src/dev/gallery/content.tsx b/webui/src/dev/gallery/content.tsx
index e402daa06..c012eb2da 100644
--- a/webui/src/dev/gallery/content.tsx
+++ b/webui/src/dev/gallery/content.tsx
@@ -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} />' },
diff --git a/webui/src/dev/gallery/locales/previews/en.json b/webui/src/dev/gallery/locales/previews/en.json
index 6c4770266..2323b6fc6 100644
--- a/webui/src/dev/gallery/locales/previews/en.json
+++ b/webui/src/dev/gallery/locales/previews/en.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/es.json b/webui/src/dev/gallery/locales/previews/es.json
index 1265ef76e..a5591df76 100644
--- a/webui/src/dev/gallery/locales/previews/es.json
+++ b/webui/src/dev/gallery/locales/previews/es.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/fr.json b/webui/src/dev/gallery/locales/previews/fr.json
index 17508b710..510c8f240 100644
--- a/webui/src/dev/gallery/locales/previews/fr.json
+++ b/webui/src/dev/gallery/locales/previews/fr.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/id.json b/webui/src/dev/gallery/locales/previews/id.json
index 9f0f4a22c..31ec13341 100644
--- a/webui/src/dev/gallery/locales/previews/id.json
+++ b/webui/src/dev/gallery/locales/previews/id.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/ja.json b/webui/src/dev/gallery/locales/previews/ja.json
index b41baf1b2..619a08097 100644
--- a/webui/src/dev/gallery/locales/previews/ja.json
+++ b/webui/src/dev/gallery/locales/previews/ja.json
@@ -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": "タスクの表示、編集、無効化、削除と読み込み・エラー状態を試せます。",
diff --git a/webui/src/dev/gallery/locales/previews/ko.json b/webui/src/dev/gallery/locales/previews/ko.json
index 61cb17fcc..8d82f4a99 100644
--- a/webui/src/dev/gallery/locales/previews/ko.json
+++ b/webui/src/dev/gallery/locales/previews/ko.json
@@ -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": "작업 조회, 편집, 비활성화, 삭제와 로딩·오류 상태를 시험합니다.",
diff --git a/webui/src/dev/gallery/locales/previews/pt-BR.json b/webui/src/dev/gallery/locales/previews/pt-BR.json
index 450c3b814..609390b9c 100644
--- a/webui/src/dev/gallery/locales/previews/pt-BR.json
+++ b/webui/src/dev/gallery/locales/previews/pt-BR.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/vi.json b/webui/src/dev/gallery/locales/previews/vi.json
index 2e966beb2..942c6346f 100644
--- a/webui/src/dev/gallery/locales/previews/vi.json
+++ b/webui/src/dev/gallery/locales/previews/vi.json
@@ -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.",
diff --git a/webui/src/dev/gallery/locales/previews/zh-CN.json b/webui/src/dev/gallery/locales/previews/zh-CN.json
index 608008c31..e32949310 100644
--- a/webui/src/dev/gallery/locales/previews/zh-CN.json
+++ b/webui/src/dev/gallery/locales/previews/zh-CN.json
@@ -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": "查看、编辑、停用和删除会话任务。",
diff --git a/webui/src/dev/gallery/locales/previews/zh-TW.json b/webui/src/dev/gallery/locales/previews/zh-TW.json
index d2aabea61..808585590 100644
--- a/webui/src/dev/gallery/locales/previews/zh-TW.json
+++ b/webui/src/dev/gallery/locales/previews/zh-TW.json
@@ -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": "查看、編輯、停用與刪除對話任務。",
diff --git a/webui/src/dev/gallery/shell.tsx b/webui/src/dev/gallery/shell.tsx
index 3d6f7a948..5f5116f8c 100644
--- a/webui/src/dev/gallery/shell.tsx
+++ b/webui/src/dev/gallery/shell.tsx
@@ -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} />' },
diff --git a/webui/src/hooks/useFilePreviewState.ts b/webui/src/hooks/useFilePreviewState.ts
index d3d9b6722..ed37c92ec 100644
--- a/webui/src/hooks/useFilePreviewState.ts
+++ b/webui/src/hooks/useFilePreviewState.ts
@@ -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 };
}
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index c6b0a854e..6ca24e4d6 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 303a39088..69a06bc4c 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 6f28e3412..162f12ebc 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index dc0291df5..06e684d08 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 5cb0498f7..188852eae 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -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 にスターを付ける",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 5a5fc2a80..86cfa63bc 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -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에 스타 남기기",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 91bda2503..d8f9496d5 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 58e5e3721..47875eea5 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index edd558881..44faa044a 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -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",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 4c4e7367f..22b3348c2 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -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",
diff --git a/webui/src/lib/web-preview.ts b/webui/src/lib/web-preview.ts
deleted file mode 100644
index 6451e9cab..000000000
--- a/webui/src/lib/web-preview.ts
+++ /dev/null
@@ -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";
-}
diff --git a/webui/src/tests/file-preview-panel.test.tsx b/webui/src/tests/file-preview-panel.test.tsx
index 1671832f8..3170fa4f1 100644
--- a/webui/src/tests/file-preview-panel.test.tsx
+++ b/webui/src/tests/file-preview-panel.test.tsx
@@ -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)!;
diff --git a/webui/src/tests/file-reference-icon.test.tsx b/webui/src/tests/file-reference-icon.test.tsx
index c3fde7d40..12d1f5de3 100644
--- a/webui/src/tests/file-reference-icon.test.tsx
+++ b/webui/src/tests/file-reference-icon.test.tsx
@@ -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}` }} />
diff --git a/webui/src/tests/message-links-menu.test.tsx b/webui/src/tests/message-links-menu.test.tsx
deleted file mode 100644
index 79655d9e2..000000000
--- a/webui/src/tests/message-links-menu.test.tsx
+++ /dev/null
@@ -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:[email protected]) [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());
- });
-});
diff --git a/webui/src/tests/preview-pane.test.tsx b/webui/src/tests/preview-pane.test.tsx
index 7a5d56698..af5f8cc60 100644
--- a/webui/src/tests/preview-pane.test.tsx
+++ b/webui/src/tests/preview-pane.test.tsx
@@ -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>
diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsx
index b3ebce5df..74ad9b988 100644
--- a/webui/src/tests/temporary-chat-navigation.test.tsx
+++ b/webui/src/tests/temporary-chat-navigation.test.tsx
@@ -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([]);
diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsx
index 9eccbae9a..18c817dda 100644
--- a/webui/src/tests/thread-messages.test.tsx
+++ b/webui/src/tests/thread-messages.test.tsx
@@ -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) => {
diff --git a/webui/src/tests/web-link.test.tsx b/webui/src/tests/web-link.test.tsx
new file mode 100644
index 000000000..ca4ccfa85
--- /dev/null
+++ b/webui/src/tests/web-link.test.tsx
@@ -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:[email protected]", "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:[email protected]/", "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();
+ },
+ );
+});
diff --git a/webui/src/tests/web-preview.test.tsx b/webui/src/tests/web-preview.test.tsx
deleted file mode 100644
index e04e37b9d..000000000
--- a/webui/src/tests/web-preview.test.tsx
+++ /dev/null
@@ -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:[email protected]/", "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:[email protected]">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();
-});