feat(ui): onboarding suggestion chips with one-tap submit, keyboard access, and mobile scroll row

This commit is contained in:
2026-08-21 18:18:47 -04:00
parent cbf8e39e63
commit 2364e1ee7d
7 changed files with 350 additions and 51 deletions
+1
View File
@@ -25,6 +25,7 @@ BOR_MAX_CONTEXT_CHARS=24000 # cap on total document text sent to the LLM
BOR_CHUNK_TARGET_CHARS=2000 BOR_CHUNK_TARGET_CHARS=2000
BOR_CHUNK_OVERLAP_CHARS=200 BOR_CHUNK_OVERLAP_CHARS=200
BOR_EMBED_BATCH_SIZE=16 BOR_EMBED_BATCH_SIZE=16
# BOR_SUGGESTIONS=["How is my Kubernetes cluster set up?"] # JSON list of onboarding chips
# --- Debugging (0/1 — 1 enables attach-on-demand debugpy on port 5678) --- # --- Debugging (0/1 — 1 enables attach-on-demand debugpy on port 5678) ---
DEBUGPY=0 DEBUGPY=0
+52 -41
View File
@@ -1,13 +1,14 @@
/* Brain of Reese — chat shell. /* Brain of Reese — chat shell.
* *
* Renders suggestions, shows KB health, and runs chat turns against * Renders suggestions (onboarding chips + "Maybe try" deflection chips —
* POST /api/chat (SSE, PLAN §4): deltas render live into the Brain bubble, * one shared .suggestion-chip component, renderChips below), shows KB
* the done event appends source chips (and "Maybe try" chips when the * health, and runs chat turns against POST /api/chat (SSE, PLAN §4):
* turn was deflected — honesty gate, phase 04), errors surface as a red * deltas render live into the Brain bubble, the done event appends source
* banner. The full feedback state machine lands with the loading-feedback * chips (and "Maybe try" chips when the turn was deflected — honesty gate,
* story; this keeps the "never stale" contract: the button is busy for the * phase 04), errors surface as a red banner. The full feedback state
* whole turn and is always re-enabled at the end. * machine lands with the loading-feedback story; this keeps the "never
* All DOM ids match frontend/index.html. * stale" contract: the button is busy for the whole turn and is always
* re-enabled at the end. All DOM ids match frontend/index.html.
*/ */
const messagesEl = document.querySelector("#messages"); const messagesEl = document.querySelector("#messages");
@@ -99,27 +100,51 @@ function removeTyping() {
document.querySelector("#typing-indicator")?.remove(); document.querySelector("#typing-indicator")?.remove();
} }
/* ---------- suggestions ---------- */ /* ---------- suggestions (shared chip component, phase 05) ----------
*
* One component, two homes: the onboarding row in the empty state and the
* "Maybe try" row under a deflected answer. The container must be
* role="list" with an accessible name ("Suggested questions" / "Maybe
* try"); each chip is a real <button type="button"> with role="listitem".
* Clicking a chip is one tap → question: it fills the composer, focuses it,
* and submits — the same behavior everywhere (submitSuggestion).
*/
function submitSuggestion(text) {
input.value = text;
autoGrow();
input.focus();
composer.requestSubmit();
}
function renderChips(container, items, { onSelect } = {}) {
// Replace only previous chips; keep any other children (e.g. the
// visually-hidden group label inside a "maybe-try" row).
container.querySelectorAll(".suggestion-chip").forEach((c) => c.remove());
for (const item of items || []) {
const text = String(item || "").trim();
if (!text) continue;
const btn = document.createElement("button");
btn.type = "button";
btn.className = "suggestion-chip";
btn.setAttribute("role", "listitem");
btn.textContent = text;
btn.addEventListener("click", () => {
submitSuggestion(text);
if (onSelect) onSelect(text, btn);
});
container.appendChild(btn);
}
return container;
}
async function loadSuggestions() { async function loadSuggestions() {
try { try {
const r = await fetch("/api/suggestions"); const r = await fetch("/api/suggestions");
if (!r.ok) return; if (!r.ok) return;
const { suggestions } = await r.json(); const { suggestions } = await r.json();
suggestionsEl.innerHTML = ""; renderChips(suggestionsEl, suggestions);
for (const s of suggestions) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "suggestion-chip";
btn.textContent = s;
btn.setAttribute("role", "listitem");
btn.addEventListener("click", () => {
input.value = s;
input.focus();
});
suggestionsEl.appendChild(btn);
}
} catch { } catch {
/* suggestions are progressive enhancement */ /* suggestions are progressive enhancement: no chips, no error spam */
} }
} }
@@ -200,11 +225,9 @@ function appendSources(wrap, sources) {
} }
} }
/* "Maybe try:" chips under a deflected bubble (honesty gate, phase 04). /* "Maybe try:" chips under a deflected bubble (honesty gate, phase 04,
Same .suggestion-chip component as onboarding; clicking wires what shared component + one-tap submit, phase 05). The group is accessible
exists today — fill the input + focus. One-tap submit lands with the (role=list + aria-label) and wraps cleanly at every width. */
phase 05 chip component. The group is accessible (role=list +
aria-label) and wraps cleanly at every width. */
function appendMaybeTry(wrap, suggestions) { function appendMaybeTry(wrap, suggestions) {
if (!suggestions || !suggestions.length) return; if (!suggestions || !suggestions.length) return;
const body = wrap.querySelector(".msg-body"); const body = wrap.querySelector(".msg-body");
@@ -216,19 +239,7 @@ function appendMaybeTry(wrap, suggestions) {
label.className = "visually-hidden"; label.className = "visually-hidden";
label.textContent = "Maybe try:"; label.textContent = "Maybe try:";
group.appendChild(label); group.appendChild(label);
for (const s of suggestions) { renderChips(group, suggestions);
const btn = document.createElement("button");
btn.type = "button";
btn.className = "suggestion-chip";
btn.setAttribute("role", "listitem");
btn.textContent = s;
btn.addEventListener("click", () => {
input.value = s;
autoGrow();
input.focus();
});
group.appendChild(btn);
}
body.appendChild(group); body.appendChild(group);
} }
+6 -9
View File
@@ -137,17 +137,14 @@ def test_deflection_suggestions_are_clickable(
chip_text = chips.first.inner_text().strip() chip_text = chips.first.inner_text().strip()
assert chip_text assert chip_text
# Phase 04 chip contract (wire what exists): click fills + focuses. # Shared chip component (phase 05): one tap submits — the click fills,
# focuses AND sends. The chip's topic is one Brain really covers, so
# this follow-up turn is a grounded (non-deflected) answer quoting the
# question, and the composer is left empty (submitted, not queued).
chips.first.click() chips.first.click()
expect(page.locator("#message-input")).to_have_value(chip_text) expect(page.locator("#message-input")).to_have_value("")
expect(page.locator("#message-input")).to_be_focused()
# Completing the question asks it: a new user bubble + a reply —
# and the chip's topic is one Brain really covers, so this turn is
# a grounded (non-deflected) answer quoting the question.
page.press("#message-input", "Enter")
expect(page.locator(".msg.user .bubble")).to_have_count(2, timeout=30_000) expect(page.locator(".msg.user .bubble")).to_have_count(2, timeout=30_000)
expect(page.locator(".msg.user .bubble").nth(1)).to_contain_text(chip_text) expect(page.locator(".msg.user .bubble").nth(1)).to_have_text(chip_text)
expect(page.locator(".msg.brain .bubble")).to_have_count(2, timeout=30_000) expect(page.locator(".msg.brain .bubble")).to_have_count(2, timeout=30_000)
second = page.locator(".msg.brain .bubble").nth(1) second = page.locator(".msg.brain .bubble").nth(1)
expect(second).to_contain_text(chip_text, timeout=30_000) expect(second).to_contain_text(chip_text, timeout=30_000)
+232
View File
@@ -0,0 +1,232 @@
"""Phase 05 E2E (Playwright): onboarding suggestion chips, one-tap submit.
Story: ``.agent/user_stories/suggestion-chips.md``
Run in isolation (DB must be up: ``podman compose up -d db``):
uv run pytest tests/e2e/test_suggestion_chips.py -v --no-cov
The onboarding row in the empty state renders real ``<button>`` chips from
``GET /api/suggestions`` (settings defaults). Clicking — or Tab + Enter —
fills the composer AND submits: one tap produces a user bubble with the
chip's exact text and a streamed Brain reply. On mobile (375px) the row
becomes a single horizontally scrollable line.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
from threading import Thread
from typing import Any
import httpx
import pytest
from playwright.sync_api import Browser, Page, expect
from sqlalchemy import text
from app.config import Settings
from app.db import SessionLocal
from app.rag.importer import ImportSummary, import_sources
from app.rag.llm import LLMClient
REPO = Path(__file__).resolve().parents[2]
FIXTURES = REPO / "tests" / "fixtures" / "docs"
MOCK_ANSWER_MARKER = "Deterministic mock answer for E2E"
async def _import_fixtures(mock_port: int) -> ImportSummary:
kwargs: dict[str, Any] = {"_env_file": None, "llm_base_url": f"http://127.0.0.1:{mock_port}/v1"}
settings = Settings(**kwargs) # pyright: ignore[reportCallIssue]
return await import_sources([FIXTURES], LLMClient(settings))
def _run_in_thread(coro: Any) -> Any:
"""Run a coroutine on a worker thread (Playwright owns the test loop)."""
box: dict[str, Any] = {}
def runner() -> None:
try:
box["value"] = asyncio.run(coro)
except BaseException as e: # noqa: BLE001 — re-raised on the test thread
box["error"] = e
t = Thread(target=runner)
t.start()
t.join()
if "error" in box:
raise box["error"]
return box["value"]
def _seed_kb(mock_port: int) -> ImportSummary:
"""Deterministic KB: truncate everything, import the fixture docs."""
with SessionLocal() as db:
db.execute(text("TRUNCATE chunks, documents, query_log"))
db.commit()
summary = _run_in_thread(_import_fixtures(mock_port))
assert summary is not None and summary.added == 3
return summary
def _api_suggestions(app_url: str) -> list[str]:
body = httpx.get(f"{app_url}/api/suggestions", timeout=10).json()
return body["suggestions"]
def _chip_locator(page: Page) -> Any:
return page.locator("#suggestions .suggestion-chip")
def test_onboarding_chips_render(
page: Page, app_url: str, mock_llm: int, db_ready: None
) -> None:
_seed_kb(mock_llm)
page.set_default_timeout(30_000)
page.goto(app_url)
# Accessible group: role=list + a name screen readers can announce.
group = page.locator("#suggestions")
expect(group).to_have_attribute("role", "list")
expect(group).to_have_attribute("aria-label", "Suggested questions")
# 3+ visible chips, real buttons, each with non-empty text — and the
# texts match what the API returned (chips are drawn from the endpoint).
chips = _chip_locator(page)
expect(chips.first).to_be_visible(timeout=30_000)
assert chips.count() >= 3
api_texts = _api_suggestions(app_url)
for i in range(chips.count()):
chip = chips.nth(i)
expect(chip).to_be_visible()
expect(chip).to_have_attribute("type", "button")
expect(chip).to_have_attribute("role", "listitem")
text = chip.inner_text().strip()
assert text, "every chip needs non-empty label text"
assert text in api_texts
assert len(set(api_texts)) >= 3
# Chips live in the empty state, which is visible before any message.
expect(page.locator("#empty-state")).to_be_visible()
# Chip component contract: brand pill, >=44px touch target.
style = chips.first.evaluate("el => getComputedStyle(el)")
assert style["backgroundColor"] == "rgb(238, 240, 254)" # --brand-soft
assert style["color"] == "rgb(55, 48, 163)" # --brand-ink
assert style["borderRadius"] == "999px"
box = chips.first.bounding_box()
assert box is not None and box["height"] >= 44
def test_chip_click_submits(
page: Page, app_url: str, mock_llm: int, db_ready: None
) -> None:
_seed_kb(mock_llm)
page.set_default_timeout(30_000)
page.goto(app_url)
first = _chip_locator(page).first
expect(first).to_be_visible(timeout=30_000)
chip_text = first.inner_text().strip()
assert chip_text
# One tap = one question: the click fills AND submits.
first.click()
expect(page.locator("#empty-state")).to_be_hidden()
expect(page.locator("#message-input")).to_have_value("") # submitted, not queued
expect(page.locator(".msg.user .bubble")).to_have_count(1, timeout=30_000)
expect(page.locator(".msg.user .bubble")).to_have_text(chip_text)
# A grounded mock reply follows (the seeded KB answers this topic).
brain = page.locator(".msg.brain .bubble").first
expect(brain).to_contain_text(MOCK_ANSWER_MARKER, timeout=30_000)
expect(brain).to_contain_text(chip_text)
expect(page.locator(".msg.brain.is-deflected")).to_have_count(0)
# Never stale: the send button recovers after the turn.
expect(page.locator("#send-btn")).to_be_enabled()
expect(page.locator("#send-label")).to_have_text("Send")
def test_chips_keyboard_accessible(
page: Page, app_url: str, mock_llm: int, db_ready: None
) -> None:
_seed_kb(mock_llm)
page.set_default_timeout(30_000)
page.goto(app_url)
first = _chip_locator(page).first
expect(first).to_be_visible(timeout=30_000)
chip_text = first.inner_text().strip()
assert chip_text
# Tab from the page start: the first chip must be reachable on the
# keyboard, and before the composer input (skip-link + 2 nav links come
# first). Track tab stops until we land on a chip.
reached_chip_at: int | None = None
for step in range(1, 11):
page.keyboard.press("Tab")
state = page.evaluate(
"""() => {
const el = document.activeElement;
return {
id: el ? el.id : "",
isChip: !!(el && el.classList && el.classList.contains("suggestion-chip")
&& el.closest("#suggestions")),
};
}"""
)
if state["id"] == "message-input":
pytest.fail("the composer input was reached before the suggestion chips")
if state["isChip"]:
reached_chip_at = step
break
assert reached_chip_at is not None, "no suggestion chip is keyboard-reachable"
expect(first).to_be_focused()
# Enter activates the focused chip button → it submits.
page.keyboard.press("Enter")
expect(page.locator("#empty-state")).to_be_hidden()
expect(page.locator("#message-input")).to_have_value("")
expect(page.locator(".msg.user .bubble")).to_have_count(1, timeout=30_000)
expect(page.locator(".msg.user .bubble")).to_have_text(chip_text)
expect(page.locator(".msg.brain .bubble").first).to_contain_text(
MOCK_ANSWER_MARKER, timeout=30_000
)
expect(page.locator("#send-btn")).to_be_enabled()
def test_chips_mobile_row(
browser: Browser, app_url: str, mock_llm: int, db_ready: None
) -> None:
_seed_kb(mock_llm)
page = browser.new_page(viewport={"width": 375, "height": 720})
try:
page.set_default_timeout(30_000)
page.goto(app_url)
row = page.locator("#suggestions")
expect(row).to_be_visible(timeout=30_000)
# The row is a single line that scrolls horizontally: content is
# wider than the viewport, the container scrolls, nothing wraps.
wrap = row.evaluate("el => getComputedStyle(el)")
assert wrap["flexWrap"] == "nowrap"
assert wrap["overflowX"] in {"auto", "scroll"}
dims = row.evaluate(
"el => ({ sw: el.scrollWidth, cw: el.clientWidth, h: el.clientHeight })"
)
assert dims["sw"] > dims["cw"], "chips must overflow into a scroll row"
assert row.evaluate("el => { el.scrollLeft = 24; return el.scrollLeft; }") > 0
# Exactly one line: every chip shares the same top edge, and the
# line height fits a single 44px-tall chip (no vertical clipping).
chips = _chip_locator(page)
assert chips.count() >= 3
tops: list[float] = []
for i in range(chips.count()):
box = chips.nth(i).bounding_box()
assert box is not None
assert box["height"] >= 44, "chips stay >=44px tall on mobile"
tops.append(box["y"])
assert max(tops) - min(tops) < 0.5, "all chips sit on one horizontal line"
row_box = row.bounding_box()
assert row_box is not None
assert row_box["height"] < 2 * 44, "the mobile row is a single line tall"
finally:
page.close()
+30 -1
View File
@@ -1,6 +1,10 @@
"""Integration tests: HTTP API surface (no database required).""" """Integration tests: HTTP API surface (no database required)."""
from __future__ import annotations from __future__ import annotations
import json
from app.config import get_settings
def test_health_reports_ok(client) -> None: def test_health_reports_ok(client) -> None:
r = client.get("/api/health") r = client.get("/api/health")
@@ -16,7 +20,32 @@ def test_suggestions_returns_list(client) -> None:
assert r.status_code == 200 assert r.status_code == 200
suggestions = r.json()["suggestions"] suggestions = r.json()["suggestions"]
assert isinstance(suggestions, list) assert isinstance(suggestions, list)
assert all(isinstance(s, str) and s for s in suggestions) assert len(suggestions) >= 3
assert all(isinstance(s, str) and s.strip() for s in suggestions)
def test_suggestions_honors_bor_suggestions_env_override(monkeypatch) -> None:
"""GET /api/suggestions reflects the BOR_SUGGESTIONS JSON env override."""
from fastapi.testclient import TestClient
from app.main import create_app
override = [
"How do I back up with Borg?",
"How is my K3S cluster set up?",
"How do I deploy a service?",
"What proxy fronts reeseapps.com?",
]
get_settings.cache_clear()
try:
monkeypatch.setenv("BOR_SUGGESTIONS", json.dumps(override))
fresh_client = TestClient(create_app())
finally:
get_settings.cache_clear()
r = fresh_client.get("/api/suggestions")
assert r.status_code == 200
assert r.json() == {"suggestions": override}
def test_index_html_served_locally(client) -> None: def test_index_html_served_locally(client) -> None:
+29
View File
@@ -1,8 +1,12 @@
"""Unit tests: settings defaults & env overrides.""" """Unit tests: settings defaults & env overrides."""
from __future__ import annotations from __future__ import annotations
import json
from typing import Any from typing import Any
import pytest
from pydantic_settings import SettingsError
from app.config import Settings from app.config import Settings
@@ -32,6 +36,31 @@ def test_env_override(monkeypatch) -> None:
assert s.llm_chat_model == "juggernaut" assert s.llm_chat_model == "juggernaut"
def test_suggestions_default_is_three_plus_real_questions() -> None:
s = _settings()
assert len(s.suggestions) >= 3
assert all(isinstance(q, str) and q.strip() for q in s.suggestions)
# Distinct chips only — duplicates in the onboarding row are noise.
assert len({q.strip().lower() for q in s.suggestions}) == len(s.suggestions)
def test_suggestions_env_override_is_json_list(monkeypatch) -> None:
override = [
"How do I back up with Borg?",
"How is my K3S cluster set up?",
"How do I deploy a service?",
]
monkeypatch.setenv("BOR_SUGGESTIONS", json.dumps(override))
s = _settings()
assert s.suggestions == override
def test_suggestions_malformed_json_fails_loudly(monkeypatch) -> None:
monkeypatch.setenv("BOR_SUGGESTIONS", "[not valid json")
with pytest.raises(SettingsError):
_settings()
def test_effective_api_key_fallback(monkeypatch) -> None: def test_effective_api_key_fallback(monkeypatch) -> None:
monkeypatch.delenv("AIPI_KEY", raising=False) monkeypatch.delenv("AIPI_KEY", raising=False)
s = _settings() s = _settings()