agnes-the-ai-analyst/tests/test_v28_migration.py
Vojtech 2e2e1a1eca
feat(home): state-aware /home + /setup-advanced + schema v26 (#228)
* feat(home+news): state-aware /home + /news + admin-edited news section

Squash of the vr/home-page feature work for clean rebase onto main.
Original 18-commit history preserved in branch backup/vr-home-page-pre-rebase.

What's in this PR:

**State-aware /home page**
- New `/home` route with hero + auto-mode + connectors (Asana / GWS /
  Atlassian) + lookarounds. Onboarded vs not-onboarded state-machine
  branches a single template (`home_not_onboarded.html`); the install
  steps, "Setup a new Claude Code" CTA (90-day PAT mint), and per-
  connector setup prompts hide once `users.onboarded=TRUE`. A
  completion badge replaces them.
- "Mark me as offboarded" button reverses the flag without an SQL UPDATE.
- `users.onboarded BOOLEAN` column added; default FALSE; flipped by the
  CLI's `agnes init` post-success POST and the `/admin/users` API.
- Connector setup prompts pre-check whether the tool is already
  installed/connected before re-running setup.
- GWS scope set widened to include Google Chat (`chat.spaces`,
  `chat.messages`).

**Single template + design tokens**
- `dashboard.html` now extends `base.html` via the new
  `{% block layout %}` opt-out (full-width pages skip the 800px
  `.container`). Net: every page shares one shell.
- `style-custom.css` `:root` extended with `--space-{7,9,10,12}`,
  `--radius-2xl`, `--shadow-{card,elevated}`, `--text-{muted,disabled}`,
  `--focus-ring`, `--transition-*`, `--width-{narrow,app,wide}` so
  inline page styles can migrate incrementally.

**Auth redirects honor AGNES_HOME_ROUTE**
- `safe_next_path` resolves the configured home route when no `default=`
  is passed; OAuth callbacks, magic-link clicks, password form, and
  LOCAL_DEV_MODE shortcuts now land on `/home` (or whatever the operator
  picked) instead of always /dashboard.

**News section + /news permalink + /admin/news editor**
- Schema-bumped `news_template` table (single versioned entity, draft +
  publish gate). `published BOOLEAN` distinguishes draft from public;
  monotonically-increasing `version` per save; rows >30d pruned on
  save except the currently-displayed published version.
- `/home` bottom-of-page renders the latest published intro with a
  "Read more →" link to `/news` (which renders the full body).
- `/admin/news` editor with sandboxed live preview, versions table,
  per-row Unpublish, Format-help cheatsheet.
- `agnes admin news show / draft / edit / publish / unpublish /
  versions / export` (CLI). Talks to the live server via the
  `/api/admin/news/*` endpoints (PAT-authed) — no direct DB access
  so it coexists with a running uvicorn.
- **Optimistic-lock guard**: `agnes admin news publish --version N` and
  PUT/PATCH endpoints accept `expected_version` and 409 with structured
  `{error: "version_conflict", expected, actual, actual_by}` when a
  concurrent admin replaced the draft. Edit refuses to overwrite a
  draft authored by someone else without `--force` or
  `--expect-version`.
- nh3 (Rust-backed ammonia) HTML sanitizer; iframe pre-pass strips
  any iframe whose src is not on the YouTube/Vimeo/Loom allowlist;
  javascript:/data: schemes blocked everywhere.
- Author CSS vocabulary: `.news-hero` (blue gradient hero block),
  `.callout`/`.callout-{info,warn,success,danger}`,
  `.video-embed`, `.news-section`, `.news-grid-{2,3}`, `.news-cta` —
  all consolidated in `style-custom.css` under "News content
  vocabulary (shared)" so /home perex, /news body, and /admin/news
  preview share one source of styling.
- Code-inside-`<pre>` contrast fix (was unreadable amber-on-silver).
- `.news-content` table styling (border, header band, row-hover).

**`scripts/dev/run-local.sh`** — local uvicorn launcher. Pulls Google
OAuth client id/secret from GCP Secret Manager
(`AGNES_OAUTH_GCP_PROJECT`-driven, no vendor defaults), points
`AGNES_CLI_DIST_DIR` at `./dist` so the wheel endpoint resolves, and
`--dev` flips `LOCAL_DEV_MODE=1` + `AGNES_HOME_ROUTE=/home` for one-
command iteration. `LOCAL_DEV_MODE=1` also enables the FastAPI debug
toolbar.

**CLAUDE.md "Run tests before every push" section** codifies
`pytest tests/ -n auto -q` as non-negotiable before each push.

**Tests**: 51 + 14 + 8 = 73 new tests across news-template repo,
sanitizer, API, web, CLI; plus updated home/auth/template tests for
the new shared-shell architecture.

Origin docs (gitignored, customer-fork content):
docs/brainstorms/home-page-requirements.md,
docs/plans/2026-05-07-001-feat-home-page-plan.md.

* feat(cli): agnes onboarded {on,off,status} — self-scoped flag toggle

User-facing equivalent of the in-page "Mark me as (off)boarded" button
on /home. POSTs /api/me/onboarded with {onboarded, source}; --source
overrides the audit-log marker so flips made from the CLI vs the web
button vs agnes init automation stay distinguishable.

`status` reads via /api/me/profile (when present); falls back to a
quick body-marker scan of /home so the read path doesn't write an
audit_log row. PAT-authed via cli.client.api_post — same convention
as agnes admin news / agnes admin add-user etc.

Tests: 5 covering on/off/status round-trip, idempotency, and
audit-log source recording. Full suite holds at 12 pre-existing
failures (same set as before).

* ui(nav+home): primary nav reorg + green What's new band + /marketplace link fix

Primary nav (post-rebase audit + per-user feedback):

- Items: Home → Marketplace → Data Packages → Memory. Admin dropdown
  for admins only. The "Dashboard" label was renamed Home — point still
  resolves through `home_route` so customer instances on /dashboard
  still land there.
- Activity Center moved into the Admin dropdown. Per-team adoption
  analytics is admin-consumed in practice; the route still allows
  any authed user for direct deep-links so existing /home tile +
  bookmarks keep working.
- Memory link added (→ /corporate-memory) — was previously buried in
  the /home "Look around" tiles.
- Setup local agent + My Stack dropped from main nav. Setup is the
  /home install flow's home now; My Stack lives as a tab inside
  /marketplace.

/home tweaks:

- Plugin marketplace tile now points at /marketplace (was /store —
  legacy from before the marketplace rebrand landed in #230).
- "What's new" section header gets a green band (success-flavored
  D1FAE5 background, A7F3D0 border, darker green title) so the
  bottom-of-page news block visibly distinguishes from the blue
  install-hero at the top. Header strip only — body stays white.

Test fix: test_home_route_resolution renamed `dashboard_link_uses_home_route`
→ `home_link_uses_home_route` and asserts `href="/home">Home` instead
of `href="/home">Dashboard` after the label change.

* fix(home): decouple Step 3 + Connect-tools collapse from server onboarded flag

The server-side `users.onboarded` flip happens through two paths:

1. Explicit user click on "Mark me as onboarded" or `agnes onboarded on`.
2. Implicit `agnes init` POST → /api/me/onboarded on success.

Path 2 produced a UX surprise: an analyst running `agnes init` mid-flow
reloaded /home and saw Step 3 (auto-mode) + Connect-your-tools auto-
collapse to summary bars. They were actively working through those
sections — the install POST never signalled "I'm done with the rest
of setup", just "Agnes itself is installed".

Decouple the section-collapse decision from the server flag:

- Step 1 + Step 2 install blocks: still hidden on `onboarded=TRUE`
  (their completion is a hard server signal — Agnes IS installed).
- Step 3 + Connect-your-tools: render flat by default in BOTH states.
  Wrapped in `<details class="setup-collapsible" open>` so the
  browser's native disclosure handles per-section toggle without JS,
  but the `<summary>` is CSS-hidden until the page-level
  `data-setup-minimized="1"` attribute is set on `.home-mock`.
- New "Minimize setup view" toggle inside the blue install-hero,
  rendered only when onboarded. Click flips the data-attr on
  `.home-mock` AND removes the `open` attribute from each
  `<details>`. State persists in `localStorage["agnes_home_setup_minimized"]`
  so the choice survives reloads but is per-device.
- "Show full setup view" (the same button when minimized) re-opens
  both `<details>` and clears localStorage.

When minimized, each `<details>` still has its own native expand/
collapse — click the gray summary bar to peek at one section without
toggling the page-level minimize off.

Tests:
- test_step3_and_connectors_render_flat_when_onboarded_by_default —
  asserts `<details class="setup-collapsible" ... open>` for both
  sections post-onboarding and the absence of any server-rendered
  `data-setup-minimized` attribute on the `.home-mock` root.
- test_minimize_toggle_visible_only_when_onboarded — toggle button
  rendered only when onboarded.

Full pytest holds at 12 pre-existing failures (same set).
2026-05-08 18:28:47 +02:00

201 lines
7.1 KiB
Python

"""v28 migration: instance_templates consolidation + users.onboarded.
Consolidates the v21 welcome_template and v23 claude_md_template singletons
into a generic instance_templates(key, content, ...) table. Adds users.onboarded
boolean for the /home state-aware landing page (default FALSE, explicit signal
required to flip).
"""
import duckdb
from src.db import SCHEMA_VERSION, _ensure_schema, get_schema_version
def test_v28_migration_landed():
"""v28 = home page (instance_templates consolidation + users.onboarded).
The schema version moves on with subsequent migrations (v29 added the
news_template table). This test guards that v28's instance_templates
+ users.onboarded landed and stayed; the exact SCHEMA_VERSION value
is verified in tests/test_db_schema_version.py.
"""
assert SCHEMA_VERSION >= 28
def test_v28_creates_instance_templates(tmp_path):
"""Fresh install at v28 creates instance_templates with three seeded keys."""
db_path = tmp_path / "system.duckdb"
conn = duckdb.connect(str(db_path))
_ensure_schema(conn)
tables = {
r[0]
for r in conn.execute(
"SELECT table_name FROM information_schema.tables "
"WHERE table_schema = 'main'"
).fetchall()
}
assert "instance_templates" in tables, f"instance_templates missing from {tables}"
rows = {
row[0]: row[1]
for row in conn.execute(
"SELECT key, content FROM instance_templates ORDER BY key"
).fetchall()
}
assert set(rows.keys()) == {"welcome", "claude_md", "home"}
assert rows["home"] is None
assert rows["welcome"] is None
assert rows["claude_md"] is None
conn.close()
def test_v28_drops_legacy_template_tables(tmp_path):
"""Fresh install at v28 does NOT have welcome_template or claude_md_template
as separate tables — they're consolidated into instance_templates."""
db_path = tmp_path / "system.duckdb"
conn = duckdb.connect(str(db_path))
_ensure_schema(conn)
tables = {
r[0]
for r in conn.execute(
"SELECT table_name FROM information_schema.tables "
"WHERE table_schema = 'main'"
).fetchall()
}
assert "welcome_template" not in tables, (
f"welcome_template should be dropped post-v28, found in {tables}"
)
assert "claude_md_template" not in tables, (
f"claude_md_template should be dropped post-v28, found in {tables}"
)
# setup_banner (v22 reserved) stays as compat per brainstorm decision
assert "setup_banner" in tables
conn.close()
def test_v28_users_onboarded_column(tmp_path):
"""v28 adds users.onboarded BOOLEAN DEFAULT FALSE."""
db_path = tmp_path / "system.duckdb"
conn = duckdb.connect(str(db_path))
_ensure_schema(conn)
cols = {
r[0]
for r in conn.execute(
"SELECT column_name FROM information_schema.columns "
"WHERE table_name = 'users'"
).fetchall()
}
assert "onboarded" in cols, f"users.onboarded missing from {cols}"
# Insert a user, verify default FALSE
conn.execute(
"INSERT INTO users (id, email) VALUES ('u1', 'a@example.com')"
)
row = conn.execute("SELECT onboarded FROM users WHERE id = 'u1'").fetchone()
assert row[0] is False, "users.onboarded should default to FALSE for new users"
conn.close()
def test_v25_db_migrates_to_v28_preserving_template_content(tmp_path):
"""A v25 DB with content in welcome_template + claude_md_template upgrades
cleanly: rows land in instance_templates, old tables dropped, content
preserved."""
db_path = tmp_path / "system.duckdb"
conn = duckdb.connect(str(db_path))
# Build a minimal v25-shaped DB with the two singletons populated.
conn.execute(
"CREATE TABLE schema_version (version INTEGER, "
"applied_at TIMESTAMP DEFAULT current_timestamp)"
)
conn.execute("INSERT INTO schema_version (version) VALUES (25)")
conn.execute(
"""CREATE TABLE users (
id VARCHAR PRIMARY KEY, email VARCHAR UNIQUE NOT NULL,
name VARCHAR, password_hash VARCHAR,
setup_token VARCHAR, setup_token_created TIMESTAMP,
reset_token VARCHAR, reset_token_created TIMESTAMP,
active BOOLEAN NOT NULL DEFAULT TRUE,
deactivated_at TIMESTAMP, deactivated_by VARCHAR,
created_at TIMESTAMP DEFAULT current_timestamp,
updated_at TIMESTAMP
)"""
)
conn.execute(
"INSERT INTO users (id, email) VALUES ('legacy_user', 'legacy@example.com')"
)
conn.execute(
"""CREATE TABLE welcome_template (
id INTEGER PRIMARY KEY DEFAULT 1, content TEXT,
updated_at TIMESTAMP, updated_by VARCHAR,
CONSTRAINT singleton CHECK (id = 1)
)"""
)
conn.execute(
"INSERT INTO welcome_template (id, content, updated_by) "
"VALUES (1, '<p>legacy welcome</p>', 'admin@example.com')"
)
conn.execute(
"""CREATE TABLE claude_md_template (
id INTEGER PRIMARY KEY DEFAULT 1, content TEXT,
updated_at TIMESTAMP, updated_by VARCHAR,
CONSTRAINT singleton CHECK (id = 1)
)"""
)
conn.execute(
"INSERT INTO claude_md_template (id, content, updated_by) "
"VALUES (1, '# legacy claude md', 'admin@example.com')"
)
_ensure_schema(conn)
# Migration is a one-shot ladder; once v25 runs, the connection lands
# at the current SCHEMA_VERSION (no longer 28 after v29 added the
# news_template table). Assert ≥ 28 so this test stays focused on
# what v28 itself contributed (instance_templates consolidation).
assert get_schema_version(conn) >= 28
rows = {
row[0]: row
for row in conn.execute(
"SELECT key, content, updated_by FROM instance_templates"
).fetchall()
}
assert rows["welcome"][1] == "<p>legacy welcome</p>"
assert rows["welcome"][2] == "admin@example.com"
assert rows["claude_md"][1] == "# legacy claude md"
assert rows["claude_md"][2] == "admin@example.com"
assert rows["home"][1] is None # newly seeded, never had a legacy source
# Old tables gone
tables = {
r[0]
for r in conn.execute(
"SELECT table_name FROM information_schema.tables "
"WHERE table_schema = 'main'"
).fetchall()
}
assert "welcome_template" not in tables
assert "claude_md_template" not in tables
# Existing user backfilled to FALSE per Decision §2 (no PAT-heuristic auto-flip)
onboarded = conn.execute(
"SELECT onboarded FROM users WHERE id = 'legacy_user'"
).fetchone()
assert onboarded[0] is False
conn.close()
def test_v28_migration_idempotent(tmp_path):
"""Running _ensure_schema twice on a fresh DB is a no-op (no duplicate rows,
no errors)."""
db_path = tmp_path / "system.duckdb"
conn = duckdb.connect(str(db_path))
_ensure_schema(conn)
_ensure_schema(conn) # second pass, no error
count = conn.execute("SELECT COUNT(*) FROM instance_templates").fetchone()[0]
assert count == 3
conn.close()