Merge branch 'bb/gui' into bb/gui-glass

Brings in main (via bb/gui) plus the bb/gui-only changes since the
last sync, so a future bb/gui-glass → bb/gui merge is conflict-free.

Conflicts resolved:
- apps/desktop/src/app/chat/composer/focus.ts (add/add): keep the
  glass version. It is a strict superset of the bb/gui original —
  same focus API (`requestComposerFocus`, `onComposerFocusRequest`,
  `markActiveComposer`) plus the insert bus
  (`requestComposerInsert`, `onComposerInsertRequest`,
  `focusComposerInput`) that the glass composer / right-rail
  preview / use-composer-actions already depend on.
- apps/desktop/src/app/skills/index.tsx: keep the glass rewrite
  built on `PageSearchShell` + `Codicon` + `TextTab` — bb/gui's
  older `titlebarHeaderBaseClass` + ad-hoc `Input`/`Search`/`X`
  layout is the version this PR was meant to replace.

`npm run type-check` in apps/desktop passes against the merged tree.
This commit is contained in:
Brooklyn Nicholson
2026-05-16 21:57:56 -05:00
13 changed files with 2650 additions and 3 deletions
+387
View File
@@ -0,0 +1,387 @@
"""Tests for the ``hermes send`` CLI subcommand.
Covers the argument parsing / stdin / file / list behavior of
``hermes_cli.send_cmd``. The underlying ``send_message_tool`` is stubbed so
no network I/O or gateway is required.
"""
from __future__ import annotations
import io
import json
from pathlib import Path
import pytest
from hermes_cli import send_cmd
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _parse(argv):
"""Build the top-level parser and return the parsed args for ``argv``."""
import argparse
parser = argparse.ArgumentParser(prog="hermes")
subparsers = parser.add_subparsers(dest="command")
send_cmd.register_send_subparser(subparsers)
return parser.parse_args(["send", *argv])
class _FakeTool:
"""Replacement for ``tools.send_message_tool.send_message_tool``."""
def __init__(self, payload):
self.payload = payload
self.calls = []
def __call__(self, args, **_kw):
self.calls.append(dict(args))
return json.dumps(self.payload)
@pytest.fixture
def fake_tool(monkeypatch):
"""Install a fake send_message_tool and return the stub for inspection."""
import sys
import types
fake = _FakeTool({"success": True, "message_id": "m123"})
mod = types.ModuleType("tools.send_message_tool")
mod.send_message_tool = fake
# Register the stub so ``from tools.send_message_tool import ...`` inside
# cmd_send resolves to our fake. Also patch the parent ``tools`` package
# entry so attribute lookup works.
monkeypatch.setitem(sys.modules, "tools.send_message_tool", mod)
return fake
# ---------------------------------------------------------------------------
# Happy path
# ---------------------------------------------------------------------------
def test_positional_message_success(fake_tool, capsys):
args = _parse(["--to", "telegram", "hello world"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
assert fake_tool.calls == [
{"action": "send", "target": "telegram", "message": "hello world"}
]
out = capsys.readouterr()
assert "sent" in out.out or out.out == "" # "sent" is the default success banner
def test_stdin_message(fake_tool, monkeypatch, capsys):
# Piped stdin (not a tty) should be consumed as the message body.
monkeypatch.setattr("sys.stdin", io.StringIO("piped body\n"))
# Force isatty to return False so the CLI reads from stdin.
monkeypatch.setattr("sys.stdin.isatty", lambda: False)
args = _parse(["--to", "discord:#ops"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
assert fake_tool.calls[0]["message"] == "piped body\n"
assert fake_tool.calls[0]["target"] == "discord:#ops"
def test_file_message(fake_tool, tmp_path):
body = tmp_path / "msg.txt"
body.write_text("from a file\n")
args = _parse(["--to", "slack:#eng", "--file", str(body)])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
assert fake_tool.calls[0]["message"] == "from a file\n"
def test_file_dash_means_stdin(fake_tool, monkeypatch):
monkeypatch.setattr("sys.stdin", io.StringIO("dash body"))
args = _parse(["--to", "telegram", "--file", "-"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
assert fake_tool.calls[0]["message"] == "dash body"
def test_subject_prepends_header(fake_tool):
args = _parse(["--to", "telegram", "--subject", "[CI]", "body text"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
assert fake_tool.calls[0]["message"] == "[CI]\n\nbody text"
def test_json_mode_emits_payload(fake_tool, capsys):
args = _parse(["--to", "telegram", "--json", "hi"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
out = capsys.readouterr().out
payload = json.loads(out)
assert payload.get("success") is True
assert payload.get("message_id") == "m123"
def test_quiet_suppresses_stdout(fake_tool, capsys):
args = _parse(["--to", "telegram", "--quiet", "shh"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
out = capsys.readouterr()
assert out.out == ""
# ---------------------------------------------------------------------------
# Error paths
# ---------------------------------------------------------------------------
def test_missing_target(fake_tool, capsys, monkeypatch):
# Ensure stdin is a tty so the CLI does not try to consume it as a body.
monkeypatch.setattr("sys.stdin.isatty", lambda: True)
args = _parse(["hello"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 2
err = capsys.readouterr().err
assert "--to" in err
def test_missing_message(fake_tool, capsys, monkeypatch):
monkeypatch.setattr("sys.stdin.isatty", lambda: True)
args = _parse(["--to", "telegram"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 2
err = capsys.readouterr().err
assert "no message" in err.lower()
def test_file_not_found_is_usage_error(fake_tool, capsys, monkeypatch):
monkeypatch.setattr("sys.stdin.isatty", lambda: True)
args = _parse(["--to", "telegram", "--file", "/nonexistent/does-not-exist.txt"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 2
err = capsys.readouterr().err
assert "cannot read" in err.lower()
def test_tool_error_returns_failure_exit(monkeypatch, capsys):
import sys as _sys
import types as _types
fake_mod = _types.ModuleType("tools.send_message_tool")
def _bad_tool(args, **_kw):
return json.dumps({"error": "platform blew up"})
fake_mod.send_message_tool = _bad_tool
monkeypatch.setitem(_sys.modules, "tools.send_message_tool", fake_mod)
args = _parse(["--to", "telegram", "nope"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 1
err = capsys.readouterr().err
assert "platform blew up" in err
def test_skipped_result_is_success(monkeypatch):
import sys as _sys
import types as _types
fake_mod = _types.ModuleType("tools.send_message_tool")
fake_mod.send_message_tool = lambda args, **_kw: json.dumps(
{"success": True, "skipped": True, "reason": "duplicate"}
)
monkeypatch.setitem(_sys.modules, "tools.send_message_tool", fake_mod)
args = _parse(["--to", "telegram", "dup"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
# ---------------------------------------------------------------------------
# --list
# ---------------------------------------------------------------------------
def test_list_human_output(monkeypatch, capsys):
import sys as _sys
import types as _types
fake_dir = _types.ModuleType("gateway.channel_directory")
fake_dir.format_directory_for_display = lambda: "Available messaging targets:\n\nTelegram:\n telegram:-100123\n"
fake_dir.load_directory = lambda: {
"platforms": {"telegram": [{"id": "-100123", "name": "Test Group"}]}
}
monkeypatch.setitem(_sys.modules, "gateway.channel_directory", fake_dir)
args = _parse(["--list"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
out = capsys.readouterr().out
assert "Telegram" in out
def test_list_json(monkeypatch, capsys):
import sys as _sys
import types as _types
fake_dir = _types.ModuleType("gateway.channel_directory")
fake_dir.format_directory_for_display = lambda: "(ignored in json mode)"
fake_dir.load_directory = lambda: {
"platforms": {"telegram": [{"id": "-100123", "name": "Test Group"}]}
}
monkeypatch.setitem(_sys.modules, "gateway.channel_directory", fake_dir)
args = _parse(["--list", "--json"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
out = capsys.readouterr().out
payload = json.loads(out)
assert payload["platforms"]["telegram"][0]["name"] == "Test Group"
def test_list_filter_platform(monkeypatch, capsys):
import sys as _sys
import types as _types
fake_dir = _types.ModuleType("gateway.channel_directory")
fake_dir.format_directory_for_display = lambda: "(should not be called when filter set)"
fake_dir.load_directory = lambda: {
"platforms": {
"telegram": [{"id": "-100123", "name": "TG Chat"}],
"discord": [{"id": "555", "name": "bot-home"}],
}
}
monkeypatch.setitem(_sys.modules, "gateway.channel_directory", fake_dir)
# When --list is set, argparse puts the optional bareword in the
# `message` positional slot (where the send-mode body would go).
args = _parse(["--list", "telegram"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 0
out = capsys.readouterr().out
assert "telegram" in out.lower()
assert "discord" not in out.lower()
def test_list_unknown_platform_fails(monkeypatch, capsys):
import sys as _sys
import types as _types
fake_dir = _types.ModuleType("gateway.channel_directory")
fake_dir.format_directory_for_display = lambda: ""
fake_dir.load_directory = lambda: {"platforms": {"telegram": []}}
monkeypatch.setitem(_sys.modules, "gateway.channel_directory", fake_dir)
args = _parse(["--list", "pigeon-post"])
with pytest.raises(SystemExit) as exc:
send_cmd.cmd_send(args)
assert exc.value.code == 1
err = capsys.readouterr().err
assert "pigeon-post" in err
# ---------------------------------------------------------------------------
# Parser registration contract
# ---------------------------------------------------------------------------
def test_register_send_subparser_is_reusable():
"""Sanity check: the registrar returns a parser and wires ``cmd_send``."""
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command")
send_parser = send_cmd.register_send_subparser(subparsers)
assert send_parser is not None
args = parser.parse_args(["send", "--to", "telegram", "hi"])
assert args.func is send_cmd.cmd_send
assert args.to == "telegram"
assert args.message == "hi"
# ---------------------------------------------------------------------------
# Env loader
# ---------------------------------------------------------------------------
def test_load_hermes_env_bridges_config_yaml_scalars(tmp_path, monkeypatch):
"""Top-level config.yaml scalars should be bridged into os.environ.
This mirrors the gateway/run.py bootstrap behavior: without this, running
``hermes send`` from a fresh shell cannot resolve the home channel
because ``TELEGRAM_HOME_CHANNEL`` (saved by ``hermes config set``) lives
in config.yaml, not in .env — and the gateway's config loader reads via
``os.getenv(...)``.
"""
import os
hermes_home = tmp_path / ".hermes"
hermes_home.mkdir()
(hermes_home / ".env").write_text("SOME_TOKEN=abc123\n")
(hermes_home / "config.yaml").write_text(
"TELEGRAM_HOME_CHANNEL: '5550001111'\nnested:\n ignored: true\n"
)
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
monkeypatch.delenv("TELEGRAM_HOME_CHANNEL", raising=False)
monkeypatch.delenv("SOME_TOKEN", raising=False)
# Force get_hermes_home() to re-resolve under the patched env.
from importlib import reload
import hermes_cli.config as _hc_config
reload(_hc_config)
send_cmd._load_hermes_env()
assert os.environ.get("SOME_TOKEN") == "abc123"
assert os.environ.get("TELEGRAM_HOME_CHANNEL") == "5550001111"
def test_load_hermes_env_does_not_override_existing(tmp_path, monkeypatch):
"""Existing env vars must not be clobbered by config.yaml values."""
import os
hermes_home = tmp_path / ".hermes"
hermes_home.mkdir()
(hermes_home / "config.yaml").write_text("TELEGRAM_HOME_CHANNEL: yaml_value\n")
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
monkeypatch.setenv("TELEGRAM_HOME_CHANNEL", "env_value")
from importlib import reload
import hermes_cli.config as _hc_config
reload(_hc_config)
send_cmd._load_hermes_env()
assert os.environ.get("TELEGRAM_HOME_CHANNEL") == "env_value"
def test_load_hermes_env_handles_missing_files(tmp_path, monkeypatch):
"""No .env or config.yaml should be a silent no-op, not an exception."""
hermes_home = tmp_path / ".hermes"
hermes_home.mkdir()
monkeypatch.setenv("HERMES_HOME", str(hermes_home))
from importlib import reload
import hermes_cli.config as _hc_config
reload(_hc_config)
# Should not raise.
send_cmd._load_hermes_env()
+180
View File
@@ -0,0 +1,180 @@
"""Unit tests for hermes_cli.session_recap."""
from __future__ import annotations
import json
import pytest
from hermes_cli.session_recap import build_recap
def _user(text):
return {"role": "user", "content": text}
def _assistant(text=None, tool_calls=None):
msg = {"role": "assistant", "content": text}
if tool_calls:
msg["tool_calls"] = tool_calls
return msg
def _tool_call(name, args):
return {
"id": f"call_{name}",
"type": "function",
"function": {"name": name, "arguments": json.dumps(args)},
}
def _tool_result(content="ok"):
return {"role": "tool", "content": content}
def test_empty_history():
out = build_recap([])
assert "Session recap" in out
assert "nothing to recap" in out
def test_header_shows_title_when_provided():
out = build_recap([_user("hello")], session_title="Refactor the adapter")
assert "Refactor the adapter" in out.splitlines()[0]
def test_header_shows_short_id_when_no_title():
out = build_recap([_user("hello")], session_id="abcdef1234567890")
assert "abcdef12" in out.splitlines()[0]
def test_counts_recent_turns():
msgs = [
_user("one"),
_assistant("first reply"),
_user("two"),
_assistant("second reply"),
]
out = build_recap(msgs)
assert "2 user turn" in out
assert "assistant repl" in out
def test_last_ask_and_reply_are_surfaced():
msgs = [
_user("old question"),
_assistant("old answer"),
_user("summarise the docs"),
_assistant("here is the summary of the docs you asked for"),
]
out = build_recap(msgs)
assert "summarise the docs" in out
assert "summary of the docs" in out
def test_tool_counts_and_files():
msgs = [
_user("edit the readme and run tests"),
_assistant(
tool_calls=[
_tool_call("read_file", {"path": "README.md"}),
_tool_call("patch", {"path": "README.md"}),
]
),
_tool_result(),
_tool_result(),
_assistant(
tool_calls=[
_tool_call("terminal", {"command": "pytest"}),
]
),
_tool_result("tests ok"),
_assistant("All green."),
]
out = build_recap(msgs)
assert "patch×1" in out
assert "terminal×1" in out
assert "read_file×1" in out
# README.md should appear (may include cwd-relative prefix stripping).
assert "README.md" in out
def test_tool_preview_length_truncates_long_user_prompt():
long = "x " * 500
out = build_recap([_user(long)])
ask_line = [l for l in out.splitlines() if "Last ask" in l][0]
assert len(ask_line) < 300 # truncated with ellipsis
assert "" in ask_line
def test_respects_recent_window():
# 30 turns of user+assistant; only the most recent 20 should be summarised.
msgs = []
for i in range(30):
msgs.append(_user(f"question {i}"))
msgs.append(_assistant(f"answer {i}"))
out = build_recap(msgs)
# We scoped to the 20-turn window but show "of 30/30 total".
assert "of 30/30 total" in out
def test_multimodal_content_blocks_flattened():
msgs = [
{
"role": "user",
"content": [
{"type": "text", "text": "check this file"},
{"type": "image_url", "image_url": {"url": "..."}},
],
},
_assistant("Looked at your image."),
]
out = build_recap(msgs)
assert "check this file" in out
assert "Looked at your image" in out
def test_handles_arguments_as_dict_not_string():
# Some providers return arguments already as a dict.
msgs = [
_user("go"),
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"type": "function",
"function": {
"name": "patch",
"arguments": {"path": "foo.py"},
},
}
],
},
]
out = build_recap(msgs)
assert "patch×1" in out
assert "foo.py" in out
def test_no_assistant_activity_hint():
out = build_recap([_user("just sent my first message")])
assert "no assistant activity" in out or "Last ask" in out
def test_tool_message_count_reported():
msgs = [
_user("go"),
_assistant(tool_calls=[_tool_call("read_file", {"path": "a"})]),
_tool_result(),
_tool_result(),
_assistant("done"),
]
out = build_recap(msgs)
assert "2 tool result" in out
def test_ignores_non_mapping_entries_gracefully():
msgs = [None, "stray", _user("hi"), _assistant("hello")]
# Should not raise.
out = build_recap(msgs)
assert "Session recap" in out