feat(chat): save by default + share anonymously — auto-saved chats, guest-facing Share, success toast, action row

This commit is contained in:
2026-08-31 05:20:25 -04:00
parent c564e317ed
commit 914097abcf
17 changed files with 1803 additions and 491 deletions
+69 -45
View File
@@ -6,13 +6,17 @@ Run in isolation (DB must be up: ``podman compose up -d db``):
uv run pytest tests/e2e/test_chat_history.py -v --no-cov
The owner-locked loop under test (A10 extension, 2026-08-29):
The owner-locked loop under test (A10 extension, 2026-08-29; phase 55
replaced the Save pill with auto-save — the tests below wait for the
auto-saved row via the admin list, since auto-saves are SILENT, A2):
* **Save** — on the chat page, admin-only (the pill ships hidden and
whoami reveals it): the current conversation POSTs to ``/api/chats``
(auto-title = the first question, whitespace-collapsed, 120-char cap)
and links to the created row; a re-Save PUTs the SAME row (upsert);
"New chat" unlinks, so the next Save creates again;
* **Auto-save** — on the chat page, no control (the pill is GONE,
phase 55): the current conversation upserts itself at the save
points — create on the first user message (auto-title = the first
question, whitespace-collapsed, 120-char cap) and update on each
brain-done; the SAME row updates (upsert — the conversation never
spawns a second row, the link survives reloads); "New chat" unlinks,
so the next conversation creates a fresh row;
* **History** — ``/history.html`` lists the saved chats in a full-width
table (Title | Messages | Updated | Actions); the Title cell IS the
Open link (``/?chat=<id>`` — "return to that history with a click"),
@@ -24,9 +28,12 @@ The owner-locked loop under test (A10 extension, 2026-08-29):
session (pixel-identical), links it, and a subsequent Save updates
that row; a deleted/unknown id degrades to the local restore with the
error banner;
* **Anonymous** — no Save button, no History nav link, the History page
shows the gated state WITHOUT ever fetching ``/api/chats`` (the router
403s them — pinned via the request log), and the API 403s.
* **Anonymous** — no Save control (the element is absent from the DOM
at every width — phase 55), but the Share pill IS visible (phase 55
task 03 — the write surface is public, the pill is static markup),
no History nav link, the History page shows the gated state WITHOUT
ever fetching ``/api/chats`` (the router 403s them — pinned via the
request log), and the API 403s.
DB isolation: the shared e2e Postgres keeps ``saved_chats`` rows across
suites, so every test here uses a DISTINCTIVE question text (its
@@ -38,6 +45,7 @@ embeddings); ``saved_chats`` is never touched by the reset.
from __future__ import annotations
import asyncio
import time
from pathlib import Path
from threading import Thread
from typing import Any
@@ -144,15 +152,30 @@ def _delete_chat(app_url: str, cookies: dict[str, str], chat_id: str) -> None:
httpx.delete(f"{app_url}/api/chats/{chat_id}", timeout=10, cookies=cookies)
def _save(page: Page) -> None:
"""Press Save and wait for the live-region confirmation (the
never-stale contract: the status line is the success feedback)."""
page.locator("#save-chat-btn").click()
expect(page.locator("#send-status")).to_have_text("Conversation saved.")
def _wait_saved_row(
app_url: str,
cookies: dict[str, str],
title: str,
messages: int = 2,
) -> dict[str, Any]:
"""Wait for the auto-saved row (phase 55: auto-saves are SILENT —
A2 — so there is no status line to wait on). The upsert is
fire-and-forget from the UI's point of view, so poll the admin
list until the row with the conversation's auto-title appears with
the expected message count."""
deadline = time.monotonic() + 15
last: dict[str, Any] | None = None
while time.monotonic() < deadline:
last = _find_row(_chats(app_url, cookies), title)
if last is not None and last["message_count"] >= messages:
return last
time.sleep(0.2)
raise AssertionError(f"no auto-saved row for {title!r} (last: {last!r})")
# ---------------------------------------------------------------------------
# 1. Save on the chat page → the row exists (UI + API agree)
# 1. Auto-save on the chat page (no Save control) → the row exists
# (API is the proof — auto-saves are silent, A2)
# ---------------------------------------------------------------------------
@@ -168,21 +191,19 @@ def test_save_and_see_history(
q = "How is my Kubernetes cluster set up? (hist-save)"
_ask(page, q)
# Admin: the Save pill is revealed (ship-hidden, whoami reveals it).
save = page.locator("#save-chat-btn")
expect(save).to_be_visible()
expect(save).to_have_attribute("aria-label", "Save chat")
save.click()
expect(page.locator("#send-status")).to_have_text("Conversation saved.")
# Phase 55: there is NO Save control — the conversation auto-saved
# at the save points (create on the first question, update on the
# brain-done). There is nothing to click and no status line to wait
# on (A2 silent): the API is the proof.
# Also: the pill is gone from the DOM at every width.
expect(page.locator("#save-chat-btn")).to_have_count(0)
cookies = _admin_cookies(page)
created: str | None = None
try:
# The API agrees: the row exists, auto-titled from the first
# question (whitespace-collapsed, <=120 chars), two messages.
row = _find_row(_chats(app_url, cookies), " ".join(q.split())[:120])
assert row is not None, "the saved chat row must exist"
row = _wait_saved_row(app_url, cookies, " ".join(q.split())[:120])
assert row["message_count"] == 2
created = row["id"]
@@ -221,10 +242,10 @@ def test_open_chat_returns_to_history(
# The answer text the History session saw (rendered bubble).
answer_before = page.locator(".msg.brain .bubble").first.inner_text()
_save(page)
# Phase 55: the conversation auto-saved (no Save pill) — wait for
# the row via the admin list.
cookies = _admin_cookies(page)
row = _find_row(_chats(app_url, cookies), q)
assert row is not None
row = _wait_saved_row(app_url, cookies, q)
chat_id = row["id"]
try:
# From the History page, the title IS the Open link…
@@ -267,12 +288,13 @@ def test_open_chat_returns_to_history(
_ask(page, "How is my Kubernetes cluster set up? (hist-open-2)")
expect(page.locator(".msg.user .bubble")).to_have_count(2)
# …and a re-Save UPSERTS: the same single row, count grown to 4.
_save(page)
# …and the next brain-done auto-save UPSERTS: the same single
# row, count grown to 4 (phase 55 — no Save pill).
row2 = _wait_saved_row(app_url, cookies, q, messages=4)
mine = [c for c in _chats(app_url, cookies) if c["title"] == q]
assert len(mine) == 1, "the re-Save must not spawn a second row"
assert mine[0]["id"] == chat_id, "the re-Save updates the SAME row"
assert mine[0]["message_count"] == 4
assert len(mine) == 1, "the auto-save must not spawn a second row"
assert mine[0]["id"] == chat_id, "the auto-save updates the SAME row"
assert row2["message_count"] == 4
finally:
_delete_chat(app_url, cookies, chat_id)
@@ -294,12 +316,10 @@ def test_new_chat_unlinks(
q1 = "How is my Kubernetes cluster set up? (hist-unlink)"
_ask(page, q1)
_save(page)
cookies = _admin_cookies(page)
cleanup: list[str] = []
try:
row1 = _find_row(_chats(app_url, cookies), q1)
assert row1 is not None
row1 = _wait_saved_row(app_url, cookies, q1) # auto-saved (phase 55)
cleanup.append(row1["id"])
# New chat clears the conversation AND unlinks it from the row.
@@ -307,11 +327,12 @@ def test_new_chat_unlinks(
expect(page.locator("#send-status")).to_contain_text("New chat started")
expect(page.locator(".msg")).to_have_count(0)
# A fresh conversation, saved: a NEW row (a create, not the
# previous row's update) — the list now carries two of ours.
# A fresh conversation, auto-saved (phase 55): a NEW row (a
# create, not the previous row's update) — the list now carries
# two of ours.
q2 = "How is my Kubernetes cluster set up? (hist-unlink-2)"
_ask(page, q2)
_save(page)
_wait_saved_row(app_url, cookies, q2) # wait for the fresh auto-save
rows = _chats(app_url, cookies)
mine = [c for c in rows if c["title"] in (q1, q2)]
assert len(mine) == 2, "Save after New chat must create a second row"
@@ -343,10 +364,8 @@ def test_delete_two_step(
q = "How is my Kubernetes cluster set up? (hist-delete)"
_ask(page, q)
_save(page)
cookies = _admin_cookies(page)
row = _find_row(_chats(app_url, cookies), q)
assert row is not None
row = _wait_saved_row(app_url, cookies, q) # auto-saved (phase 55)
chat_id = row["id"]
try:
page.goto(app_url + "/history.html")
@@ -396,7 +415,8 @@ def test_delete_two_step(
# ---------------------------------------------------------------------------
# 5. Anonymous: no Save button, no History nav link, the History page is
# 5. Anonymous: no Save control (absent), the Share pill visible
# (phase 55 task 03), no History nav link, the History page is
# gated WITHOUT fetching /api/chats, and the API 403s
# ---------------------------------------------------------------------------
@@ -414,9 +434,13 @@ def test_anonymous_cannot(
page.goto(app_url + "/")
# Settled anonymous state (the whoami round-trip has landed)…
expect(page.locator("#sign-in-link")).to_be_visible(timeout=15_000)
# …and the phase-50 surface is absent for anonymous: no Save pill,
# no History nav link (both ship hidden and stay hidden).
expect(page.locator("#save-chat-btn")).to_be_hidden()
# …and the phase-50 surface is absent for anonymous: no Save control
# (the element is GONE from the DOM — phase 55 — there is nothing
# to hide) and no History nav link (ships hidden and stays hidden)
# — but the Share pill IS visible (phase 55 task 03: the write
# surface is public, the pill is static markup).
expect(page.locator("#save-chat-btn")).to_have_count(0)
expect(page.locator("#share-chat-btn")).to_be_visible()
expect(page.locator("#nav-history")).to_be_hidden()
# Direct visit to the History page: it loads and shows the gated
+562
View File
@@ -0,0 +1,562 @@
"""Phase 55 E2E (Playwright): save by default + anonymous share + action-row layout.
TODO.md L3–L6 (owner 2026-08-31, roadmap confirmation — the four items
this suite verifies, in the browser):
L3 "Share chat should work anonymously without login"
L4 "Save shouldn't be a button, every chat should be saved by default"
L5 "Need feedback (probably dropdown notification toast) to show share worked"
L6 "New Chat and Share buttons should only be vertically stacked when in
mobile, otherwise they should be horizontally next to each other"
Run in isolation (DB must be up: ``podman compose up -d db``):
uv run pytest tests/e2e/test_save_share_ux.py -v --no-cov
The owner-locked loop under test (2026-08-31):
* **Anonymous auto-save (L4 / A2)** — there is NO Save control in the
DOM at any width; a signed-out visitor's first question auto-upserts
EXACTLY ONE ``saved_chats`` row (the auto-title, both messages) —
verified through the admin's ``GET /api/chats`` (the management
surface stays admin-only, phase 55 task 01) with no button press
anywhere;
* **No duplicate across reload (L4)** — a plain reload restores the
conversation from localStorage AND the row link (``chatId`` in the
``bor.chat.v1`` record, task 02): a second question updates the SAME
row — the title's row count stays one, the message count grows
2 → 4;
* **Anonymous share + toast (L3 / L5 / A4)** — the Share pill is
visible WITHOUT login; clicking it on a non-empty conversation mints
the public link (clipboard path, the inline field on non-secure
origins) and raises the top-right toast ("Share link copied.",
``aria-hidden`` visual-only, a single instance, auto-dismiss ~4s); a
FRESH incognito context opens ``/shared/<token>`` read-only (title +
both bubbles, the phase-51 zero-controls surface); the admin's
History Unshare (inline two-step) revokes — the SAME URL then shows
the "invalid or revoked" state;
* **Layout (L6 / A5)** — desktop 1280×800: ``#new-chat-btn`` and
``#share-chat-btn`` share one horizontal row inside ``.chat-actions``
(overlapping y bands, Share's x beyond New chat's x + width, each
pill at intrinsic width — never the full 46rem column); mobile
390×844: stacked vertically (Share below New chat, full-width);
360px wide: no horizontal page overflow;
* **Admin still works (A1 sanity)** — the same auto-save machinery
fires for a signed-in admin (the write surface is public either way;
the row lands in the admin's History).
DB isolation: the shared e2e Postgres keeps ``saved_chats`` rows across
suites, so every test uses a DISTINCTIVE question (its auto-title is
therefore unique), selects rows by auto-title (never absolute counts),
``_reset_db``s first (the KB tables are truncated + re-seeded the house
way — deterministic mock embeddings; ``saved_chats`` is never touched
by the reset), and deletes the rows it creates in a ``finally`` (admin
cookie).
"""
from __future__ import annotations
import asyncio
import re
import time
from pathlib import Path
from threading import Thread
from typing import Any
import httpx
from playwright.sync_api import Browser, BrowserContext, 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
from e2e.auth_helpers import login
REPO = Path(__file__).resolve().parents[2]
FIXTURES = REPO / "tests" / "fixtures" / "docs"
MOCK_ANSWER_MARKER = "Deterministic mock answer for E2E"
SHARE_URL_RE = re.compile(r"^/shared/[0-9a-f-]{36}$")
#: The invalid/revoked card's line (frontend/shared.html, phase 51).
INVALID_TEXT = "This share link is invalid or was revoked."
#: The toast's clipboard-path line (app.js shareCurrentChat success).
TOAST_CLIP_TEXT = "Share link copied."
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's sync API keeps an asyncio loop running on the test
thread, so ``asyncio.run`` cannot be called directly from a test
body.
"""
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 _reset_db(mock_port: int, seed: bool) -> ImportSummary | None:
"""Truncate the KB (and query log + steering notes — deterministic
mock answers), then optionally re-import fixtures. ``saved_chats``
is deliberately NOT touched: rows persist across suites and every
test here cleans up after itself."""
with SessionLocal() as db:
db.execute(text("TRUNCATE chunks, documents, query_log, steering_notes"))
db.commit()
if not seed:
return None
return _run_in_thread(_import_fixtures(mock_port))
def _ask(page: Page, question: str) -> None:
"""Send one turn and wait until the grounded answer has fully
landed (the ``done`` event restored the Send button)."""
page.fill("#message-input", question)
page.click("#send-btn")
expect(page.locator(".msg.user .bubble").last).to_contain_text(question)
expect(page.locator(".msg.brain .bubble").last).to_contain_text(
MOCK_ANSWER_MARKER, timeout=30_000
)
expect(page.locator("#send-btn")).to_be_enabled()
expect(page.locator("#send-label")).to_have_text("Send")
def _admin_cookies(page: Page) -> dict[str, str]:
"""The signed session cookies the browser holds after a form login —
used to call the admin API with plain httpx (the test's API side
sees exactly what the signed-in browser sees)."""
return {
c["name"]: c["value"]
for c in page.context.cookies()
if "name" in c and "value" in c
}
def _open_admin(browser: Browser, app_url: str) -> tuple[BrowserContext, Page, dict[str, str]]:
"""A SECOND, logged-in context — the admin's eyes for the management
surface (``GET /api/chats`` list/detail, delete, the History
Unshare), which stays admin-only since phase 55 task 01."""
ctx = browser.new_context(viewport={"width": 1280, "height": 800})
pg = ctx.new_page()
pg.set_default_timeout(30_000)
login(pg, app_url, next="/")
return ctx, pg, _admin_cookies(pg)
def _chats(app_url: str, cookies: dict[str, str]) -> list[dict[str, Any]]:
r = httpx.get(f"{app_url}/api/chats", timeout=10, cookies=cookies)
assert r.status_code == 200
return r.json()["chats"]
def _auto_title(question: str) -> str:
"""The phase-50 auto-title convention: the first question,
whitespace-collapsed, capped at 120 chars."""
return " ".join(question.split())[:120]
def _find_row(rows: list[dict[str, Any]], title: str) -> dict[str, Any] | None:
return next((c for c in rows if c["title"] == title), None)
def _title_rows(app_url: str, cookies: dict[str, str], title: str) -> list[dict[str, Any]]:
"""Every row carrying ``title`` — the "exactly one row" pin (never
an absolute count: the shared DB keeps other suites' rows)."""
return [c for c in _chats(app_url, cookies) if c["title"] == title]
def _delete_chat(app_url: str, cookies: dict[str, str], chat_id: str) -> None:
"""Best-effort row cleanup (a 404 — already deleted — is fine)."""
httpx.delete(f"{app_url}/api/chats/{chat_id}", timeout=10, cookies=cookies)
def _wait_saved_row(
app_url: str,
cookies: dict[str, str],
title: str,
messages: int = 2,
) -> dict[str, Any]:
"""Wait for the auto-saved row (phase 55: auto-saves are SILENT —
A2 — so there is no status line to wait on). The upsert is
fire-and-forget from the UI's point of view, so poll the admin
list until the row with the conversation's auto-title appears with
the expected message count."""
deadline = time.monotonic() + 15
last: dict[str, Any] | None = None
while time.monotonic() < deadline:
last = _find_row(_chats(app_url, cookies), title)
if last is not None and last["message_count"] >= messages:
return last
time.sleep(0.2)
raise AssertionError(f"no auto-saved row for {title!r} (last: {last!r})")
def _grant_clipboard(page: Page, app_url: str) -> None:
"""Grant the async-clipboard permissions on the context.
``http://127.0.0.1`` is a secure context, so ``navigator.clipboard``
exists — but headless Chromium still requires the permission grant
before ``writeText``/``readText`` resolve (without it the
owner-locked inline-link fallback fires). The assertion below
branches on the API's availability, so a non-secure origin still
passes through the fallback branch deterministically.
"""
page.context.grant_permissions(
["clipboard-read", "clipboard-write"], origin=app_url
)
def _wait_toast_dismissed(page: Page, timeout_s: float = 8.0) -> None:
"""Poll until the toast's ``is-visible`` state class is gone.
The auto-dismiss (~4s, A4) drops the class (opacity/transform stay
— opacity is not part of Playwright's visibility model, so the
class is the honest state pin). The ~8s deadline leaves headroom
over the 4s contract without masking a stuck toast."""
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
visible = page.evaluate(
"() => { const t = document.querySelector('.toast');"
" return !!(t && t.classList.contains('is-visible')); }"
)
if not visible:
return
time.sleep(0.2)
raise AssertionError("the share toast did not auto-dismiss (~4s contract)")
# ---------------------------------------------------------------------------
# 1. Anonymous auto-save (L4 / A2): no Save control anywhere, one
# question → exactly one saved_chats row (auto-title, both messages),
# verified through the admin's list — no button press in this test
# ---------------------------------------------------------------------------
def test_anonymous_auto_save(
page: Page, browser: Browser, app_url: str, mock_llm: int, db_ready: None
) -> None:
_reset_db(mock_llm, seed=True)
page.set_default_timeout(30_000)
# Anonymous by construction: the page fixture's context never logs
# in — this is the signed-out visitor.
page.goto(app_url + "/")
# L4: there is NO Save control at any width — the element is gone
# from the DOM (phase 55, task 02), the pills are New chat + Share.
expect(page.locator("#save-chat-btn")).to_have_count(0)
expect(page.locator("#new-chat-btn")).to_be_visible()
expect(page.locator("#share-chat-btn")).to_be_visible()
q = "How is my Kubernetes cluster set up? (save-ux-auto)"
_ask(page, q) # the ONLY click in this test — no Save press exists
admin_ctx, _admin, cookies = _open_admin(browser, app_url)
created: str | None = None
try:
# The admin's management list sees the auto-saved row: the
# auto-title, both messages, created by the anonymous visitor.
row = _wait_saved_row(app_url, cookies, _auto_title(q), messages=2)
assert row["message_count"] == 2, "the auto-saved row holds both messages"
assert len(_title_rows(app_url, cookies, _auto_title(q))) == 1, (
"exactly ONE row for the auto-title — the auto-save must not duplicate"
)
created = row["id"]
# A2 quiet contract: a successful auto-save is SILENT — no toast
# (reserved for share) and no error banner on the anonymous page.
expect(page.locator(".toast")).to_have_count(0)
expect(page.locator("#kb-banner")).to_be_hidden()
finally:
if created is not None:
_delete_chat(app_url, cookies, created)
admin_ctx.close()
# ---------------------------------------------------------------------------
# 2. No duplicate across reload (L4): the row link (chatId in
# bor.chat.v1, task 02) survives a plain reload — the second
# question updates the SAME row (count one, messages 2 → 4)
# ---------------------------------------------------------------------------
def test_no_duplicate_row_across_reload(
page: Page, browser: Browser, app_url: str, mock_llm: int, db_ready: None
) -> None:
_reset_db(mock_llm, seed=True)
page.set_default_timeout(30_000)
page.goto(app_url + "/")
q1 = "How is my Kubernetes cluster set up? (save-ux-reload)"
_ask(page, q1)
admin_ctx, _admin, cookies = _open_admin(browser, app_url)
created: str | None = None
try:
row = _wait_saved_row(app_url, cookies, _auto_title(q1), messages=2)
chat_id: str = row["id"]
created = chat_id
# Plain reload: the conversation restores from localStorage
# (both bubbles) — and the row link restores with it.
page.reload()
expect(page.locator(".msg.user .bubble").last).to_contain_text(q1)
expect(page.locator(".msg.brain .bubble").last).to_contain_text(
MOCK_ANSWER_MARKER, timeout=30_000
)
# The second question must UPDATE the same row — not spawn a
# second one (the unlinked-upgrade path would create a fresh
# row; the chatId persistence is what prevents that).
q2 = "Which node runs the Kubernetes control plane? (save-ux-reload)"
_ask(page, q2)
row = _wait_saved_row(app_url, cookies, _auto_title(q1), messages=4)
assert row["id"] == chat_id, "the reloaded conversation kept its row link"
assert row["message_count"] == 4, "both turns' four messages landed on the row"
assert len(_title_rows(app_url, cookies, _auto_title(q1))) == 1, (
"still exactly ONE row after the reload — no duplicate"
)
finally:
if created is not None:
_delete_chat(app_url, cookies, created)
admin_ctx.close()
# ---------------------------------------------------------------------------
# 3. Anonymous share + toast (L3 / L5 / A4): the Share pill is visible
# without login; the click mints the link + the top-right toast; a
# fresh incognito context reads it read-only; the admin's History
# Unshare revokes the same URL
# ---------------------------------------------------------------------------
def test_anonymous_share_toast_and_unshare(
page: Page, browser: Browser, app_url: str, mock_llm: int, db_ready: None
) -> None:
_reset_db(mock_llm, seed=True)
page.set_default_timeout(30_000)
# Anonymous by construction — no login anywhere in this test.
page.goto(app_url + "/")
# L3: the Share pill is visible WITHOUT login (static markup — the
# phase-51 admin-only reveal gate is gone, task 03).
share = page.locator("#share-chat-btn")
expect(share).to_be_visible()
expect(share).to_have_attribute("aria-label", "Share chat")
q = "How is my Kubernetes cluster set up? (save-ux-share)"
_ask(page, q)
# A4: the toast is reserved for share — nothing before the click
# (the auto-save that just fired is silent).
expect(page.locator(".toast")).to_have_count(0)
_grant_clipboard(page, app_url)
share.click()
# The top-right toast: a SINGLE instance, the visible state class,
# the success text, aria-hidden (visual only — #send-status is the
# a11y announcer and keeps its phase-51 line).
toast = page.locator(".toast")
expect(toast).to_have_count(1)
expect(toast).to_have_class(re.compile(r"\bis-visible\b"), timeout=15_000)
expect(toast).to_have_text(TOAST_CLIP_TEXT)
expect(toast).to_have_attribute("aria-hidden", "true")
expect(page.locator("#send-status")).to_have_text(TOAST_CLIP_TEXT, timeout=15_000)
# A4: it auto-dismisses in ~4s (the class drops; the node stays).
_wait_toast_dismissed(page)
# Read the link — the clipboard when the origin allows it, else the
# inline fallback field (the phase-51 owner-locked branch).
if page.evaluate("() => !!navigator.clipboard"):
link: str | None = page.evaluate("() => navigator.clipboard.readText()")
expect(page.locator(".share-link-fallback")).to_have_count(0)
else:
field = page.locator(".share-link-fallback")
expect(field).to_be_visible()
link = field.get_attribute("href")
assert link is not None and link.startswith(app_url), f"bad share link: {link!r}"
path = link.removeprefix(app_url)
assert SHARE_URL_RE.fullmatch(path), f"bad share path shape: {path!r}"
admin_ctx, admin, cookies = _open_admin(browser, app_url)
anon_ctx: BrowserContext | None = None
created: str | None = None
try:
# A FRESH incognito context: the guest's only credential is the
# token in the URL — the conversation renders read-only.
anon_ctx = browser.new_context()
anon = anon_ctx.new_page()
anon.set_default_timeout(30_000)
anon.goto(app_url + path)
expect(anon.locator("#shared-title")).to_have_text(_auto_title(q))
expect(anon.locator(".msg.user .bubble")).to_have_count(1)
expect(anon.locator(".msg.user .bubble")).to_contain_text(q)
expect(anon.locator(".msg.brain .bubble")).to_have_count(1)
expect(anon.locator(".msg.brain .bubble").first).to_contain_text(
MOCK_ANSWER_MARKER, timeout=30_000
)
# The phase-51 zero-controls surface: no composer, no pills,
# no Tune/Retry, no button chips — and the guest header.
expect(anon.locator("#composer")).to_have_count(0)
expect(anon.locator("#save-chat-btn, #share-chat-btn")).to_have_count(0)
expect(anon.locator(".tune-btn")).to_have_count(0)
expect(anon.locator(".retry-btn")).to_have_count(0)
expect(anon.locator("button.suggestion-chip")).to_have_count(0)
expect(anon.locator("#sign-in-link")).to_be_visible(timeout=15_000)
# The API agrees (the admin's eyes): the guest's auto-saved row
# carries the SAME /shared/<token> link.
row = _find_row(_chats(app_url, cookies), _auto_title(q))
assert row is not None, "the guest's auto-saved row must exist"
created = row["id"]
assert row["share_url"] == path, "the shared row carries the link just used"
# The admin revokes from the History page (inline two-step —
# no native dialog).
admin.goto(app_url + "/history.html")
tr = admin.locator(
"#history-tbody tr", has=admin.locator(f"a[href='/?chat={created}']")
)
expect(tr.locator("button.history-unshare")).to_be_visible(timeout=15_000)
tr.locator("button.history-unshare").click()
expect(tr.locator(".history-confirm-text")).to_have_text("Unshare?")
expect(tr.locator(".history-confirm-yes")).to_be_visible()
tr.locator(".history-confirm-yes").click()
expect(tr.locator("button.history-share-create")).to_be_visible(timeout=15_000)
# The SAME URL is revoked now — in the SAME fresh context.
anon.goto(app_url + path)
expect(anon.locator("#shared-invalid")).to_be_visible(timeout=15_000)
expect(anon.locator("#shared-invalid")).to_contain_text(INVALID_TEXT)
expect(anon.locator(".msg")).to_have_count(0)
# The API agrees: share_url is ABSENT (the omission rule).
r = httpx.get(f"{app_url}/api/chats/{created}", timeout=10, cookies=cookies)
assert r.status_code == 200
assert "share_url" not in r.json(), "unshared → share_url must be absent"
finally:
if anon_ctx is not None:
anon_ctx.close()
if created is not None:
_delete_chat(app_url, cookies, created)
admin_ctx.close()
# ---------------------------------------------------------------------------
# 4. Action-row layout (L6 / A5): horizontal at desktop, stacked at
# ≤640px, no horizontal overflow at 360px
# ---------------------------------------------------------------------------
def test_action_row_layout(page: Page, app_url: str, mock_llm: int, db_ready: None) -> None:
_reset_db(mock_llm, seed=True)
page.set_default_timeout(30_000)
# No conversation needed — the pills are static markup, always
# present (the page fixture's viewport is the 1280×800 desktop).
page.goto(app_url + "/")
new_btn = page.locator("#new-chat-btn")
share_btn = page.locator("#share-chat-btn")
expect(new_btn).to_be_visible()
expect(share_btn).to_be_visible()
# Both pills live in ONE .chat-actions row, New chat before Share.
expect(page.locator(".chat-actions")).to_have_count(1)
row_el = page.locator(".chat-actions")
assert row_el.locator("#new-chat-btn").count() == 1
assert row_el.locator("#share-chat-btn").count() == 1
assert page.evaluate(
"() => {"
" const n = document.getElementById('new-chat-btn');"
" const s = document.getElementById('share-chat-btn');"
" return !!(n && s && (n.compareDocumentPosition(s) & Node.DOCUMENT_POSITION_FOLLOWING));"
" }"
), "the DOM order must be New chat, then Share"
# Desktop (1280×800): one horizontal row — overlapping y bands,
# Share to the right of New chat, each pill at its INTRINSIC width
# (never the full 46rem chat column).
nb = new_btn.bounding_box()
sb = share_btn.bounding_box()
assert nb is not None and sb is not None
assert nb["y"] < sb["y"] + sb["height"] and sb["y"] < nb["y"] + nb["height"], (
f"the pills must share one row (new={nb}, share={sb})"
)
assert sb["x"] > nb["x"] + nb["width"], "Share must sit right of New chat"
column_w = page.evaluate(
"() => document.querySelector('.chat-shell').getBoundingClientRect().width"
)
assert nb["width"] < column_w / 2 and sb["width"] < column_w / 2, (
"each pill must keep its intrinsic width on desktop, not stretch the column"
)
# Mobile (390×844): stacked vertically — Share BELOW New chat, both
# full-width (the ≤640px stretch rule).
page.set_viewport_size({"width": 390, "height": 844})
nb = new_btn.bounding_box()
sb = share_btn.bounding_box()
assert nb is not None and sb is not None
assert sb["y"] > nb["y"] + nb["height"], (
f"the pills must stack at 390px, Share below New chat (new={nb}, share={sb})"
)
# Full-width within the column: the stacked pills stretch to the
# .chat-actions row (the column's content box — .chat-shell is a
# .container, whose getBoundingClientRect includes its padding).
row_box = page.locator(".chat-actions").bounding_box()
assert row_box is not None
assert abs(nb["width"] - sb["width"]) < 2, "the stacked pills share one full width"
assert abs(nb["width"] - row_box["width"]) < 2, "the stacked pills stretch the column"
# 360px wide: no horizontal page overflow (the two stacked pills +
# container padding must fit).
page.set_viewport_size({"width": 360, "height": 800})
scroll_w = page.evaluate("() => document.documentElement.scrollWidth")
assert scroll_w <= 360, f"horizontal overflow at 360px: scrollWidth={scroll_w}"
# ---------------------------------------------------------------------------
# 5. Admin still works (A1 sanity): the same auto-save machinery fires
# for a signed-in admin — session or not, the row lands
# ---------------------------------------------------------------------------
def test_admin_auto_save_still_works(
page: Page, app_url: str, mock_llm: int, db_ready: None
) -> None:
_reset_db(mock_llm, seed=True)
page.set_default_timeout(30_000)
login(page, app_url, next="/")
expect(page).to_have_url(app_url + "/", timeout=30_000)
q = "How is my Kubernetes cluster set up? (save-ux-admin)"
_ask(page, q)
cookies = _admin_cookies(page)
created: str | None = None
try:
row = _wait_saved_row(app_url, cookies, _auto_title(q), messages=2)
assert row["message_count"] == 2, "the admin's auto-saved row holds both messages"
created = row["id"]
expect(page.locator(".toast")).to_have_count(0) # auto-save is silent (A2)
finally:
if created is not None:
_delete_chat(app_url, cookies, created)
+53 -24
View File
@@ -6,15 +6,21 @@ Run in isolation (DB must be up: ``podman compose up -d db``):
uv run pytest tests/e2e/test_share_chat.py -v --no-cov
The owner-locked loop under test (2026-08-29, roadmap confirmation):
The owner-locked loop under test (2026-08-29, roadmap confirmation;
phase 55 replaced the Save pill with auto-save — by the time the answer
settles the conversation is already saved, so the chat page's Share
click is the idempotent share of the linked row):
* **Share from the chat page** — the Share pill (admin-only, ships
hidden) on an UNSAVED conversation saves AND shares in ONE action
(``POST /api/chats`` with ``share: true`` — the row appears in
``GET /api/chats`` with a non-null ``share_url`` of the shape
``/shared/<uuid4>``); the absolute URL is copied to the clipboard,
with the inline-link fallback on a non-secure origin (the assertion
branches on ``navigator.clipboard`` availability);
hidden) on the AUTO-SAVED conversation shares the linked row via
``POST /api/chats/<id>/share`` — the row appears in ``GET
/api/chats`` with a non-null ``share_url`` of the shape
``/shared/<uuid4>`` (the unlinked save-then-share one-action wire
path — ``POST /api/chats`` with ``share: true`` — is pinned by the
integration suite, guest-reachable since phase 55 task 01); the
absolute URL is copied to the clipboard, with the inline-link
fallback on a non-secure origin (the assertion branches on
``navigator.clipboard`` availability);
* **Anonymous view** — a FRESH browser context (a separate session, no
cookies) opening ``/shared/<token>`` sees the full conversation
read-only through the same record shape: title = the auto-title,
@@ -49,6 +55,7 @@ from __future__ import annotations
import asyncio
import re
import time
from pathlib import Path
from threading import Thread
from typing import Any
@@ -163,6 +170,27 @@ def _delete_chat(app_url: str, cookies: dict[str, str], chat_id: str) -> None:
httpx.delete(f"{app_url}/api/chats/{chat_id}", timeout=10, cookies=cookies)
def _wait_saved_row(
app_url: str,
cookies: dict[str, str],
title: str,
messages: int = 2,
) -> dict[str, Any]:
"""Wait for the auto-saved row (phase 55: auto-saves are SILENT —
A2 — so there is no status line to wait on). The upsert is
fire-and-forget from the UI's point of view, so poll the admin
list until the row with the conversation's auto-title appears with
the expected message count."""
deadline = time.monotonic() + 15
last: dict[str, Any] | None = None
while time.monotonic() < deadline:
last = _find_row(_chats(app_url, cookies), title)
if last is not None and last["message_count"] >= messages:
return last
time.sleep(0.2)
raise AssertionError(f"no auto-saved row for {title!r} (last: {last!r})")
def _grant_clipboard(page: Page, app_url: str) -> None:
"""Grant the async-clipboard permissions on the admin context.
@@ -203,8 +231,9 @@ def _click_share_and_assert_status(page: Page, app_url: str) -> None:
# ---------------------------------------------------------------------------
# 1. Share from the chat page: an UNSAVED conversation is saved + shared
# in one action; the API row carries the /shared/<uuid> link
# 1. Share from the chat page: the AUTO-SAVED conversation is shared
# (the idempotent share of the linked row — phase 55); the API row
# carries the /shared/<uuid> link
# ---------------------------------------------------------------------------
@@ -221,25 +250,28 @@ def test_share_from_chat_page(
_ask(page, q)
# Admin: the Share pill is revealed (ships hidden, whoami reveals
# it — the same block as Save). The conversation is UNSAVED at this
# point: no row exists yet under the auto-title.
# it). Phase 55: the conversation is AUTO-SAVED by the time the
# answer settles (the Save pill is gone) — the row exists under the
# auto-title, and the Share click below shares the linked row.
share = page.locator("#share-chat-btn")
expect(share).to_be_visible()
expect(share).to_have_attribute("aria-label", "Share chat")
cookies = _admin_cookies(page)
assert (
_find_row(_chats(app_url, cookies), _auto_title(q)) is None
), "the conversation is unsaved before the Share click"
row = _wait_saved_row(app_url, cookies, _auto_title(q))
assert row["message_count"] == 2, "auto-saved with both messages before the Share click"
_grant_clipboard(page, app_url)
_click_share_and_assert_status(page, app_url)
created: str | None = None
try:
# The API agrees: ONE action saved AND shared — the new row
# exists with a non-null share_url of the token shape.
# The API agrees: the Share click shared the auto-saved row —
# it carries a non-null share_url of the token shape. (The
# unlinked save-then-share one-action path is pinned by the
# integration suite — from the chat page the conversation is
# always linked by the time there is anything to share.)
row = _find_row(_chats(app_url, cookies), _auto_title(q))
assert row is not None, "the Share click must have saved the conversation"
assert row is not None, "the auto-saved row must exist"
assert row["message_count"] == 2, "the saved conversation holds both messages"
share_url = row.get("share_url")
assert share_url is not None, "the share_url must be present (non-null)"
@@ -370,15 +402,12 @@ def test_share_from_history_and_unshare(
q = "How is my Kubernetes cluster set up? (share-history)"
_ask(page, q)
# Save first (this test drives the History column, not the
# save-then-share one-action path — test 1 covers that).
page.locator("#save-chat-btn").click()
expect(page.locator("#send-status")).to_have_text("Conversation saved.")
# Phase 55: the conversation is already AUTO-SAVED by the time the
# answer settles (no Save pill) — wait for the row via the admin
# list (this test drives the History column).
cookies = _admin_cookies(page)
_grant_clipboard(page, app_url)
row = _find_row(_chats(app_url, cookies), _auto_title(q))
assert row is not None
row = _wait_saved_row(app_url, cookies, _auto_title(q))
chat_id: str = row["id"]
anon_ctx: BrowserContext | None = None
try:
+8 -2
View File
@@ -255,10 +255,16 @@ def test_no_orphan_brain_message_when_navigated_before_first_token(
# Wait until the scratchpad's tail is rendered (phase-17 thinking body,
# ~2 700 chars / ≈4.5s, lengthened in phase 21) — the 4s pre-content
# pause (SLOW_PRETOKEN_TRIGGER) is now running, so the navigation below
# lands inside pure thinking with a wide margin.
# lands inside pure thinking with a wide margin. Explicit timeout:
# the mock streams the tail at ≈12 chars / 0.02s (≈4.7s end-to-end),
# which outruns Playwright's 5s assertion auto-wait on a loaded host
# (the wait started at the FIRST thinking frame — the pre-existing
# race, phase 55 task 02 fix).
thinking = page.locator(".msg.brain").last.locator("details.thinking")
thinking.wait_for(state="attached", timeout=10_000)
expect(thinking.locator(".thinking-text")).to_contain_text(THINKING_TAIL)
expect(thinking.locator(".thinking-text")).to_contain_text(
THINKING_TAIL, timeout=30_000
)
# Still pre-token: the button is the enabled Stop control (phase 48 —
# the old disabled "Thinking…" busy state is gone).
expect(page.locator("#send-btn")).to_be_enabled()
+29 -16
View File
@@ -8,10 +8,11 @@ Run in isolation (DB must be up: ``podman compose up -d db``):
The full user-visible invalidation loop under test:
* **Save (fresh)** — as admin: ask (the mock answers deterministically),
Save via the chat-page pill; ``GET /api/chats`` (admin cookie) reports
the row with ``stale: false``; opening the FRESH row at ``/?chat=<id>``
shows NO banner;
* **Auto-save (fresh, phase 55)** — as admin: ask (the mock answers
deterministically) — the conversation auto-saves at the save points
(the Save pill is gone); ``GET /api/chats`` (admin cookie) reports
the row with ``stale: false``; opening the FRESH row at
``/?chat=<id>`` shows NO banner;
* **KB change** — the test process (which shares the app's environment)
bumps the ``sources_meta`` seed row through ``bump_sources_version``
over a short ``SessionLocal()`` — the exact helper BOTH real sync
@@ -60,6 +61,7 @@ the click.
from __future__ import annotations
import asyncio
import time
import uuid
from pathlib import Path
from threading import Thread
@@ -174,11 +176,25 @@ def _ask(page: Page, question: str) -> None:
expect(page.locator("#send-label")).to_have_text("Send")
def _save(page: Page) -> None:
"""Press Save and wait for the live-region confirmation (the
never-stale contract: the status line is the success feedback)."""
page.locator("#save-chat-btn").click()
expect(page.locator("#send-status")).to_have_text("Conversation saved.")
def _wait_saved_row(
app_url: str,
cookies: dict[str, str],
title: str,
messages: int = 2,
) -> dict[str, Any]:
"""Wait for the auto-saved row (phase 55: auto-saves are SILENT —
A2 — so there is no status line to wait on). The upsert is
fire-and-forget from the UI's point of view, so poll the admin
list until the row with the conversation's auto-title appears with
the expected message count."""
deadline = time.monotonic() + 15
last: dict[str, Any] | None = None
while time.monotonic() < deadline:
last = _find_row(_chats(app_url, cookies), title)
if last is not None and last["message_count"] >= messages:
return last
time.sleep(0.2)
raise AssertionError(f"no auto-saved row for {title!r} (last: {last!r})")
def _admin_cookies(page: Page) -> dict[str, str]:
@@ -298,11 +314,10 @@ def test_full_invalidation_loop(
q = "How is my Kubernetes cluster set up? (stale-loop)"
_ask(page, q)
# --- Save (fresh): the API agrees, and a fresh open shows NO banner.
_save(page)
# --- Auto-save (fresh, phase 55 — no Save pill): the API agrees,
# and a fresh open shows NO banner.
cookies = _admin_cookies(page)
row = _find_row(_chats(app_url, cookies), _auto_title(q))
assert row is not None, "the saved chat row must exist"
row = _wait_saved_row(app_url, cookies, _auto_title(q))
assert row["message_count"] == 2
assert row["stale"] is False, "a just-saved chat is fresh, not stale"
chat_id: str = row["id"]
@@ -467,11 +482,9 @@ def test_anonymous_shared_snapshot_has_no_staleness_surface(
q = "How is my Kubernetes cluster set up? (stale-share)"
_ask(page, q)
_save(page)
cookies = _admin_cookies(page)
row = _find_row(_chats(app_url, cookies), _auto_title(q))
assert row is not None
row = _wait_saved_row(app_url, cookies, _auto_title(q)) # auto-saved (phase 55)
chat_id: str = row["id"]
anon_ctx: BrowserContext | None = None
try:
+136 -12
View File
@@ -1,10 +1,13 @@
"""Integration: saved-chat CRUD (phase 50, task 02) — the ``/api/chats``
contract.
Real Postgres (``podman compose up -d db``). The router sits behind the
phase-16 ``require_admin`` gate exactly like ``/api/steering`` (the
house pattern of ``test_steering_api.py``): anonymous callers get 403 on
every route; the admin CRUD exercises the auto-title convention (first
Real Postgres (``podman compose up -d db``). Phase 55 (task 01) split
the phase-16 ``require_admin`` gate: the WRITE surface (``POST`` create
incl. save-then-share, ``PUT`` re-Save, ``POST /{id}/share``) is public
— the guest pins below exercise exactly that — while the MANAGEMENT
surface (list / detail / delete / unshare) stays admin-only (guests get
403 on exactly those four routes). The admin CRUD pins stay green
unchanged: the auto-title convention (first
user message, whitespace-collapsed, 120-char cap + the no-user-message
fallback), the list order (``updated_at desc, id desc``), the
full-payload round-trip (a ``bor.chat.v1``-shaped brain record carrying
@@ -161,29 +164,150 @@ def _assert_no_chats(admin_client: TestClient) -> None:
assert admin_client.get("/api/chats").json() == {"chats": []}
# ---------- anonymous: 403 on every route (phase 16 gate) ----------
# ---------- guest (no session): the public write surface (phase 55,
# task 01 — the router-wide phase-16 gate moved off POST/PUT/share,
# onto exactly the four management routes) ----------
def test_anonymous_every_route_returns_403(client: TestClient) -> None:
def test_guest_create_returns_201_with_id_and_auto_title(client: TestClient) -> None:
"""A guest saves their own conversation (no session cookie): 201,
a valid row id, and the same auto-title convention as the admin
(first user message) — the save surface is public since phase 55,
task 01."""
r = client.post("/api/chats", json={"messages": _simple_conversation()})
assert r.status_code == 201
body = r.json()
assert set(body) == OUT_KEYS
assert body["title"] == FIRST_QUESTION # auto-title = first user message
assert body["message_count"] == 2
assert body["messages"] == _expect(_simple_conversation())
uuid.UUID(body["id"]) # valid UUID
assert "share_url" not in body # unshared: the key is ABSENT
def test_guest_put_replaces_messages_and_bumps_updated_at(client: TestClient) -> None:
"""The re-Save upsert is guest-reachable (phase 55, task 01): the
same row's messages are fully replaced and ``updated_at`` moves —
the auto-save contract (task 02) relies on this working without a
session."""
created = client.post("/api/chats", json={"messages": _simple_conversation()}).json()
updated_before = created["updated_at"]
time.sleep(0.1) # now() has µs resolution — make the bump observable
new_messages = [
_user("How do I prune deleted docs?"),
{"who": "brain", "text": "Use --prune."},
]
r = client.put(f"/api/chats/{created['id']}", json={"messages": new_messages})
assert r.status_code == 200
body = r.json()
assert body["id"] == created["id"]
assert body["title"] == FIRST_QUESTION # absent title keeps the current one
assert body["messages"] == _expect(new_messages) # full replacement
assert datetime.fromisoformat(body["updated_at"]) > datetime.fromisoformat(
updated_before
), "updated_at must bump on a guest re-Save (onupdate=func.now())"
def test_guest_share_returns_share_url_and_is_idempotent(
client: TestClient, db: Session
) -> None:
"""``POST /{id}/share`` is guest-reachable (phase 55, task 01):
200 + ``share_url`` (token shape), the token persists on the row,
and a second guest share returns the SAME token (idempotent)."""
created = client.post("/api/chats", json={"messages": _simple_conversation()}).json()
r1 = client.post(f"/api/chats/{created['id']}/share")
assert r1.status_code == 200
body1 = r1.json()
assert set(body1) == {"chat_id", "share_url"}
assert body1["chat_id"] == created["id"]
assert SHARE_URL_RE.fullmatch(body1["share_url"]), (
f"share_url must be /shared/<lowercase uuid>: {body1['share_url']}"
)
token = uuid.UUID(body1["share_url"].removeprefix("/shared/"))
assert _stored_token(db, created["id"]) == token # persisted on the row
r2 = client.post(f"/api/chats/{created['id']}/share")
assert r2.status_code == 200
assert r2.json() == body1, "a guest re-share returns the SAME token"
assert _stored_token(db, created["id"]) == token
def test_guest_create_with_share_saves_and_shares_in_one_action(
client: TestClient, db: Session
) -> None:
"""The save-then-share contract, now guest-reachable (phase 55,
task 01): ONE request — 201 + ``share_url``, the token persisted in
the SAME commit (no second request), and the link reads
anonymously the moment the 201 lands."""
r = client.post(
"/api/chats", json={"messages": _simple_conversation(), "share": True}
)
assert r.status_code == 201
body = r.json()
assert set(body) == OUT_KEYS | {"share_url"}
assert body["title"] == FIRST_QUESTION # auto-title applies as for admin
assert SHARE_URL_RE.fullmatch(body["share_url"]), (
f"share_url must be /shared/<lowercase uuid>: {body['share_url']}"
)
token = uuid.UUID(body["share_url"].removeprefix("/shared/"))
assert _stored_token(db, body["id"]) == token # same commit, one INSERT
anon = TestClient(fastapi_app) # fresh jar: truly anonymous
got = anon.get(f"/api{body['share_url']}")
assert got.status_code == 200
assert set(got.json()) == SHARED_OUT_KEYS
assert got.json()["messages"] == _expect(_simple_conversation())
def test_guest_is_403_only_on_the_management_surface(client: TestClient) -> None:
"""The router-wide phase-16 gate MOVED, it did not disappear: a
guest (no session cookie) is 403 ``admin only`` on exactly the
four management routes — list / detail / delete / unshare (the
owner's History surface). The public ``/api/shared/<token>`` read
is NOT in this list (it is anonymous by design, as before)."""
anon = TestClient(fastapi_app) # fresh jar: truly anonymous
unknown = uuid.uuid4()
cases = [
("GET", "/api/chats", None),
("POST", "/api/chats", {"messages": _simple_conversation()}),
("GET", f"/api/chats/{unknown}", None),
("PUT", f"/api/chats/{unknown}", {"messages": _simple_conversation()}),
("DELETE", f"/api/chats/{unknown}", None),
("POST", f"/api/chats/{unknown}/share", None),
("POST", f"/api/chats/{unknown}/unshare", None),
]
# The public read is NOT in this list — it is anonymous by design
# (a wrong token 404s there, it never 403s).
for method, path, body in cases:
r = anon.request(method, path, json=body)
assert r.status_code == 403, f"{method} {path} must be 403 for anonymous"
assert r.status_code == 403, f"{method} {path} must be 403 for a guest"
assert r.json() == {"detail": "admin only"}
def test_guest_unshare_403s_but_admin_revocation_still_works(
admin_client: TestClient,
) -> None:
"""Revocation end-to-end across the split gate (phase 55, task
01): the guest who created + shared the chat cannot unshare (403 —
the link stays live), but the admin's unshare revokes it — the
public ``GET /api/shared/<token>`` read 404s afterwards for guest
AND admin (the public read itself is unaffected by this task)."""
guest = TestClient(fastapi_app) # fresh jar: truly anonymous
created = guest.post("/api/chats", json={"messages": _simple_conversation()}).json()
share_url = guest.post(f"/api/chats/{created['id']}/share").json()["share_url"]
anon = TestClient(fastapi_app) # a second guest, to prove the read
assert anon.get(f"/api{share_url}").status_code == 200 # live
r = guest.post(f"/api/chats/{created['id']}/unshare")
assert r.status_code == 403 # management surface — a guest cannot revoke
assert r.json() == {"detail": "admin only"}
assert anon.get(f"/api{share_url}").status_code == 200 # still live
assert (
admin_client.post(f"/api/chats/{created['id']}/unshare").status_code == 200
)
assert anon.get(f"/api{share_url}").status_code == 404, "guest: revoked"
assert admin_client.get(f"/api{share_url}").status_code == 404, "admin: revoked"
# ---------- create ----------
+23 -5
View File
@@ -6,7 +6,10 @@ styles.css so a silent regression (key rename, dropped try/catch, missing
restore, New chat control lost) is caught without a browser.
Pinned design (PLAN §7.4 note / phase 14):
* versioned key ``bor.chat.v1`` → ``{v: 1, messages: [...]}``, raw text only;
* versioned key ``bor.chat.v1`` → ``{v: 1, chatId: string | null,
messages: [...]}`` (phase 55 A2: the shape extends IN PLACE with the
saved_chats row link — a pre-55 record without it reads as null),
raw text only;
* save points: user message on send, brain message on ``done``;
* every ``localStorage`` access wrapped in try/catch (failure-safe);
* size budget ~700k chars, oldest dropped first;
@@ -45,13 +48,28 @@ def _index() -> str:
def test_versioned_storage_key_and_v1_payload() -> None:
"""`bor.chat.v1` (versioned — a format bump is a clean start) with the
{v, messages} payload shape (A11: raw localStorage JSON, no library)."""
{v, chatId, messages} payload shape (A11: raw localStorage JSON, no
library). Phase 55 (A2): the shape extends IN PLACE with `chatId` —
the saved_chats row link (null when unlinked), so a reload restores
the conversation AND its link; the trimToBudget size probe measures
the same shape."""
js = _js()
assert 'const STORAGE_KEY = "bor.chat.v1"' in js
assert "export const STORAGE_VERSION = 1" in js
# The payload written to the key is always {v: STORAGE_VERSION, messages}
# (two write paths: saveConversation and the trimToBudget size probe).
assert js.count("v: STORAGE_VERSION, messages") >= 2
# The write carries the version, the row link, and the trimmed
# messages (the single write path — saveConversation).
save_start = js.find("function saveConversation")
save_body = js[save_start : js.find("\n}\n", save_start)]
assert "v: STORAGE_VERSION" in save_body
assert "chatId: currentChatId" in save_body, (
"phase 55: the link is written with the record (null when unlinked)"
)
assert "trimToBudget(conversation)" in save_body
# The size probe measures the same shape (the link is a fixed-length
# field — null stands in for the size estimate).
probe_start = js.find("function trimToBudget")
probe = js[probe_start : js.find("\n}\n", probe_start)]
assert "v: STORAGE_VERSION" in probe and "chatId: null" in probe
# Restore validates the version before trusting anything.
assert "data.v !== STORAGE_VERSION" in js
+480 -158
View File
@@ -1,18 +1,60 @@
"""Unit: the phase-50 task-03 save-chat contract on the chat page.
"""Unit: the save/share contract on the chat page (phase 50 → phase 55).
The browser behavior itself is E2E-gated by the story suite (task 05);
like the other frontend-adjacent unit files, this module pins the
JS/CSS/HTML markers the save/load contract depends on, so a silent
regression is caught without a browser:
The browser behavior itself is E2E-gated by the story suites (phase 50
+ phase 55 task 06); like the other frontend-adjacent unit files, this
module pins the JS/CSS/HTML markers the save/load contract depends on,
so a silent regression is caught without a browser:
* the ``currentChatId`` lifecycle (set on create/open, cleared by New
chat and by the 404-PUT fallback);
* the upsert branch (PUT when linked, POST when not, the 404→recreate
fallback, the live-region feedback strings);
* phase 55 (A2): the Save pill is GONE — no ``#save-chat-btn`` in
index.html, no ``.save-chat-btn`` in styles.css, no ``saveBtn`` /
``saveCurrentChat`` symbol in app.js; the headless
``persistConversation()`` upsert (PUT when linked, POST when not, the
404→recreate fallback) is wired to the save points (the user send in
runTurn's ``!reask`` block, ``rememberBrainTurn`` — the pagehide
partial rides it, no direct call there) with the A2 quiet contract
(one-line status note on failure, NO error banner, silent success)
and the module-level ``persisting`` double-fire guard;
* the ``bor.chat.v1`` record carries ``chatId`` (the row link survives
reloads; a pre-55 record without the field reads as null — never
throws);
* the ``currentChatId`` lifecycle (set on create/open, hydrated from the
record on the local restore, cleared by New chat and by the 404-PUT
fallback);
* the boot-load precedence (a valid ``?chat=`` uuid + admin replaces the
local restore and mirrors it to localStorage; anonymous / invalid /
404 / network → the local restore);
* the ship-hidden / reveal-for-admin gate on ``#save-chat-btn``.
* the phase-55 task-03 Share contract on ``#share-chat-btn``: static,
ALWAYS-VISIBLE markup — no ``hidden`` attribute, NO reveal step
(no ``shareBtn.hidden`` assignment anywhere in app.js), and NEUTRAL
error copy on a failed share (the write surface is public — no
sign-in wording);
* phase 55 task 04 (the share-success toast, owner-locked A4):
``showToast`` — the SINGLE aria-hidden ``.toast`` node (lazy-created
once, reused — no stacking; text via ``textContent``, never
``innerHTML``; the pending dismiss cleared + reflow forced so a
second toast re-runs the entry; ~4s auto-dismiss) is called from
BOTH ``shareCurrentChat`` success branches with their own texts and
NEVER from a failure branch (the error banner is the failure UI);
styles.css ``.toast`` — fixed top-right just under the sticky header
(z-index 1000, brand fill — --bg on --brand 5.2:1 AA, a small
max-width, hidden by default with ``pointer-events: none``), a ~200ms
slide-down + fade entry via ``.toast.is-visible``, and the
reduced-motion override (transform dropped for BOTH states, the
opacity fade kept);
* phase 55 task 05 (the action row, owner-locked A5): a single
``<div class="chat-actions">`` in index.html wraps BOTH pills as its
element children (DOM order New chat → Share), replacing the two
pills as direct children of ``.chat-shell`` — the row sits inside the
shell, above ``#messages``, with the kb-banner / stale-banner /
steering / announcer structure around it untouched; styles.css
``.chat-actions`` — base ``display: flex; flex-direction: row;
align-items: center; gap: 0.6rem`` (the row's cross-axis override of
the column's stretch: the pills keep their intrinsic widths, side by
side, left-aligned) and the ≤640px override
``flex-direction: column; align-items: stretch; gap: 0.5rem`` (full-
width stack, New chat above Share) with the existing ≤640px pill
rules (padding, icon/label handling, the ``.chat-shell`` label
overrides) left intact for the stacked pills.
"""
from __future__ import annotations
@@ -52,62 +94,29 @@ def _fn(js: str, name: str) -> str:
# ---------- the Save button on the chat page ----------
def test_save_button_ships_hidden_beside_new_chat() -> None:
"""#save-chat-btn: a real type=button with the accessible name
"Save chat", SHIPPED HIDDEN (app.js reveals it for admin only),
beside #new-chat-btn in .chat-shell inside <main>, above
#messages — the two chat-shell actions read as a pair. No other
page carries it (chat-page only, like New chat)."""
def test_save_pill_is_gone_from_the_chat_page() -> None:
"""Phase 55 (A2): the Save control is RETIRED — there is no
#save-chat-btn anywhere in index.html (at no width), no
.save-chat-btn rule anywhere in styles.css (base, ≤900px squeeze,
≤640px overrides), and no saveBtn / saveCurrentChat symbol left in
app.js (the headless persistConversation() replaced the handler)."""
html = _index()
btn = re.search(r'<button[^>]*id="save-chat-btn"[^>]*>', html)
assert btn, "index.html must contain #save-chat-btn"
tag = btn.group(0)
assert 'type="button"' in tag
assert 'aria-label="Save chat"' in tag
assert "hidden" in tag, "the button ships hidden (reveal is app.js's job)"
# Beside New chat: after it, still inside .chat-shell, above #messages.
main_idx = html.find('main id="main"')
shell_idx = html.find('class="container chat-shell"')
new_idx = html.find('id="new-chat-btn"')
messages_idx = html.find('id="messages"')
assert -1 < main_idx < shell_idx < new_idx < btn.start() < messages_idx, (
"the button must sit beside #new-chat-btn in .chat-shell, above #messages"
)
for other in (SOURCES_HTML, GIT_SOURCES_HTML, DOCUMENT_HTML, LOGIN_HTML, TUNING_HTML):
assert 'id="save-chat-btn"' not in other.read_text(encoding="utf-8"), (
f"{other.name}: the Save button is chat-page only"
)
def test_save_button_css_is_the_exact_new_chat_family() -> None:
"""styles.css: .save-chat-btn carries the EXACT visual family of
.new-chat-btn — solid brand pill (--bg on --brand = 5.2:1, AA),
borderless, 999px radius, ≥44px target, hover lightens the brand
fill; the ≤640px block mirrors the New chat overrides (label stays
visible in .chat-shell, icon hidden there; icon-only elsewhere)."""
assert 'id="save-chat-btn"' not in html, "index.html must not carry #save-chat-btn"
assert "save-chat-label" not in html, "no Save label left in index.html"
css = _css()
block = re.search(r"\.save-chat-btn \{([\s\S]*?)\n\}", css)
assert block, "styles.css must style .save-chat-btn"
body = block.group(1)
assert "min-height: 44px" in body
assert "border-radius: 999px" in body
assert "border: 0" in body
assert "background: var(--brand)" in body, "same solid brand fill as New chat"
assert "color: var(--bg)" in body, "--bg text on --brand = 5.2:1 (AA)"
hover = re.search(r"\.save-chat-btn:hover \{([\s\S]*?)\n\}", css)
assert hover and "#f55a72" in hover.group(1), "hover lightens the brand fill"
svg = re.search(r"\.save-chat-btn svg \{([\s\S]*?)\n\}", css)
assert svg and "display: none" in svg.group(1), "icon hidden on desktop (like New chat)"
mobile = re.search(r"@media \(max-width: 640px\) \{([\s\S]*?)\n\}", css)
assert mobile, "mobile media query missing"
mbody = mobile.group(1)
assert ".save-chat-btn { padding: 0.4rem 0.3rem; }" in mbody, "squeezes with New chat"
assert ".save-chat-label { display: none; }" in mbody
assert ".save-chat-btn svg { display: block; }" in mbody
assert ".chat-shell .save-chat-label { display: inline; }" in mbody, (
"in .chat-shell the label stays visible, as for New chat"
assert "save-chat-btn" not in css, "styles.css must not style .save-chat-btn"
assert "save-chat-label" not in css, "styles.css must not style .save-chat-label"
# The ≤900px combined squeeze rule drops the Save pill (New chat +
# auth only).
tablet = re.search(r"@media \(max-width: 900px\) \{([\s\S]*?)\n\}", css)
assert tablet, "tablet media query missing"
assert ".new-chat-btn, .auth-link { padding: 0.45rem 0.5rem; }" in tablet.group(1), (
"the tablet squeeze rule is New chat + auth only"
)
assert ".chat-shell .save-chat-btn svg { display: none; }" in mbody
js = _js()
assert "saveBtn" not in js, "no saveBtn symbol left in app.js"
assert "saveCurrentChat" not in js, "no saveCurrentChat symbol left in app.js"
assert 'querySelector("#save-chat-btn")' not in js, "the pill query is gone"
# ---------- currentChatId lifecycle ----------
@@ -115,20 +124,27 @@ def test_save_button_css_is_the_exact_new_chat_family() -> None:
def test_current_chat_id_module_scope_and_lifecycle() -> None:
"""currentChatId: module scope, string | null — set to the created
row's id on a fresh Save (201), set to the opened id on a
successful boot load, cleared by "New chat" AND by the 404-PUT
fallback (a stale link must never leave the conversation unsaved)."""
row's id on a fresh auto-save (201), set to the opened id on a
successful boot load, hydrated from the record on the local restore
(phase 55 — the link survives reloads), cleared by "New chat" AND by
the 404-PUT fallback (a stale link must never wedge the
conversation)."""
js = _js()
assert "let currentChatId = null" in js, "module-scope link, null = unlinked"
# Set on create: the 201 branch links to the created row's id.
save_body = _fn(js, "saveCurrentChat")
save_body = _fn(js, "persistConversation")
assert "res.status === 201" in save_body
assert "currentChatId = String(created.id)" in save_body, (
"a fresh Save links to the created row's id"
"a fresh auto-save links to the created row's id"
)
# Set on open: the boot load links to the fetched id.
load_body = _fn(js, "restoreSavedChatFromUrl")
assert "currentChatId = chatId" in load_body
# Hydrated on the local restore: the record carries the link.
restore_body = _fn(js, "restoreConversation")
assert "currentChatId = record ? record.chatId : null" in restore_body, (
"the local restore hydrates the link from the record (phase 55)"
)
# Cleared by New chat.
new_body = _fn(js, "startNewChat")
assert "currentChatId = null" in new_body, "New chat unlinks"
@@ -137,24 +153,24 @@ def test_current_chat_id_module_scope_and_lifecycle() -> None:
assert save_body.count("currentChatId = null") >= 1
# ---------- the upsert branch ----------
# ---------- the headless auto-save (phase 55, A2) ----------
def test_save_upsert_put_when_linked_post_when_not() -> None:
"""saveCurrentChat: linked → PUT /api/chats/<id> with the messages
payload (re-Save updates the SAME row — no title in the body, so the
row keeps its current one); unlinked → POST /api/chats (the server
auto-titles). The 404 from the PUT unlinks and retries as a create.
Empty conversation → no request, live-region "Nothing to save
yet."; success → live-region "Conversation saved." (status text
only, no banner); 403/5xx/network → the error banner."""
def test_persist_conversation_upsert_semantics() -> None:
"""persistConversation (the headless replacement of the phase-50
Save handler): the EXACT upsert semantics, unchanged — linked →
PUT /api/chats/<id> with the messages payload (the SAME row updates
— no title in the body, so the row keeps its current one);
unlinked → POST /api/chats (the server auto-titles) and link to the
created id (201). The 404 from the PUT unlinks and retries as a
create — a stale link can never wedge the conversation. Empty
conversation → no-op (no request, no feedback line)."""
js = _js()
body = _fn(js, "saveCurrentChat")
# No-op first: nothing to save → live-region line, no fetch.
noop = body.find('sendStatus.textContent = "Nothing to save yet."')
body = _fn(js, "persistConversation")
# No-op first: nothing to save → silent return before any fetch.
noop = body.find("if (!conversation.length) return;")
first_fetch = body.find("await fetch(")
assert 0 < noop < first_fetch, "the empty-conversation no-op precedes any fetch"
assert "if (!conversation.length)" in body
# The branch: PUT when linked, POST when not.
assert "if (currentChatId)" in body
assert '`/api/chats/${currentChatId}`' in body
@@ -170,46 +186,125 @@ def test_save_upsert_put_when_linked_post_when_not() -> None:
assert notfound_idx != -1, "the PUT 404 must be handled"
fallback = body[notfound_idx:post_idx]
assert "currentChatId = null" in fallback, "the stale link is dropped"
# Success is status text only — the live region, never stale — and
# nothing between the 201 link and the success line may raise a
# banner (the !res.ok branch returns before either).
assert body.count('sendStatus.textContent = "Conversation saved."') == 1
saved_line = 'sendStatus.textContent = "Conversation saved."'
between = body[body.find("res.status === 201") : body.find(saved_line)]
assert "showErrorBanner" not in between, "no banner on the success path"
# Failures raise an actionable banner (non-ok HTTP + network).
assert 'showErrorBanner("Couldn\'t save the conversation — is the app reachable?")' in body
assert "check you're still signed in and try again" in body, "403/5xx: actionable line"
# The double-click guard releases on EVERY outcome.
finally_idx = body.rfind("finally")
assert finally_idx != -1 and "saveBtn.disabled = false" in body[finally_idx:], (
"the button is re-enabled in the finally — never stale"
# The 201 branch links to the created row.
assert "res.status === 201" in body
assert "currentChatId = String(created.id)" in body
def test_persist_conversation_is_headless_and_quiet() -> None:
"""The A2 quiet contract: NO error banner anywhere in the helper
(the phase-50 banner lines are gone), NO success status text
("Conversation saved." is retired — success is silent; the History
page is the visible proof), and the failure feedback is the
one-line #send-status note — on BOTH failure paths (non-ok HTTP and
network) — with the "next save point retries" promise. The
module-level `persisting` flag is the double-fire guard (released
in the finally — never stuck)."""
js = _js()
body = _fn(js, "persistConversation")
assert "showErrorBanner" not in body, "A2: a failed auto-save never raises a banner"
assert "Conversation saved." not in body, "A2: success is silent (no status text)"
note = "Couldn't save automatically — will try on the next message."
assert body.count(note) == 2, "the one-line note covers non-ok AND network failure"
# The non-ok branch notes and returns (no banner, no 201 handling).
notok = body.find("if (!res.ok)")
first_note = body.find(note)
assert -1 < notok < first_note, "the non-ok branch lands on the one-line note"
# The network path (catch) notes too.
catch_idx = body.find("} catch {")
assert catch_idx != -1 and first_note < body.rfind(note) < body.rfind("finally"), (
"the catch branch carries the second note"
)
# The module-level double-fire guard, released on EVERY outcome.
assert re.search(r"^let persisting = false", js, re.M), (
"the persisting flag is module scope (save points can overlap)"
)
assert "if (persisting) return;" in body, "an in-flight upsert skips the second call"
assert "persisting = true;" in body
finally_idx = body.rfind("finally")
assert finally_idx != -1 and "persisting = false" in body[finally_idx:], (
"the flag is released in the finally — never stuck"
)
def test_auto_save_wired_to_the_save_points() -> None:
"""The headless helper is referenced from the save points: the user
send (runTurn's ``!reask`` block — after the localStorage
saveConversation()) and the brain save point (rememberBrainTurn —
after its saveConversation()). The pagehide partial rides
rememberBrainTurn: NO second direct call there."""
js = _js()
# Save point 1: the user send in runTurn's !reask block.
turn = js.find("async function runTurn")
reask_block = js[js.find("if (!reask) {", turn) : js.find("let wrap = null", turn)]
save1 = reask_block.find("saveConversation();")
persist1 = reask_block.find("persistConversation();")
assert -1 < save1 < persist1, "the user-send save point rides persistConversation()"
# Save point 2: rememberBrainTurn (the brain-done + stop + pagehide path).
body = _fn(js, "rememberBrainTurn")
save2 = body.find("saveConversation();")
persist2 = body.find("persistConversation();")
assert -1 < save2 < persist2, "the brain save point rides persistConversation()"
# The pagehide handler itself carries no direct persist call — the
# partial rides rememberBrainTurn (no extra wiring, phase 20
# contract untouched).
m = re.search(r'window\.addEventListener\("pagehide", \(\) => \{([\s\S]*?)\n\}\);', js)
assert m, "the pagehide handler must exist"
assert "persistConversation" not in m.group(1), (
"the pagehide partial rides rememberBrainTurn — no second call"
)
def test_record_carries_the_row_link() -> None:
"""Phase 55 (A2): the bor.chat.v1 record carries ``chatId``. The
write (saveConversation) persists the CURRENT currentChatId (null
when unlinked) with the versioned record; the reader
(loadStoredRecord) reads it back with old-record safety — a
pre-55 record without the field (or a non-string) reads as null,
never throws; the restore validates the version before trusting
anything."""
js = _js()
save_body = _fn(js, "saveConversation")
assert "chatId: currentChatId" in save_body, ("the write persists the current link")
assert "v: STORAGE_VERSION" in save_body
assert "trimToBudget(conversation)" in save_body
read_body = _fn(js, "loadStoredRecord")
assert "data.v !== STORAGE_VERSION" in read_body, "version validated first"
assert "Array.isArray(data.messages)" in read_body
# Old-record safety: optional field, string check, null fallback.
assert 'typeof data.chatId === "string"' in read_body
assert "data.chatId.length ? data.chatId : null" in read_body
# The defensive message filter survives the reshape.
assert 'm.who === "user" || m.who === "brain"' in read_body
assert 'typeof m.text === "string"' in read_body
# ---------- boot-load precedence ----------
def test_boot_load_precedence_saved_chat_over_local_restore() -> None:
"""Inside the boot IIFE: after fetchIsAdmin() + the reveal gate,
restoreSavedChatFromUrl() runs; only when it returns false does the
phase-14 local restore run. Header init stays first (shared-module
contract)."""
"""Inside the boot IIFE: after fetchIsAdmin(), restoreSavedChatFromUrl()
runs; only when it returns false does the phase-14 local restore run
(which hydrates the row link from the record — phase 55). Header init
stays first (shared-module contract). The phase-50 Save-reveal line is
GONE — and phase 55 task 03 removed the Share-reveal line too (the
pill is static, always-visible markup: no reveal step at boot)."""
js = _js()
boot_start = js.find("(async () => {")
assert boot_start != -1, "the boot IIFE must exist"
boot = js[boot_start:]
init_i = boot.find("await initSharedHeader();")
admin_i = boot.find("isAdmin = await fetchIsAdmin();")
reveal_i = boot.find("saveBtn.hidden = !isAdmin")
saved_i = boot.find("await restoreSavedChatFromUrl();")
local_i = boot.find("restoreConversation();")
assert -1 < init_i < admin_i < reveal_i < saved_i < local_i, (
"boot order: header init → whoami → Save reveal → ?chat= load → local fallback"
assert -1 < init_i < admin_i < saved_i < local_i, (
"boot order: header init → whoami → ?chat= load → local fallback"
)
assert "shareBtn.hidden" not in boot, ("no Share-reveal line left in boot (phase 55 task 03)")
assert "if (!openedSaved) restoreConversation();" in boot, (
"the local restore runs ONLY when the saved-chat load did not open"
)
assert "saveBtn" not in boot, "no Save-reveal line left in boot (phase 55)"
def test_boot_load_gates_valid_uuid_and_admin_only() -> None:
@@ -261,20 +356,17 @@ def test_boot_load_gates_valid_uuid_and_admin_only() -> None:
# ---------- the reveal gate ----------
def test_save_button_revealed_only_for_admin() -> None:
"""The ship-hidden/reveal-for-admin contract: app.js queries
#save-chat-btn, binds the click to saveCurrentChat, and the boot
IIFE sets saveBtn.hidden = !isAdmin (phase 16 absent-not-hidden —
hidden is display:none, no trace for anonymous)."""
def test_no_save_pill_wiring_left_in_app_js() -> None:
"""Phase 55 (A2): the Save pill's wiring is GONE — no
#save-chat-btn query, no click binding to a save handler, no boot
reveal line. The headless persistConversation() replaces all of it
(no button, no admin gate: every visitor's conversation auto-saves
— the write surface is public, phase 55 task 01)."""
js = _js()
assert 'document.querySelector("#save-chat-btn")' in js
assert 'saveBtn?.addEventListener("click", saveCurrentChat)' in js
assert "saveBtn.hidden = !isAdmin" in js, "revealed for admin only, at boot"
# The reveal happens in the boot IIFE (after whoami), not at module
# evaluation (isAdmin is false there).
boot_start = js.find("(async () => {")
reveal = js.find("saveBtn.hidden = !isAdmin")
assert boot_start < reveal, "the reveal must run at boot, after whoami resolves"
assert 'querySelector("#save-chat-btn")' not in js, "the pill query is gone"
assert "saveCurrentChat" not in js, "the button handler is gone"
assert 'addEventListener("click", saveCurrentChat)' not in js, "no save binding"
assert "saveBtn" not in js, "no saveBtn symbol anywhere (the tune form uses its own)"
def test_boot_load_adds_no_direct_storage_access() -> None:
@@ -296,29 +388,32 @@ def test_no_cdn_added() -> None:
# ---------- the Share button on the chat page (phase 51, task 02) ----------
def test_share_button_ships_hidden_beside_save() -> None:
def test_share_button_ships_visible_beside_new_chat() -> None:
"""#share-chat-btn: a real type=button with the accessible name
"Share chat", SHIPPED HIDDEN (app.js reveals it for admin only),
BESIDE #save-chat-btn in .chat-shell inside <main>, above
#messages — the chat-shell actions read as a pair (Save | Share).
No other page carries it (chat-page only, like Save)."""
"Share chat", SHIPPED VISIBLE to every visitor (phase 55 task 03 —
NO ``hidden`` attribute, no reveal step; the phase-51 admin-only
ship-hidden gate is gone), BESIDE #new-chat-btn in .chat-shell
inside <main>, above #messages — the chat-shell actions read as a
pair (New chat | Share; the Save pill is gone, phase 55). No other
page carries it (chat-page only, like New chat)."""
html = _index()
btn = re.search(r'<button[^>]*id="share-chat-btn"[^>]*>', html)
assert btn, "index.html must contain #share-chat-btn"
tag = btn.group(0)
assert 'type="button"' in tag
assert 'aria-label="Share chat"' in tag
assert "hidden" in tag, "the button ships hidden (reveal is app.js's job)"
assert "hidden" not in tag, ("the button ships visible — no reveal step (phase 55 task 03)")
# The label: the visible text is "Share" (the link SVG is aria-hidden
# decoration; the aria-label carries the accessible name).
btn_block = html[btn.start() : html.find("</button>", btn.start())]
assert '>Share</span>' in btn_block
# Beside Save: after it, still inside .chat-shell, above #messages.
# Beside New chat (the Save pill is gone): after it, still inside
# .chat-shell, above #messages.
shell_idx = html.find('class="container chat-shell"')
save_idx = html.find('id="save-chat-btn"')
new_idx = html.find('id="new-chat-btn"')
messages_idx = html.find('id="messages"')
assert -1 < shell_idx < save_idx < btn.start() < messages_idx, (
"the button must sit beside #save-chat-btn in .chat-shell, above #messages"
assert -1 < shell_idx < new_idx < btn.start() < messages_idx, (
"the button must sit beside #new-chat-btn in .chat-shell, above #messages"
)
for other in (SOURCES_HTML, GIT_SOURCES_HTML, DOCUMENT_HTML, LOGIN_HTML,
TUNING_HTML, Path(FRONTEND / "history.html")):
@@ -328,11 +423,13 @@ def test_share_button_ships_hidden_beside_save() -> None:
def test_share_button_css_is_the_exact_save_family() -> None:
"""styles.css: .share-chat-btn carries the EXACT visual family of
.save-chat-btn (same solid brand pill — --bg on --brand = 5.2:1, AA;
borderless; 999px radius; ≥44px target; hover lightens the brand
fill); the ≤640px block mirrors the Save overrides (label stays
visible in .chat-shell, icon hidden there; icon-only elsewhere)."""
"""styles.css: .share-chat-btn carries the EXACT visual family of the
phase-50 Save pill (now the .new-chat-btn family — the Save rules
are gone with the pill, phase 55): same solid brand pill — --bg on
--brand = 5.2:1, AA; borderless; 999px radius; ≥44px target; hover
lightens the brand fill; the ≤640px block mirrors the New chat
overrides (label stays visible in .chat-shell, icon hidden there).
"""
css = _css()
block = re.search(r"\.share-chat-btn \{([\s\S]*?)\n\}", css)
assert block, "styles.css must style .share-chat-btn"
@@ -368,9 +465,11 @@ def test_share_current_chat_save_then_share_branch() -> None:
copied — the clipboard try succeeds → the live region reads
"Share link copied."; the rejection (a non-secure http origin)
renders the .share-link-fallback field + "Share link ready — copy it
from the field." 403/5xx → the actionable banner (signed-out hint);
network → the reachable? banner. The double-click guard releases in
the finally — never stale."""
from the field." 403/5xx → the actionable banner (NEUTRAL "try
again" — the write surface is public, phase 55 task 01, so a 403
is no longer a sign-in problem for a guest); network → the
reachable? banner. The double-click guard releases in the finally —
never stale."""
js = _js()
body = _fn(js, "shareCurrentChat")
# No-op first: nothing to share → live-region line, no fetch.
@@ -405,11 +504,15 @@ def test_share_current_chat_save_then_share_branch() -> None:
' : "Share link ready — copy it from the field."'
) in body
# Failures raise an actionable banner (non-ok HTTP + network).
# Phase 55 task 03: the 403/5xx copy is NEUTRAL ("try again") — no
# sign-in wording anywhere in the share handler (the write surface
# is public); the network banner keeps its own line.
assert 'showErrorBanner("Couldn\'t share the conversation — is the app reachable?")' in body
assert "check you're still signed in and try again" in body, "403/5xx: actionable line"
assert body.count("check you're still signed in and try again") == 2, (
"both the linked and the unlinked branch carry the non-ok banner"
neutral = "Couldn't share the conversation — try again."
assert body.count(neutral) == 2, (
"both the linked and the unlinked branch carry the neutral non-ok banner"
)
assert "signed in" not in body, "no sign-in wording left in the share handler (task 03)"
# The double-click guard releases on EVERY outcome.
finally_idx = body.rfind("finally")
assert finally_idx != -1 and "shareBtn.disabled = false" in body[finally_idx:], (
@@ -430,23 +533,239 @@ def test_share_current_chat_save_then_share_branch() -> None:
assert "document.createRange()" in sel and "selectNodeContents(el)" in sel
def test_share_button_revealed_only_for_admin() -> None:
"""The ship-hidden/reveal-for-admin contract: app.js queries
#share-chat-btn, binds the click to shareCurrentChat, and the boot
IIFE sets shareBtn.hidden = !isAdmin in the SAME admin-reveal block
as Save (phase 16 absent-not-hidden — no trace for anonymous)."""
def test_share_button_has_no_reveal_gate() -> None:
"""Phase 55 task 03: the pill is VISIBLE TO EVERY VISITOR — app.js
queries #share-chat-btn and binds the click to shareCurrentChat, but
there is NO reveal step: no ``shareBtn.hidden`` assignment ANYWHERE
in app.js (the phase-51 ship-hidden/admin-reveal gate is gone; the
markup ships visible and task 01 opened the write surface to all).
"""
js = _js()
assert 'document.querySelector("#share-chat-btn")' in js
assert 'shareBtn?.addEventListener("click", shareCurrentChat)' in js
assert "shareBtn.hidden = !isAdmin" in js, "revealed for admin only, at boot"
# The reveal happens in the boot IIFE (after whoami), not at module
# evaluation — and right next to Save's own reveal line.
boot_start = js.find("(async () => {")
reveal = js.find("shareBtn.hidden = !isAdmin")
save_reveal = js.find("saveBtn.hidden = !isAdmin")
assert boot_start < save_reveal < reveal, (
"the Share reveal joins the same admin-reveal block as Save"
assert "shareBtn.hidden" not in js, "no reveal step — the pill ships visible to all"
# ---------- the share-success toast (phase 55, task 04, A4) ----------
def test_show_toast_helper_single_instance_and_aria_hidden() -> None:
"""showToast (A4 owner-locked): a SINGLE node — lazy-created on the
first call and REUSED thereafter (toasts never stack), a plain
``<div class="toast">`` appended to ``document.body``; the text
lands via ``textContent`` (XSS-safe — never innerHTML); the node is
``aria-hidden="true"`` (visual only — #send-status is the
announcer). Re-triggering the entry (a second share while the first
toast is up): clear the pending dismiss timer, remove the visible
state class, force a reflow (``offsetWidth`` — restarts the CSS
transition), re-add the class. Auto-dismiss: a 4000ms timer set
AFTER the visible class is added, removing the class on fire."""
js = _js()
body = _fn(js, "showToast")
# Lazy single instance, appended to <body>, marked visual-only.
assert "if (!toastEl)" in body, "the node is created once, on first use"
assert 'document.createElement("div")' in body
assert 'toastEl.className = "toast"' in body
assert 'toastEl.setAttribute("aria-hidden", "true")' in body, ("A4: visual only")
assert "document.body.appendChild(toastEl)" in body
# textContent only — never innerHTML.
assert "toastEl.textContent = message" in body
assert "innerHTML" not in body, "XSS contract: textContent only"
# Single instance: module-scope node + timer, reused (no stacking).
assert re.search(r"^let toastEl = null", js, re.M), ("the node is module scope")
assert re.search(r"^let toastTimer = 0", js, re.M), ("the timer is module scope")
# Re-trigger order: clear dismiss → remove class → force reflow →
# re-add the visible class.
clear_i = body.find("clearTimeout(toastTimer)")
remove_i = body.find('toastEl.classList.remove("is-visible")')
reflow_i = body.find("void toastEl.offsetWidth")
add_i = body.find('toastEl.classList.add("is-visible")')
assert -1 < clear_i < remove_i < reflow_i < add_i, (
"dismiss cleared → class removed → reflow forced → visible re-added"
)
# Auto-dismiss ~4s, armed AFTER the visible class is set.
timer_i = body.find("setTimeout")
assert -1 < add_i < timer_i and "4000" in body
assert 'toastEl.classList.remove("is-visible")' in body[timer_i:], (
"the pending dismiss removes the visible state"
)
def test_toast_called_from_both_share_success_branches_only() -> None:
"""shareCurrentChat (task 04): BOTH success paths call showToast
with their own text — the clipboard path → "Share link copied.",
the fallback-field path → "Share link ready — copy it from the
field." — and both calls ride the SUCCESS branch (after the copy,
after the untouched #send-status live-region lines). showToast
appears EXACTLY twice in the handler and never in a failure branch
(the two !res.ok banners precede the copy; the network catch —
the error banner is the failure UI — carries no toast)."""
js = _js()
body = _fn(js, "shareCurrentChat")
assert body.count("showToast(") == 2, "exactly one toast per success path"
copy_i = body.find("copyShareLinkWithFallback(absoluteShareUrl(shareUrl))")
assert copy_i != -1, "the copy (the success branch) must exist"
t1 = body.find('showToast("Share link copied.")')
t2 = body.find('showToast("Share link ready — copy it from the field.")')
assert t1 != -1 and t2 != -1, "both success paths toast their own text"
assert -1 < copy_i < min(t1, t2), ("the toasts ride the SUCCESS branch (after the copy)")
# The #send-status lines stay exactly as they were (the a11y
# announcer) and precede the toast calls.
status_i = body.find("sendStatus.textContent = copied")
assert -1 < status_i < min(t1, t2)
# Never on failure: the catch block carries no toast.
catch_i = body.rfind("} catch {")
assert catch_i != -1 and "showToast" not in body[catch_i:], (
"a failed share shows the error banner, no toast"
)
def test_toast_css_top_right_brand_family_and_reduced_motion() -> None:
"""styles.css (task 04): .toast — position: fixed, top-right just
under the sticky header (--header-h + offset — the variable steps
64px → 58px at ≤640px), z-index 1000 (the modal overlay contract —
above the header's 20), a small max-width so long text wraps, the
solid brand fill (--bg text on --brand = 5.2:1, AA — the
.new-chat-btn family), rounded + shadowed. Hidden by default
(opacity 0 + pointer-events: none — it never intercepts clicks when
idle) and resting at translateY(-8px), with the ~200ms entry
transition; .toast.is-visible lands at opacity 1 / translateY(0).
Under prefers-reduced-motion: reduce the transform is dropped for
BOTH states (.is-visible would otherwise out-specify the bare
.toast) and the opacity fade remains."""
css = _css()
block = re.search(r"\.toast \{([\s\S]*?)\n\}", css)
assert block, "styles.css must style .toast"
body = block.group(1)
for prop in (
"position: fixed",
"top: calc(var(--header-h) + 0.75rem)",
"right: 1rem",
"z-index: 1000",
"max-width: min(22rem, calc(100vw - 2rem))",
"background: var(--brand)",
"color: var(--bg)",
"border-radius: var(--radius-sm)",
"box-shadow: var(--shadow)",
"opacity: 0",
"pointer-events: none",
"transform: translateY(-8px)",
):
assert prop in body, f".toast must keep {prop}"
assert "transition:" in body and "200ms" in body, ("the entry is a ~200ms slide-down + fade")
visible = re.search(r"\.toast\.is-visible \{([\s\S]*?)\n\}", css)
assert visible, "the .toast.is-visible state class (toggled by showToast) must exist"
assert "opacity: 1" in visible.group(1)
assert "transform: translateY(0)" in visible.group(1)
# The reduced-motion override: transform dropped (BOTH states
# named), the opacity fade kept.
rm = None
for m in re.finditer(r"@media \(prefers-reduced-motion: reduce\) \{([\s\S]*?)\n\}", css):
if ".toast" in m.group(1):
rm = m.group(1)
break
assert rm is not None, "a reduced-motion block must cover .toast"
assert ".toast.is-visible { transform: none; }" in rm, ("the slide is dropped for BOTH states")
assert re.search(r"\.toast \{ transition: opacity", rm), ("the opacity fade remains")
# ---------- the chat-actions row (phase 55, task 05, A5) ----------
def test_chat_actions_wrapper_holds_both_pills_in_order() -> None:
"""index.html (task 05, A5): ONE ``<div class="chat-actions">``
wraps BOTH pills — its element children are exactly the two
buttons, in the A5 order New chat → Share. The wrapper replaces
the two pills as direct children of ``.chat-shell`` (a normal
column child): inside the shell, above ``#messages``; nothing else
lands between the steering announcer and the row, and nothing but
the phase-49 comment lands between the row and ``#messages``. No
other page carries ``.chat-actions`` (chat-page only, like the
pills)."""
html = _index()
start = html.find('<div class="chat-actions">')
assert start != -1, "index.html must carry the .chat-actions wrapper"
end = html.find("</div>", start)
assert end != -1, "the wrapper must close"
wrap = html[start:end]
# Exactly two element children: the two pill buttons, New chat first.
assert wrap.count("<div") == 1, "no nested div inside the row wrapper"
assert wrap.count("<button") == 2, "the row holds exactly the two pills"
new_i = wrap.find('id="new-chat-btn"')
share_i = wrap.find('id="share-chat-btn"')
assert -1 < new_i < share_i, "A5 order: New chat first, then Share"
# Position: a .chat-shell column child, above #messages — the
# kb-banner / stale-banner / steering / announcer structure is
# untouched (nothing else with an id around the row).
shell_idx = html.find('class="container chat-shell"')
messages_idx = html.find('id="messages"')
assert -1 < shell_idx < start < end < messages_idx, (
"the row is a .chat-shell column child, above #messages"
)
ann_idx = html.find('id="steering-announcer"')
between = html[html.find("</p>", ann_idx):start]
assert "id=" not in between and "<button" not in between, (
"no other element lands between the announcer and the row"
)
after = html[end:messages_idx]
assert "id=" not in after and "<button" not in after, (
"nothing but the phase-49 comment lands between the row and #messages"
)
for other in (SOURCES_HTML, GIT_SOURCES_HTML, DOCUMENT_HTML, LOGIN_HTML,
TUNING_HTML, Path(FRONTEND / "history.html")):
assert "chat-actions" not in other.read_text(encoding="utf-8"), (
f"{other.name}: the action row is chat-page only"
)
def test_chat_actions_row_on_desktop_and_stack_at_640() -> None:
"""styles.css (task 05, A5): the base ``.chat-actions`` rule is a
horizontal flex row — ``display: flex; flex-direction: row;
align-items: center; gap: 0.6rem``. The ``align-items: center`` is
load-bearing: the wrapper is a flex ITEM of the ``.chat-shell``
column (which stretches its items), and the row's own
cross-axis ``center`` (not the column default ``stretch``) keeps
each pill at its intrinsic content width — two pills side by side,
left-aligned, never full-column. The ≤640px override flips the
row to a full-width vertical stack — ``flex-direction: column;
align-items: stretch; gap: 0.5rem`` (New chat above Share) — and
the EXISTING ≤640px pill rules (padding squeeze, the icon/label
handling, the ``.chat-shell`` label overrides) stay in place for
the stacked pills."""
css = _css()
block = re.search(r"\.chat-actions \{([\s\S]*?)\n\}", css)
assert block, "styles.css must style .chat-actions (base row)"
for prop in (
"display: flex",
"flex-direction: row",
"align-items: center",
"gap: 0.6rem",
):
assert prop in block.group(1), f".chat-actions must keep {prop}"
mobile = re.search(r"@media \(max-width: 640px\) \{([\s\S]*?)\n\}", css)
assert mobile, "mobile media query missing"
mbody = mobile.group(1)
m = re.search(r"\.chat-actions \{([^}]*)\}", mbody)
assert m, "the ≤640px override (vertical stack) must exist"
for prop in (
"flex-direction: column",
"align-items: stretch",
"gap: 0.5rem",
):
assert prop in m.group(1), f"the ≤640px .chat-actions must keep {prop}"
# The stacked pills keep their existing mobile treatment (the rules
# the phase-50/51 pairs established — untouched by this task).
for rule in (
".new-chat-btn { padding: 0.4rem 0.3rem; }",
".share-chat-btn { padding: 0.4rem 0.3rem; }",
".new-chat-label { display: none; }",
".share-chat-label { display: none; }",
".chat-shell .new-chat-label { display: inline; }",
".chat-shell .new-chat-btn svg { display: none; }",
".chat-shell .share-chat-label { display: inline; }",
".chat-shell .share-chat-btn svg { display: none; }",
):
assert rule in mbody, f"the existing ≤640px pill rule must stay: {rule}"
# ---------- stale saved chat: banner + Regenerate (phase 53, task 05) ----------
@@ -571,7 +890,7 @@ def test_stale_regenerate_persists_the_linked_row() -> None:
"""The post-regenerate persist (the existing upsert path): linked →
PUT /api/chats/<id> (the server re-stamps sources_version → the row
is fresh); a 404 (the row was deleted from History meanwhile)
follows saveCurrentChat's stale-link rule — unlink + recreate
follows persistConversation's stale-link rule — unlink + recreate
(POST), and the recreate links the new id. Success hides the banner
AND announces the outcome in the #send-status live region; 403/5xx
→ the actionable error banner (the row stays as the turn left it);
@@ -616,19 +935,22 @@ def test_stale_regenerate_binding_and_element_queries() -> None:
assert 'staleRegenBtn?.addEventListener("click", regenerateStaleChat)' in js
def test_stale_banner_cleared_on_new_chat_and_resave() -> None:
def test_stale_banner_cleared_on_new_chat_and_autosave() -> None:
"""Never-stale (PLAN §7.4): "New chat" replaces the conversation the
banner described (and unlinks it) — the banner hides; a successful
manual re-Save re-stamps the row to the current generation (task
03) — the banner is done the moment the save succeeds."""
auto-save re-stamps the row to the current generation (task 03) —
the banner is done the moment the save succeeds (on the success
path only — after the !res.ok early return and the 201 link)."""
js = _js()
new_body = _fn(js, "startNewChat")
assert "staleBanner.hidden = true" in new_body, "New chat hides the banner"
save_body = _fn(js, "saveCurrentChat")
saved_line = 'sendStatus.textContent = "Conversation saved."'
after = save_body[save_body.find(saved_line):]
assert "staleBanner.hidden = true" in after, (
"a successful re-save re-stamps the row — the banner is done"
save_body = _fn(js, "persistConversation")
notok_idx = save_body.find("if (!res.ok)")
two01_idx = save_body.find("res.status === 201")
hide_idx = save_body.find("staleBanner.hidden = true")
catch_idx = save_body.find("} catch {")
assert -1 < notok_idx < two01_idx < hide_idx < catch_idx, (
"the banner clears on the success path, after the 201 link, never on failure"
)