# Phase 13 — Document Back Button Returns to Where You Came From **Story:** `.agents/user_stories/document-back-navigation.md` **Context:** owner report 2026-08-22 — "clicking a document from the chat tab pulls up the document correct, but the back button goes back to sources, not the chat." ## Goal The viewer's back button returns to **the page the document was opened from**: chat chip → Chat; Sources table → Sources. ## Diagnosis Chips/links open the viewer with `target="_blank"`. In the fresh tab `window.history.length` is 1, so `document.js`'s heuristic (`history.length > 1 ? history.back() : href`) always falls through to the static `href="/sources.html"` — wrong for chat-originated visits. ## Implementation steps 1. **Chat chips** (`frontend/assets/app.js`): `documentUrl(source, path, back = "/")` — appends `&back=`; chat passes `"/"`. Existing phase-10 E2E href assertion updates to include `&back=%2F`. 2. **Sources links** — unchanged: no `back` param in the URL; the viewer's default target is `/sources.html`, so the phase-10 assertion stays green. 3. **Viewer** (`frontend/document.js`): - Resolve back target: `back` param wins **only** when it is a same-origin relative URL (starts with `/`, not `//`); otherwise `/sources.html`. (Rejects `https://…`, `//…`, `javascript:…`.) - Set `#doc-back` href + label: `/` → "Chat", `/sources.html` → "Sources", anything else relative → "Back". - Click: deterministic navigation to the resolved target (drop the `history.length` heuristic — both entry points are new tabs, and determinism is what the story demands). - The static `href="/sources.html"` in `document.html` remains the no-JS fallback. 4. **E2E:** `tests/e2e/test_document_back_navigation.py` per the story mapping; update `test_document_viewer.py` chip-href assertion. ## Locked decisions None. A10/A11 untouched (no new endpoint, no new asset). ## Testing & Quality - E2E in isolation (new file) + `test_document_viewer.py` regression in isolation. - Coverage gate unchanged (frontend-only phase). ## Commit ```bash git add -A .agents/ frontend/ tests/e2e/ && git commit --no-gpg-sign -m "fix(ui): document viewer back button returns to the page you came from (chat or sources)" ```