chore(agent): phase roadmap from TODO.md, 7 phases (127-133)

Converts the TODO list into the phased-execution roadmap (Protocol B
append): incremental folder summaries on sync (127), the mobile sync
label with the pinned (n/m) count (128), per-chunk embed progress in
the sync label (129), chat answer clusters with the bottom-right
actions row (130), read(offset/limit) line ranges for huge documents
(131), visible chat image-upload feedback (132), and the garbage-PDF
text gate with the page-screenshot vision fallback (133 — includes
the diagnosed root cause of the hnb guide's pre-phase-126 binary
import). Each phase carries its dedicated in-isolation Playwright
suite; TODO.md is cleared (items now live in .agents/phases/todo/).

LLM-Generated: true
This commit is contained in:
2026-09-27 12:34:16 -04:00
parent bdeea71f5d
commit 0c8018971f
35 changed files with 1207 additions and 8 deletions
@@ -0,0 +1,38 @@
# Phase 127 — Incremental folder summaries: sync rewrites only the directories its changed files touch
**Source:** `TODO.md` L3 — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `app/api/sync.py` — `_run_sync` step 5 (the changed-KB full-regeneration call to `generate_folder_summaries`, the unchanged-walk gap probe, the `_summary_hook` progress closure, the `SyncStatus` phase machine); `app/rag/folder_summaries.py` — `folder_of`, `group_by_folder` (the recursive-subtree concept), `_candidates`, `_stored_keys`, `missing_folder_summaries`, `generate_folder_summaries` (full / `only_missing` modes, manual-row skip, fail-soft, prune pass, `on_progress` hook, "only flushes — the caller commits"); `app/rag/importer.py` — `ImportSummary` (L212, counts only — no path tracking), the `summary.added += 1` / `summary.updated += 1` increment sites (grep them: the text path ~L794, the image path ~L1068, the PDF path ~L1328, ~L1730, ~L1994) and `_prune` (L2015, deletes vanished docs); `scripts/import_docs.py` — the CLI caller (passes no changed set — full regeneration stays its contract); `tests/unit/test_folder_summaries.py`, `tests/unit/test_importer.py`, `tests/unit/test_sync_button.py` — the existing suites to extend; `tests/e2e/test_sync_summary_visibility.py` — the sync E2E pattern (local `kind=local` source fixture, autouse truncate cleanup, mock-only).
## Objective
A KB-changing sync regenerates folder summaries for ONLY the folders affected by the documents that actually changed (each changed document's folder chain up to its source root) — one changed file rewrites a handful of rows, not the whole table. Unchanged folders keep their stored rows byte-identical (text AND `updated_at`). Full regeneration remains available and stays the exact behavior for callers that pass no change set (the CLI, any future full-regen need); the unchanged-walk gap probe is untouched.
## Dependencies
- `126_pdf_support` (complete) — last completed phase; this phase builds on the shipped sync pipeline (phases 32/64/98), the folder-summary generator (phases 94/96/97/98) and the importer.
## Design (shared by all tasks — the executor reads this, not the chat)
- **Change tracking (task 01):** `ImportSummary` gains `changed_paths: list[tuple[str, str]] = field(default_factory=list)` — one `(source, path)` entry per document that was **added, updated, or pruned** in the run, in the order encountered (added/updated in walk order, pruned in `_prune` order). Recorded at EVERY `summary.added += 1` / `summary.updated += 1` site with the site's `(source, rel)` / `(doc.source, doc.path)`, and in `_prune` for each deleted doc (record before `db.delete`). No dedupe needed: a document is added-or-updated at most once per run and pruned docs are gone; the consumer builds a set anyway. `unchanged` / `summary_backfilled` / `dates_updated` NEVER record (their contract is no-regeneration, phase 106/118). The `log()` line is unchanged (the count is derivable: `len(changed_paths) == added + updated + pruned`).
- **Affected keys (task 02):** `app/rag/folder_summaries.py` gains a pure helper `affected_folder_keys(changed: Iterable[tuple[str, str]]) -> set[tuple[str, str]]` — for each `(source, path)`: the source-root key `(source, "")` plus every folder prefix obtained by walking `folder_of` from the document's nearest folder up to `""` (the SAME one concept `group_by_folder` pass 1 uses — a doc under `a/b/` affects `a/b`, `a`, and the root). `generate_folder_summaries` gains `changed_docs: Sequence[tuple[str, str]] | None = None`:
- `None` (default) → today's full regeneration, byte-identical (the CLI path and any explicit full-regen call).
- given → `keys = sorted(set(candidates) & affected_folder_keys(changed_docs))`; the generation loop, the manual-row skip (`kept_manual`), the per-folder fail-soft, and the `on_progress` hook (whose `total` becomes the affected count — the sync status's `summaries_total` then reports the affected count through the existing hook) all run over exactly those keys. An affected folder with NO stored row (a gap in an affected folder) is generated like any other candidate. Missing rows in UNaffected folders stay the unchanged-walk gap probe's job (untouched).
- the prune pass runs in BOTH modes, unchanged (vanished folders' rows are dropped there, manual rows exempt — the phase-97 rule).
- `only_missing=True` (the gap-fill) is untouched and orthogonal.
- **Sync wiring (task 03):** `app/api/sync.py` `_run_sync` step 5, the changed-KB branch only: `generate_folder_summaries(fs_db, llm, changed_docs=summary.changed_paths, on_progress=_summary_hook)`; the unchanged-walk gap probe branch is byte-identical. The module docstring's step-5 description and the `SyncStatus` docstring get updated to the incremental contract. The success log line names the change count (`sync: folder_summaries changed=N stats=…` — the stats dict stays log-only, the detail shape untouched, phase-98 convention).
## Tasks
1. `01_importer_changed_paths.md` — `ImportSummary.changed_paths` recorded at every added/updated/prune site.
2. `02_folder_summaries_affected_mode.md` — `affected_folder_keys` + `generate_folder_summaries(changed_docs=…)`.
3. `03_sync_wiring.md` — the sync's changed-KB branch passes the change set; docstrings + logging.
4. `04_e2e_incremental_sync.md` — dedicated Playwright E2E, run in isolation.
## Testing & Quality
- Unit/integration: every behavior above — the change-set contents/order (all three doc kinds + prune), the affected-keys math (nested folders, roots, multi-source, `#page=`-fragment paths), the generator's changed mode (only-affected upserts, untouched rows byte-identical text AND `updated_at`, manual skip, fail-soft, prune pass, hook total), the CLI no-change path (byte-identical full regen), the sync status's `summaries_total` = affected count.
- Coverage: **>90%** on new/modified code (`app/`).
- E2E: one dedicated Playwright file, run in isolation (`uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov`), mock-only.
## Completion Criteria
- [ ] a one-file change in a folder rewrites exactly that folder's chain (folder + ancestors + source root) — sibling and other-source rows keep their `updated_at` and text
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%
- [ ] `uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (CLI full regen, gap probe, manual rows, phase machine, keep-final-counts)
- [ ] one atomic Conventional Commit with `--no-gpg-sign` per the AGENTS.md git protocol
@@ -0,0 +1,36 @@
# Task 01 — `ImportSummary.changed_paths`: the importer records which documents it changed
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
## Objective
`ImportSummary` carries the identity of every document the run added, updated, or pruned — `(source, path)` tuples — so the sync path can scope the folder-summary regeneration to exactly the folders those documents touch.
## Work
1. `app/rag/importer.py` — `ImportSummary` (L212): add the field with a docstring comment matching the house style:
```python
#: Documents this run ADDED, UPDATED, or PRUNED, as (source, path)
#: tuples in encounter order (added/updated in walk order, pruned in
#: _prune order). Drives the sync's incremental folder-summary
#: regeneration (phase 127): len(changed_paths) == added + updated +
#: pruned. Unchanged / backfilled / date-only refreshes NEVER record.
changed_paths: list[tuple[str, str]] = field(default_factory=list)
```
2. `app/rag/importer.py` — record at every increment site. Grep `summary.added +=` and `summary.updated +=` (currently the text path ~L794/796, the image path ~L1068/1070, the PDF path ~L1328/1330, ~L1730, ~L1994/1996 — the exact set may have shifted; the rule is: **every** site). At each, immediately beside the counter increment, append the site's identity: `summary.changed_paths.append((source, rel))` (the variables each site already has — `source` + `rel` for the index paths; where a site only has the `doc` row, use `(doc.source, doc.path)`).
3. `app/rag/importer.py` — `_prune` (L2015): in the delete loop, for each document that is actually deleted (i.e. NOT skipped by the images-off guard and NOT skipped by the phase-126 embedded-image parent rule), append `(doc.source, doc.path)` to `summary.changed_paths` BEFORE `session.delete(...)` — `_prune` needs the summary passed in (add a `summary: ImportSummary | None = None` parameter, recorded only when given; the existing callers — `import_sources`'s prune call — pass it; any other caller keeping `None` stays byte-identical). Check every existing `_prune` call site and update only the `import_sources` one.
4. `app/rag/importer.py` — do NOT touch `ImportSummary.log()` (the new count is derivable) and do NOT touch the sync's `detail` dict shape (task 03 keeps it log-only).
ASSUMPTION: one entry per changed document is enough (no per-file verb) — the consumer only needs folder keys, and the verb is already in the counters.
## Testing & Quality
- Unit: `tests/unit/test_importer.py` (extend) or a focused new file —
- a walk with 2 added + 1 updated + 1 pruned doc (text files, a temp source dir) → `changed_paths` holds exactly those 4 `(source, path)` pairs, added/updated in walk order, the pruned pair last (or in `_prune` order);
- an images-on run with a changed image file records its `(source, rel)` (the image increment site);
- a PDF run with a changed PDF records its pair (the PDF increment site);
- an unchanged re-run (all `unchanged`) → `changed_paths` empty;
- a backfill/date-only run (phase 118/106 shapes, if covered by existing fixtures) → still empty.
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] `ImportSummary()` default construction gives `changed_paths == []` (no migration of existing construction sites)
- [ ] every `added`/`updated`/`pruned` increment in the importer has a matching `changed_paths` append (a grep audit passes: same count of sites)
- [ ] `uv run pytest tests/unit -q` green; full suite green; no behavior change in completed work
@@ -0,0 +1,51 @@
# Task 02 — `affected_folder_keys` + `generate_folder_summaries(changed_docs=…)`: regenerate only the folders a change touches
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
## Objective
The folder-summary generator can be told the set of changed documents and then regenerates ONLY the candidate folders whose recursive subtree contains at least one of them — the change's folder chain per document, plus each source root — with every existing guarantee (manual skip, fail-soft, prune pass, progress hook) intact.
## Work
1. `app/rag/folder_summaries.py` — new pure helper (place it next to `folder_of` / `group_by_folder`, with a docstring tying it to the recursive-subtree concept):
```python
def affected_folder_keys(
changed: Iterable[tuple[str, str]],
) -> set[tuple[str, str]]:
"""The candidate folder keys a changed-document set invalidates.
For each ``(source, path)``: the source-root key ``(source, "")``
plus every folder prefix of *path* — ``folder_of`` walked from the
document's nearest folder up to ``""`` — the SAME prefix walk
``group_by_folder`` pass 1 uses (one concept): a doc under
``a/b/`` affects ``a/b``, ``a``, and the source root. A
root-level file (``folder_of(path) == ""``) affects ONLY the
source root. Embedded-image fragment paths (``x.pdf#page=…#img=…``,
phase 126) fold into their parent's folder chain with no special
case — ``folder_of`` never sees a ``/`` inside the fragment.
Returns a set; the generator sorts it (deterministic order).
"""
```
Empty input → empty set.
2. `app/rag/folder_summaries.py` — `generate_folder_summaries`: add the kwarg `changed_docs: Sequence[tuple[str, str]] | None = None` (after `only_missing`, before `on_progress` — keyword-only section). Inside, after `candidates = _candidates(_catalog_rows(db))` and the `existing` fetch:
- `keys = sorted(candidates)` stays the full-mode default;
- when `changed_docs is not None`: `keys = sorted(set(candidates) & affected_folder_keys(changed_docs))` — generation is restricted to affected CANDIDATES (a folder that exists in the catalogue but is unaffected keeps its row; an affected folder with no stored row — a gap — is a candidate and gets generated);
- `only_missing=True` keeps its exact current semantics (restricts to missing candidates; the two kwargs are never combined by any caller — document that in the docstring);
- the generation loop, `kept_manual` skip, per-folder `LLMError` fail-soft, and the `on_progress(i + 1, len(keys), source, folder_path)` hook are untouched code — `total` simply becomes the affected count when restricted;
- the prune pass is untouched (runs in both modes, deletes rows for folders that dropped below the minimum, manual rows exempt).
Update the function docstring: the new mode, the one-line contract ("a document's change invalidates exactly its folder chain + source root — the folders whose subtree summary text can change"), and that `changed_docs=None` is the byte-identical full regeneration (the `scripts/import_docs.py` CLI).
3. `scripts/import_docs.py` — verify (do not modify) that the CLI call passes no `changed_docs` — it must stay a full regeneration.
ASSUMPTION: the intersection (`candidates & affected`) is the correct restriction — an affected folder that no longer has any document is handled by the prune pass, not by generation; an unaffected folder's summary cannot change because its subtree's documents and their first-summary-lines are untouched.
## Testing & Quality
- Unit: `tests/unit/test_folder_summaries.py` (extend) —
- `affected_folder_keys`: a root-level file → `{(src, "")}`; `a/b/c.md` → `{(src, ""), (src, "a"), (src, "a/b")}`; mixed multi-source input; an embedded-image fragment path (`img.pdf#page=2#img=0` under `dir/`) → the `dir` chain; empty input → empty.
- `changed_docs=` mode over a seeded catalogue (3 sources, nested folders, a manual row, a failing folder): exactly the affected keys are upserted (fake LLM counts calls — one per non-manual affected key); unaffected rows keep their stored `summary` AND `updated_at` (assert both); manual affected row → `kept_manual`, untouched; a failing affected folder → `failed`, its previous row kept, others still land; the hook fires `len(affected)` times with `total == len(affected)`; the prune pass still drops a vanished folder's row;
- `changed_docs=None` over the same catalogue → the pre-task full-regeneration behavior (all candidates, byte-identical stats shape).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] `affected_folder_keys` is a pure function unit-tested on nested / root / multi-source / fragment paths
- [ ] `generate_folder_summaries(db, llm)` (no new kwarg) behaves exactly as before (existing suite green, unchanged)
- [ ] restricted mode leaves every unaffected row byte-identical (text AND `updated_at`)
- [ ] `uv run pytest tests/unit -q` green; full suite green
@@ -0,0 +1,25 @@
# Task 03 — Sync wiring: the changed-KB branch regenerates only affected folders
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
## Objective
`POST /api/sync` passes the import's change set into the folder-summary generator, so a one-file sync burns `lite` calls only for that file's folder chain. The status phase machine, progress hook, gap probe, and terminal conventions are unchanged in behavior (the hook's `total` now naturally reports the affected count).
## Work
1. `app/api/sync.py` — `_run_sync`, step 5, the CHANGED-KB branch (the `if summary.added + summary.updated > 0:` arm that currently calls `generate_folder_summaries(fs_db, llm, on_progress=_summary_hook)`): pass `changed_docs=summary.changed_paths`. The else arm (unchanged walk → `missing_folder_summaries` gap probe → `only_missing=True`) stays byte-identical, including the no-gap skip's "stays `import`" phase behavior.
2. `app/api/sync.py` — logging: the changed-KB branch's existing `logger.info("sync: folder_summaries stats=%s", folder_stats)` becomes `logger.info("sync: folder_summaries changed=%d stats=%s", len(summary.changed_paths), folder_stats)` (PLAN §9 ample logging — the owner can see how many folders a sync actually rewrote). The gap-fill log line is unchanged.
3. `app/api/sync.py` — docstrings: the module docstring's step-5 paragraph (the "full regeneration" sentence) and the `SyncStatus` docstring's `summaries_done`/`summaries_total` note — update to the incremental contract: on a changed KB the phase runs over the CHANGED set's folder keys (the hook's `total` is the affected count, not the table's candidate count); on an unchanged walk the gap-fill total is the missing count (as before); terminal states keep the final counts (the phase-64 convention, unchanged).
4. Verify: the `detail` dict shape is untouched (no new key — the stats stay log-only, phase-98 convention); `GET /api/sync/status` shape is untouched (the chunk-free status fields are already there; no new fields in this phase).
## Testing & Quality
- Unit/integration: extend the sync unit suite (`tests/unit/test_sync_button.py` and/or the sync-pipeline test file that fakes `import_sources` + `generate_folder_summaries` — inspect the existing fakes first):
- a changed-KB sync (fake import returning 1 updated doc) → `generate_folder_summaries` receives `changed_docs=` equal to the fake's change set (assert on the fake's captured kwargs) and the success detail is unchanged in shape;
- an unchanged walk with a gap → still `only_missing=True`, no `changed_docs` (the gap probe is orthogonal);
- the status during the summaries phase reports `summaries_total == len(affected keys)` (fake generator whose hook total is its key count — follow the existing phase-machine test pattern).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a changed-KB sync calls the generator with `changed_docs=summary.changed_paths`; an unchanged walk calls it exactly as before
- [ ] `GET /api/sync/status` and the success `detail` shapes are byte-identical to pre-phase
- [ ] docstrings + log lines reflect the incremental contract
- [ ] `uv run pytest tests/unit -q` green; full suite green
@@ -0,0 +1,24 @@
# Task 04 — E2E: a one-file change rewrites only that folder's summary chain
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix end to end: after a first full sync, changing ONE file in ONE folder and re-syncing re-stamps exactly that folder's chain (the folder + its ancestors + the source root) and leaves every other stored row byte-identical.
## Work
1. `tests/e2e/test_incremental_folder_summaries.py` (new) — follow `tests/e2e/test_sync_summary_visibility.py`'s house pattern exactly (module-level app fixture over the shared E2E Postgres, host temp-dir `kind=local` source registered via the admin git-sources API, autouse cleanup that truncates `documents`/`chunks`/`query_log`/`steering_notes`/`kb_overview`/`git_sources`/`folder_summaries` and waits for no running sync, mock-only — `E2E_REAL_LLM=1` unsupported). No slow-LLM proxy needed: the assertions are on POST-terminal DB state + the terminal status (the keep-final-counts convention), not on in-flight sampling.
KB fixture — one local source `incsum/` (temp dir) with FOUR folders `alpha/`, `bravo/`, `charlie/`, `delta/`, two markdown docs each, plus one root-level doc: the generator's candidate set is exactly 5 rows (source root + 4 folders — the recursive-subtree ≥ 1 rule).
2. Test → observable mapping (Playwright Mapping Rule):
- `test_first_sync_generates_all_rows` — admin sync #1 settles `success`; the `folder_summaries` table holds exactly the 5 rows (the mock's deterministic `FOLDER_SUMMARY_MODE` canned text names each folder — `tests/e2e/mock_llm.py`'s existing canned reply), each `updated_at` non-null.
- `test_one_file_change_restamps_only_that_folders_chain` — after test 1's state is re-seeded (autouse truncates, so seed again): re-run sync #1, capture each row's `(summary, updated_at)`; then modify ONE doc inside `alpha/` (change its content), sync #2 settles `success`; assert: `alpha` + the source root rows have a NEW `updated_at` (strictly after the captured ones) and the canned text; `bravo`/`charlie`/`delta` rows are byte-identical (same `summary` AND same `updated_at`); the terminal `GET /api/sync/status` keeps `summaries_done == summaries_total == 2` (the affected count — alpha + root, the keep-final-counts convention) and `detail.added/updated/unchanged/pruned` show the single-file change.
- `test_pruned_file_restamps_only_its_chain_and_prunes_the_vanished_folder` — seed + full sync; capture; delete `bravo/`'s LAST doc (the folder vanishes) and modify one doc in `charlie/`; sync settles; assert: the `bravo` row is PRUNED (gone — the prune pass), the source root + `charlie` rows re-stamped, `alpha`/`delta` byte-identical.
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov`), the mock-only gate, the fixture layout, and the test→observable table (the house format).
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's unit/integration coverage bar (>90% on `app/`) is already carried by tasks 01–03; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the three tests above map 1:1 to the TODO's observable: one changed file → a handful of rewrites, not 700+
- [ ] no behavior change in completed phases (the full-regen first sync, the gap probe, the phase machine)
@@ -0,0 +1,32 @@
# Phase 128 — The sync label shows on mobile, count always visible
**Source:** `TODO.md` L4 — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (the item is truncated in the TODO; ASSUMPTION A1 — read as: the running label must be fully visible on mobile, with the `(n/m)` position never clipped off-screen).
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `frontend/index.html` L449–451 — the `#sync-btn` / `#sync-label` markup (one span holds the whole label string); `frontend/assets/sources.js` — `fmtSyncLabel(kind, currentFile, done, total)` (~L650) and `fmtSyncPhaseLabel(status)` (~L669) build the running labels as ONE string, the poll loop applies them to `#sync-label` + the button `title` + `#sync-result` (the aria-live announcer — the untruncated text rides both, A4 convention); `frontend/assets/styles.css` — `.sync-label` (~L2067: `inline-block`, `max-width: min(16rem, 40vw)`, ellipsis, `nowrap`) and the mobile media query (~L5323: `.sync-btn { width: 100%; }`, `.sync-label { max-width: none; min-width: 0; }` — with `max-width: none` the inline-block sizes to its FULL content, so the label's tail — where `(n/m)` lives — runs off-screen: the reported bug); `tests/unit/test_frontend_sync_upload.py` — the pinned frontend label tests to update.
## Objective
On a phone, the running sync label is fully visible: the file path ellipsizes to fit, and the `(n/m)` position sits in its own non-shrinking span that is NEVER clipped — in the import phase (`Syncing… <file> (2/3)`) and the summaries phase (`Summarizing folders… <folder> (n/m)`). Desktop renders the same content with its existing visual layout (the cap, the ellipsis, the title/aria-live untruncated text all preserved).
## Dependencies
- `127_sync_incremental_folder_summaries` (todo) — pipeline order only; code dependencies are the completed phase-64/98 label contract.
## Design (shared by all tasks — the executor reads this, not the chat)
- **Markup (task 01):** `#sync-label` gains two child spans — `<span class="sync-label-main"></span><span class="sync-label-count" hidden></span>` (static markup in `index.html`). The JS builders no longer return one string: a single `setSyncLabel(mainText, countText)` helper writes `textContent` into the parts (the createElement/textContent house rule — no HTML strings) and toggles the count span's `hidden` (absent count → hidden, empty). The FULL untruncated label (`mainText + (countText ? " " + countText : "")`) is still set on the button `title` and `#sync-result` exactly as today (A4 — screen readers hear the whole thing).
- **Label mapping (task 01):** main/count per state — prelude (null phase, no file): main `"Syncing…"`, no count; import: main `"Syncing… <file>"`, count `"(n/m)"` while `total > 0`; overview: main `"Writing KB overview…"`, no count; summaries: main `"Summarizing folders… <folder>"` (no folder part while `current_summary` is null), count `"(n/m)"`; upload: main `"Importing"`, no count (phase-90 contract — the upload status carries no file or counts); idle/settle labels (`"Sync sources"`, `"Synced HH:MM"`): main only. `fmtSyncPhaseLabel`'s decision tree is preserved 1:1 — only the OUTPUT shape changes (string → parts).
- **CSS (task 02):** `.sync-label` becomes a flex row (`display: inline-flex; align-items: baseline; gap: 0.35rem; min-width: 0; max-width: min(16rem, 40vw);`); `.sync-label-main { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }`; `.sync-label-count { flex: 0 0 auto; white-space: nowrap; }`. Mobile media query (the existing block at ~L5323): `.sync-label { max-width: none; flex: 1 1 auto; min-width: 0; }` — the label fills the full-width pill, the main part ellipsizes against the remaining width, the count span stays visible at the right edge. The `#sync-result` mobile clip (visually-hidden) is untouched.
## Tasks
1. `01_label_parts.md` — markup + `setSyncLabel` part builders in `sources.js` (all label states, A4 untruncated text preserved).
2. `02_mobile_css.md` — the flex-part CSS + the mobile media query.
3. `03_e2e_mobile_label.md` — dedicated Playwright E2E, run in isolation.
## Testing & Quality
- Unit: `tests/unit/test_frontend_sync_upload.py` — the pinned label outputs updated to the part shape (main/count per state, the byte-identical label strings where they must hold: prelude, upload, settle); the `title`/`#sync-result` untruncated text pins stay.
- E2E: one dedicated Playwright file, run in isolation, mobile viewport, slow-LLM pattern.
- Coverage: **>90%** on new/modified code (frontend: the JS is covered by the pinned unit tests + the E2E; `app/` untouched this phase).
## Completion Criteria
- [ ] at a phone viewport (390×844) the running label is fully in the viewport — file path ellipsized, `(n/m)` visible — in BOTH the import and summaries phases
- [ ] desktop label visually unchanged (same strings, same cap/ellipsis, same `title`/`#sync-result` untruncated text)
- [ ] `uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov` green in isolation
- [ ] `uv run pytest` (unit + integration) green; no behavior change in completed phases
@@ -0,0 +1,29 @@
# Task 01 — `#sync-label` becomes parts: the file path ellipsizes, the `(n/m)` count is pinned
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
## Objective
The label's string is split into a shrinks-to-fit main part (prefix + file/folder path) and a pinned count part (`(n/m)`), so CSS can ellipsize the path while the position always stays on-screen. Every existing label state keeps its exact rendered text.
## Work
1. `frontend/index.html` (L449–451) — inside `#sync-label`, replace the bare text with the two part spans (the initial text lives in the main span so the pre-JS idle label renders):
```html
<span class="sync-label" id="sync-label"><span class="sync-label-main">Sync sources</span><span class="sync-label-count" hidden></span></span>
```
2. `frontend/assets/sources.js` — one new helper where `fmtSyncLabel`/`fmtSyncPhaseLabel` live (~L650): `setSyncLabel(mainText, countText = "")` — sets `syncLabelMain.textContent = mainText`; if `countText`: `syncLabelCount.textContent = countText`, `syncLabelCount.hidden = false`; else `syncLabelCount.textContent = ""`, `hidden = true`; then sets the UNTRUNCATED full label — `mainText + (countText ? " " + countText : "")` — on `syncBtn.title` and `syncResult.textContent` (the A4 convention: title + aria-live always carry the whole thing). Get the part elements once at `mount` scope (the `querySelector` house pattern; null-guard like `syncLabel`).
- `fmtSyncLabel(kind, currentFile, done, total)` → return the PARTS: `main = currentFile ? `${prefix} ${currentFile}` : prefix` (prefix `"Syncing…"` / `"Importing"` as today), `count = total > 0 ? `(${done}/${total})` : ""`; call `setSyncLabel(main, count)`. The byte-identical full strings hold: `"Syncing…"` (no file), `"Syncing… <file>"` (no total), `"Syncing… <file> (n/m)"`, `"Importing"`.
- `fmtSyncPhaseLabel(status)` → same decision tree (overview / summaries / fall-through), emitting parts: overview → `("Writing KB overview…", "")`; summaries → `(`Summarizing folders…${folder}`, `(${status.summaries_done}/${status.summaries_total})`)` with the folder part omitted while `current_summary` is null (as today) — the count is ALWAYS emitted in this phase (the hook always carries a total); fall-through → the `fmtSyncLabel` parts. The full-string shape is byte-identical to the pre-task strings.
- Every OTHER call site that writes `#sync-label` (idle `"Sync sources"`, settle `"Synced HH:MM"`, the 202/409 click fallback, the re-attach `initSyncButton` path) goes through `setSyncLabel(main)` — count hidden.
- The upload job keeps the bare `"Importing"` (no file, no counts — phase-90 contract).
3. `tests/unit/test_frontend_sync_upload.py` — update the pinned label tests to the part shape: pin the main/count pair per state (prelude, import with/without total, overview, summaries with/without folder, upload, idle, settle) AND the `title` / `#sync-result` untruncated concatenation (the A4 pins).
ASSUMPTION (A1 restated): the truncated TODO item is satisfied by "label fully visible on mobile + count never clipped" — no wrapping, no progress bar.
## Testing & Quality
- Unit: the updated pins above green; no HTML strings anywhere in the label path (textContent only).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] every running/idle/settle label renders the SAME full string as pre-task on desktop (the part concatenation is byte-identical)
- [ ] the count span is `hidden` whenever there is no `(n/m)` to show
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,46 @@
# Task 02 — CSS: the label parts flex — path ellipsizes, count pinned, mobile fully visible
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
## Objective
The label's two parts are laid out so the path can ellipsize against whatever width is available — and on a phone, where the pill is full-width, the path ellipsizes and the `(n/m)` count sits pinned at the right edge, always on-screen.
## Work
1. `frontend/assets/styles.css` — replace the `.sync-label` rule (~L2067, the phase-64 comment block above it stays, updated to name the parts):
```css
.sync-label {
display: inline-flex;
align-items: baseline;
gap: 0.35rem;
min-width: 0;
max-width: min(16rem, 40vw);
}
.sync-label-main {
min-width: 0; /* the flex item that shrinks — what engages the ellipsis */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.sync-label-count {
flex: 0 0 auto; /* NEVER clipped — the (n/m) position is the point */
white-space: nowrap;
font-family: var(--mono); /* the .sync-result mono language (position reads as data) */
}
```
(The old `display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom;` moves to `.sync-label-main` — `vertical-align` is gone: the flex row aligns it.)
2. `frontend/assets/styles.css` — the mobile media query block (~L5323, the "full-width LABELED pills" comment): update the two sync rules:
```css
.sync-btn { width: 100%; }
.sync-label { max-width: none; flex: 1 1 auto; min-width: 0; }
```
— the label now fills the full-width pill; `.sync-label-main` (min-width: 0 inside a flex row that can shrink) ellipsizes against the width left by the pinned count; the count stays visible at the right edge. Do NOT touch the `#sync-result` visually-hidden clip, the `#sync-btn` aria-label, or the other mobile rules in that block.
3. Audit: grep for every `.sync-label` reference in `styles.css` — the only rules are the base + this mobile block (the phase-64/98 history is in comments). Confirm no other stylesheet (theme override, page-scoped) styles the label; the built-in theme must stay byte-identical in the no-row case (B4 — no `ui_settings` dependency here, this is static CSS).
## Testing & Quality
- The visual gate is the E2E (task 03) — desktop vs mobile bounding-box + text assertions; no new Python surface.
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
## Completion Criteria
- [ ] desktop: long paths still ellipsize inside the `min(16rem, 40vw)` cap, count visible after the ellipsis
- [ ] mobile (390 px): label fills the pill, path ellipsized, `(n/m)` on-screen at the right edge (the E2E asserts bounding boxes)
- [ ] `uv run pytest` green; no behavior change in completed phases
@@ -0,0 +1,24 @@
# Task 03 — E2E: the running sync label is fully visible with its count on mobile (and unchanged on desktop)
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the label's geometry: at a phone viewport the rendered `#sync-label` fits the viewport with the `(n/m)` count span visible in BOTH long spans (import + summaries); at a desktop viewport the label keeps its pre-phase strings and cap.
## Work
1. `tests/e2e/test_sync_label_mobile.py` (new) — follow `tests/e2e/test_sync_summary_visibility.py`'s house pattern (module app fixtures over the shared E2E Postgres, host temp-dir `kind=local` source, autouse truncate cleanup, mock-only). Use the SLOW app (the `tests/e2e/slow_llm.py` proxy, `SLOW_DELAY_S = 1.5` as there) so each phase span outlives the UI's 2 s poll — the rendered-label assertions are deterministic, not races.
KB fixture — one local source `synclabel/` with TWO files in `alpha/` and TWO in `bravo/` (the summaries phase then has 3 candidate folders: root + 2 — a non-trivial `(n/m)`).
2. Test → observable mapping (Playwright Mapping Rule):
- `test_mobile_label_fits_viewport_with_count_in_import` — admin page on the sources view at viewport **390×844** (mobile); click **Sync sources**; while the import phase is running (the page's own 2 s poll): the rendered `#sync-label`'s bounding box is INSIDE the viewport (left ≥ 0, right ≤ 390) — the bug's direct negation; `.sync-label-count` is visible (`boundingBox` non-null, not clipped: its right edge ≤ the button's right edge) with text matching `\(\d+/\d+\)` once a file is in flight; `.sync-label-main` carries `Syncing… <file>` (the file part may be visually ellipsized — assert the button `title` carries the UNTRUNCATED label, A4).
- `test_mobile_label_shows_summaries_count` — same mobile viewport; through to the summaries phase: `.sync-label-main` matches `Summarizing folders…` (folder part optional), `.sync-label-count` matches `\(\d+/3\)` and stays visible; settle: the button leaves the running label (`Synced HH:MM` or the phase-32 terminal shape), the count span hidden/empty.
- `test_desktop_label_unchanged` — viewport 1280×800; same sync: during import the FULL rendered label text (main + count concatenation) matches `Syncing… <full source/relative/path> (n/m)` — the pre-phase byte-identical string — and the label's width respects the `min(16rem, 40vw)` cap (bounding box width ≤ 256 px + slack); `title` carries the same untruncated string.
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov`), the mock-only + slow-proxy rationale (re-sized from the phase-98 suite's comment), the fixture layout, the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% bar is carried by task 01's updated unit pins (frontend JS); this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the mobile tests fail against the pre-phase markup/CSS (the count ran off-screen) — i.e. the suite actually pins the fix
- [ ] no behavior change in completed phases (label strings, phase machine, aria-live)
@@ -0,0 +1,36 @@
# Phase 129 — The sync label shows what chunk we're on out of how many
**Source:** `TODO.md` L5 — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (ASSUMPTION A6, owner-confirmed 2026-09-27: "chunk" = the current file's EMBEDDING CHUNKS; position reported at BATCH granularity — `n` = first chunk of the in-flight token-budgeted embed batch — because the transport embeds batches per HTTP call and per-chunk calls would be a latency regression; the summary-chunk embed is excluded from the counter; label `Syncing… <file> (2/3) · chunk 14/38`).
**Story:** n/a (TODO-derived phase, Protocol B append; a NEW feature — distinct from phase 128's mobile fix, per the owner).
**Context:** `app/rag/llm.py` — `LLMClient.embed(texts)` (L346: iterates `self._batch_texts(texts)` — token-budgeted batches, `BOR_EMBED_BATCH_SIZE` cap, `_REQUEST_TOKEN_BUDGET` ≈ 2800 chars), `_embed_batch` (L289: the halving backstop on `_TooLarge`), `self.embed_batches` counter (L249); `app/rag/importer.py` — `import_sources` (L408, the per-file `progress(source, rel, done, total)` hook fired BEFORE each `_index_file`), `_index_file` (L647 — text branch → `_replace_content_chunks`, image branch → `_index_image_file`, PDF branch → `_index_pdf_file`), `_replace_content_chunks` (L603 — chunks the content, `llm.embed([c.content for c in doc.chunks])` in ONE call, token-cap re-chunk retry loop), `_store_summary` (embeds the ONE summary chunk — EXCLUDED from the counter); `app/api/sync.py` — `SyncStatus` (the phase-64/98 progress fields: `current_file`, `files_done/total`, `phase`, `current_summary`, `summaries_done/total`; `_run_sync`'s `_hook` closure convention; terminal-state clearing); `frontend/assets/sources.js` — the phase-128 part builders (`setSyncLabel`, `.sync-label-main` / `.sync-label-count`); `tests/e2e/slow_llm.py` + `tests/e2e/test_sync_summary_visibility.py` — the slow-proxy sampling pattern.
## Objective
While a file is being imported, the sync status (endpoint + button label) shows the file's embedding-chunk position: `Syncing… <file> (2/3) · chunk 14/38` — 14 = the first chunk of the embed batch in flight, 38 = the file's total content chunks. The position climbs through the file's batches and is cleared when the file (or the run) moves on. Everything that passes no callback stays a zero-cost no-op (the CLI, the chat path).
## Dependencies
- `128_sync_label_mobile` (todo) — the label's part structure (`.sync-label-main` + pinned count span) is the carrier; this phase adds the pinned chunk span.
## Design (shared by all tasks — the executor reads this, not the chat)
- **The embed hook (task 01):** `LLMClient.embed(texts, on_progress: Callable[[int, int], None] | None = None)` — before EACH top-level batch request, `on_progress(first_1based, len(texts))` where `first_1based` = 1 + the cumulative chunk counts of the already-sent batches. `None` (every existing caller — the chat retrieval path, `embed_one`, the summarizer, the CLI) is a zero-cost guarded no-op. The `_embed_batch` halving backstop does NOT sub-report — the top-level loop reports batch starts; a halved batch means the position is approximate (document in the docstring; the backstop is rare by construction).
- **Importer plumbing (task 02):** `import_sources(..., on_chunk_progress: Callable[[int, int], None] | None = None)` — a new keyword-only param, plumbed: `import_sources` → `_index_file(..., on_chunk=...)` (all three branches: text, image, PDF — the PDF branch's content embed is the same `_replace_content_chunks` call; the image branch's ONE description-chunk embed reports `1/1` — acceptable, it IS the file's only chunk) → `_replace_content_chunks(..., on_chunk=...)` → `llm.embed([...], on_progress=on_chunk)`. The token-cap re-chunk retry re-embeds with the NEW (smaller-target) chunk list — the hook naturally reports against the new total (no special case). `_store_summary`'s single summary-chunk embed NEVER receives the hook (the counter is content chunks only — no `1/1` noise after the real progress ends). The `scripts/import_docs.py` CLI passes nothing — byte-identical.
- **Sync status (task 03):** `SyncStatus` gains `current_chunk: int = 0` and `chunks_total: int = 0` (documented: the current file's embed-batch position — 0/0 before the first batch and in terminal states). `_run_sync`: reset to 0/0 at run start (with the other progress fields); a closure `_chunk_hook(chunk, total)` (the file's `_hook` convention) sets them; passed as `on_chunk_progress` to `import_sources`. CLEARED (0/0) when the import phase ends — set at the `phase = "overview"` and `phase = "summaries"` transitions AND in both terminal states (the `current_file` clearing points — same convention, same spots). `GET /api/sync/status` exposes both fields (0/0 idle — the dataclass defaults). The `SyncStatus` docstring + module docstring get the chunk-position paragraph (the phase-64/98 style).
- **UI (task 04):** `sources.js` — the import-phase label gains a THIRD pinned part `.sync-label-chunk` (markup in `index.html`'s `#sync-label`, `hidden` by default): when `status.chunks_total > 0` the import fall-through emits `· chunk ${status.current_chunk}/${status.chunks_total}` into it; every other phase/state leaves it hidden/empty (the summaries phase has its own `(n/m)` — no chunk part; the prelude has no file yet). The UNTRUNCATED concatenation (main + count + chunk part) rides the button `title` + `#sync-result` (A4). The pinned unit tests (`tests/unit/test_frontend_sync_upload.py`) gain the chunk-part pins.
## Tasks
1. `01_llm_embed_hook.md` — `LLMClient.embed`'s optional per-batch `on_progress`.
2. `02_importer_chunk_progress.md` — `import_sources` → `_index_file` → `_replace_content_chunks` → `embed` plumbing.
3. `03_sync_status_chunk_fields.md` — `SyncStatus` fields, the closure, clearing, the endpoint.
4. `04_ui_chunk_part.md` — the label's chunk part + unit pins.
5. `05_e2e_chunk_progress.md` — dedicated Playwright E2E, run in isolation.
## Testing & Quality
- Unit/integration: the embed hook's call sequence (batch boundaries, `None` no-op, halving-approximate documented); the importer plumbing (hook fires per file with its own total; the CLI path unchanged; the summary-chunk embed never fires it); the sync status (fields in the endpoint JSON, reset per run, cleared at phase transitions + terminal, 0/0 idle).
- Coverage: **>90%** on new/modified code (`app/`).
- E2E: one dedicated Playwright file, run in isolation, slow-LLM sampling.
## Completion Criteria
- [ ] `GET /api/sync/status` reports `current_chunk` climbing 1 → N with `chunks_total` = the file's true content-chunk count while a file imports (E2E, sampled)
- [ ] the rendered mobile/desktop label shows `· chunk n/m` during the import phase only; the untruncated text rides `title` + `#sync-result`
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%
- [ ] `uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (chat embed path, CLI import, the phase-64/98 label contract minus the new part)
@@ -0,0 +1,28 @@
# Task 01 — `LLMClient.embed`'s optional per-batch `on_progress` hook
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
## Objective
`embed` can report, before each top-level batch request, which chunk of the input list starts that batch — `on_progress(first_1based, total)` — so a caller can render `chunk n/m`. No callback → zero-cost no-op, byte-identical behavior for every existing caller.
## Work
1. `app/rag/llm.py` — `LLMClient.embed` (L346): new keyword-only param `on_progress: Callable[[int, int], None] | None = None`. In the batch loop, BEFORE `await self._embed_batch(chunk)` (and before the try/except, so a failing batch still announced its start):
```python
if on_progress is not None:
on_progress(len(out) + 1, len(texts)) # first chunk of THIS batch (1-based), total
```
(`len(out)` = chunks already embedded in earlier batches — the accumulator's length is exactly that, since each batch's vectors extend it 1:1.)
Docstring: the contract — called once per TOP-LEVEL batch, before the request, with `(first_chunk_1based, total_chunks)`; the `_embed_batch` halving backstop does not sub-report (a halved batch makes the position approximate — documented; the backstop is rare by construction, phase-114 `_TooLarge` handling); `None` is a zero-cost guarded no-op (every pre-task caller — chat retrieval, `embed_one`, the summarizer, the importer — passes nothing and is byte-identical).
2. Do NOT touch `_batch_texts` / `_embed_batch` internals, `embed_batches` counting, or `embed_one`.
## Testing & Quality
- Unit: `tests/unit/` (extend the existing LLM-client test file — inspect `tests/unit/test_llm*.py` first):
- N texts sized to force ≥ 3 batches (shrink the token budget via settings or pick chunk lengths against `_REQUEST_TOKEN_BUDGET`) → `on_progress` called with `(1, N)`, `(k2, N)`, … `total` always `len(texts)`, first-indices strictly increasing, each = previous first + previous batch size (assert against `_batch_texts`'s actual partition — call it directly to get the expected boundaries);
- `on_progress=None` → the call sequence and return value are identical to pre-task (the existing suite is the pin);
- empty `texts` → no hook calls (the early return).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] the hook fires per top-level batch with the correct `(first, total)` pair (unit-pinned)
- [ ] every existing `embed`/`embed_one` call site is untouched and its tests green
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,28 @@
# Task 02 — Importer plumbing: `on_chunk_progress` from `import_sources` to the content-chunk embed
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
## Objective
`import_sources` accepts an optional `on_chunk_progress` callback that fires with the CURRENT FILE's content-chunk position while that file's chunks embed — so the sync status can attribute the position to the file its per-file `progress` hook already named.
## Work
1. `app/rag/importer.py` — `import_sources` (L408): new keyword-only param `on_chunk_progress: Callable[[int, int], None] | None = None` (documented in the docstring next to the `progress` paragraph: same "only when provided — `None` callers pay nothing" rule; it carries the in-flight FILE's chunk position, not the file identity — the per-file `progress` hook owns that).
2. `app/rag/importer.py` — the processing loop's `_index_file` call: pass `on_chunk=on_chunk_progress` (a new keyword-only param on `_index_file`, default `None`).
3. `app/rag/importer.py` — `_index_file`:
- the TEXT branch → `_replace_content_chunks(session, doc=doc, llm=llm, content=content, rel=rel, on_chunk=on_chunk)`;
- the IMAGE branch (`_index_image_file`) and the PDF branch (`_index_pdf_file`) → pass `on_chunk` through to THEIR `_replace_content_chunks` calls (the image branch's one description-chunk embed reports `1/1` — it IS the file's only chunk; the PDF branch's content embed is the primary target). Verify each branch's embed path: if a branch embeds chunks somewhere other than `_replace_content_chunks`, route the hook there too (one hook per branch, content chunks only).
4. `app/rag/importer.py` — `_replace_content_chunks` (L603): new keyword-only param `on_chunk: Callable[[int, int], None] | None = None`, forwarded to `llm.embed([c.content for c in doc.chunks], on_progress=on_chunk)`. The token-cap re-chunk retry loop (the `while True` that halves `target`) re-embeds with the new chunk list — the hook reports against the NEW total automatically (no special case; document it in the docstring). The `doc.chunks = []` empty-content `break` never embeds (no hook fire).
5. `_store_summary` (and its summary-chunk `embed_one`/`embed` call) NEVER receives the hook — the counter is content chunks only (A6: no `1/1` noise after the real progress ends). The `scripts/import_docs.py` CLI passes nothing — byte-identical (verify the call site).
## Testing & Quality
- Unit: `tests/unit/test_importer.py` (extend) —
- a text file that chunks into ≥ 2 batches (size the fixture against the token budget, or monkeypatch `_batch_texts`) with a fake `on_chunk_progress` recorder → the recorder sees `(first, total)` pairs with `total == the file's chunk count`, one batch-run per file, and a SECOND file in the same run gets its OWN sequence (the position restarts per file — the recorder's `(first, total)` pairs never mix the two files' totals);
- the image branch (images toggle on, a fixture image) → the recorder sees exactly `(1, 1)` for that file;
- `on_chunk_progress=None` (the CLI shape) → no recorder, behavior byte-identical (the existing suite is the pin);
- the summary-chunk embed never fires the hook (the recorder's call count == the content-embed batches only).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a multi-batch file's embed position is fully observable through `import_sources(on_chunk_progress=…)` (unit-pinned)
- [ ] the CLI path and the summary-chunk embed are untouched (byte-identical, verified by the existing suite)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,43 @@
# Task 03 — `SyncStatus` chunk fields: `current_chunk` / `chunks_total` on the status endpoint
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
## Objective
`GET /api/sync/status` carries the in-flight file's embed-chunk position (`current_chunk`, `chunks_total`) so the UI can render `· chunk n/m` — reset per run, cleared when the import phase ends, 0/0 idle (the phase-64/98 field conventions).
## Work
1. `app/api/sync.py` — `SyncStatus` dataclass: add
```python
# Phase 129: the current file's EMBED chunk position — the first
# chunk of the in-flight token-budgeted batch and the file's total
# content chunks (the LLMClient.embed hook, batch granularity).
# 0/0 before the first batch, during the prelude/overview/summaries
# phases, and in terminal states.
current_chunk: int = 0
chunks_total: int = 0
```
Update the `SyncStatus` docstring (the phase-64/98 progress-field paragraph) to name the new fields and their clearing contract.
2. `app/api/sync.py` — `_run_sync`:
- run start: `_status.current_chunk = 0`, `_status.chunks_total = 0` (with the other progress-field resets);
- the closure (the file's `_hook` convention — closures capture the module `_status`):
```python
def _chunk_hook(chunk: int, total: int) -> None:
_status.current_chunk = chunk
_status.chunks_total = total
```
passed to `import_sources(..., on_chunk_progress=_chunk_hook)` (alongside the existing `progress=_hook`);
- CLEARING (0/0) at every point the import phase ends — the `_status.phase = "overview"` assignment, the `_status.phase = "summaries"` assignment, and BOTH terminal states (the success and except blocks where `_status.current_file = None` — the phase-64 keep-final-FILE-counts convention does NOT extend to the sub-file chunk position: the file counts survive the terminal for the result line's context, the chunk position is a sub-position of a file that's done — it clears, like `current_file`);
- the unchanged-walk / no-sync-idle paths never set them (defaults 0/0).
3. `app/api/sync.py` — `sync_status` endpoint: add `"current_chunk": _status.current_chunk, "chunks_total": _status.chunks_total` to the returned dict (place them after the `files_*` fields; the dataclass defaults make idle 0/0 with no special-casing). Update the endpoint docstring's field list (the phase-98 paragraph) and the module docstring's status paragraph with the chunk-position contract.
## Testing & Quality
- Unit/integration: extend the sync unit suite (the file that fakes `import_sources` — inspect `tests/unit/test_sync_button.py` and the sync-pipeline test first):
- idle → `current_chunk == 0`, `chunks_total == 0` in the JSON (the dataclass defaults — the endpoint shape test);
- a running sync whose fake `import_sources` invokes `on_chunk_progress(1, 38)` then `(13, 38)` → the status between ticks reports the pair (assert on `_status` directly or via the endpoint through the existing app fixture);
- phase transition to `overview`/`summaries` → the fields are 0/0 again; terminal success/failed → 0/0 while `files_done`/`files_total` keep their final values (the convention split, pinned).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] the status endpoint JSON carries both fields; idle is 0/0; a running import reports the hook's pair
- [ ] the fields clear at phase transitions + terminal states while the file counts keep-final (pinned test)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,25 @@
# Task 04 — The label's chunk part: `Syncing… <file> (2/3) · chunk 14/38`
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
## Objective
The running sync label shows the chunk position as a third pinned part — rendered ONLY while `chunks_total > 0` (the import phase, after the file's first batch), hidden in every other state — and the untruncated full label (main + count + chunk part) keeps riding the button `title` + `#sync-result` (A4).
## Work
1. `frontend/index.html` — `#sync-label` (the phase-128 two-part markup): add the third part after the count span: `<span class="sync-label-chunk" hidden></span>`.
2. `frontend/assets/styles.css` — `.sync-label-chunk { flex: 0 0 auto; white-space: nowrap; font-family: var(--mono); }` (the same pinned-part language as `.sync-label-count` — place it right after that rule; both mono parts read as data).
3. `frontend/assets/sources.js` —
- get the chunk part at `mount` scope (the phase-128 `querySelector` pattern, null-guarded);
- `setSyncLabel(mainText, countText = "", chunkText = "")` — the new third arg: when `chunkText`, set `.sync-label-chunk.textContent` + `hidden = false`, else `""` + `hidden = true`; the UNTRUNCATED concatenation for `title` + `#sync-result` becomes `mainText` + (count? `" " + countText`) + (chunk? `" " + chunkText`) (A4 — the announcer hears the whole `Syncing… <file> (2/3) · chunk 14/38`);
- the import fall-through (the `fmtSyncPhaseLabel` fall-through / the 202/409 click label site — everywhere the import label is emitted with a status): `chunkText = status.chunks_total > 0 ? `· chunk ${status.current_chunk}/${status.chunks_total}` : ""` — every OTHER state (prelude, overview, summaries, upload, idle, settle) passes no chunk text (the part hides): the summaries phase's own `(n/m)` count is its position — no chunk part there;
- the `title`/`#sync-result` set on EVERY running label (the house rule) automatically carries the chunk part via the concatenation.
4. `tests/unit/test_frontend_sync_upload.py` — extend the phase-128 part pins: the import state with `chunks_total > 0` emits the chunk part (`· chunk 14/38` for the fixture values) and the untruncated `title` string is `Syncing… <file> (2/3) · chunk 14/38`; the import state with `chunks_total == 0` (before the first batch) hides the part; every other state's pins stay (the part hidden).
## Testing & Quality
- Unit: the pins above green; textContent-only (no HTML strings in the label path).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] `· chunk n/m` renders only while `chunks_total > 0`; hidden in all other states (unit-pinned)
- [ ] the untruncated full label (with the chunk part) rides `title` + `#sync-result` (A4, unit-pinned)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed phases (phase-128 pins still pass)
@@ -0,0 +1,24 @@
# Task 05 — E2E: the chunk position climbs through a large file's embed batches, endpoint + label
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the feature at both surfaces: the endpoint's `current_chunk` climbs 1 → N with `chunks_total` = the file's true chunk count, and the rendered label shows `· chunk n/m` while the file's embed span runs (then the part clears).
## Work
1. `tests/e2e/test_sync_chunk_progress.py` (new) — house pattern from `tests/e2e/test_sync_summary_visibility.py` (module app fixtures over the shared E2E Postgres, host temp-dir `kind=local` source, autouse truncate cleanup, mock-only, the `tests/e2e/slow_llm.py` proxy).
Sizing (the phase-98 rationale, re-sized for batches): the fixture is ONE local source `chunkprog/` holding ONE large markdown file (`big.md`, ~60 KB, ~30+ chunks at the default target — compute the expected chunk count deterministically in the test by calling `chunk_document` with the app's settings, the same function the importer uses — and assert `chunks_total` equals it) plus ONE tiny second file (the file counter then reads `(1/2)` → `(2/2)`, proving the chunk position restarts per file). `SLOW_DELAY_S` sized so each embed batch outlives the recorder's ~100 ms cadence (the proxy delays EVERY LLM call — embeds included — so the import span is densely sampled).
2. Test → observable mapping (Playwright Mapping Rule):
- `test_endpoint_reports_the_chunk_position` (the slow leg — tight-poll recorder on `GET /api/sync/status`, the phase-64 recorder pattern): while `phase == "import"`: some ticks have `chunks_total == <expected chunk count>` and `current_chunk` strictly climbing from 1 toward `chunks_total` (batch granularity — the sequence's LAST tick before the file ends is `chunks_total` or its final batch's first index; assert the climb + the total, not a contiguous run); while the second (tiny) file is in flight the position restarts (a later tick has `current_chunk == 1` with `chunks_total == 1`); the terminal state has `current_chunk == 0` and `chunks_total == 0` while `files_done == files_total == 2` (the keep-final-file-counts split, the phase-129 convention).
- `test_label_shows_the_chunk_part` (the slow leg — UI, the page's own 2 s poll): at the import span the rendered `#sync-label` parts: `.sync-label-main` matches `Syncing… chunkprog/big.md`, `.sync-label-count` matches `(1/2)`, and at some tick `.sync-label-chunk` is visible matching `· chunk \d+/\d+` with the total == the expected chunk count; the button `title` carries the UNTRUNCATED concatenation (A4 — assert it contains `· chunk` on the same tick); after the file's embed span the chunk part is hidden (`.sync-label-chunk.hidden` true) while the file label continues.
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov`), the mock-only gate, the sizing rationale (why the file is ~60 KB, why the slow proxy's delay doubles as the batch sampler), the fixture layout, the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% `app/` bar is carried by tasks 01–03; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the endpoint's `chunks_total` equals the deterministic `chunk_document` count for the fixture (the total is the file's TRUE chunk count, not a batch count)
- [ ] the chunk part renders only during the import phase and clears at the phase transition/terminal (UI-pinned)
- [ ] no behavior change in completed phases (the phase-64/98 label contract + the keep-final-counts convention hold)
@@ -0,0 +1,36 @@
# Phase 130 — Chat answer clusters: chips row, images row, bottom-right actions cluster
**Source:** `TODO.md` L6 — "The chat output is getting messy. I think it's because the `source-chip`, `source-image`, `tune-btn`, `retry-btn`, and `save-as-doc-btn` end up in the same div which causes them to push each other in weird ways. Those three buttons should be in a button cluster in the bottom right. We don't need to display the `source-chip` for images, just the image itself is fine. `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `frontend/assets/app.js` — `appendSources` (~L1561: builds the FIRST `.msg-meta` row, interleaving a `.source-image` figure after each chip for refs carrying `image_url`), `appendRelated` (~L1618: the "Nearby docs" row, appended LAST among meta rows), `appendSourceImageFigure` (~L1660: the compact figure; on `img` error it removes the figure and the chip remains), `appendAnswerImage` (~L1735: the `.answer-image` figure — appended by callers right BEFORE `appendSources`), `appendTuneButton` (~L484, admin-gated), `appendRetryButton` (~L598), `appendSaveAsDocButton` (~L793, admin + docs-repo gated; `margin-inline-start: auto` pushes it right), `markLastRetryable` (~L620: re-appends the Retry button on the last bubble and re-appends the save button after it — "the auto margins split the free space"), `appendStoppedNote` / `appendFailedNote` (~L520/~L560: join the first `.msg-meta` row); `frontend/assets/styles.css` — the `.msg-meta`, `.source-chip`, `.source-image`, `.tune-btn`, `.retry-btn`, `.save-as-doc-btn` rules (grep each — the auto-margin rules live here); `frontend/index.html` — no chat markup changes expected (the bubble DOM is JS-built); E2E image-KB fixture patterns in `tests/e2e/test_chat_image_questions.py` / `test_image_documents.py` (the mock's `IMAGE_DESCRIPTION_MODE` canned vision reply makes image docs retrievable).
## Objective
A completed brain bubble's metadata reads as organized clusters, top to bottom: the answer text → the answer figure (phase 124, unchanged) → the **source chips row** (text documents only — an image document gets NO chip, just its figure) → the **source images row** (all retrieved image figures) → the "Nearby docs" row (unchanged) → the **actions row** (a right-aligned cluster holding Tune / Retry / Save-as-doc and the Stopped/Failed notes) — never one soup div where buttons push chips around.
## Dependencies
- `129_sync_chunk_progress` (todo) — pipeline order only; code dependencies are the completed chat-render contract (phases 26/49/59/113/120/122/124).
## Design (shared by all tasks — the executor reads this, not the chat)
- **Row structure per brain bubble (top → bottom):** (1) answer text; (2) `.answer-image` figure — the phase-124 position is UNCHANGED (below the text, before the source rows — A3); (3) `.msg-meta` chips row (`role=list`, `aria-label="Sources"`) — one `.source-chip` per NON-image ref; refs with `image_url` contribute NO chip (ASSUMPTION A3 — the figure is the citation for image docs); (4) `.msg-meta.msg-images` images row (`role=list`, `aria-label="Source images"`) — one `.source-image` figure per image ref, in ref order; the row is absent when there are no image refs; (5) `.msg-meta.related-docs` — the phase-113 row, UNCHANGED in content, placed after the images row (ASSUMPTION A4); (6) `.msg-meta.msg-actions` actions row (`role=list`, `aria-label="Answer actions"`) — the ONLY row the action buttons + the stopped/failed notes join (ASSUMPTION A7).
- **Call order at every render site** (the `done` branch, the empty-answer fallback, the stop finalize, the phase-14 restore path): answer image → `appendSources` (now builds the chips row AND the images row) → `appendRelated` → the action buttons/notes. The current "buttons claim the FIRST `.msg-meta` row" behavior is REPLACED — the buttons get-or-create `.msg-actions` instead.
- **Image-load failure (ASSUMPTION A3):** `appendSourceImageFigure`'s `img` error handler replaces the figure IN PLACE with a plain `.source-chip` anchor for that document (same `documentUrl` href, same modal click behavior, the label as text) — the citation survives a lost byte copy; no broken-image icon.
- **Actions row:** one get-or-create `.msg-actions` per bubble (the house pattern). DOM order = Tune, Retry, Save-as-doc (each present per its gate — non-admins see only Retry; a stopped bubble sees the note + Retry). The note (`appendStoppedNote` / `appendFailedNote`) joins this row. `markLastRetryable`'s re-append logic moves the Retry button into `.msg-actions` and DROPS the save-button re-append hack (row-level alignment replaces the per-button `margin-inline-start: auto` — CSS task). ARIA: `role=list` + `role=listitem` on every child (the existing convention).
- **CSS:** `.msg-actions { justify-content: flex-end; }` (the right-aligned cluster — "bottom right" = the bubble's last row, right edge); remove the per-button auto margins (`.save-as-doc-btn`'s `margin-inline-start: auto` + the tune/retry auto margins the `markLastRetryable` comment names); the chips row keeps its wrap; `.msg-images` wraps with the `.msg-meta` gap; the row ORDER is DOM order (no positioning tricks); mobile: rows stack naturally, the actions row stays right-aligned.
## Tasks
1. `01_sources_clusters.md` — `appendSources`/figure split: chips-only row + images-only row, no chip for image docs, the in-place chip fallback.
2. `02_actions_cluster.md` — the `.msg-actions` row: the three buttons + the notes, `markLastRetryable` rework, ARIA kept.
3. `03_css_clusters.md` — the cluster CSS (actions right-aligned, auto margins removed, images row).
4. `04_e2e_clusters.md` — dedicated Playwright E2E, run in isolation.
## Testing & Quality
- Unit: the frontend unit suite — the pinned behaviors that move (the button-row target, the no-chip-for-images rule, the fallback) — inspect `tests/unit/test_frontend_*.py` for the chat-render pins and update them.
- E2E: one dedicated Playwright file, run in isolation, image-KB fixture (text doc + image doc both cited).
- Coverage: **>90%** on new/modified code (frontend: unit pins + E2E; `app/` untouched this phase).
## Completion Criteria
- [ ] a bubble citing a text doc + an image doc renders: chips row (text chip only, NO chip for the image) → images row (the figure) → actions row (bottom right) — asserted in the DOM, not the pixels
- [ ] Tune/Retry/Save-as-doc sit in ONE `.msg-actions` row, right-aligned; non-admin sees only Retry; the restore path renders the identical structure
- [ ] an image whose bytes 404 renders as its plain chip (the citation survives)
- [ ] `uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (chips still open the modal, the related row, the answer figure's position, the ARIA names)
@@ -0,0 +1,26 @@
# Task 01 — Sources split: chips-only row, then images-only row; no chip for image docs
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...We don't need to display the `source-chip` for images, just the image itself is fine. `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
## Objective
`appendSources` stops interleaving figures after chips. It builds the chips row from the NON-image refs only, then (when any image ref exists) a separate images row holding all the figures — chips cluster first, images cluster second, image documents cited by their figure alone.
## Work
1. `frontend/assets/app.js` — `appendSources(wrap, sources)`:
- Partition the refs: `imageRefs = sources.filter(s => s.image_url)`, `textRefs = sources.filter(s => !s.image_url)` (the `image_url` presence is the existing image-doc signal — phase 122).
- CHIPS ROW: build it (the existing `.msg-meta` + `role=list` + `aria-label="Sources"` + per-chip `documentUrl`/modal click/`title`/clipped `aria-label` code) from `textRefs` ONLY. Skip the row entirely when `textRefs` is empty (an image-only citation still gets its images row + the actions row).
- IMAGES ROW: when `imageRefs.length > 0`, build a SECOND `.msg-meta` row — add the `msg-images` class, `role=list`, `aria-label="Source images"` — and append one `appendSourceImageFigure` per image ref (in ref order). No chips in this row.
- Preserve the existing post-build clipped-chip `aria-label` pass (the `scrollWidth > clientWidth` check) over the chips row only.
- The row ORDER in `.msg-body` is: answer figure (appended by the caller before `appendSources`, phase 124 — unchanged) → chips row → images row. `appendRelated` (the next caller) lands after both (task 02's call-order change guarantees the actions row is last).
2. `frontend/assets/app.js` — `appendSourceImageFigure(meta, s)`: the `img` error handler currently does `fig.remove()` (the chip remains — but there is no chip for image docs anymore). Change it to the IN-PLACE CHIP FALLBACK: build a plain `.source-chip` anchor for `s` (the same `documentUrl` href + `title` + left-click → modal handler the chips row uses; `textContent`/`aria-label` = the `source/path` label) and `replaceWith` the figure (the citation survives a lost byte copy — ASSUMPTION A3). The figure's fetch-summary swap is untouched.
3. `frontend/assets/app.js` — `appendRelated`: the related tier's refs ALSO carry `image_url` for image docs (phase 122 — `appendSourceImageFigure(row, s)` is called there today). Keep the related row's own behavior (its chips + figures) — the related row is a separate tier and is NOT reorganized by this phase (ASSUMPTION A4: it stays where it is, below the citation clusters). Do not change `appendRelated`'s chip/figure logic.
## Testing & Quality
- Unit: the frontend unit suite — inspect `tests/unit/test_frontend_*.py` for any `appendSources`/figure pins and update: no chip emitted for an `image_url` ref; the images row is built only when image refs exist; the in-place fallback replaces the figure with a chip (the figure's `img` error path).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a mixed citation (1 text + 2 image refs) renders a 1-chip row then a 2-figure row — no chip for either image
- [ ] an image-only citation renders NO chips row and a figures-only images row
- [ ] a figure whose bytes 404 becomes its plain chip in place (the citation survives)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,23 @@
# Task 02 — The actions row: Tune / Retry / Save-as-doc + the notes in one bottom-right cluster
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...Those three buttons should be in a button cluster in the bottom right."
## Objective
The three action buttons (and the Stopped/Failed notes) stop joining whatever the first `.msg-meta` row happens to be. They get-or-create a dedicated `.msg-actions` row — the bubble's LAST row, right-aligned by CSS (task 03) — so chips and images can never push the buttons around.
## Work
1. `frontend/assets/app.js` — a shared helper next to the button appenders: `getActionsRow(wrap)` — find or create the bubble's `.msg-meta.msg-actions` row inside `.msg-body` (`role=list`, `aria-label="Answer actions"`), the house get-or-create pattern (the same shape as the current "reuse the `.msg-meta` row when it exists" code, but scoped to the `msg-actions` class so it NEVER grabs the chips row).
2. `frontend/assets/app.js` — `appendTuneButton` (~L484), `appendRetryButton` (~L598), `appendSaveAsDocButton` (~L793): replace their "reuse the first `.msg-meta` row" logic with `getActionsRow(wrap)`; keep everything else (the gates, the one-button-per-bubble guards, the icons, the `role=listitem` when the row is `role=list`).
3. `frontend/assets/app.js` — `appendStoppedNote` (~L520) + `appendFailedNote` (~L560): join the actions row via `getActionsRow(wrap)` instead of the first `.msg-meta` row (ASSUMPTION A7 — the notes are answer-status markers; the actions row is their home). Keep the `failed-detail` textContent contract (no HTML from error strings).
4. `frontend/assets/app.js` — `markLastRetryable` (~L620): the retry button is removed from EVERY bubble and re-appended — but now into `getActionsRow(lastBrainWrap)`. DELETE the save-button re-append hack (the `saveDocBtn.parentElement.appendChild(saveDocBtn)` block) — the row's `justify-content: flex-end` (task 03) right-aligns the whole cluster; DOM order inside the row is the insertion order (Tune, Retry, Save-as-doc per their gates). Update the function's comment (the "auto margins split the free space" rationale is gone).
5. Call-order audit: at every site that renders a COMPLETED brain bubble (the `done` branch, the empty-answer fallback, the stop finalize, the phase-14 restore), confirm the order is answer figure → `appendSources` → `appendRelated` → action buttons/notes, so `.msg-actions` is the LAST row (the "bottom right" = the bubble's bottom, right edge). If a site appends actions before `appendRelated`, reorder the calls (the DOM order decides the visual order — no CSS tricks).
## Testing & Quality
- Unit: the frontend unit suite — update the pins that target the button row: the buttons/notes land in `.msg-actions` (not the chips row); `markLastRetryable` moves the Retry button into the actions row and no longer re-appends the save button.
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a bubble with sources + all three buttons renders the actions row LAST, containing exactly the gated buttons (the notes when present)
- [ ] a non-admin bubble's actions row holds only Retry (the gate unchanged)
- [ ] the restore path renders the identical row (a saved chat re-opens with the buttons in `.msg-actions`)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,33 @@
# Task 03 — CSS: the cluster rows (actions right-aligned, auto margins removed, images row)
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...Those three buttons should be in a button cluster in the bottom right. ... `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
## Objective
The cluster layout is CSS: the actions row right-aligns its buttons as a cluster (no per-button auto margins), the images row wraps its figures like the chips row wraps chips, and the rows stack in DOM order with the existing `.msg-meta` rhythm.
## Work
1. `frontend/assets/styles.css` — grep the current button-row rules (`.tune-btn`, `.retry-btn`, `.save-as-doc-btn`, and any `margin-inline-start: auto` on them — the `markLastRetryable`/phase-59 comments name the auto-margin mechanism; `.save-as-doc-btn`'s is explicit in the app.js comment at ~L653). Remove the per-button auto margins (the buttons become plain flex items of the actions row).
2. `frontend/assets/styles.css` — add the cluster rules (place them with the other `.msg-meta` / chip / figure rules — the house grouping):
```css
/* Phase 130: the actions cluster — the bubble's LAST row, right-aligned.
The row's justify does the "bottom right" (no per-button auto margins). */
.msg-meta.msg-actions {
justify-content: flex-end;
}
/* Phase 130: the source-IMAGES cluster — wraps like the chips row. */
.msg-meta.msg-images {
flex-wrap: wrap;
gap: 0.4rem; /* match the .msg-meta chip gap (read the existing value) */
}
```
(Match the EXISTING `.msg-meta` gap/align values — read the rule first; do not invent new spacing values that diverge from the chips row.)
3. Audit: confirm the chips row (`.msg-meta` with `role=list`) and the related row (`.msg-meta.related-docs`) rules are untouched; the `.source-image` figure styles are untouched (they were already sized for a row context); mobile: the rows stack naturally (the `.msg-body` flex gap handles it) — verify in the mobile media query block that no rule pins the actions row left; the actions row stays right-aligned at every width.
## Testing & Quality
- Visual gate: the E2E (task 04) — bounding-box assertions (the actions row's buttons' right edge ≈ the row's right edge; the row is the last `.msg-meta` in the bubble).
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
## Completion Criteria
- [ ] the actions cluster is right-aligned by `.msg-actions` alone (the per-button auto margins are gone — grep confirms)
- [ ] the images row wraps its figures with the chips row's gap
- [ ] `uv run pytest` green; no behavior change in completed phases
@@ -0,0 +1,26 @@
# Task 04 — E2E: the answer renders as organized clusters (DOM-asserted), live + restored
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "The chat output is getting messy. ... Those three buttons should be in a button cluster in the bottom right. We don't need to display the `source-chip` for images ... `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix in the real DOM: a grounded answer citing a text doc AND an image doc renders the chips row (text chip only, NO chip for the image) before the images row (the figure), and the buttons sit in one right-aligned `.msg-actions` row that is the bubble's last row — on the live turn and after a page reload (the phase-14 restore path).
## Work
1. `tests/e2e/test_chat_answer_clusters.py` (new) — house pattern (module app fixture over the shared E2E Postgres, autouse cleanup, mock-only). KB fixture: follow `tests/e2e/test_chat_image_questions.py` / `test_image_documents.py`'s image-KB pattern — a local source with ONE text doc (the mock's grounded-answer trigger, e.g. the existing "use your tools" / read flow that cites a doc) and ONE image doc (the mock's `IMAGE_DESCRIPTION_MODE` canned description makes it retrievable; the done frame's `sources` must carry both refs — the image ref with `image_url`). Inspect those suites first and reuse their fixture builders — do not invent a new mock flow unless the existing done-frame shape cannot cite both docs in one answer (if a new mock trigger is needed, add it to `tests/e2e/mock_llm.py` in the house style: a user-message marker, a deterministic reply, a module-header docstring entry).
Run as ADMIN (the whoami gate — the Tune + Save-as-doc buttons exist; the Retry button exists for everyone) with a configured docs repo (the `docsRepoConfigured` gate for Save-as-doc — follow the existing admin chat E2E setup).
2. Test → observable mapping (Playwright Mapping Rule):
- `test_answer_clusters_render_in_order` — send the question; on `done`: the LAST brain bubble's `.msg-body` direct children include, in order: the `.answer-image` (if the mock offers one — else skip) → a `.msg-meta` chips row containing EXACTLY the text doc's `.source-chip` and NO `.source-chip` for the image doc (assert by the chip's `source/path` label) → a `.msg-meta.msg-images` row containing the image's `.source-image` figure (the `img` loaded, the caption = the canned description/summary) → (the related row, if present) → a `.msg-meta.msg-actions` row that is the bubble's LAST `.msg-meta`, containing the `.tune-btn`, `.retry-btn`, `.save-as-doc-btn` (all three — admin); the actions row's buttons are right-aligned (the rightmost button's bounding-box right edge ≈ the row's right edge, slack for the row padding) and the row's bounding box is BELOW the images row's (the "bottom right" geometry).
- `test_image_without_chip_keeps_its_citation_via_figure` — in the same bubble: the image doc is cited (the figure's `href` = its `documentUrl`, left-click opens the same-page modal — the phase-26 affordance) and there is NO `.source-chip` whose label is the image's `source/path` (the owner's exact ask).
- `test_restore_renders_the_same_clusters` — the turn auto-saves (phase-66); reload the page; the restored last brain bubble has the IDENTICAL structure (chips row text-only, images row, `.msg-actions` last with the gated buttons — the restore path renders through the same appenders).
- `test_non_admin_sees_retry_only_actions` — a second, non-admin browser context on a FRESH chat (no admin cookie): send the same question; the `.msg-actions` row holds ONLY the `.retry-btn` (Tune/Save gated out — the phase-16/59 gates unchanged).
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov`), the mock-only gate, the fixture + mock-trigger notes, the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% bar is carried by tasks 01–02's updated frontend unit pins; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the DOM order assertion (chips → images → actions-last) is pinned for BOTH the live and the restored bubble
- [ ] the suite fails against the pre-phase markup (buttons inside the chips row) — i.e. it actually pins the fix
- [ ] no behavior change in completed phases (modal navigation, the related tier, the ARIA names)
@@ -0,0 +1,51 @@
# Phase 131 — `read` gains line ranges: grep finds the line, read(offset, limit) reads it
**Source:** `TODO.md` L7 — "The agent is struggling with huge documents. It can search for the text it wants and it finds the text, including line number, but then it gets stuck saying 'However, read takes a path, not a line number.' and can't figure out how to read that part of the document. Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck. I have a huge test pdf (the DND player's handbook) in test_sources called 'pdf_tests.tar' that you can use for testing. It's a massive pdf. The question the agent got stuck on was 'What are the components of the find traps spell?' which is toward the end of the players handbook so it will need to search and read specific lines. I've been setting BOR_READ_MAX_CHARS to 24000 to keep things relatively quick so the agent realizes quickly its answer isn't in the first few pages."
(LOCKED A2, owner-confirmed 2026-09-27: the parameter names are `offset`/`limit` — 1-based line number + line count — mirroring the pi-harness `read` tool the model was trained on, the phase-70 "harness-aligned surface" anchor.)
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `app/rag/agent.py` — `AGENT_TOOLS` (L258+: the `ls`/`read`/`grep` pi.dev-shaped schemas; the `read` schema at ~L304 takes ONLY `path`; the `grep` description promises `source/path:line: text` locators), `_execute_tool` (L1266+, the `read` branch at ~L1348: `arg` resolution, the `ALREADY_IN_CONTEXT` dedupe on `holder.read_docs`, the `BOR_READ_MAX_CHARS` truncation with `TRUNCATION_MARKER` + `READ_TRUNCATION_NOTICE` (~L506 — today it points at `grep` and then dead-ends), the `holder.read_truncations` tuples), `AgentHolder` (the `read_docs` / `read_truncations` bookkeeping); `app/rag/llm.py` — `ToolCallPiece` (the `arguments` dict the model sends); `tests/e2e/mock_llm.py` — the scripted tool-call flows (the "use your tools" / multi-read / grep patterns — the module header documents each trigger); `tests/unit/test_agent.py` — the read-branch unit suite (the `ALREADY_IN_CONTEXT` pins, the truncation pins); `test_sources/players_handbook.pdf` (the DND player's handbook from `pdf_tests.tar` — on disk, untracked); `settings.read_max_chars` (`BOR_READ_MAX_CHARS`).
## Objective
The agent stops dead-ending on huge documents: `read` accepts an optional 1-based line `offset` + line-count `limit`, the truncation notice and tool descriptions teach the grep → read(offset/limit) workflow, and the dedupe rules allow the ONE case that matters — re-reading a range of a document whose first read was truncated — while still refusing pointless re-reads of text already in context. The owner's repro (the handbook, "find traps", `BOR_READ_MAX_CHARS=24000`) passes as an integration test.
## Dependencies
- `130_chat_answer_clusters` (todo) — pipeline order only; code dependencies are the completed agent surface (phases 70/72/95/118).
## Design (shared by all tasks — the executor reads this, not the chat)
- **Schema + teaching (task 01):** `read` gains two OPTIONAL integer params — `offset` ("The first line to read, 1-based. Omit it to read from the beginning of the document.") and `limit` ("The maximum number of lines to read. Omit it to read as many lines as fit under the character cap."). `required` stays `["path"]`. The `read` description keeps its existing teaching and GAINS the workflow: for a very large document, use `grep` to find where your text is (it reports line numbers), then `read` that part with `offset` + `limit`; re-reading a document already read in full adds nothing. `READ_TRUNCATION_NOTICE` (L506) is REWRITTEN to end the dead-end: "…The rest is NOT shown. Use grep (pattern) to find what you need — it reports line numbers — then read that part with `offset` (1-based first line) and `limit` (number of lines)." The `grep` description gets the light touch: "read the winner with `read` — for a large document, use the reported line number as `offset`."
- **Execution (task 02):** in `_execute_tool`'s read branch:
- Validation: `offset`/`limit`, when present, must be ints ≥ 1 (NOT bools — the house `isinstance(x, int) and not isinstance(x, bool)` guard); a bad value → a teaching refusal echoing the bad value ("`offset` and `limit` are whole line numbers ≥ 1 — you passed `…`") — counts in nothing, consumes a round (the phase-72 refusal style).
- The dedupe matrix (`known` = the `read_docs` (source, path) set; `truncated` = the set of (source, path) from `holder.read_truncations`):
| call | doc in `known` | previously truncated | result |
|---|---|---|---|
| plain `read(path)` | no | — | full read (truncate at the cap as today) |
| plain `read(path)` | yes | yes | NEW teaching line (no re-emit, no count): "You already have the first {shown} characters of {source}/{path} in your context. To read the rest, find where your text is with grep (it reports line numbers), then call read with `offset` (1-based first line) and `limit` (lines)." — `{shown}` from the matching `read_truncations` tuple |
| plain `read(path)` | yes | no | `ALREADY_IN_CONTEXT` (byte-identical to today) |
| `read(path, offset, limit)` | yes | yes | ALLOWED (the stuck-scenario fix — the range the model names is exactly the part it does NOT have) |
| `read(path, offset, limit)` | yes | no | `ALREADY_IN_CONTEXT` (the full text is already in context — the range is a subset) |
| `read(path, offset, limit)` | no | — | ALLOWED (a range read of an unread doc) |
- `offset > total_lines` (the doc's `len(content.splitlines())`) → teaching refusal: "{source}/{path} is {total_lines} lines long — `offset` {offset} is past the end. Use a smaller offset (grep reports the exact line numbers)." Counts in nothing.
- Result shape: line 1 `Document {source}/{path}:` + line 2 `date: YYYY-MM-DD` stay BYTE-IDENTICAL for plain reads (the E2E mock's `_READ_RESULT_PREFIX` contract); a RANGE read inserts a third line `lines: {offset}-{end} of {total_lines}` (the actual end = min(offset + limit − 1, total_lines); the model sees the true extent), then the image-doc marker (as today), then the slice (`"\n".join(lines[offset-1 : offset-1+limit])`).
- The cap still applies to the SLICE: `len(slice) > settings.read_max_chars` → cut + `TRUNCATION_MARKER` + the (rewritten) notice; the `read_truncations` tuple for a range read is `(arg, cap, len(slice))` — the slice's requested size (documented: for range reads the tuple's `chars_total` is the slice length, not the document's).
- A range read appends the doc to `read_docs` ONCE (the `known` set prevents a re-append) — so a later plain read of a range-read doc is `ALREADY_IN_CONTEXT` (the model has committed to this doc; the range result's `lines:` line told it what it holds).
- **Handbook repro (task 03):** an integration test that imports `test_sources/players_handbook.pdf` as a local source (the mock LLM's deterministic embed/summary fakes — the in-process `tests/fakes.py` pattern; the handbook is ~1.5 MB of text ≈ 1200 chunks — in-process embedding is fast, keep the test under ~60 s) and drives the agent turn "What are the components of the find traps spell?" with `BOR_READ_MAX_CHARS=24000`: a scripted fake (the `test_agent.py` pattern) — round 1 → a `grep` tool call (pattern "find traps"), round 2 (the grep result carries the real line number) → a `read(path, offset=<that line>, limit=40)` call, round 3 → the answer echoing the read result's content (the phase-94 "read document reached the context" echo convention). Assert the echo contains the handbook's actual find-traps text (grep it from the extracted PDF text in the test — do not hardcode the handbook wording).
- **Mock flow + E2E (task 04):** `tests/e2e/mock_llm.py` gains ONE scripted flow (house style — a user-message marker, deterministic reply, module-header docstring entry): the marker `read the lines` → request 1: a `grep` tool call (a canned pattern); request 2 (a `tool`-role grep result with a `source/path:line:` line present): a `read` tool call with `offset` = the parsed line number and `limit` = 30; request 3 (the read result present): the answer "Found it at line N." + the first 80 chars of the read result (the existing read-echo shape). `tests/e2e/test_read_line_ranges.py` (dedicated, in isolation, mock-only): a KB fixture with ONE large doc (> 24000 chars, the marker line `TRAP_COMPONENTS_LINE` near line ~1500), `BOR_READ_MAX_CHARS=24000`; ask a question containing the marker → assert the SSE `tool` frames (grep, then read with `offset`/`limit` args) and the final answer echoing the marker line; a second test: a plain read of the large doc truncates with the REWRITTEN notice (the notice names `offset`/`limit` — assert the `tool_result`/result surface carries it).
## Tasks
1. `01_tool_surface.md` — the schema, the descriptions, the rewritten truncation notice.
2. `02_range_read_execution.md` — the read branch: validation, the dedupe matrix, the slicing, the result shape.
3. `03_handbook_repro.md` — the integration repro (the handbook + the owner's exact question) + the unit matrix.
4. `04_mock_flow_e2e.md` — the mock-LLM `read the lines` flow + the dedicated E2E.
## Testing & Quality
- Unit: the full dedupe matrix (6 rows), the validation refusals, the slice math (boundaries, offset past EOF, 1-line docs), the result shapes (plain reads byte-identical — the existing pins must pass unchanged), the cap on slices.
- Integration: the handbook repro (the owner's scenario, the owner's `BOR_READ_MAX_CHARS=24000`).
- E2E: one dedicated Playwright file, run in isolation, mock-only.
- Coverage: **>90%** on new/modified code (`app/`).
## Completion Criteria
- [ ] `read(path, offset, limit)` returns exactly the named lines with the `lines: a-b of N` header; plain reads are byte-identical to pre-phase
- [ ] a truncated first read followed by a range read SUCCEEDS (the stuck scenario is gone); every other re-read is refused with the teaching
- [ ] the handbook integration test answers the find-traps question from the real PDF text (no hardcoded wording)
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (the grep/ls surfaces, the plain-read contract, the `ALREADY_IN_CONTEXT` full-read refusal)
@@ -0,0 +1,43 @@
# Task 01 — The tool surface: `offset`/`limit` on `read`, the descriptions, the rewritten notice
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. It can search for the text it wants and it finds the text, including line number, but then it gets stuck saying 'However, read takes a path, not a line number.' ... Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck."
## Objective
The model's contract for `read` names the line-range capability (LOCKED A2: `offset`/`limit`, 1-based, pi-harness shape) and the truncation dead-end is rewritten into the working workflow: grep for the line numbers, then read that range.
## Work
1. `app/rag/agent.py` — `AGENT_TOOLS`, the `read` entry (~L304): add to `properties`:
```python
"offset": {
"type": "integer",
"description": (
"The first line to read, 1-based. Omit it to read from the "
"beginning of the document. Use it to read a specific part "
"of a large document — grep reports the line numbers of "
"what you found."
),
},
"limit": {
"type": "integer",
"description": (
"The maximum number of lines to read, starting at offset. "
"Omit it to read as many lines as fit under the character "
"cap. Keep it small — you are reading a part, not the "
"document."
),
},
```
`required` stays `["path"]`.
2. `app/rag/agent.py` — the `read` `description`: keep the existing sentences (the `<documents>`-summaries teaching, the no-re-read rule, the truncation/`grep` paragraph — but REPLACE the truncation paragraph with the workflow): "Very large documents are truncated: you receive the first part plus a TRUNCATED notice naming how many more characters exist. To read the rest: use `grep` (pattern) to find where your text is — it reports line numbers — then call `read` again on the same document with `offset` (1-based first line) and `limit` (number of lines) to read exactly that part. Do not re-read a document you have already read in full — its full text is already in your prompt."
3. `app/rag/agent.py` — `READ_TRUNCATION_NOTICE` (~L506): rewrite the tail (keep the `TRUNCATED — this document is {total} characters; only the first {shown} are in your context. The rest is NOT shown.` opening): "Use grep (pattern) to find what you need — it reports line numbers — then read that part with `offset` (1-based first line) and `limit` (number of lines)."
4. `app/rag/agent.py` — the `grep` `description`: the "read the winner with `read`" sentence becomes "read the winner with `read` — for a large document, use the reported line number as `offset`".
5. `tests/unit/test_agent.py` — update/extend the `AGENT_TOOLS` schema pins: the `read` schema has `offset`/`limit` (integer, optional — `required` is still `["path"]`), the descriptions contain the `offset`/`limit` teaching (the pinned substrings), and `READ_TRUNCATION_NOTICE` names both parameters.
## Testing & Quality
- Unit: the schema/notice pins above green; the `ls`/`grep` schemas' OTHER pins unchanged (byte-identical where not rewritten).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a model reading `AGENT_TOOLS` knows: grep → line number → `read(offset, limit)` (schema + descriptions + notice all agree)
- [ ] the old dead-end sentence ("use grep to locate the rest" with no way to act on the line number) is gone from the notice
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,49 @@
# Task 02 — Range-read execution: validation, the dedupe matrix, the slice, the result shape
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. ... then it gets stuck saying 'However, read takes a path, not a line number.' and can't figure out how to read that part of the document."
## Objective
`_execute_tool`'s read branch executes `offset`/`limit`: it validates the arguments with teaching refusals, applies the six-row dedupe matrix (the truncated-then-range case is the one that must succeed), slices the document's lines, and shapes the result so plain reads stay byte-identical while range reads carry their `lines: a-b of N` extent.
## Work
1. `app/rag/agent.py` — `_execute_tool`, the `read` branch (~L1348): after `arg` is resolved and before the dedupe check, parse the range args:
```python
offset = call.arguments.get("offset")
limit = call.arguments.get("limit")
```
with a helper `_read_range_args(offset, limit)` returning `(ok, error_line, offset, limit)`:
- absent/None → ok, `(1, None)` semantics = plain read (no range);
- present but not `isinstance(x, int) and not isinstance(x, bool)`, or `< 1` → the teaching refusal: "`offset` and `limit` are whole line numbers — pass integers ≥ 1 (you passed offset={offset!r}, limit={limit!r})." (echo the bad values; counts in nothing, consumes a round — the phase-72 refusal style, a new pinned constant `BAD_RANGE_ARGS`);
- ok → the (offset, limit) pair (either may be None — `offset` without `limit` reads to the end, `limit` without `offset` is treated as `offset=1` — document both in the constant's docstring).
2. `app/rag/agent.py` — the dedupe matrix (the phase-131 design table; `truncated_pairs = {(source, path) of holder.read_truncations}` — build it from the holder's tuples, matching on the RESOLVED pair, not the raw arg string):
- plain read + in `known` + truncated → the new pinned teaching line `REREAD_TRUNCATED` ("You already have the first {shown} characters of {source}/{path} in your context. To read the rest, find where your text is with grep (it reports line numbers), then call read with `offset` (1-based first line) and `limit` (lines).") — `{shown}` from the matching tuple; no re-emit, `tool_calls` NOT incremented (a refusal);
- plain read + in `known` + not truncated → `ALREADY_IN_CONTEXT` (the existing byte-identical path — do not touch that constant);
- range read + in `known` + truncated → PROCEED (the fix);
- range read + in `known` + not truncated → `ALREADY_IN_CONTEXT`;
- range read + not in `known` → PROCEED.
(The current code's dedupe check runs on the RAW arg before resolution for speed — keep that fast path for the plain-read `ALREADY_IN_CONTEXT` case; the truncated-set check needs the resolved pair, so it runs after `_resolve_path`, exactly where the `doc` is known. Restructure minimally: the raw-arg fast path handles "plain read + known"; everything else resolves first, then consults the matrix.)
3. `app/rag/agent.py` — the slice + result (after `doc` is resolved and the matrix passed):
- `lines = doc.content.splitlines()`; `total_lines = len(lines)`;
- `offset > total_lines` → the teaching refusal `OFFSET_PAST_END` ("{source}/{path} is {total_lines} lines long — `offset` {offset} is past the end. Use a smaller offset (grep reports the exact line numbers).") — no count;
- `end = min(offset + (limit or 1) - 1, total_lines)`; `slice_lines = lines[offset - 1 : end]`; `slice_text = "\n".join(slice_lines)`;
- `holder.read_docs.append(doc)` (the `known` check already guarantees no duplicate); `holder.tool_calls += 1` (a range read is a successful call — the plain-read convention);
- result: plain read → EXACTLY today's bytes (header, date, marker, content/truncated-content — the existing code path untouched); range read →
```
Document {source}/{path}:
date: YYYY-MM-DD
lines: {offset}-{end} of {total_lines}
{marker}{slice_text}
```
(the `lines:` line replaces the position the marker/`TRUNCATION_MARKER` occupy in the plain read — for a range read the marker line comes after `lines:` exactly as after the date line in the plain read);
- the cap on the slice: `len(slice_text) > settings.read_max_chars` → `slice_text[:cap]` + `\n{TRUNCATION_MARKER}\n{READ_TRUNCATION_NOTICE.format(shown=cap, total=len(slice_text))}` and `holder.read_truncations.append((arg, cap, len(slice_text)))` — for range reads the tuple's `chars_total` is the SLICE's requested size (document in the `AgentHolder.read_truncations` field comment: "for range reads the slice length, not the document's").
4. `tests/unit/test_agent.py` — the full matrix (six rows, each pinned): the six dedupe outcomes; `BAD_RANGE_ARGS` (a float, a string, a bool, a 0, a negative); `OFFSET_PAST_END` (offset = total+1 on a 10-line doc); the slice math (offset=1/limit=None → the whole doc; offset=total → the last line; limit overshoot → `end` clamps to `total_lines`; a 1-line doc; offset past EOF); the result shapes (the plain-read pins pass UNCHANGED — byte-identical; a range read's `lines: a-b of N` line + slice; the cap on a huge slice + the tuple's slice-length `chars_total`).
## Testing & Quality
- Unit: the matrix + the pins above — this task's suite.
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] the six-row matrix is pinned one test per row (the truncated-then-range row PASSES — the stuck scenario's unit proof)
- [ ] plain reads are byte-identical to pre-phase (the existing pins green, unmodified)
- [ ] a range read's result names its true extent (`lines: a-b of N`) and respects the cap
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,30 @@
# Task 03 — The handbook repro: "find traps" on the real D&D player's handbook
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "I have a huge test pdf (the DND player's handbook) in test_sources called 'pdf_tests.tar' that you can use for testing. It's a massive pdf. The question the agent got stuck on was 'What are the components of the find traps spell?' which is toward the end of the players handbook so it will need to search and read specific lines. I've been setting BOR_READ_MAX_CHARS to 24000 to keep things relatively quick so the agent realizes quickly its answer isn't in the first few pages."
## Objective
The owner's exact incident is an integration test: the real `players_handbook.pdf` is indexed, the agent is asked the find-traps question with the owner's `BOR_READ_MAX_CHARS=24000`, and the scripted agent loop performs the grep → read(offset/limit) dance against the REAL document and lands an answer grounded in the handbook's actual find-traps text.
## Work
1. `tests/integration/test_read_line_ranges_handbook.py` (new) — the house integration pattern (inspect `tests/integration/` for the agent-loop test that runs a scripted fake LLM against a real-ish pipeline — `tests/unit/test_agent.py`'s fake-LLM/scripted-rounds pattern is the model; lift it into an integration test that ALSO runs the real PDF extraction + real chunking/embedding fakes from `tests/fakes.py`):
- Fixture: a temp source dir containing `test_sources/players_handbook.pdf` (copy — never mutate the untracked fixture), registered/imported with the REAL importer (`import_sources`, the mock embed/summary fakes — the in-process fakes make the ~1200-chunk embed fast; keep the whole test under ~60 s; if the import is slower, the test may pre-import once at module scope and share it across its tests).
- The scripted fake (deterministic, the `test_agent.py` round pattern):
- round 1 (no tool results yet) → a `grep` tool call, `pattern="find traps"` (lowercase — grep is case-insensitive);
- round 2 (the grep result carries `…:LINE: …find traps…` — parse the REAL line number from the grep result the loop produced, do not hardcode it) → a `read` tool call: `path` = the handbook's `source/path`, `offset` = the parsed line, `limit` = 40;
- round 3 (the read result present) → the answer: the read result's content, verbatim (the phase-94 "the read document reached the context" echo convention — the loop's reply IS the slice).
- Settings: `BOR_READ_MAX_CHARS=24000` (the owner's env — the handbook is far longer, so round 1's plain-read alternative would truncate; the script goes straight to grep, but the setting must be in force for the notice/teaching path to be realistic).
2. Assertions (the observable contract):
- the final answer contains the handbook's REAL find-traps text — derive the expected substring at test time: extract the PDF's text (the phase-126 `extract_pdf_text`), grep it for the find-traps passage in the test itself (the same way the model does), and assert the ANSWER contains that passage's first 60 chars (NO hardcoded handbook wording — the test stays true if the fixture is re-extracted);
- the agent's `read` call carried `offset`/`limit` (assert on the fake's captured round-2 tool call: `offset == the grep-reported line`, `limit == 40`);
- the loop made exactly 3 rounds (grep → range read → answer) with `tool_calls == 2` (the owner's stuck loop made 2 and dead-ended — the fixed loop closes in 3).
3. `tests/integration/test_read_line_ranges_handbook.py` — a SECOND test, the plain-read-first variant: the fake round 1 does a PLAIN `read(path)` (the handbook truncates at 24000 with the rewritten notice), round 2 does `read(path, offset=<grep line>, limit=40)` AFTER a grep — asserting the truncated-then-range matrix row works on the REAL document (the `REREAD_TRUNCATED` teaching is never needed because the model went straight to the range — the matrix row itself is unit-pinned in task 02; here the end-to-end path is the point).
## Testing & Quality
- Integration: this file IS the task's suite (plus task 02's unit matrix).
- Coverage: **>90%** on new/modified code (the test file is covered by the suite run; `app/` changes are task 02's).
## Completion Criteria
- [ ] `uv run pytest tests/integration/test_read_line_ranges_handbook.py -v` green in ~60 s (the owner's scenario passes on the real PDF)
- [ ] the expected text is derived from the fixture at test time (grep the extracted text — no hardcoded handbook wording)
- [ ] the read call's `offset` is the grep-reported line (parsed, not literal)
- [ ] no behavior change in completed phases
@@ -0,0 +1,31 @@
# Task 04 — The mock flow `read the lines` + the dedicated E2E
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. ... Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck."
## Objective
The E2E mock deterministically performs the grep → read(offset/limit) dance, and a dedicated, in-isolation Playwright suite pins the full SSE surface: the `tool` frames carry the range args, the answer is grounded in the large doc's tail, and the truncation notice now teaches the workflow instead of dead-ending.
## Work
1. `tests/e2e/mock_llm.py` — one new scripted flow in the house style (a user-message marker + a module-header docstring entry, exactly like the existing "use your tools" / multi-read / grep flows — read the module header first and match its format):
- Marker: the user message containing `read the lines` (a dedicated trigger — no overlap with the existing grep-flow trigger; if the existing grep flow's trigger could also match, make the new marker more specific, e.g. `read the lines of` — the header documents the exact string).
- Flow (classified by the count of `tool`-role results in the messages, the house pattern):
- 0 results → a `grep` tool call, `pattern="LINE_MARKER"` (a canned constant the fixture doc contains);
- a `tool`-role grep result present (a line matching `^[\w/]+:(\d+):` — parse the FIRST match's line number) → a `read` tool call: `path` = the grep result's `source/path`, `offset` = the parsed line number, `limit` = 30 (structured `tool_calls`, no reasoning — the terminal-shape convention);
- the read result present (a `tool`-role result whose content starts with `Document `) → the forced answer, byte-stable: `Found it at line N.` (N = the offset the model passed — parse it from the `read` call's arguments in the messages) + the first 80 chars of the read result's content (the phase-94 read-echo convention — proves the RANGE reached the model's context).
2. `tests/e2e/test_read_line_ranges.py` (new) — dedicated, in isolation, mock-only, house pattern (module app fixture, temp local source, autouse cleanup):
- KB fixture: ONE large markdown doc `linedoc/big.md` — ~100 KB, generated deterministically in the test (numbered filler lines `Line <i>: …`, so line numbers are exact), with the marker line `LINE_MARKER the trap components are documented here` at a known line ~1500 (far beyond the 24000-char cap — the doc's first 24000 chars hold NO marker);
- app env: `BOR_READ_MAX_CHARS=24000` (the owner's setting — the plain read MUST truncate).
- Test → observable mapping (Playwright Mapping Rule):
- `test_range_read_flow_over_sse` — send a question containing `read the lines` → the SSE `tool` frames, in order: the `grep` call (args `pattern="LINE_MARKER"`), then the `read` call (args: `path` = the doc's `source/path`, `offset` an int == the marker's true line, `limit` == 30 — assert on the frame's args, not a substring); the `done` frame's answer contains `Found it at line <N>` (N == the marker's line) and the marker text's first 80 chars (the read-echo — the range reached the context); NO truncation-notice dead-end (the answer is the grounded echo, not a "I can't read that part" shape — assert the marker text is present).
- `test_plain_read_truncation_notice_teaches_the_workflow` — a SECOND trigger (reuse the mock's existing plain-read flow on this large doc — the `read` of `linedoc/big.md` truncates at 24000): the surfaced truncation (the `tool_result` frame / the result the model sees — assert on the SSE `tool_result` surface per A15) contains the REWRITTEN notice text naming `offset` and `limit` (the pinned substrings `"offset"` + `"limit"` in the notice — the old dead-end wording is gone).
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov`), the mock-only gate, the fixture's determinism (the generated line numbers), the `BOR_READ_MAX_CHARS=24000` rationale (the owner's env), the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% `app/` bar is carried by tasks 01–02; the handbook integration repro by task 03; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the `read` tool frame carries REAL `offset`/`limit` ints (parsed from the grep result — the mock does the owner's exact dance)
- [ ] the truncation notice surfaces the workflow teaching (the dead-end is gone)
- [ ] no behavior change in completed phases (the existing mock flows' triggers still fire unchanged)
@@ -0,0 +1,35 @@
# Phase 132 — Chat image upload: visible "uploading" feedback
**Source:** `TODO.md` L8 — "Uploading an image in the chat provides no feedback to the user. The user clicks the paperclick, selects and image, presses 'send' and then nothing happens. No loading bar, no 'uploading image', no indication. This results in the user spamming 'send' over and over because they think it's frozen. We need to visually show the user's image is uploading."
(A5, owner-confirmed 2026-09-27: the affordance = a spinner + "Uploading image…" in the preview strip AND the Send button disabled with the label "Uploading…" — the double-spam is blocked visually, not just by the internal guard.)
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `frontend/assets/app.js` — `handleSend` (~L2700: the `attachedImage` branch — the `attachUpload` double-fire guard, `await uploadAttachedImage(attachedImage.file)` with NO visual state between the await's start and its resolution, then `image = { path, src, alt }` + `runTurn`), `uploadAttachedImage` (~L2641: the `POST /api/chat-images` multipart — every failure path is an out-of-turn banner + null), `showAttachPreview` / `clearAttachedImage` (~L2680: the strip's reveal/clear — static markup, only `textContent`/`src` move), `setUiState` (the turn-state owner — NOT used for the upload: the upload is a PRE-turn operation, `uiState` stays `idle`, the turn loader must not spin during the upload); `frontend/index.html` L280–322 — the static attach markup (`#attach-preview` with `img` + `.attach-preview-name` + `#attach-remove`; `#send-btn` with `#send-label`); `frontend/assets/styles.css` — the `.attach-preview*` / `.send-btn` rules (the existing `:disabled` styles); `tests/unit/test_frontend_sync_upload.py` or a sibling — the pinned frontend JS unit pattern.
## Objective
Between the user pressing Send and the upload resolving, the UI proves the image is moving: the preview strip shows a spinner + "Uploading image…" (the remove button disabled), and the Send button is disabled with the label "Uploading…". When the upload resolves — success proceeds to the turn exactly as today; failure clears the state and keeps the existing banner + the typed text + the attachment for the retry. No frozen-looking gap, no visible double-send.
## Dependencies
- `131_read_line_ranges` (todo) — pipeline order only; code dependencies are the completed phase-123 attach/upload contract.
## Design (shared by all tasks — the executor reads this, not the chat)
- **State scope (task 01):** the uploading state is the `attachedImage` branch of `handleSend` — from just after the `attachUpload = true` guard until the `attachUpload = false` line (success AND failure paths — the helper never throws). `setUiState` is NOT touched (the upload is pre-turn; `uiState` stays `idle`; the turn's own thinking/streaming feedback starts only when `runTurn` does). The `attachUpload` guard stays exactly as is (the visual state reinforces it — the disabled Send is the user-facing half).
- **Preview strip (task 01):** the static markup gains ONE status element inside `#attach-preview`: `<span class="attach-preview-status" hidden><svg spinner…></svg><span class="attach-preview-status-text">Uploading image…</span></span>`. The JS sets `attachPreview.classList.add("is-uploading")` + un-hides the status + `attachRemove.disabled = true` on entry; on exit it removes the class + hides the status + `attachRemove.disabled = false`. The thumbnail + filename stay visible (the user watches THEIR image uploading).
- **Send button (task 01):** `sendBtn.disabled = true` + `sendLabel.textContent = "Uploading…"` on entry; on exit (both paths) `sendBtn.disabled = false` + `sendLabel.textContent = "Send"` — restored BEFORE the success path calls `runTurn` (the turn's `setUiState("thinking")` then takes over the button as usual) and BEFORE the failure path returns (the banner + editable input + the still-attached image).
- **Reduced motion (task 02):** the spinner animation is still under `prefers-reduced-motion` (the house `@media (prefers-reduced-motion: reduce)` block pattern).
## Tasks
1. `01_upload_state.md` — the static markup + the uploading state in `handleSend` (enter/exit on both paths).
2. `02_css_upload_state.md` — the strip's uploading styles + the disabled Send + reduced motion.
3. `03_e2e_upload_feedback.md` — dedicated Playwright E2E, run in isolation.
## Testing & Quality
- Unit: the pinned frontend JS suite — the state transitions (the strip's class/status/remove-disabled, the Send's disabled/label) on entry, on success exit, on failure exit (the banner path).
- E2E: one dedicated Playwright file, run in isolation, with a route-delayed upload (Playwright `page.route` delaying `POST /api/chat-images`) so the in-flight window is observable.
- Coverage: **>90%** on new/modified code (frontend: unit pins + E2E; `app/` untouched this phase).
## Completion Criteria
- [ ] while the upload is in flight: the strip shows the spinner + "Uploading image…", the remove button is disabled, the Send button is disabled with "Uploading…" (E2E-asserted mid-flight)
- [ ] a second Send press during the flight does nothing (no second upload request — E2E request count)
- [ ] success: the indicator clears and the turn proceeds exactly as pre-phase (the user bubble carries the image); failure: the indicator clears, the banner shows, the text + attachment remain
- [ ] `uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (the phase-123 upload contract, the A5 path-never-bytes rule, the out-of-turn banner)
@@ -0,0 +1,49 @@
# Task 01 — The uploading state: markup + `handleSend` enter/exit on both paths
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. ... We need to visually show the user's image is uploading."
## Objective
The `attachedImage` branch of `handleSend` enters a visible uploading state the moment the upload starts and clears it the moment the upload resolves — success or failure — so the user always sees whether the app is moving.
## Work
1. `frontend/index.html` (L280–284, the `#attach-preview` block) — add the status element INSIDE the strip (after the name span, before the remove button), static + hidden by default (the house "ships hidden" rule):
```html
<span class="attach-preview-status" hidden>
<svg class="attach-preview-status-icon" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.2-8.56"/></svg>
<span class="attach-preview-status-text">Uploading image…</span>
</span>
```
(The spinner arc is the house loading glyph — check `#turn-loader`'s icon for the exact shape and reuse it; the spinner's spin animation is the CSS task. `aria-hidden` on the svg — the text carries the meaning; the strip's `role`/label are untouched.)
2. `frontend/assets/app.js` — get the new elements at module scope with the existing attach-family consts (L313–316, the null-guard pattern): `attachStatus = document.querySelector(".attach-preview-status")`, `attachStatusText` (not needed — the text is static), alongside `attachPreview`/`attachRemove`.
3. `frontend/assets/app.js` — two tiny helpers next to `showAttachPreview`/`clearAttachedImage`:
```js
function enterUploadState() {
if (attachPreview) attachPreview.classList.add("is-uploading");
if (attachStatus) attachStatus.hidden = false;
if (attachRemove) attachRemove.disabled = true;
sendBtn.disabled = true;
sendLabel.textContent = "Uploading…";
}
function exitUploadState() {
if (attachPreview) attachPreview.classList.remove("is-uploading");
if (attachStatus) attachStatus.hidden = true;
if (attachRemove) attachRemove.disabled = false;
sendBtn.disabled = false;
sendLabel.textContent = "Send";
}
```
(The label literals "Send"/"Uploading…" — check the idle label's exact current text in the markup/`setUiState` and match it byte-for-byte; if `setUiState` owns the idle label restore, use its restore helper instead of a literal — inspect first.)
4. `frontend/assets/app.js` — `handleSend`, the `attachedImage` branch (~L2700):
- after the `attachUpload = true;` line, BEFORE `await uploadAttachedImage(...)`: `enterUploadState();`
- on the `attachUpload = false;` line (the helper never throws — this is reached on BOTH success and failure): `exitUploadState();` — the success path then continues to `image = { path, src, alt }` + the rest of the send (the turn's `setUiState` takes the button over); the failure path (`path === null`) returns with the banner shown, the input text intact, and the attachment still attached (the strip is back in its normal preview state — the user can retry or remove).
- Do NOT touch the `attachUpload` guard, the `uploadAttachedImage` helper, or `clearAttachedImage` (the New-chat reset already hides the strip — the uploading class is transient and never persists: if a New chat happened mid-upload, the strip is hidden; the class on a hidden element is harmless, and `exitUploadState` still clears it when the upload resolves).
## Testing & Quality
- Unit: the pinned frontend JS suite (extend `tests/unit/test_frontend_sync_upload.py` or the chat-frontend pin file — inspect what exists): the state transitions — entry sets the class/status/unhides/disables remove/disables Send with "Uploading…"; exit (success) clears everything and restores "Send"; exit (failure) clears everything the same way (the banner is the failure's signal, not the strip's); a second `handleSend` during the flight is a no-op (the existing `attachUpload` guard pin).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] the uploading state is entered exactly once per upload (after the guard, before the await) and exited on BOTH resolution paths
- [ ] `uiState`/`setUiState`/the turn loader are untouched (the upload is pre-turn — the loader spins only when the turn starts)
- [ ] the idle label after exit matches the pre-phase idle label byte-for-byte
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,54 @@
# Task 02 — CSS: the strip's uploading look, the disabled Send, reduced motion
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. ... We need to visually show the user's image is uploading."
## Objective
The uploading state reads as "in motion": the strip's thumbnail dims with a spinning arc + the "Uploading image…" text beside it, and the Send button shows the disabled affordance the app already has for a disabled Send — no new color, no new weight, the existing `--ink-soft`/opacity language.
## Work
1. `frontend/assets/styles.css` — with the other `.attach-preview*` rules (grep the existing block first — read the strip's current layout: the thumbnail, the name, the remove button):
```css
/* Phase 132: the uploading state — the strip proves the image is
moving (the TODO: no feedback → the user spams Send). The
thumbnail dims, the spinner arc spins, the status text stands in
the name's place. */
.attach-preview.is-uploading .attach-preview-img {
opacity: 0.5;
}
.attach-preview.is-uploading .attach-preview-name {
visibility: hidden; /* keep the layout; the status takes its spot */
}
.attach-preview-status {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: var(--ink-soft);
font-size: 0.85rem; /* the strip's small text (match the name's size) */
min-width: 0;
}
.attach-preview-status-icon {
width: 14px;
height: 14px;
flex: 0 0 auto;
animation: spin 1s linear infinite; /* the .sync-icon spinner (the house spin keyframes) */
}
@media (prefers-reduced-motion: reduce) {
.attach-preview-status-icon { animation: none; }
}
.attach-preview.is-uploading .attach-preview-remove {
opacity: 0.5; /* the disabled attribute's visual half (the house :disabled language) */
}
```
(Match the EXISTING values — the strip's font sizes, the `spin` keyframes' name (verify they exist — the `.sync-icon.is-spinning` rule uses `spin`), the disabled-button opacity. If the strip's name span has `overflow: hidden; text-overflow: ellipsis` (a long filename), the status span inherits the row's clamp — verify the "Uploading image…" text never clips at 320 px; if it does, let the status text wrap or ellipsize per the strip's existing pattern.)
2. `frontend/assets/styles.css` — verify the `#send-btn:disabled` rule exists and reads as disabled (the Send is disabled via the `disabled` attribute — the existing rule applies; if the disabled Send currently looks identical to the enabled one, add the house `opacity`/`cursor: wait` there — inspect the current rule first, do not invent a new visual).
3. Theme audit: every value used is a theme variable or a neutral (no raw hex/rgb — the B4 byte-identical built-in theme contract; the status text's `--ink-soft` on the strip's background meets 4.5:1 — the strip's bg is `--bg-soft` or similar, verify the pair's contrast the way the theme phases did).
## Testing & Quality
- Visual gate: the E2E (task 03) — the status is visible mid-flight, the thumbnail is dimmed (an `opacity` computed-style assertion is optional — the visibility of the status text is the pin).
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
## Completion Criteria
- [ ] the uploading strip shows the spinning arc + "Uploading image…" with the dimmed thumbnail (E2E-asserted mid-flight)
- [ ] `prefers-reduced-motion` stills the arc (the house block)
- [ ] the disabled Send reads as disabled (the existing rule, verified)
- [ ] `uv run pytest` green; no behavior change in completed phases
@@ -0,0 +1,25 @@
# Task 03 — E2E: the upload window shows "uploading", blocks the double-send, then the turn proceeds
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. The user clicks the paperclick, selects and image, presses 'send' and then nothing happens. ... This results in the user spamming 'send' over and over because they think it's frozen. We need to visually show the user's image is uploading."
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix: while `POST /api/chat-images` is in flight (route-delayed so the window is observable), the strip shows the uploading state, the Send button is disabled with "Uploading…", a second press produces NO second upload request — and once the upload resolves, the state clears and the turn proceeds exactly as pre-phase.
## Work
1. `tests/e2e/test_image_upload_feedback.py` (new) — house pattern (module app fixture over the shared E2E Postgres, autouse cleanup, mock-only). The app boots with `BOR_IMAGES=1` (the `/api/config` `images: true` gate reveals `#attach-btn` — follow `tests/e2e/test_chat_image_questions.py`'s app env). KB fixture: a minimal local source with ONE text doc (the mock's grounded answer for a plain question — the turn after the upload needs to complete normally).
2. The upload window (Playwright's `page.route`): intercept `POST /api/chat-images` — `route.waitForRequest`-style: the handler DELAYS (e.g. `await asyncio.sleep(2.0)` in the route handler, or `page.route` + a fixture that holds the response) then `route.continue_()` — the server's real handler runs, the response is just late. Count the intercepted upload requests (a module counter) for the double-send assertion. A small PNG fixture (the house test image — reuse the existing one the image E2E suites use; do not commit a new binary if one exists).
3. Test → observable mapping (Playwright Mapping Rule):
- `test_upload_window_shows_uploading_and_blocks_resend` — admin or anonymous (chat is public — anonymous is the simpler context) page on the chat view; click `#attach-btn` → `#attach-file` set_input_files (the small PNG); the strip is revealed (the phase-123 preview — `#attach-preview` not hidden, the thumbnail's `src` set); type a question; click Send. MID-FLIGHT (poll for the state within the delayed window): `#attach-preview` has the `is-uploading` class; `.attach-preview-status` is visible (not hidden) with the text "Uploading image…"; `#attach-remove` is disabled; `#send-btn` is disabled with `#send-label` text "Uploading…". THEN press `#send-btn` twice more (the user's exact spam — the button is disabled so the presses are no-ops; also try an Enter-to-submit while disabled — the form submit's `sendBtn.disabled` guard) → after the window, the upload-request counter is EXACTLY 1 (no double upload, no second turn).
- `test_upload_success_clears_and_turn_proceeds` — the SAME flow, past the window: the `is-uploading` class is gone, `.attach-preview-status` hidden, `#attach-remove` enabled, `#send-label` back to the idle "Send"; the strip HIDEs with the send (the phase-123 contract — the preview clears when the question goes out); the user bubble renders with the attached image (the phase-123 `attachBubbleImage` — the data-URL `img`), and the turn completes (the mock's grounded answer streams to `done` — the brain bubble is non-empty).
- `test_upload_failure_clears_state_and_keeps_the_draft` — a SECOND app/route that FAILS the upload (the route aborts or the handler is pointed at a 413 shape — the simplest: `route.abort("failed")` → `uploadAttachedImage`'s network-drop banner path): mid-flight the uploading state is visible (same assertions); after resolution: the state is CLEARED (no `is-uploading`, Send re-enabled with "Send"), the out-of-turn banner is shown ("Couldn't attach the image — try again." — the network-drop copy), the input text is INTACT, and the strip is back in its normal preview (the attachment remains for the retry — `#attach-preview` not hidden, no `is-uploading`).
4. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov`), the mock-only gate, the route-delay rationale (the in-flight window is otherwise ~50 ms — unsamplable), the fixture notes, the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% bar is carried by task 01's unit pins; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the mid-flight assertions are deterministic (the route delay makes the window ≥ 2 s — the UI's no-poll direct state, asserted by waiting for the class, not a race)
- [ ] exactly ONE upload request per Send-press sequence (the spam is visibly AND functionally dead)
- [ ] no behavior change in completed phases (the phase-123 upload contract, the A5 path-never-bytes rule, the out-of-turn banner)
@@ -0,0 +1,43 @@
# Phase 133 — Garbage PDF text is detected; the page-screenshot vision fallback extracts it
**Source:** `TODO.md` L9 — "test_sources/hnb_2026_guide.tar.gz contains a pdf that is being read as binary. Figure out why. It contains images, tables, and text but none of that is being extracted correctly. Instead, the raw xml is being embedded and the preview shows the entire document as lines like `<illustrator:StartupProfile>Web</illustrator:StartupProfile>`. This project should support this kind of PDF and should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
**FINDING (diagnosed 2026-09-27, before phase authoring — the evidence, verified against the real fixture):**
1. The archive holds ONE file: `HBI-2026-Guide-Year-Round_260704_131221.pdf` (6.2 MB, 48 pages, PDFium-produced, **Adobe Illustrator export** — the raw bytes carry 222 × `illustrator:StartupProfile` + 138 × `<x:xmpmeta` uncompressed XMP blocks).
2. The CURRENT code (phase 126 onward) extracts it CORRECTLY: `extract_pdf_text` returns 2,585 lines, **0 XML-ish**; a full real-importer run stores clean content (`---PAGE-N---` blocks, "2026 U.S. Benefits Guide" first page), the title, and vision-described embedded images.
3. The garbage the owner saw is the **pre-126 import**: `pdf` was already in `BOR_IMPORT_EXTENSIONS` in the local `.env` (untracked — predates the parser) BEFORE `126_pdf_support` shipped (commit `e0f11e7`, 2026-09-27 09:36). The generic text path (`importer.py` L689: `read_text(encoding="utf-8", errors="replace").replace("\x00", "")`) read the raw PDF bytes — the uncompressed XMP/structure blocks survive as literal text (reproduced: 138,170 non-empty lines, **46% XML-ish** — `<</Pages 2 0 R /Type/Catalog>>`, `<illustrator:StartupProfile>Web</…>`, exactly the owner's preview) — and that garbage was chunked + embedded.
4. **Production fix is a re-sync**: the importer's content-hash delta sees the old garbage row's digest ≠ the newly extracted text's digest → the next sync re-indexes the file as `updated` with clean content (deploy phase 126 first — it is already on `main`). No migration needed. This is documented here, not a code task.
**Story:** n/a (TODO-derived phase, Protocol B append).
**Context:** `app/rag/pdf.py` (phase 126 — `extract_pdf_text` (L109, `page.get_text("text")` per page, `PAGE_SEPARATOR` blocks, fail-soft `""`), `extract_pdf_images` (L145), the fitz import); `app/rag/importer.py` — `_index_pdf_file` (the phase-126 PDF branch: extract → doc row → digest over extracted text → chunk + embed → lite summary → embedded images via `_describe_or_skip` (L1779)); `app/rag/summarizer.py` — `describe_image` (L208: ONE chat-model call, multimodal user message, `data: bytes` + `mime`, returns `str | None`, no app-level retry); `ImportSummary` (L212, the stats counters + `log()` line); `tests/e2e/mock_llm.py` — the `IMAGE_DESCRIPTION_MODE` canned vision reply (deterministic for the E2E); `test_sources/hnb_2026_guide.tar.gz` (the untracked fixture, 2.6 MB compressed).
## Objective
Two guarantees, one for today and one for the class of problem: (a) the owner's guide is pinned as a regression — it imports through the real pipeline with CLEAN content (the root cause is documented above: a pre-126 binary-text import, self-healed by a re-sync); (b) any future PDF whose extracted text is GARBAGE (XML/binary soup, empty text layer) is DETECTED by a deterministic gate and falls back to the owner's specified path — every page rendered to a screenshot and read by the vision model, preserving what the text layer couldn't.
## Dependencies
- `132_image_upload_feedback` (todo) — pipeline order only; code dependencies are the completed phase-126 PDF pipeline + the phase-122 vision path.
## Design (shared by all tasks — the executor reads this, not the chat)
- **The gate (task 02):** `app/rag/pdf.py` gains `is_usable_pdf_text(text: str) -> bool` — pure, deterministic, unit-testable. Unusable when ANY of: `text.strip() == ""` (the empty text layer — the fallback's other target); the fraction of non-empty lines that look like XML is ≥ 0.30 (a line is XML-ish: `re.search(r"</?[A-Za-z_][\w:.-]*[\s/>=]", line)` — covers `<tag>`, `</tag>`, `<tag attr=`, and the PDF-structure `<</Key…` noise); the non-printable fraction (U+FFFD replacement chars + C0 control chars, over the whole text) is ≥ 0.05 (the binary-soup signal — the pre-126 read is 46% XML-ish AND heavy on U+FFFD; a real document about XML with ≥ 30% tag-like lines is a documented false-positive cost — ASSUMPTION A8). Applied in `_index_pdf_file` AFTER `extract_pdf_text` (the extractor stays pure).
- **The fallback (task 03):** when the gate fails, `_index_pdf_file` takes the owner's specified path — "screenshotting the pages and reading each one as an image": `app/rag/pdf.py` gains `render_pdf_pages(pdf_path: Path, dpi: int = 150) -> list[bytes]` (one PNG per page, PyMuPDF `page.get_pixmap(dpi=dpi).tobytes("png")`, in page order; an unreadable page → a zero-byte entry the caller replaces with the placeholder — no page index may shift); for each page, `describe_image(llm, data=png, mime="image/png")` — the phase-122 vision call, fail-soft per page (`None` → the placeholder line). The stored `content` = `PAGE_SEPARATOR` blocks of the page descriptions (`---PAGE-N---\n<description or "page N — description unavailable">`) — the SAME separator convention as the text path, so the chunker's page-boundary handling works unchanged. `is_image` stays `False` (it is a PDF document whose content happens to be vision text). The digest is over the constructed content (the phase-126 convention — the fallback output is stable for a stable file, so re-syncs don't re-burn vision: a cached row re-imports as unchanged). ONE loud log line (PLAN §9): `pdf: text layer unusable for <source>/<path> (xml_frac=… nonprint=…) — falling back to N page screenshots`. `ImportSummary` gains `pdfs_screenshotted: int = 0` (the counter + the `log()` field; the sync `detail` shape stays untouched — the stats log-only convention).
- **The regression pin (task 01):** the real guide, imported through the REAL importer (the fake LLM with a multimodal `chat` override for the embedded images), must land clean content — 0/low XML-ish fraction + the real first-page text present. The fixture stays the tar.gz (the test extracts it into `tmp_path` — never the repo, `test_sources/` is untracked).
## Tasks
1. `01_diagnosis_regression_test.md` — the FINDING is documented in this overview; the task pins the real guide's clean import as a regression integration test.
2. `02_pdf_text_gate.md` — `is_usable_pdf_text` (the heuristic) + the pre-126-garbage reproduction fixture.
3. `03_page_screenshot_fallback.md` — `render_pdf_pages` + `_index_pdf_file`'s fallback branch + the stats counter.
4. `04_e2e_garbage_pdf.md` — dedicated Playwright E2E, run in isolation (the real guide's happy path + a synthetic garbage PDF's fallback path).
## Testing & Quality
- Unit: the gate (clean text, the REAL pre-126 garbage string — reproduced by reading the fixture with the old `errors="replace"` recipe, XML-heavy text, empty text, a borderline document about XML); `render_pdf_pages` (page count, PNG magic bytes, the zero-byte unreadable-page placeholder); the fallback content assembly (separators, placeholders, the digest stability).
- Integration: the real-guide regression (task 01).
- E2E: one dedicated Playwright file, run in isolation, mock-only (the `IMAGE_DESCRIPTION_MODE` canned reply is the fallback's vision surface).
- Coverage: **>90%** on new/modified code (`app/`).
## Completion Criteria
- [ ] the real guide imports with clean content through the real pipeline (the regression test green — the owner's exact file)
- [ ] a PDF whose text layer is XML/binary garbage (synthetic) lands with the vision-described page content — the owner's specified fallback fires end to end
- [ ] a clean PDF NEVER burns a single vision call for the fallback (the gate is the only gate — the happy path is byte-identical to phase 126)
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov` green in isolation
- [ ] no behavior change in completed phases (the phase-126 clean-PDF path, the image pipeline, the sync)
- [ ] the production stale row is fixed by a re-sync (documented above — verify post-deploy: the guide's content no longer shows XML lines)
@@ -0,0 +1,30 @@
# Task 01 — The regression pin: the real guide imports CLEAN through the real pipeline
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "test_sources/hnb_2026_guide.tar.gz contains a pdf that is being read as binary. Figure out why. ... This project should support this kind of PDF and should be able to extract it correctly"
## Objective
The owner's exact file is a permanent regression: importing `test_sources/hnb_2026_guide.tar.gz`'s PDF through the REAL importer (extraction, digest, chunking, summary, embedded images) lands CLEAN content — the pre-126 XML-garbage import can never come back, and the phase-126 happy path on this 48-page Illustrator PDF is pinned.
## Work
1. `tests/integration/test_pdf_hnb_guide_regression.py` (new) — the house integration pattern (the local compose Postgres, the `tmp_path` fixture, the `tests/fakes.py` `FakeEmbedder`):
- Fixture: extract `test_sources/hnb_2026_guide.tar.gz` into `tmp_path` (the test's local source dir — `test_sources/` is untracked, the tar.gz is the stable reference; the extraction is ~6 MB, seconds). The inner file keeps its name (`HBI-2026-Guide-Year-Round_260704_131221.pdf`).
- The fake LLM: `FakeEmbedder` with (a) `settings = Settings(_env_file=".env")` (the real extension set — `pdf` is in the owner's live config; a `_env_file=None` fake would silently skip the PDF — the exact trap that hid this class before) and (b) a `chat` override that returns a deterministic string for MULTIMODAL user content (the `list`-of-parts shape `describe_image` sends — the fake's string-only `chat` crashes on it; the override: `"A rendered page of the guide (test vision description)."` — the docstring names it as the task-03-style vision mock the `fakes.py` comment anticipates).
- Import with `import_sources([dir], llm)` (the real walk + the real PDF branch).
2. Assertions (the observable contract):
- `summary.added == 1` (the guide PDF) — the file is ADMITTED by the walk and indexed through the PDF branch (not the text branch: if the text branch ever ran on it again, the content assertions below fail);
- the stored `content` is CLEAN: the XML-ish line fraction (< the task-02 gate's 0.30 threshold — assert < 0.05 to be strict: the real extraction is 0/2,585) AND the non-printable fraction < 0.01;
- the real first-page text is present: `"2026 U.S. Benefits Guide"` in `content` (pinned fixture text — the file is a stable untracked fixture; if the owner ever re-cuts it, the test failure names the regression, which is the point);
- `is_image is False`, `title == "HBI-2026-Guide-Year-Round_260704_131221"` (the stem fallback — the PDF's metadata carries no title, only PDFium creator/producer), the content starts with `---PAGE-1---`;
- the embedded-image docs (the phase-126 `#page=…#img=…` rows) got the FAKE vision description (the multimodal `chat` was called — assert `llm.chat_calls` contains ≥ 1 multimodal message) or are absent when the fake "fails" (not this test's scope — the fail-soft is the phase-126 contract).
- Wall-time guard: the test completes in < 120 s (48 pages × in-process fakes; if it drifts, the test is too heavy — the suite must stay fast).
3. Header docstring: the FINDING summary (the pre-126 root cause in two lines — see the phase overview's FINDING block), the run command (`uv run pytest tests/integration/test_pdf_hnb_guide_regression.py -v`), the fixture provenance.
## Testing & Quality
- Integration: this file IS the task's suite.
- Coverage: **>90%** on new/modified code (test-only task — the bar is carried by the suite run).
## Completion Criteria
- [ ] `uv run pytest tests/integration/test_pdf_hnb_guide_regression.py -v` green (DB up: `podman compose up -d db`)
- [ ] the test fails if the PDF is ever routed through the text branch again (a temporary experiment moving the branch order must break it — the pin has teeth)
- [ ] the test does not commit the extracted PDF (it lives in `tmp_path`; `git status` stays clean of binaries)
- [ ] no behavior change in completed phases
@@ -0,0 +1,54 @@
# Task 02 — `is_usable_pdf_text`: the deterministic garbage gate
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
## Objective
A pure, deterministic predicate decides whether an extracted PDF text layer is real content or garbage (the pre-126 XML/binary soup class, the empty text layer class) — so the screenshot fallback has exactly one trigger, unit-testable without any PDF.
## Work
1. `app/rag/pdf.py` — new module-level predicate (place it after `extract_pdf_text`, with a docstring citing the FINDING — the pre-126 `read_text(errors="replace")` soup, the 46%-XML-ish reproduction, the owner's `<illustrator:StartupProfile>` preview):
```python
#: A line "looks like XML" when it carries a tag-shaped token — the
#: pre-126 garbage's signature (raw XMP blocks, PDF-structure noise).
_XMLISH_LINE_RE = re.compile(r"</?[A-Za-z_][\w:.-]*[\s/>=]")
def is_usable_pdf_text(text: str) -> bool:
"""Whether an extracted PDF text layer is REAL content (not garbage).
Unusable (→ the page-screenshot fallback) when ANY of:
* ``text.strip() == ""`` — the empty text layer (a scanned/image-
only PDF has nothing to read);
* ≥ :data:`XMLISH_LINE_FRACTION` (0.30) of the non-empty lines
match :data:`_XMLISH_LINE_RE` — the raw-XMP / binary-soup
signature (the FINDING's reproduced pre-126 read is 46%);
* ≥ :data:`NONPRINT_CHAR_FRACTION` (0.05) of all characters are
non-printable (U+FFFD replacement chars + C0 controls) — the
``errors="replace"`` binary-soup signal.
Pure + deterministic (no PDF, no I/O) — the unit tests pin the
thresholds against the REAL reproduced garbage string, not a
hand-drawn one. A real document ABOUT xml whose tag-like lines
reach 30% is a documented false positive (ASSUMPTION A8 — the
fallback still extracts it correctly via vision; the cost is a
few vision calls).
"""
```
with the two threshold constants (`XMLISH_LINE_FRACTION = 0.30`, `NONPRINT_CHAR_FRACTION = 0.05`) — named, documented, not magic. Non-empty-line counting: `line.strip()` truthy (house convention); the non-printable set: `"\ufffd"` + `unicodedata.category(ch).startswith("C")` (or an explicit C0 range check — pick one, document it; exclude the structural `\\n`/`\\t` the extractor legitimately emits — Cc category would catch them, so use the explicit set: `"\ufffd"` + control chars EXCEPT `\\t\\n\\r` — document the exclusion).
2. `tests/unit/test_pdf.py` (extend — the phase-126 suite) — the gate's pins:
- clean text (a few real paragraphs + the `---PAGE-N---` separators) → `True`;
- THE REAL GARBAGE: reproduce the pre-126 read in the test — read `test_sources/hnb_2026_guide.tar.gz`'s PDF (extract to `tmp_path` — share a module-scoped fixture with the integration test's pattern, or a smaller inline reproduction: the test may instead read the tar.gz's PDF bytes with `read_text(errors="replace").replace("\\x00", "")` and pin `is_usable_pdf_text(garbage) is False` — the REAL string, the owner's exact file, the airtight pin);
- the empty text layer (`""` / whitespace) → `False`;
- an XML-heavy layer (≥ 30% tag-like lines) → `False`;
- a borderline document ABOUT xml (29% tag-like lines, printable) → `True` (the threshold's edge, from below) and 31% → `False` (from above);
- the U+FFFD-heavy soup (5%+ replacement chars, few tags) → `False` (the second signal fires alone);
- the structural `\\n`/`\\t` exclusion (text full of newlines/indents is printable).
## Testing & Quality
- Unit: the pins above — this task's suite.
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] `is_usable_pdf_text` is pure (no PDF dependency) and pinned on the REAL reproduced garbage string (the owner's file, not a lookalike)
- [ ] both failure signals (XML-ish fraction, non-printable fraction) are tested independently
- [ ] the thresholds are named constants with the false-positive cost documented
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,51 @@
# Task 03 — The screenshot fallback: unusable text layer → render pages, read each by vision
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
## Objective
When the gate (task 02) says the text layer is garbage or empty, `_index_pdf_file` takes the owner's specified path: every page is rendered to a PNG screenshot and read by the vision model — the stored content is the page-anchored descriptions, so tables/images/whatever the text layer lost are preserved as the model saw them on the page.
## Work
1. `app/rag/pdf.py` — new pure renderer:
```python
def render_pdf_pages(pdf_path: Path, dpi: int = 150) -> list[bytes]:
"""Render every page of *pdf_path* to a PNG (page order, 1-based
meaning — list index i is page i+1).
The fallback's visual input (ASSUMPTION A8: fixed 150 DPI — the
balance of vision legibility vs data-URL payload; a page that
cannot be rendered yields b"" (the caller's placeholder — the
page index NEVER shifts, so ---PAGE-N--- stays truthful).
A file that cannot be OPENED yields [] (the caller's existing
empty-content path — the doc lands with the no-extractable-text
behavior, unchanged).
"""
```
PyMuPDF: `page.get_pixmap(dpi=dpi).tobytes("png")` per page, per-page try/except (the `extract_pdf_text` fail-soft style — log a warning per skipped page).
2. `app/rag/importer.py` — `_index_pdf_file`: after `content = extract_pdf_text(full_path)`, insert the gate branch (BEFORE the doc-row upsert, so the digest/chunk/summary pipeline runs on the FINAL content exactly once):
```python
if not is_usable_pdf_text(content):
summary.pdfs_screenshotted += 1
content = await _fallback_page_screenshots(session, source=source, rel=rel,
full_path=full_path, llm=llm)
```
with the new module-level helper `_fallback_page_screenshots` (place it near `_index_pdf_file`):
- `pages = render_pdf_pages(full_path)`;
- the loud one-line log (PLAN §9, the FINDING's signature): `logger.warning("pdf: text layer unusable for %s/%s — falling back to %d page screenshots", source, rel, len(pages))` (the gate's fractions ride the log at DEBUG: `logger.debug("pdf: gate xml_frac=%.2f nonprint=%.2f …")` — computed by a small `_gate_fractions(text)` helper the unit tests pin too, if the warning wants them — optional, keep the required line exact);
- per page (index i, page = i+1): `png = pages[i]`; if `png == b""` → `block_text = f"page {page} — description unavailable"`; else `desc = await describe_image(llm, data=png, mime="image/png")` (the phase-122 call — `settings` default, `context` None); `desc is None` or blank → the same placeholder (fail-soft per page — a dead vision endpoint must not sink the doc, the phase-122 fail-soft spirit); else `block_text = desc.strip()`;
- `content = "\n\n".join(f"{PAGE_SEPARATOR.format(page=p)}\n{block}" for p, block in ...)` — the SAME separator convention as `extract_pdf_text` (the chunker's page-boundary handling works unchanged);
- an ALL-failed render (`pages == []` or every page placeholder) → return `""` (the existing empty-content path — the doc lands as a zero-text doc, the phase-126 no-extractable-text behavior);
- the embedded-image extraction (`extract_pdf_images` + `_describe_or_skip`) still runs AFTER the gate branch on BOTH paths — the fallback doc's embedded images join the pipeline exactly as a clean PDF's do (the screenshots are the CONTENT; the extracted images are the citation figures — both, no conflict).
3. `app/rag/importer.py` — `ImportSummary`: add `pdfs_screenshotted: int = 0` (documented: "PDFs whose text layer failed the gate and took the page-screenshot vision fallback (phase 133)") + the field in `log()`'s format string (append to the existing line — the house ample-logging shape).
4. `app/rag/importer.py` — the digest: the fallback's constructed content is what the sha256 runs over (the existing `digest = hashlib.sha256(content.encode(...))` line — no change needed, just verify it runs AFTER the gate branch so a fallback doc's row is stable across re-syncs: same pages + same vision model → same descriptions → same digest → unchanged on the next sync, no vision re-burn. If `describe_image`'s reply is non-deterministic in production, note it in the docstring — the re-burn is then a cost, not a bug).
## Testing & Quality
- Unit: `tests/unit/test_pdf.py` (extend) — `render_pdf_pages`: a 2-page temp PDF (built with fitz in the test — the phase-126 fixture pattern) → 2 PNGs (magic bytes `\\x89PNG`), page order; an unreadable path → `[]`; a corrupted page (if constructible — else the b"" path via a monkeypatched `get_pixmap` raising) → the zero-byte entry at its index, the index intact.
- Unit: `tests/unit/test_importer.py` (extend) — the fallback branch, with a REAL tiny garbage PDF (build one in the test: a fitz page whose inserted text is ONLY XML-ish lines — `<foo:bar>x</foo:bar>` repeated — so the gate fails deterministically) + a fake LLM whose multimodal `chat` returns a canned page description: the stored doc's content = `---PAGE-1---\\n<canned>` (the separator convention), `summary.pdfs_screenshotted == 1`, the loud warning logged (the caplog pin); a CLEAN tiny PDF (the phase-126 fixtures) → `pdfs_screenshotted == 0` and the vision multimodal `chat` is NEVER called for the fallback (only the embedded-image describes — the gate never burns vision on a clean layer).
- Coverage: **>90%** on this task's new/modified code.
## Completion Criteria
- [ ] a garbage-text PDF lands with the page-screenshot content (the synthetic test: `---PAGE-N---` + the canned descriptions)
- [ ] a clean PDF's path is byte-identical to phase 126 (no fallback, no extra vision calls, `pdfs_screenshotted == 0`)
- [ ] the fallback is fail-soft per page (a dead vision call → the placeholder line, the doc still lands)
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
@@ -0,0 +1,29 @@
# Task 04 — E2E: the real guide stays clean, a synthetic garbage PDF takes the screenshot path
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...the raw xml is being embedded and the preview shows the entire document as lines like `<illustrator:StartupProfile>Web</illustrator:StartupProfile>`. This project should support this kind of PDF and should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image..."
## Objective
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) pins both legs of the guarantee at the user surface: (a) the owner's REAL guide, imported through the admin sync, previews CLEAN text (no XML lines — the exact complaint, negated); (b) a synthetic PDF whose text layer is pure XML garbage takes the screenshot fallback end to end — its content is the mock's canned vision descriptions, and the preview shows them.
## Work
1. `tests/e2e/test_garbage_pdf.py` (new) — house pattern (module app fixture over the shared E2E Postgres, host temp-dir `kind=local` source registered via the admin git-sources API, autouse truncate cleanup, mock-only — `E2E_REAL_LLM=1` unsupported: the fallback's vision surface is the deterministic `IMAGE_DESCRIPTION_MODE` canned reply).
App env: `BOR_IMPORT_EXTENSIONS` must include `pdf` (the owner's live config — the app fixture's env, the phase-126/127 suites' pattern) and `BOR_IMAGES=1` (the embedded-image pipeline is live).
2. Fixtures (two local sources, two tests):
- `hnb/` — the REAL guide: extract `test_sources/hnb_2026_guide.tar.gz` into the temp dir (module-scoped, once — the 6 MB extraction is seconds).
- `garbagedoc/` — a synthetic garbage PDF built IN the test with PyMuPDF (the fixture pattern from task 03's unit test, lifted here): 2 pages, each page's ONLY text = repeated XML-ish lines (`<illustrator:StartupProfile>Web</illustrator:StartupProfile>` × ~20 — the owner's exact line shape, so the test is a faithful reproduction of the report), plus one small embedded raster image per page (fitz `insert_image` from a tiny PNG built in the test — the fallback's embedded-image leg runs too).
3. Test → observable mapping (Playwright Mapping Rule):
- `test_real_guide_previews_clean_text` — admin sync over `hnb/` settles `success`; `GET /api/documents/content?source=hnb&path=<the guide's pdf>` (the PREVIEW surface — the endpoint the document viewer's content uses): the body contains `"2026 U.S. Benefits Guide"` (the real first-page text) and NO line matching the XML-ish regex (the owner's complaint, asserted on the served content, not the DB); the document viewer page (`/document.html?source=hnb&path=…`) renders that content (the preview shows real text, not `<illustrator:…>` lines).
- `test_garbage_pdf_takes_the_screenshot_path` — admin sync over `garbagedoc/` settles `success`; the stored doc's content (the same content endpoint): starts with `---PAGE-1---`, contains the mock's CANNED vision description (the `IMAGE_DESCRIPTION_MODE` reply's deterministic text — assert the first 40 chars) for BOTH pages (2 separators, 2 descriptions), and contains NO `<illustrator:StartupProfile>` line (the garbage text layer is NOT what got stored — the screenshot path replaced it); the sync's `detail` is `success` with `added == 1` (the garbage PDF is a normal import — the fallback is invisible in the status shape; the loud log line is server-side, PLAN §9).
- `test_clean_pdf_never_burns_the_fallback` — a third source `cleandoc/` with ONE small clean PDF (fitz, real prose text): sync → the stored content is the PROSE (the text layer, byte-faithful to the extraction) — NOT the canned vision description (the fallback did not fire on a clean layer — the gate's no-false-negative pin at the E2E level).
4. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov`), the mock-only gate + why (the canned vision reply makes the fallback deterministic), the fixture provenance (the real tar.gz + the synthetic builder), the test→observable table.
## Testing & Quality
- E2E: this file IS the task's suite — run in isolation, green.
- Coverage: the phase's >90% `app/` bar is carried by tasks 02–03; the real-guide regression by task 01; this task adds the in-isolation Playwright gate.
## Completion Criteria
- [ ] `uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
- [ ] the real guide's PREVIEW (the owner's exact surface) is clean — the `<illustrator:StartupProfile>` line is asserted ABSENT on the served content
- [ ] the synthetic garbage PDF's stored content is the canned vision descriptions (the fallback fired end to end, mock-deterministic)
- [ ] the clean PDF is byte-faithful to its text layer (no false-positive fallback)
- [ ] no behavior change in completed phases (the phase-126 pipeline, the sync, the document viewer)
-8
View File
@@ -1,9 +1 @@
# TODO
- [ ] On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time.
- [ ] The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to
- [ ] The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many
- [ ] The chat output is getting messy. I think it's because the `source-chip`, `source-image`, `tune-btn`, `retry-btn`, and `save-as-doc-btn` end up in the same div which causes them to push each other in weird ways. Those three buttons should be in a button cluster in the bottom right. We don't need to display the `source-chip` for images, just the image itself is fine. `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized.
- [ ] The agent is struggling with huge documents. It can search for the text it wants and it finds the text, including line number, but then it gets stuck saying "However, read takes a path, not a line number." and can't figure out how to read that part of the document. Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck. I have a huge test pdf (the DND player's handbook) in test_sources called "pdf_tests.tar" that you can use for testing. It's a massive pdf. The question the agent got stuck on was "What are the components of the find traps spell?" which is toward the end of the players handbook so it will need to search and read specific lines. I've been setting BOR_READ_MAX_CHARS to 24000 to keep things relatively quick so the agent realizes quickly its answer isn't in the first few pages.
- [ ] Uploading an image in the chat provides no feedback to the user. The user clicks the paperclick, selects and image, presses "send" and then nothing happens. No loading bar, no "uploading image", no indication. This results in the user spamming "send" over and over because they think it's frozen. We need to visually show the user's image is uploading.
- [ ] test_sources/hnb_2026_guide.tar.gz contains a pdf that is being read as binary. Figure out why. It contains images, tables, and text but none of that is being extracted correctly. Instead, the raw xml is being embedded and the preview shows the entire document as lines like `<illustrator:StartupProfile>Web</illustrator:StartupProfile>`. This project should support this kind of PDF and should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working.