diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts index 7a019bb4230c..5b8fccd8bb00 100644 --- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts +++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event.ts @@ -22,6 +22,7 @@ import { $gateway } from '@/store/gateway' import { dispatchNativeNotification } from '@/store/native-notifications' import { notify } from '@/store/notifications' import { requestDesktopOnboarding } from '@/store/onboarding' +import { revealDesktopPane } from '@/store/pane-focus' import { flashPetActivity, markPetUnread, setPetActivity } from '@/store/pet' import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile' import { followActiveSessionCwd } from '@/store/projects' @@ -750,6 +751,14 @@ export function useGatewayEventHandler(deps: GatewayEventDeps) { // Agent closed its own read-only tab via the desktop-gated close_terminal tool. // The process is untouched — this only drops the view. closeAgentTerminalByProc(payload?.process_id ?? '') + } else if (event.type === 'pane.reveal') { + // Agent revealed a pane via the desktop-gated focus_pane tool, in + // response to an explicit user request. Active session only — a + // background turn must never move the user's focus (desktop AGENTS.md: + // offer, don't hijack). + if (isActiveEvent) { + revealDesktopPane(payload?.pane ?? '') + } } else if (event.type === 'status.update') { if (sessionId && payload?.kind === 'compacting') { setSessionCompacting(sessionId, true) diff --git a/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx b/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx index 3af7455a9535..e62cfb4ad071 100644 --- a/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx @@ -120,6 +120,42 @@ describe('usePreviewRouting', () => { expect(window.hermesDesktop.normalizePreviewTarget).not.toHaveBeenCalled() }) + it('opens the preview pane on a preview.open event for the active session', async () => { + render( + { + handleEvent = handler + }} + /> + ) + + act(() => + handleEvent({ payload: { url: 'https://www.cnn.com', label: 'CNN' }, session_id: 'session-1', type: 'preview.open' }) + ) + + await waitFor(() => { + expect($previewTarget.get()).toMatchObject({ kind: 'url', label: 'CNN', url: 'https://www.cnn.com' }) + }) + }) + + it('ignores a preview.open event for a background session', async () => { + render( + { + handleEvent = handler + }} + /> + ) + + act(() => + handleEvent({ payload: { url: 'https://www.cnn.com' }, session_id: 'other-session', type: 'preview.open' }) + ) + + // Give any (wrongly) scheduled async open a tick to resolve before asserting. + await Promise.resolve() + expect($previewTarget.get()).toBeNull() + }) + it('does not auto-open a preview from tool results', async () => { render( { baseHandleGatewayEvent(event) + if (event.type === 'preview.open') { + // Agent-driven open in response to an explicit user request ("show + // cnn.com in the preview pane"). Honor it only for the active session — + // a background turn must not yank the pane open (see desktop AGENTS.md: + // offer, don't hijack). Routes through the same normalizer as the file + // browser so URLs, localhost, and file paths all resolve correctly. + const { url, label } = asRecord(event.payload) + const target = typeof url === 'string' ? url.trim() : '' + + if (target && (!event.session_id || event.session_id === activeSessionIdRef.current)) { + void normalizeOrLocalPreviewTarget(target, $currentCwd.get() || currentCwd || undefined).then(resolved => { + if (resolved) { + const trimmedLabel = typeof label === 'string' ? label.trim() : '' + setCurrentSessionPreviewTarget(trimmedLabel ? { ...resolved, label: trimmedLabel } : resolved, 'tool-result') + } + }) + } + + return + } + if (event.type === 'preview.restart.complete') { const { task_id, text } = asRecord(event.payload) @@ -126,7 +149,7 @@ export function usePreviewRouting({ requestPreviewReload() } }, - [activeSessionIdRef, baseHandleGatewayEvent] + [activeSessionIdRef, baseHandleGatewayEvent, currentCwd] ) return { handleDesktopGatewayEvent, restartPreviewServer } diff --git a/apps/desktop/src/lib/chat-messages.ts b/apps/desktop/src/lib/chat-messages.ts index 0a6d56d5a6b3..74beafcffd60 100644 --- a/apps/desktop/src/lib/chat-messages.ts +++ b/apps/desktop/src/lib/chat-messages.ts @@ -80,6 +80,8 @@ export type GatewayEventPayload = { count?: number // status.update (kind=process → background process completion/watch-match) kind?: string + // pane.reveal (agent focusing a desktop pane via the focus_pane tool) + pane?: string // session.title (live auto-title push) — stored session id + generated title session_id?: string title?: string diff --git a/apps/desktop/src/store/pane-focus.test.ts b/apps/desktop/src/store/pane-focus.test.ts new file mode 100644 index 000000000000..192a6d941885 --- /dev/null +++ b/apps/desktop/src/store/pane-focus.test.ts @@ -0,0 +1,42 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { revealDesktopPane } from './pane-focus' + +const { openReview, revealTreePane, setFileBrowserOpen, setSidebarOpen, setTerminalTakeover } = vi.hoisted(() => ({ + openReview: vi.fn(), + revealTreePane: vi.fn(), + setFileBrowserOpen: vi.fn(), + setSidebarOpen: vi.fn(), + setTerminalTakeover: vi.fn() +})) + +vi.mock('@/app/right-sidebar/store', () => ({ setTerminalTakeover })) +vi.mock('@/components/pane-shell/tree/store', () => ({ revealTreePane })) +vi.mock('./layout', () => ({ setFileBrowserOpen, setSidebarOpen })) +vi.mock('./review', () => ({ openReview })) + +describe('revealDesktopPane', () => { + beforeEach(() => vi.clearAllMocks()) + + it("drives each pane's own reveal path", () => { + revealDesktopPane('chat') + expect(revealTreePane).toHaveBeenCalledWith('workspace') + revealDesktopPane('files') + expect(setFileBrowserOpen).toHaveBeenCalledWith(true) + revealDesktopPane('review') + expect(openReview).toHaveBeenCalledOnce() + revealDesktopPane('sessions') + expect(setSidebarOpen).toHaveBeenCalledWith(true) + revealDesktopPane('terminal') + expect(setTerminalTakeover).toHaveBeenCalledWith(true) + }) + + it('returns false for an unknown pane and touches nothing', () => { + expect(revealDesktopPane('nope')).toBe(false) + expect(revealTreePane).not.toHaveBeenCalled() + }) + + it('returns true for a known pane', () => { + expect(revealDesktopPane('terminal')).toBe(true) + }) +}) diff --git a/apps/desktop/src/store/pane-focus.ts b/apps/desktop/src/store/pane-focus.ts new file mode 100644 index 000000000000..2b5c99e4ac6a --- /dev/null +++ b/apps/desktop/src/store/pane-focus.ts @@ -0,0 +1,30 @@ +import { setTerminalTakeover } from '@/app/right-sidebar/store' +import { revealTreePane } from '@/components/pane-shell/tree/store' + +import { setFileBrowserOpen, setSidebarOpen } from './layout' +import { openReview } from './review' + +// Explicit-request pane reveals, keyed to the backend `focus_pane` tool. Each +// entry drives the pane's own reveal path (some are toggle-bound) so a revealed +// pane matches a user-driven open. files/review are workspace-gated — a no-op +// without a project cwd, which is the honest behavior. +const PANE_REVEALERS: Record void> = { + chat: () => revealTreePane('workspace'), + files: () => setFileBrowserOpen(true), + review: () => openReview(), + sessions: () => setSidebarOpen(true), + terminal: () => setTerminalTakeover(true) +} + +/** Reveal a desktop pane by name. Returns false for an unknown pane. */ +export function revealDesktopPane(pane: string): boolean { + const reveal = PANE_REVEALERS[pane] + + if (!reveal) { + return false + } + + reveal() + + return true +} diff --git a/tests/tools/test_desktop_ui.py b/tests/tools/test_desktop_ui.py new file mode 100644 index 000000000000..4e35eab6c4b2 --- /dev/null +++ b/tests/tools/test_desktop_ui.py @@ -0,0 +1,30 @@ +"""Tests for the desktop-only renderer-event bridge.""" + +import pytest + +from tools import desktop_ui + + +@pytest.fixture(autouse=True) +def _reset_emitter(): + desktop_ui.set_emitter(None) + yield + desktop_ui.set_emitter(None) + + +def test_unavailable_without_emitter(): + assert desktop_ui.available() is False + assert desktop_ui.emit("preview.open", {"url": "x"}) is False + + +def test_routes_event_to_owning_window(monkeypatch): + monkeypatch.setattr( + desktop_ui, "get_session_env", + lambda name, default="": "win-7" if name == "HERMES_UI_SESSION_ID" else default, + ) + seen = [] + desktop_ui.set_emitter(lambda sid, event, payload: seen.append((sid, event, payload))) + + assert desktop_ui.available() is True + assert desktop_ui.emit("pane.reveal", {"pane": "terminal"}) is True + assert seen == [("win-7", "pane.reveal", {"pane": "terminal"})] diff --git a/tests/tools/test_focus_pane_tool.py b/tests/tools/test_focus_pane_tool.py new file mode 100644 index 000000000000..cef279d1bc30 --- /dev/null +++ b/tests/tools/test_focus_pane_tool.py @@ -0,0 +1,42 @@ +"""Tests for the desktop-gated ``focus_pane`` tool.""" + +import json + +import pytest + +from tools import desktop_ui, focus_pane_tool as fp + + +@pytest.fixture(autouse=True) +def _reset_emitter(): + desktop_ui.set_emitter(None) + yield + desktop_ui.set_emitter(None) + + +def test_gated_on_desktop(monkeypatch): + monkeypatch.delenv("HERMES_DESKTOP", raising=False) + assert fp.check_focus_pane_requirements() is False + + monkeypatch.setenv("HERMES_DESKTOP", "1") + assert fp.check_focus_pane_requirements() is True + + +def test_rejects_unknown_pane(): + desktop_ui.set_emitter(lambda *a: None) + assert json.loads(fp.focus_pane_tool("banana"))["error"] + + +def test_desktop_only_without_emitter(): + assert "desktop" in json.loads(fp.focus_pane_tool("terminal"))["error"].lower() + + +@pytest.mark.parametrize("pane", fp.PANES) +def test_emits_pane_reveal(pane): + calls = [] + desktop_ui.set_emitter(lambda sid, event, payload: calls.append((event, payload))) + + out = json.loads(fp.focus_pane_tool(f" {pane.upper()} ")) + + assert out == {"success": True, "pane": pane} + assert calls == [("pane.reveal", {"pane": pane})] diff --git a/tests/tools/test_open_preview_tool.py b/tests/tools/test_open_preview_tool.py new file mode 100644 index 000000000000..a401dde9d6d6 --- /dev/null +++ b/tests/tools/test_open_preview_tool.py @@ -0,0 +1,75 @@ +"""Tests for the desktop-gated ``open_preview`` tool.""" + +import json + +import pytest + +from tools import desktop_ui, open_preview_tool as op + + +@pytest.fixture(autouse=True) +def _reset_emitter(): + """Each test controls the emitter; never leak one across tests.""" + desktop_ui.set_emitter(None) + yield + desktop_ui.set_emitter(None) + + +def test_gated_on_desktop(monkeypatch): + """Hidden unless HERMES_DESKTOP is set (mirrors read_terminal/close_terminal).""" + monkeypatch.delenv("HERMES_DESKTOP", raising=False) + assert op.check_open_preview_requirements() is False + + monkeypatch.setenv("HERMES_DESKTOP", "1") + assert op.check_open_preview_requirements() is True + + +def test_requires_url(): + desktop_ui.set_emitter(lambda *a: None) + assert json.loads(op.open_preview_tool(" "))["error"] + + +def test_desktop_only_without_emitter(): + """No emitter wired (CLI/messaging) → clear desktop-only error, no raise.""" + result = json.loads(op.open_preview_tool("https://example.com")) + assert "desktop" in result["error"].lower() + + +def test_emits_preview_open(monkeypatch): + calls = [] + desktop_ui.set_emitter(lambda sid, event, payload: calls.append((event, payload))) + + out = json.loads(op.open_preview_tool("https://example.com/app", label="Docs")) + + assert out == {"success": True, "url": "https://example.com/app", "label": "Docs"} + assert calls == [("preview.open", {"url": "https://example.com/app", "label": "Docs"})] + + +@pytest.mark.parametrize( + "raw,expected", + [ + ("www.cnn.com", "https://www.cnn.com"), + ("example.com/path", "https://example.com/path"), + ("localhost:3000", "http://localhost:3000"), + ("127.0.0.1:8080/x", "http://127.0.0.1:8080/x"), + ("https://already.example", "https://already.example"), + ("/abs/path/index.html", "/abs/path/index.html"), + ("./rel/page.html", "./rel/page.html"), + ("`https://tick.example`", "https://tick.example"), + ], +) +def test_normalizes_bare_targets(raw, expected): + seen = {} + desktop_ui.set_emitter(lambda sid, event, payload: seen.update(payload)) + + op.open_preview_tool(raw) + + assert seen["url"] == expected + + +def test_emitter_failure_is_reported(): + def _boom(*_a): + raise RuntimeError("no window") + + desktop_ui.set_emitter(_boom) + assert "no window" in json.loads(op.open_preview_tool("https://x.example"))["error"] diff --git a/tools/desktop_ui.py b/tools/desktop_ui.py new file mode 100644 index 000000000000..94955a29bda1 --- /dev/null +++ b/tools/desktop_ui.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Bridge desktop-only tools to Hermes-desktop renderer events. + +The preview pane, pane focus, and friends live in the desktop renderer, so +desktop-gated tools reach them through an emitter the desktop ``tui_gateway`` +installs at session start via :func:`set_emitter`. Everywhere else it stays +``None`` and the tools report "desktop only". Routing keys off +``HERMES_UI_SESSION_ID`` so the event lands on the window that owns the turn +(``_emit``/``write_json`` is ``_stdout_lock``-guarded, so emitting from the +tool's thread is safe). +""" + +from typing import Callable, Optional + +from gateway.session_context import get_session_env + +# (sid, event, payload) sink, installed by the desktop gateway. +_emit: Optional[Callable[[str, str, dict], None]] = None + + +def set_emitter(fn: Optional[Callable[[str, str, dict], None]]) -> None: + """Install (or clear) the renderer-event sink. Called by the desktop gateway.""" + global _emit + _emit = fn + + +def available() -> bool: + """True when running under the desktop app (an emitter is wired).""" + return _emit is not None + + +def emit(event: str, payload: dict) -> bool: + """Route ``event`` to the window that owns the current turn. + + Returns ``False`` when no emitter is wired (i.e. not the desktop app).""" + fn = _emit + if fn is None: + return False + fn(get_session_env("HERMES_UI_SESSION_ID", ""), event, payload) + return True diff --git a/tools/focus_pane_tool.py b/tools/focus_pane_tool.py new file mode 100644 index 000000000000..d854a1ab0f8b --- /dev/null +++ b/tools/focus_pane_tool.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Reveal/focus a pane in the Hermes desktop GUI. + +Gated on ``HERMES_DESKTOP`` (like the other GUI affordances). Emits +``pane.reveal`` through the shared ``desktop_ui`` bridge; the renderer runs each +pane's own reveal path and only acts on the active window (a background turn +never moves the user's focus). To show a URL/file, use ``open_preview``. +""" + +import json + +from tools import desktop_ui +from tools.registry import registry, tool_error +from utils import env_var_enabled + +PANES = ("chat", "files", "terminal", "review", "sessions") + + +def focus_pane_tool(pane: str) -> str: + """Ask the desktop GUI to reveal and focus ``pane``.""" + name = (pane or "").strip().lower() + if name not in PANES: + return tool_error(f"pane must be one of: {', '.join(PANES)}.") + + try: + ok = desktop_ui.emit("pane.reveal", {"pane": name}) + except Exception as exc: + return tool_error(f"Failed to focus the {name} pane: {exc}") + if not ok: + return tool_error("Pane focus is only available in the Hermes desktop app.") + + return json.dumps({"success": True, "pane": name}, ensure_ascii=False) + + +def check_focus_pane_requirements() -> bool: + """Desktop GUI only — HERMES_DESKTOP is set on the gateway the app spawns.""" + return env_var_enabled("HERMES_DESKTOP") + + +FOCUS_PANE_SCHEMA = { + "name": "focus_pane", + "description": ( + "Reveal and focus a pane in the Hermes desktop app when the user asks to " + "see it — e.g. \"show me the terminal\", \"open the file browser\", \"show " + "the diff\". Panes: chat (the conversation), files (project file browser), " + "terminal (embedded shell), review (git diff), sessions (the session list). " + "To show a URL or file in the preview pane, use open_preview instead." + ), + "parameters": { + "type": "object", + "properties": { + "pane": { + "type": "string", + "enum": list(PANES), + "description": "Which pane to reveal.", + }, + }, + "required": ["pane"], + }, +} + + +registry.register( + name="focus_pane", + toolset="terminal", + schema=FOCUS_PANE_SCHEMA, + handler=lambda args, **kw: focus_pane_tool(pane=args.get("pane", "")), + check_fn=check_focus_pane_requirements, + emoji="🪟", +) diff --git a/tools/open_preview_tool.py b/tools/open_preview_tool.py new file mode 100644 index 000000000000..96b4d847e464 --- /dev/null +++ b/tools/open_preview_tool.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Open a URL, dev server, or file in the Hermes desktop GUI's preview pane. + +Gated on ``HERMES_DESKTOP`` (like ``read_terminal`` / ``close_terminal``) so it +never appears outside the GUI. Emits ``preview.open`` through the shared +``desktop_ui`` bridge; the renderer opens the pane beside the chat for the +window that asked and never steals focus for a background session. +""" + +import json +import re + +from tools import desktop_ui +from tools.registry import registry, tool_error +from utils import env_var_enabled + + +def _normalize_target(raw: str) -> str: + """Coax a bare host/domain into a fetchable URL; leave paths + schemes alone. + + ``www.cnn.com`` → ``https://www.cnn.com``; ``localhost:3000`` → + ``http://localhost:3000``. File paths and explicit schemes pass through for + the renderer's preview normalizer to classify. + """ + v = raw.strip().strip("`").strip() + if not v or "://" in v or v.startswith(("/", "./", "../", "~", "file:")): + return v + if re.match(r"^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:\d+)?(/|$)", v, re.I): + return "http://" + v + if re.match(r"^[\w.-]+\.[a-z]{2,}(:\d+)?(/.*)?$", v, re.I): + return "https://" + v + return v + + +def open_preview_tool(url: str, label: str = "") -> str: + """Ask the desktop GUI to show ``url`` in the preview pane beside the chat.""" + target = _normalize_target(url or "") + if not target: + return tool_error( + "url is required — a web URL (https://…), a localhost dev server, or a " + "file path to show in the preview pane." + ) + + label = (label or "").strip() + try: + ok = desktop_ui.emit("preview.open", {"url": target, "label": label}) + except Exception as exc: + return tool_error(f"Failed to open the preview pane: {exc}") + if not ok: + return tool_error("The preview pane is only available in the Hermes desktop app.") + + return json.dumps({"success": True, "url": target, "label": label}, ensure_ascii=False) + + +def check_open_preview_requirements() -> bool: + """Desktop GUI only — HERMES_DESKTOP is set on the gateway the app spawns.""" + return env_var_enabled("HERMES_DESKTOP") + + +OPEN_PREVIEW_SCHEMA = { + "name": "open_preview", + "description": ( + "Open something in the preview pane beside the chat in the Hermes desktop " + "app. Use this when the user asks to see a page, dev server, or file in the " + "preview pane — e.g. \"open cnn.com in the preview pane\" or \"preview " + "localhost:3000\". Accepts a web URL (a bare domain like www.cnn.com is fine), " + "a localhost dev-server URL, or a file path (HTML renders live; other files " + "show their contents). The pane opens for the current window only." + ), + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": ( + "What to preview: a web URL (https://… or a bare domain), a " + "localhost URL (localhost:3000), or a file path." + ), + }, + "label": { + "type": "string", + "description": "Optional tab label; defaults to the target's name.", + }, + }, + "required": ["url"], + }, +} + + +registry.register( + name="open_preview", + toolset="terminal", + schema=OPEN_PREVIEW_SCHEMA, + handler=lambda args, **kw: open_preview_tool(url=args.get("url", ""), label=args.get("label", "")), + check_fn=check_open_preview_requirements, + emoji="🖼️", +) diff --git a/toolsets.py b/toolsets.py index 1be62780d0ca..5cd53fa7240e 100644 --- a/toolsets.py +++ b/toolsets.py @@ -33,10 +33,10 @@ _HERMES_CORE_TOOLS = [ "web_search", "web_extract", # Terminal + process management "terminal", "process", - # Read the desktop GUI's embedded terminal pane, and close an agent's - # read-only terminal tab (both gated on HERMES_DESKTOP via check_fn — - # hidden outside the GUI). - "read_terminal", "close_terminal", + # Desktop GUI affordances: read the embedded terminal pane, close an agent's + # read-only terminal tab, open a URL/file in the preview pane, and focus a + # pane (all gated on HERMES_DESKTOP via check_fn — hidden outside the GUI). + "read_terminal", "close_terminal", "open_preview", "focus_pane", # File manipulation "read_file", "write_file", "patch", "search_files", # Vision + image generation diff --git a/tui_gateway/server.py b/tui_gateway/server.py index 03d8492d932c..054f1747f8f9 100644 --- a/tui_gateway/server.py +++ b/tui_gateway/server.py @@ -10108,9 +10108,32 @@ def _wire_agent_terminal_output() -> None: process_registry.on_close = _emit_agent_terminal_close +_desktop_ui_wired = False + + +def _wire_desktop_ui() -> None: + """Bridge desktop-only tools (open_preview, focus_pane) to renderer events. + + Idempotent. The tool hands back the turn's ``HERMES_UI_SESSION_ID`` as + ``sid`` so the event routes to the window that asked (``_emit`` / + ``write_json`` is ``_stdout_lock``-guarded, so calling it from the tool's + thread is safe).""" + global _desktop_ui_wired + if _desktop_ui_wired: + return + try: + from tools import desktop_ui + except Exception: + return + + desktop_ui.set_emitter(lambda sid, event, payload: _emit(event, sid, payload)) + _desktop_ui_wired = True + + def _start_notification_poller(sid: str, session: dict) -> threading.Event: """Start the background notification poller for a TUI session.""" _wire_agent_terminal_output() + _wire_desktop_ui() stop = threading.Event() t = threading.Thread( target=_notification_poller_loop,