fix(chat): keep in-flight answers alive across in-app view switches
Root cause (owner repro, verified in a real browser 2026-09-06): the five navbar views (Chat, RAG, Sources, Tuning, History) were separate HTML documents, so a navbar click was a REAL cross-document navigation — the chat page unloaded, the in-flight SSE fetch was aborted, and the phase-48 teardown (app/api/chat.py `finally`, "chat: turn cancelled") stopped the model. Observed: send question -> click RAG mid-stream -> click Chat -> the answer never finished: no `query_log` row, and on return a dangling question with no brain record (the pre-token pagehide partial persist skips because `acc` is empty). Phase-48 LOCKED-DECISION REFINEMENT (owner-confirmed 2026-09-06, flagged per AGENTS.md rule 3, not silently deviated): "real navigation cancels the fetch" now means LEAVING THE APP — tab close, external/other-document navigation, the Stop button. In-app navbar switches are client-side view switches and no longer cancel. Fix — Option A (SPA shell), chosen over B (Service Worker owns the stream) and C (server-side turn registry + resume): - frontend/index.html is the shell: ONE `<main id="main">` holds the five `<section class="view">` blocks; hidden views carry BOTH `hidden` and `inert` (WCAG — no focus/keyboard traversal). The shared header, the single `doc-modal-*` skeleton, and the `#app-version` footer each exist exactly once; the per-view copies from the four folded pages are dropped. - New frontend/assets/router.js (vanilla module — no framework, no bundler, No-CDN rule intact): lazy-imports a view module on FIRST show only (mount-once, hide-forever — the chat view's in-flight SSE reader persists across switches; that persistence IS the fix); intercepts same-shell navbar links with preventDefault + history.pushState (never a document load); handles popstate; single writer of `.nav-link` active state (is-active + aria-current), document.title, and the per-view meta description (values carried over from the old pages' heads, brand-resolved at write time). - Each folded page's JS becomes `export async function mount(root)` — root-scoped queries; `initSharedHeader()` dropped (the header boots once in the shell via the chat module; the admin flag comes from the same cached `fetchIsAdmin()` promise — zero extra requests). - app/main.py: a small list-driven route factory serves the shell for /tuning.html, /sources.html, /git-sources.html, /history.html — registered AFTER the API routers and BEFORE the static catch-all (routes-first). The phase-33 caching middleware applies no-cache + `?v=` rewriting unchanged; app/core/caching.py needed NO change (the view paths did not change — pinned by the integration tests). - The four old view .html files are DELETED (one source of truth); deep links to the old URLs keep working (the router picks the view from the pathname); `/?chat=<id>` is unaffected; the Containerfile bundles router.js (inlining the lazy view modules) and drops the folded page files. - app/schemas.py: HistoryTurn.text cap 4000 -> 32000 — the shell keeps long saved answers in the chat, and the old cap (stricter than the 24_000-char total history budget) 422-rejected any second turn in such a chat (found by the phase-42 E2E suite on the shell). Boundaries: login.html, shared.html, doc-edit.html, document.html REMAIN separate documents (flow pages, not navbar tabs); a mid-stream navigation to doc-edit/document.html still cancels per phase 48 (follow-up candidate, out of scope). The SSE API is unchanged. Real departures still cancel the turn — phase 48 intact (pinned by tests/e2e/test_stop_generation.py, unchanged, and by the new suite's real-departure control). Tests: - Phase-20 suite REWRITTEN to the new semantics (tests/e2e/test_sources_midstream_bug.py): a navbar switch no longer cancels — the stream survives the switch and the FULL answer settles; the pagehide partial persist REMAINS for real departures (the partial's exact shape — first streamed chunk prefix, no done metadata — is still pinned there). - NEW story suite tests/e2e/test_nav_switch_keeps_stream.py (mock LLM): the owner repro (send -> RAG mid-stream -> Chat: window sentinel survives = same document, FULL answer, exactly one brain turn in bor.chat.v1, exactly one settled query_log row, auto-saved row matches) + the same mid-stream switch against the other three views + the real-departure-still-cancels control + the no-switch baseline. - tests/unit/test_frontend_router.py: source-level pins of the router invariants (click interceptor targets ONLY same-shell view paths, pushState-only switches, mount-once guard, hidden+inert pair, single-writer active state/title); shell-route integration tests (each folded path serves the shell with no-cache + `?v=` body; a non-view path still 404s); the file-reading unit pins re-pointed at the shell (the four view files are gone — the shell is the source of truth). Verification (this commit): full suite green — 1565 unit+integration tests, app/ coverage 99% (>90% floor); ruff + pyright clean; the phase's E2E suites green in isolation (house protocol, AGENTS.md rule 9). Owner repro verified in a real browser against the real LLM (dev server :8010, headful Chromium): "tell me about everquest" -> RAG mid-stream -> Chat — the answer completed with one brain bubble and no error banner, `query_log` gained exactly one settled row (deflected=True: the dev KB holds no EverQuest docs — the settle, not the topic, is the proof), zero "chat: turn cancelled" lines for that turn; the control (real navigation to /shared.html mid-stream) still cancelled (no settled row, the cancel line logged, the partial persisted on return). Screenshots: .agents/screenshots/76_manual_*. Phase 76 (76_spa_nav_shell) complete — moved to .agents/phases/complete/.
This commit is contained in:
+726
-699
File diff suppressed because it is too large
Load Diff
+393
-372
@@ -1,11 +1,12 @@
|
||||
/* Brain of Reese — History page (saved chats, phase 50 task 04).
|
||||
/* Brain of Reese — History view (saved chats, phase 50 task 04;
|
||||
* phase 76 task 03: shell view module).
|
||||
*
|
||||
* TODO.md L5 (owner 2026-08-29): "Need a way to save and view chat
|
||||
* history in a new page, then return to that history with a click."
|
||||
*
|
||||
* Wires the admin-only `GET /api/chats` + `POST /api/chats/<id>/share`
|
||||
* + `POST /api/chats/<id>/unshare` + `DELETE /api/chats/<id>`
|
||||
* endpoints (phase 50 task 02; phase 51 task 01+02) into the page's
|
||||
* endpoints (phase 50 task 02; phase 51 task 01+02) into the view's
|
||||
* full-width table:
|
||||
*
|
||||
* • Title — an `<a href="/?chat=<id>">`: Open IS the title link
|
||||
@@ -55,408 +56,428 @@
|
||||
* • admin → the gate hides and `loadChats()` renders the rows; a
|
||||
* 0-row fetch reveals the empty-state row.
|
||||
*
|
||||
* Phase 19/34: the page joins the shared header — initSharedHeader()
|
||||
* runs first (whoami + nav reveal + the steering panel), and the gate
|
||||
* below reuses the SAME cached /api/whoami promise (one request per
|
||||
* page).
|
||||
* Phase 76 (task 03) — shell view module (the "History" view of the
|
||||
* ONE-document shell; /history.html now serves the shell, and
|
||||
* assets/router.js lazy-imports THIS module on first show):
|
||||
*
|
||||
* • the top-level boot is now `export async function mount(root)` —
|
||||
* root is the view's <section id="view-history">, and every DOM
|
||||
* lookup scopes to root (the view ids stay unique across the
|
||||
* shell — scoped lookups keep the module honest and testable).
|
||||
* The router mounts a view ONCE (mount-once, hide-forever), so
|
||||
* the binding + state survive every switch.
|
||||
* • the initSharedHeader() call is DROPPED: in the shell the shared
|
||||
* header boots exactly once, via the chat module (app.js) at shell
|
||||
* boot — the view never re-boots it. The admin gate keeps
|
||||
* fetchIsAdmin() — the SAME cached /api/whoami promise header.js
|
||||
* exports (zero extra requests; the flag decides whether the
|
||||
* table loads at all, the Sources-page gate pattern).
|
||||
* • the row actions stay REAL navigations: the Open link
|
||||
* (?chat=<id>) and the copy-link field are plain anchor targets —
|
||||
* opening a saved chat is a chat-view concern handled by app.js
|
||||
* at boot via ?chat=, and the router never intercepts them (they
|
||||
* are not navbar links, and their query string keeps them out of
|
||||
* the VIEW map).
|
||||
*/
|
||||
|
||||
import { fetchIsAdmin, initSharedHeader } from "./header.js";
|
||||
import { fetchIsAdmin } from "./header.js";
|
||||
|
||||
const tableWrap = document.querySelector("#history-table-wrap");
|
||||
const tbody = document.querySelector("#history-tbody");
|
||||
const emptyRow = document.querySelector("#history-empty-row");
|
||||
const gateEl = document.querySelector("#history-gate");
|
||||
const statusEl = document.querySelector("#history-status");
|
||||
export async function mount(root) {
|
||||
/* ---------- view elements (the view's section, scoped to root) ---------- */
|
||||
const tableWrap = root.querySelector("#history-table-wrap");
|
||||
const tbody = root.querySelector("#history-tbody");
|
||||
const emptyRow = root.querySelector("#history-empty-row");
|
||||
const gateEl = root.querySelector("#history-gate");
|
||||
const statusEl = root.querySelector("#history-status");
|
||||
|
||||
/* Action feedback — the role="status" live region above the table
|
||||
(the "never stale" contract: every row action lands a line here,
|
||||
success or failure alike). */
|
||||
function announce(message) {
|
||||
if (statusEl) statusEl.textContent = message;
|
||||
}
|
||||
|
||||
function fmtDate(iso) {
|
||||
try {
|
||||
return new Date(iso).toLocaleString();
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
/* One row. The Title cell carries the Open link (/?chat=<id> — the
|
||||
"return to that history with a click" requirement); the Updated
|
||||
cell renders the locale date+time with the full ISO on hover. */
|
||||
function makeRow(chat) {
|
||||
const tr = document.createElement("tr");
|
||||
|
||||
const titleTd = document.createElement("td");
|
||||
titleTd.className = "history-title-cell";
|
||||
titleTd.title = chat.title; // full title on hover (the column ellipsizes)
|
||||
const link = document.createElement("a");
|
||||
link.className = "history-title-link";
|
||||
link.href = "/?chat=" + chat.id; // Open: the chat page boots into this chat
|
||||
link.textContent = chat.title; // user-derived — textContent only
|
||||
titleTd.appendChild(link);
|
||||
tr.appendChild(titleTd);
|
||||
|
||||
const countTd = document.createElement("td");
|
||||
countTd.className = "history-count-cell";
|
||||
countTd.textContent = String(chat.message_count);
|
||||
tr.appendChild(countTd);
|
||||
|
||||
const updatedTd = document.createElement("td");
|
||||
updatedTd.className = "history-updated-cell";
|
||||
updatedTd.title = chat.updated_at; // full ISO on hover
|
||||
updatedTd.textContent = fmtDate(chat.updated_at);
|
||||
tr.appendChild(updatedTd);
|
||||
|
||||
// Phase 53 (task 04): the Stale cell (between Updated and Share) —
|
||||
// the READ-ONLY staleness marker. `chat.stale` is computed server-
|
||||
// side (task 03), so this branches on the flag, never on versions.
|
||||
// Stale rows get the rose pill (the exact hover copy points at the
|
||||
// Regenerate action on the chat page, task 05); fresh rows get a
|
||||
// plain em-dash. The <td> carries its own aria-label in BOTH states
|
||||
// — the marker must be conveyed without the visual (WCAG 2.1 AA).
|
||||
const staleTd = document.createElement("td");
|
||||
staleTd.className = "history-stale-cell";
|
||||
if (chat.stale) {
|
||||
staleTd.setAttribute("aria-label", "Stale — sources have changed since this chat was saved");
|
||||
const pill = document.createElement("span");
|
||||
pill.className = "stale-pill";
|
||||
pill.title = "Sources have changed since this chat was saved — open the chat to Regenerate";
|
||||
pill.textContent = "Stale";
|
||||
staleTd.appendChild(pill);
|
||||
} else {
|
||||
staleTd.setAttribute("aria-label", "Current — saved against the latest sources");
|
||||
staleTd.textContent = "—"; // the em-dash: fresh rows' marker
|
||||
}
|
||||
tr.appendChild(staleTd);
|
||||
|
||||
// Phase 51: the Share cell (between Updated and Actions) — the
|
||||
// three-state share control (unshared / shared / confirming-unshare).
|
||||
const shareTd = document.createElement("td");
|
||||
shareTd.className = "history-share-cell";
|
||||
shareTd.appendChild(makeShareControl(chat));
|
||||
tr.appendChild(shareTd);
|
||||
|
||||
const actionsTd = document.createElement("td");
|
||||
actionsTd.className = "history-actions-cell";
|
||||
actionsTd.appendChild(makeDeleteControl(chat, tr));
|
||||
tr.appendChild(actionsTd);
|
||||
return tr;
|
||||
}
|
||||
|
||||
/* The inline two-step Delete (owner-locked 2026-08-29 — NO native
|
||||
confirm dialog anywhere on this page). The Delete button is
|
||||
replaced, in place, by the "Delete? [Yes] [No]" pair; focus moves
|
||||
to Yes (keyboard-reachable confirm). Yes → DELETE /api/chats/<id>
|
||||
→ the row is removed + the live region line; No or a failed
|
||||
request keeps the row (+ the error line on failure). */
|
||||
function makeDeleteControl(chat, row) {
|
||||
const cell = document.createElement("span");
|
||||
cell.className = "history-actions";
|
||||
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "history-delete";
|
||||
del.setAttribute("aria-label", `Delete saved chat: ${chat.title}`);
|
||||
del.textContent = "Delete";
|
||||
|
||||
function restoreDelete() {
|
||||
cell.replaceChildren(del);
|
||||
del.focus(); // focus returns to the (restored) control
|
||||
/* Action feedback — the role="status" live region above the table
|
||||
(the "never stale" contract: every row action lands a line here,
|
||||
success or failure alike). */
|
||||
function announce(message) {
|
||||
if (statusEl) statusEl.textContent = message;
|
||||
}
|
||||
|
||||
del.addEventListener("click", () => {
|
||||
const label = document.createElement("span");
|
||||
label.className = "history-confirm-text";
|
||||
label.textContent = "Delete?";
|
||||
const yes = document.createElement("button");
|
||||
yes.type = "button";
|
||||
yes.className = "history-confirm-yes";
|
||||
yes.textContent = "Yes";
|
||||
const no = document.createElement("button");
|
||||
no.type = "button";
|
||||
no.className = "history-confirm-no";
|
||||
no.textContent = "No";
|
||||
yes.addEventListener("click", () =>
|
||||
confirmDelete(chat, row, yes, restoreDelete));
|
||||
no.addEventListener("click", restoreDelete);
|
||||
cell.replaceChildren(label, yes, no);
|
||||
yes.focus(); // the confirm pair takes over the focus
|
||||
});
|
||||
|
||||
cell.appendChild(del); // the shipped state IS the Delete button
|
||||
return cell;
|
||||
}
|
||||
|
||||
/* The confirmed delete: DELETE /api/chats/<id> → the row is removed
|
||||
(+ the empty-state row reappears when it was the last one) and the
|
||||
live region gets `Deleted "<title>".` A 404 means the row is gone
|
||||
(deleted elsewhere) — drop the stale row and say so. Any other
|
||||
failure or a network error keeps the row, restores the Delete
|
||||
button (retryable), and lands the error line. */
|
||||
async function confirmDelete(chat, row, yesBtn, restoreDelete) {
|
||||
yesBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}`, { method: "DELETE" });
|
||||
} catch {
|
||||
announce(`Couldn't delete "${chat.title}" — is the app reachable?`);
|
||||
restoreDelete();
|
||||
return;
|
||||
function fmtDate(iso) {
|
||||
try {
|
||||
return new Date(iso).toLocaleString();
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
if (r.status === 404) {
|
||||
|
||||
/* One row. The Title cell carries the Open link (/?chat=<id> — the
|
||||
"return to that history with a click" requirement); the Updated
|
||||
cell renders the locale date+time with the full ISO on hover. */
|
||||
function makeRow(chat) {
|
||||
const tr = document.createElement("tr");
|
||||
|
||||
const titleTd = document.createElement("td");
|
||||
titleTd.className = "history-title-cell";
|
||||
titleTd.title = chat.title; // full title on hover (the column ellipsizes)
|
||||
const link = document.createElement("a");
|
||||
link.className = "history-title-link";
|
||||
link.href = "/?chat=" + chat.id; // Open: the chat page boots into this chat
|
||||
link.textContent = chat.title; // user-derived — textContent only
|
||||
titleTd.appendChild(link);
|
||||
tr.appendChild(titleTd);
|
||||
|
||||
const countTd = document.createElement("td");
|
||||
countTd.className = "history-count-cell";
|
||||
countTd.textContent = String(chat.message_count);
|
||||
tr.appendChild(countTd);
|
||||
|
||||
const updatedTd = document.createElement("td");
|
||||
updatedTd.className = "history-updated-cell";
|
||||
updatedTd.title = chat.updated_at; // full ISO on hover
|
||||
updatedTd.textContent = fmtDate(chat.updated_at);
|
||||
tr.appendChild(updatedTd);
|
||||
|
||||
// Phase 53 (task 04): the Stale cell (between Updated and Share) —
|
||||
// the READ-ONLY staleness marker. `chat.stale` is computed server-
|
||||
// side (task 03), so this branches on the flag, never on versions.
|
||||
// Stale rows get the rose pill (the exact hover copy points at the
|
||||
// Regenerate action on the chat page, task 05); fresh rows get a
|
||||
// plain em-dash. The <td> carries its own aria-label in BOTH states
|
||||
// — the marker must be conveyed without the visual (WCAG 2.1 AA).
|
||||
const staleTd = document.createElement("td");
|
||||
staleTd.className = "history-stale-cell";
|
||||
if (chat.stale) {
|
||||
staleTd.setAttribute("aria-label", "Stale — sources have changed since this chat was saved");
|
||||
const pill = document.createElement("span");
|
||||
pill.className = "stale-pill";
|
||||
pill.title = "Sources have changed since this chat was saved — open the chat to Regenerate";
|
||||
pill.textContent = "Stale";
|
||||
staleTd.appendChild(pill);
|
||||
} else {
|
||||
staleTd.setAttribute("aria-label", "Current — saved against the latest sources");
|
||||
staleTd.textContent = "—"; // the em-dash: fresh rows' marker
|
||||
}
|
||||
tr.appendChild(staleTd);
|
||||
|
||||
// Phase 51: the Share cell (between Updated and Actions) — the
|
||||
// three-state share control (unshared / shared / confirming-unshare).
|
||||
const shareTd = document.createElement("td");
|
||||
shareTd.className = "history-share-cell";
|
||||
shareTd.appendChild(makeShareControl(chat));
|
||||
tr.appendChild(shareTd);
|
||||
|
||||
const actionsTd = document.createElement("td");
|
||||
actionsTd.className = "history-actions-cell";
|
||||
actionsTd.appendChild(makeDeleteControl(chat, tr));
|
||||
tr.appendChild(actionsTd);
|
||||
return tr;
|
||||
}
|
||||
|
||||
/* The inline two-step Delete (owner-locked 2026-08-29 — NO native
|
||||
confirm dialog anywhere on this page). The Delete button is
|
||||
replaced, in place, by the "Delete? [Yes] [No]" pair; focus moves
|
||||
to Yes (keyboard-reachable confirm). Yes → DELETE /api/chats/<id>
|
||||
→ the row is removed + the live region line; No or a failed
|
||||
request keeps the row (+ the error line on failure). */
|
||||
function makeDeleteControl(chat, row) {
|
||||
const cell = document.createElement("span");
|
||||
cell.className = "history-actions";
|
||||
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "history-delete";
|
||||
del.setAttribute("aria-label", `Delete saved chat: ${chat.title}`);
|
||||
del.textContent = "Delete";
|
||||
|
||||
function restoreDelete() {
|
||||
cell.replaceChildren(del);
|
||||
del.focus(); // focus returns to the (restored) control
|
||||
}
|
||||
|
||||
del.addEventListener("click", () => {
|
||||
const label = document.createElement("span");
|
||||
label.className = "history-confirm-text";
|
||||
label.textContent = "Delete?";
|
||||
const yes = document.createElement("button");
|
||||
yes.type = "button";
|
||||
yes.className = "history-confirm-yes";
|
||||
yes.textContent = "Yes";
|
||||
const no = document.createElement("button");
|
||||
no.type = "button";
|
||||
no.className = "history-confirm-no";
|
||||
no.textContent = "No";
|
||||
yes.addEventListener("click", () =>
|
||||
confirmDelete(chat, row, yes, restoreDelete));
|
||||
no.addEventListener("click", restoreDelete);
|
||||
cell.replaceChildren(label, yes, no);
|
||||
yes.focus(); // the confirm pair takes over the focus
|
||||
});
|
||||
|
||||
cell.appendChild(del); // the shipped state IS the Delete button
|
||||
return cell;
|
||||
}
|
||||
|
||||
/* The confirmed delete: DELETE /api/chats/<id> → the row is removed
|
||||
(+ the empty-state row reappears when it was the last one) and the
|
||||
live region gets `Deleted "<title>".` A 404 means the row is gone
|
||||
(deleted elsewhere) — drop the stale row and say so. Any other
|
||||
failure or a network error keeps the row, restores the Delete
|
||||
button (retryable), and lands the error line. */
|
||||
async function confirmDelete(chat, row, yesBtn, restoreDelete) {
|
||||
yesBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}`, { method: "DELETE" });
|
||||
} catch {
|
||||
announce(`Couldn't delete "${chat.title}" — is the app reachable?`);
|
||||
restoreDelete();
|
||||
return;
|
||||
}
|
||||
if (r.status === 404) {
|
||||
row.remove();
|
||||
showEmptyIfLast();
|
||||
announce("That chat was already deleted.");
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't delete "${chat.title}" — try again.`);
|
||||
restoreDelete();
|
||||
return;
|
||||
}
|
||||
row.remove();
|
||||
showEmptyIfLast();
|
||||
announce("That chat was already deleted.");
|
||||
return;
|
||||
announce(`Deleted "${chat.title}".`);
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't delete "${chat.title}" — try again.`);
|
||||
restoreDelete();
|
||||
return;
|
||||
|
||||
/* ---------- share column (phase 51, owner-locked 2026-08-29) ---------- */
|
||||
|
||||
/* Select every text node in the link field (an <a> has no .select();
|
||||
a range does the job) — best-effort: a selection failure only means
|
||||
the user copies by hand. */
|
||||
function selectAllInField(el) {
|
||||
try {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
const sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
} catch {
|
||||
/* selection is best-effort — the field still shows the full URL */
|
||||
}
|
||||
}
|
||||
row.remove();
|
||||
showEmptyIfLast();
|
||||
announce(`Deleted "${chat.title}".`);
|
||||
}
|
||||
|
||||
/* ---------- share column (phase 51, owner-locked 2026-08-29) ---------- */
|
||||
|
||||
/* Select every text node in the link field (an <a> has no .select();
|
||||
a range does the job) — best-effort: a selection failure only means
|
||||
the user copies by hand. */
|
||||
function selectAllInField(el) {
|
||||
try {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
const sel = window.getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
} catch {
|
||||
/* selection is best-effort — the field still shows the full URL */
|
||||
/* Clipboard + the owner-locked inline-link fallback: a non-secure
|
||||
(http) homelab origin rejects navigator.clipboard, so the failure
|
||||
path renders a TRANSIENT <a> link field in the row's share cell —
|
||||
input-like, it selects its full URL on focus (click or Tab, then
|
||||
Ctrl/Cmd+C). One field at a time (a new offer replaces the old).
|
||||
Returns true when the clipboard took it. (The per-page duplication
|
||||
house style — this is history.js's OWN copy of the ~10-line helper;
|
||||
app.js keeps the chat page's, no new shared module.) */
|
||||
async function copyShareLink(cell, absoluteUrl) {
|
||||
cell.querySelectorAll(".share-link-fallback").forEach((el) => el.remove());
|
||||
try {
|
||||
await navigator.clipboard.writeText(absoluteUrl);
|
||||
return true;
|
||||
} catch {
|
||||
const field = document.createElement("a");
|
||||
field.className = "share-link-fallback";
|
||||
field.href = absoluteUrl; // carries the full URL (copy link address works too)
|
||||
field.textContent = absoluteUrl; // the URL is data — textContent, never innerHTML
|
||||
field.title = "Share link — click, then copy (Ctrl/Cmd+C)";
|
||||
field.addEventListener("focus", () => selectAllInField(field));
|
||||
cell.appendChild(field);
|
||||
field.focus({ preventScroll: true }); // selects the URL — ready to copy
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Clipboard + the owner-locked inline-link fallback: a non-secure
|
||||
(http) homelab origin rejects navigator.clipboard, so the failure
|
||||
path renders a TRANSIENT <a> link field in the row's share cell —
|
||||
input-like, it selects its full URL on focus (click or Tab, then
|
||||
Ctrl/Cmd+C). One field at a time (a new offer replaces the old).
|
||||
Returns true when the clipboard took it. (The per-page duplication
|
||||
house style — this is history.js's OWN copy of the ~10-line helper;
|
||||
app.js keeps the chat page's, no new shared module.) */
|
||||
async function copyShareLink(cell, absoluteUrl) {
|
||||
cell.querySelectorAll(".share-link-fallback").forEach((el) => el.remove());
|
||||
try {
|
||||
await navigator.clipboard.writeText(absoluteUrl);
|
||||
return true;
|
||||
} catch {
|
||||
const field = document.createElement("a");
|
||||
field.className = "share-link-fallback";
|
||||
field.href = absoluteUrl; // carries the full URL (copy link address works too)
|
||||
field.textContent = absoluteUrl; // the URL is data — textContent, never innerHTML
|
||||
field.title = "Share link — click, then copy (Ctrl/Cmd+C)";
|
||||
field.addEventListener("focus", () => selectAllInField(field));
|
||||
cell.appendChild(field);
|
||||
field.focus({ preventScroll: true }); // selects the URL — ready to copy
|
||||
return false;
|
||||
/* The unshared state: the [Create link] button (a failed share keeps
|
||||
the cell here — Create link is retryable). */
|
||||
function renderShareUnshared(chat, cell) {
|
||||
const create = document.createElement("button");
|
||||
create.type = "button";
|
||||
create.className = "history-share-create";
|
||||
create.setAttribute("aria-label", `Create share link: ${chat.title}`);
|
||||
create.textContent = "Create link";
|
||||
create.addEventListener("click", () => void createShareLink(chat, cell, create));
|
||||
cell.replaceChildren(create);
|
||||
}
|
||||
}
|
||||
|
||||
/* The unshared state: the [Create link] button (a failed share keeps
|
||||
the cell here — Create link is retryable). */
|
||||
function renderShareUnshared(chat, cell) {
|
||||
const create = document.createElement("button");
|
||||
create.type = "button";
|
||||
create.className = "history-share-create";
|
||||
create.setAttribute("aria-label", `Create share link: ${chat.title}`);
|
||||
create.textContent = "Create link";
|
||||
create.addEventListener("click", () => void createShareLink(chat, cell, create));
|
||||
cell.replaceChildren(create);
|
||||
}
|
||||
|
||||
/* The shared state: [Copy] [Unshare]. Unshare is the inline two-step
|
||||
(the phase-50 Delete-confirm pattern — same .history-confirm-* CSS,
|
||||
focus moves to Yes so the confirm is keyboard-reachable); No or a
|
||||
failed request restores this state (retryable). */
|
||||
function renderShareShared(chat, cell) {
|
||||
const copy = document.createElement("button");
|
||||
copy.type = "button";
|
||||
copy.className = "history-share-copy";
|
||||
copy.setAttribute("aria-label", `Copy share link: ${chat.title}`);
|
||||
copy.textContent = "Copy";
|
||||
copy.addEventListener("click", () => void copyRowShareLink(chat, cell));
|
||||
const unshare = document.createElement("button");
|
||||
unshare.type = "button";
|
||||
unshare.className = "history-unshare";
|
||||
unshare.setAttribute("aria-label", `Unshare saved chat: ${chat.title}`);
|
||||
unshare.textContent = "Unshare";
|
||||
function restoreShared() {
|
||||
/* The shared state: [Copy] [Unshare]. Unshare is the inline two-step
|
||||
(the phase-50 Delete-confirm pattern — same .history-confirm-* CSS,
|
||||
focus moves to Yes so the confirm is keyboard-reachable); No or a
|
||||
failed request restores this state (retryable). */
|
||||
function renderShareShared(chat, cell) {
|
||||
const copy = document.createElement("button");
|
||||
copy.type = "button";
|
||||
copy.className = "history-share-copy";
|
||||
copy.setAttribute("aria-label", `Copy share link: ${chat.title}`);
|
||||
copy.textContent = "Copy";
|
||||
copy.addEventListener("click", () => void copyRowShareLink(chat, cell));
|
||||
const unshare = document.createElement("button");
|
||||
unshare.type = "button";
|
||||
unshare.className = "history-unshare";
|
||||
unshare.setAttribute("aria-label", `Unshare saved chat: ${chat.title}`);
|
||||
unshare.textContent = "Unshare";
|
||||
function restoreShared() {
|
||||
cell.replaceChildren(copy, unshare);
|
||||
unshare.focus({ preventScroll: true }); // focus returns to the (restored) control
|
||||
}
|
||||
unshare.addEventListener("click", () => {
|
||||
const label = document.createElement("span");
|
||||
label.className = "history-confirm-text";
|
||||
label.textContent = "Unshare?";
|
||||
const yes = document.createElement("button");
|
||||
yes.type = "button";
|
||||
yes.className = "history-confirm-yes";
|
||||
yes.textContent = "Yes";
|
||||
const no = document.createElement("button");
|
||||
no.type = "button";
|
||||
no.className = "history-confirm-no";
|
||||
no.textContent = "No";
|
||||
yes.addEventListener("click", () => void confirmUnshare(chat, cell, yes, restoreShared));
|
||||
no.addEventListener("click", restoreShared);
|
||||
cell.replaceChildren(label, yes, no);
|
||||
yes.focus({ preventScroll: true }); // the confirm pair takes over the focus
|
||||
});
|
||||
cell.replaceChildren(copy, unshare);
|
||||
unshare.focus({ preventScroll: true }); // focus returns to the (restored) control
|
||||
}
|
||||
unshare.addEventListener("click", () => {
|
||||
const label = document.createElement("span");
|
||||
label.className = "history-confirm-text";
|
||||
label.textContent = "Unshare?";
|
||||
const yes = document.createElement("button");
|
||||
yes.type = "button";
|
||||
yes.className = "history-confirm-yes";
|
||||
yes.textContent = "Yes";
|
||||
const no = document.createElement("button");
|
||||
no.type = "button";
|
||||
no.className = "history-confirm-no";
|
||||
no.textContent = "No";
|
||||
yes.addEventListener("click", () => void confirmUnshare(chat, cell, yes, restoreShared));
|
||||
no.addEventListener("click", restoreShared);
|
||||
cell.replaceChildren(label, yes, no);
|
||||
yes.focus({ preventScroll: true }); // the confirm pair takes over the focus
|
||||
});
|
||||
cell.replaceChildren(copy, unshare);
|
||||
}
|
||||
|
||||
/* The Share cell (phase 51): the span the row's Share <td> carries.
|
||||
The shipped state comes from the row's share_url (the list endpoint
|
||||
populates it — no second fetch): shared → Copy + Unshare, unshared →
|
||||
Create link. No share action ever removes the ROW (only Delete
|
||||
does) — the cell just re-renders between its states. */
|
||||
function makeShareControl(chat) {
|
||||
const cell = document.createElement("span");
|
||||
cell.className = "history-share";
|
||||
if (chat.share_url) {
|
||||
/* The Share cell (phase 51): the span the row's Share <td> carries.
|
||||
The shipped state comes from the row's share_url (the list endpoint
|
||||
populates it — no second fetch): shared → Copy + Unshare, unshared →
|
||||
Create link. No share action ever removes the ROW (only Delete
|
||||
does) — the cell just re-renders between its states. */
|
||||
function makeShareControl(chat) {
|
||||
const cell = document.createElement("span");
|
||||
cell.className = "history-share";
|
||||
if (chat.share_url) {
|
||||
renderShareShared(chat, cell);
|
||||
} else {
|
||||
renderShareUnshared(chat, cell);
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
/* Create the link: POST /api/chats/<id>/share → the response's
|
||||
share_url becomes the row's data (chat.share_url — the later Copy
|
||||
uses it), the cell re-renders to the shared state, and the ABSOLUTE
|
||||
link (the row's own origin supplies the scheme/host) is offered for
|
||||
copying — clipboard → the inline-field fallback in the cell. A
|
||||
non-2xx (a 404 — the row was deleted behind our back — or 5xx) or a
|
||||
network error keeps the unshared state (Create link re-enabled,
|
||||
retryable) and lands the error line. */
|
||||
async function createShareLink(chat, cell, createBtn) {
|
||||
createBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}/share`, { method: "POST" });
|
||||
} catch {
|
||||
announce(`Couldn't share "${chat.title}" — is the app reachable?`);
|
||||
createBtn.disabled = false;
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't share "${chat.title}" — try again.`);
|
||||
createBtn.disabled = false;
|
||||
return;
|
||||
}
|
||||
const { share_url } = await r.json();
|
||||
chat.share_url = share_url; // the row is shared from now on
|
||||
renderShareShared(chat, cell);
|
||||
} else {
|
||||
const copied = await copyShareLink(
|
||||
cell,
|
||||
new URL(share_url, window.location.origin).toString(),
|
||||
);
|
||||
announce(copied ? "Share link copied." : "Share link ready — copy it from the field.");
|
||||
}
|
||||
|
||||
/* Copy (shared state): re-copy the row's share_url — the per-page
|
||||
clipboard + fallback helper; the live region lands the outcome. */
|
||||
async function copyRowShareLink(chat, cell) {
|
||||
const copied = await copyShareLink(
|
||||
cell,
|
||||
new URL(chat.share_url, window.location.origin).toString(),
|
||||
);
|
||||
announce(copied ? "Share link copied." : "Share link ready — copy it from the field.");
|
||||
}
|
||||
|
||||
/* The confirmed unshare: POST /api/chats/<id>/unshare → the token is
|
||||
NULL (revoked — the public link 404s from now on), the cell
|
||||
re-renders to the unshared state (Create link) and the live region
|
||||
gets `Unshared "<title>".` A non-2xx / a network error keeps the
|
||||
shared state (restoreShared — Copy + Unshare, retryable) and lands
|
||||
the error line. */
|
||||
async function confirmUnshare(chat, cell, yesBtn, restoreShared) {
|
||||
yesBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}/unshare`, { method: "POST" });
|
||||
} catch {
|
||||
announce(`Couldn't unshare "${chat.title}" — is the app reachable?`);
|
||||
restoreShared();
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't unshare "${chat.title}" — try again.`);
|
||||
restoreShared();
|
||||
return;
|
||||
}
|
||||
chat.share_url = null; // revoked: the row is unshared again
|
||||
renderShareUnshared(chat, cell);
|
||||
announce(`Unshared "${chat.title}".`);
|
||||
}
|
||||
return cell;
|
||||
}
|
||||
|
||||
/* Create the link: POST /api/chats/<id>/share → the response's
|
||||
share_url becomes the row's data (chat.share_url — the later Copy
|
||||
uses it), the cell re-renders to the shared state, and the ABSOLUTE
|
||||
link (the row's own origin supplies the scheme/host) is offered for
|
||||
copying — clipboard → the inline-field fallback in the cell. A
|
||||
non-2xx (a 404 — the row was deleted behind our back — or 5xx) or a
|
||||
network error keeps the unshared state (Create link re-enabled,
|
||||
retryable) and lands the error line. */
|
||||
async function createShareLink(chat, cell, createBtn) {
|
||||
createBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}/share`, { method: "POST" });
|
||||
} catch {
|
||||
announce(`Couldn't share "${chat.title}" — is the app reachable?`);
|
||||
createBtn.disabled = false;
|
||||
return;
|
||||
/* The empty-state row reappears exactly when the last data row was
|
||||
removed (the empty row itself ships in the tbody, hidden). */
|
||||
function showEmptyIfLast() {
|
||||
if (!emptyRow || !tbody) return;
|
||||
emptyRow.hidden = tbody.querySelectorAll("tr").length > 1;
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't share "${chat.title}" — try again.`);
|
||||
createBtn.disabled = false;
|
||||
return;
|
||||
}
|
||||
const { share_url } = await r.json();
|
||||
chat.share_url = share_url; // the row is shared from now on
|
||||
renderShareShared(chat, cell);
|
||||
const copied = await copyShareLink(
|
||||
cell,
|
||||
new URL(share_url, window.location.origin).toString(),
|
||||
);
|
||||
announce(copied ? "Share link copied." : "Share link ready — copy it from the field.");
|
||||
}
|
||||
|
||||
/* Copy (shared state): re-copy the row's share_url — the per-page
|
||||
clipboard + fallback helper; the live region lands the outcome. */
|
||||
async function copyRowShareLink(chat, cell) {
|
||||
const copied = await copyShareLink(
|
||||
cell,
|
||||
new URL(chat.share_url, window.location.origin).toString(),
|
||||
);
|
||||
announce(copied ? "Share link copied." : "Share link ready — copy it from the field.");
|
||||
}
|
||||
/* 0-row fetches, non-2xx, and network failures all land on the
|
||||
empty-state row (the sources.js house fallback — the safe state
|
||||
in every case). */
|
||||
function showEmptyState() {
|
||||
if (!tbody) return;
|
||||
tbody.replaceChildren(emptyRow);
|
||||
if (emptyRow) emptyRow.hidden = false;
|
||||
}
|
||||
|
||||
/* The confirmed unshare: POST /api/chats/<id>/unshare → the token is
|
||||
NULL (revoked — the public link 404s from now on), the cell
|
||||
re-renders to the unshared state (Create link) and the live region
|
||||
gets `Unshared "<title>".` A non-2xx / a network error keeps the
|
||||
shared state (restoreShared — Copy + Unshare, retryable) and lands
|
||||
the error line. */
|
||||
async function confirmUnshare(chat, cell, yesBtn, restoreShared) {
|
||||
yesBtn.disabled = true; // no double-fire while the request is in flight
|
||||
let r;
|
||||
try {
|
||||
r = await fetch(`/api/chats/${chat.id}/unshare`, { method: "POST" });
|
||||
} catch {
|
||||
announce(`Couldn't unshare "${chat.title}" — is the app reachable?`);
|
||||
restoreShared();
|
||||
return;
|
||||
/* GET /api/chats → render the rows (latest activity first — the
|
||||
server's order). A 0-row fetch shows the empty-state row. */
|
||||
async function loadChats() {
|
||||
if (emptyRow) emptyRow.hidden = true;
|
||||
let r;
|
||||
try {
|
||||
r = await fetch("/api/chats");
|
||||
} catch {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
const { chats } = await r.json();
|
||||
if (!chats.length) {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
for (const chat of chats) {
|
||||
tbody.appendChild(makeRow(chat));
|
||||
}
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce(`Couldn't unshare "${chat.title}" — try again.`);
|
||||
restoreShared();
|
||||
return;
|
||||
}
|
||||
chat.share_url = null; // revoked: the row is unshared again
|
||||
renderShareUnshared(chat, cell);
|
||||
announce(`Unshared "${chat.title}".`);
|
||||
}
|
||||
|
||||
/* The empty-state row reappears exactly when the last data row was
|
||||
removed (the empty row itself ships in the tbody, hidden). */
|
||||
function showEmptyIfLast() {
|
||||
if (!emptyRow || !tbody) return;
|
||||
emptyRow.hidden = tbody.querySelectorAll("tr").length > 1;
|
||||
}
|
||||
|
||||
/* 0-row fetches, non-2xx, and network failures all land on the
|
||||
empty-state row (the sources.js house fallback — the safe state
|
||||
in every case). */
|
||||
function showEmptyState() {
|
||||
if (!tbody) return;
|
||||
tbody.replaceChildren(emptyRow);
|
||||
if (emptyRow) emptyRow.hidden = false;
|
||||
}
|
||||
|
||||
/* GET /api/chats → render the rows (latest activity first — the
|
||||
server's order). A 0-row fetch shows the empty-state row. */
|
||||
async function loadChats() {
|
||||
if (emptyRow) emptyRow.hidden = true;
|
||||
let r;
|
||||
try {
|
||||
r = await fetch("/api/chats");
|
||||
} catch {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
const { chats } = await r.json();
|
||||
if (!chats.length) {
|
||||
showEmptyState();
|
||||
return;
|
||||
}
|
||||
for (const chat of chats) {
|
||||
tbody.appendChild(makeRow(chat));
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
// Phase 19/34: the shared header first (whoami + nav reveal + the
|
||||
// steering panel) — the whoami promise is cached, so the gate below
|
||||
// reuses the SAME single /api/whoami request.
|
||||
await initSharedHeader();
|
||||
/* ---------- view boot (phase 76 task 03) ----------
|
||||
* The shared header is NOT booted here — in the shell it runs
|
||||
* exactly once, via the chat module (app.js) at shell boot. The
|
||||
* whoami gate reads fetchIsAdmin() — the SAME cached whoami promise
|
||||
* the header uses (zero extra requests). Anonymous: the gate in,
|
||||
* the table out — and NO /api/chats request at all (the router
|
||||
* 403s anonymous, so the view must never call it; the story E2E
|
||||
* pins the request log). */
|
||||
if (!(await fetchIsAdmin())) {
|
||||
// Anonymous: the gate in, the table out — and NO /api/chats
|
||||
// request at all: the router 403s anonymous, so the page must
|
||||
// never call it (the story E2E pins the request log).
|
||||
if (tableWrap) tableWrap.hidden = true;
|
||||
if (gateEl) gateEl.hidden = false;
|
||||
return;
|
||||
}
|
||||
if (gateEl) gateEl.hidden = true;
|
||||
loadChats();
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
/* Brain of Reese — shell router (phase 76, task 01).
|
||||
*
|
||||
* The five navbar views are views of ONE HTML shell (index.html), not
|
||||
* five documents: this module makes a navbar click a CLIENT-SIDE view
|
||||
* switch — history.pushState + show/hide — never a document load, so
|
||||
* the in-flight chat stream in the hidden view keeps streaming
|
||||
* through any switch and completes when the user returns to Chat.
|
||||
* Real departures (tab close, leaving the app, the Stop button) still
|
||||
* cancel the fetch and stop the model — the phase-48 contract, owned
|
||||
* by app.js and untouched here. The phase-48 LOCKED refinement
|
||||
* (owner-confirmed 2026-09-06): "real navigation cancels the fetch"
|
||||
* now means LEAVING THE APP — in-app navbar switches no longer cancel.
|
||||
*
|
||||
* The contract (pinned at source level in
|
||||
* tests/unit/test_frontend_router.py):
|
||||
*
|
||||
* • VIEW — the pathname → view name map for the folded views
|
||||
* ("/" → chat, "/index.html" → chat — the shell's own two URLs,
|
||||
* "/tuning.html" → tuning, "/sources.html" → rag, "/git-sources.html"
|
||||
* → git-sources, "/history.html" → history). Only a link whose href
|
||||
* is IN this map is intercepted; every other link (login, document
|
||||
* viewer, a /?chat=<id> deep link — its query string keeps it out
|
||||
* of the map) still performs its real, document-level navigation.
|
||||
* • boot from location.pathname: the matching view is shown WITHOUT
|
||||
* focus (no focus steal on load) — a direct load of /tuning.html
|
||||
* deep-links to the Tuning view (the shell route in app/main.py
|
||||
* serves this shell for that path).
|
||||
* • mount-once, hide-forever: a non-chat view's module is
|
||||
* lazy-imported on FIRST show only, and `await module.mount(root)`
|
||||
* runs once (the `mounted` guard) — the view's DOM and JS state
|
||||
* (for chat, the in-flight SSE reader; for the Sources view, the
|
||||
* upload-progress poller) persist across every switch; that
|
||||
* persistence IS the phase-76 fix. The chat view needs no module:
|
||||
* app.js already ran at shell boot.
|
||||
* • show = drop hidden + inert, hide = add BOTH (WCAG: a hidden view
|
||||
* must not receive focus or keyboard traversal — the inert pair
|
||||
* pins the [hidden] contract in the a11y tree, AGENTS.md rule 5).
|
||||
* • SINGLE WRITER of the .nav-link active state (is-active +
|
||||
* aria-current="page"), of document.title, and of the per-view
|
||||
* <meta name="description"> (values carried over from the old
|
||||
* pages' <head>s) — no page script stamps any of these.
|
||||
* • focus the target view (its tabindex="-1") ONLY on
|
||||
* user-initiated switches (navbar click / popstate back-forward);
|
||||
* a switch also lands the viewport at the top of the document,
|
||||
* the same way the old per-view page loads did (user intent — the
|
||||
* no-reply-autoscroll contract is about streaming frames, not
|
||||
* navigation the user performs).
|
||||
*
|
||||
* Boot order (index.html): brand.js (classic) → app.js (module — the
|
||||
* chat view, runs at shell boot exactly as before) → router.js
|
||||
* (module — this file). No CDN, no framework, no bundler dependency:
|
||||
* a plain ES module whose dynamic imports (./tuning.js, task 01;
|
||||
* ./sources.js + ./git-sources.js, task 02; ./history.js in task 03)
|
||||
* resolve relatively in dev and are inlined by the Containerfile's
|
||||
* esbuild stage in the image.
|
||||
*/
|
||||
|
||||
/* ---------- the view map (pathname → view name) ----------
|
||||
* The shell's own two URLs are the chat view (the shell IS the chat
|
||||
* page — app.js boots it); every folded view adds one entry. The
|
||||
* values are the <section class="view" id="view-<name>"> slugs in
|
||||
* index.html. */
|
||||
const VIEW = {
|
||||
"/": "chat",
|
||||
"/index.html": "chat", // the shell's alternate URL (HTML_PAGES)
|
||||
"/tuning.html": "tuning", // phase 76 task 01: the first folded view
|
||||
"/sources.html": "rag", // phase 76 task 02: the RAG view (knowledge base)
|
||||
"/git-sources.html": "git-sources", // phase 76 task 02: the Sources view
|
||||
"/history.html": "history", // phase 76 task 03: the History view (saved chats)
|
||||
};
|
||||
|
||||
/* The nav-link href the router stamps active for each view (the
|
||||
Chat link is href="/", the RAG link href="/sources.html", …). */
|
||||
const VIEW_PATH = {
|
||||
chat: "/",
|
||||
tuning: "/tuning.html",
|
||||
rag: "/sources.html",
|
||||
"git-sources": "/git-sources.html",
|
||||
history: "/history.html",
|
||||
};
|
||||
|
||||
/* The lazy view modules — ONLY the non-chat views (chat needs no
|
||||
import: app.js already ran at shell boot). Static specifiers so the
|
||||
Containerfile's esbuild stage can inline each module into the
|
||||
router bundle (the browser still defers its code until the first
|
||||
import() — mount-once semantics are preserved in the image). */
|
||||
const VIEW_MODULES = {
|
||||
tuning: () => import("./tuning.js"),
|
||||
rag: () => import("./sources.js"), // phase 76 task 02
|
||||
"git-sources": () => import("./git-sources.js"), // phase 76 task 02
|
||||
history: () => import("./history.js"), // phase 76 task 03
|
||||
};
|
||||
|
||||
/* Per-view document.head values, carried over from the old pages'
|
||||
<head>s (the router is the single writer of both). The values are
|
||||
the DEFAULT-deployment form: at write time they are composed through
|
||||
brandName() (below) so a configured deployment keeps its name. */
|
||||
const TITLES = {
|
||||
chat: "Brain of Reese",
|
||||
tuning: "Global Tuning · Brain of Reese",
|
||||
rag: "Sources · Brain of Reese", // old sources.html <title>
|
||||
"git-sources": "Git sources · Brain of Reese", // old git-sources.html <title>
|
||||
history: "Saved chats · Brain of Reese", // old history.html <title>
|
||||
};
|
||||
const DESCRIPTIONS = {
|
||||
chat:
|
||||
"Ask anything about your indexed documents — every answer cites the exact doc.",
|
||||
tuning:
|
||||
"Manage the global tuning notes that steer every Brain of Reese answer.",
|
||||
rag: "Documents indexed in Brain of Reese.", // old sources.html meta
|
||||
"git-sources":
|
||||
"Add and remove the git repositories Brain of Reese syncs and indexes (admin-only).",
|
||||
history:
|
||||
"Saved chats — every conversation is saved automatically, one click back.", // old history.html meta
|
||||
};
|
||||
|
||||
/* The brand-resolved display name (phase 39 — brand.js is the single
|
||||
owner: window.BOR_BRAND is "Brain of Reese" from parse time and is
|
||||
updated once /api/config settles). The router composes the per-view
|
||||
title/meta from it instead of stamping the hardcoded literal: the
|
||||
lazy view import defers switchTo PAST brand.js's one-time
|
||||
DOMContentLoaded pass, so a literal stamp would overwrite a
|
||||
configured deployment's name (e.g. "Brain of Testy") in the
|
||||
client-side head. Composing at write time keeps the name correct
|
||||
for every config/switch ordering (an unset deployment — the name IS
|
||||
the literal — stays byte-identical: replaceAll is a no-op). */
|
||||
const brandName = () => window.BOR_BRAND || "Brain of Reese";
|
||||
const titleFor = (view) => TITLES[view].replaceAll("Brain of Reese", brandName());
|
||||
const descFor = (view) => DESCRIPTIONS[view].replaceAll("Brain of Reese", brandName());
|
||||
|
||||
/* The view sections — one per view name (index.html: #view-chat is
|
||||
visible at boot, the folded views ship hidden + inert). */
|
||||
const viewEls = {};
|
||||
for (const name of new Set(Object.values(VIEW))) {
|
||||
viewEls[name] = document.getElementById(`view-${name}`);
|
||||
}
|
||||
|
||||
/* The mount-once guard: a view is imported + mounted at most ONCE per
|
||||
document life — re-shows are show/hide only (no refetch, no
|
||||
re-mount; the view's state persists). Chat starts mounted: app.js
|
||||
owns it and ran at shell boot. */
|
||||
const mounted = { chat: true };
|
||||
|
||||
const nav = document.getElementById("app-nav");
|
||||
const metaDesc = document.querySelector('meta[name="description"]');
|
||||
|
||||
let current = null; // the visible view name (null until boot resolves)
|
||||
|
||||
/* ---------- show / hide (the single writer of the view state) ---------- */
|
||||
|
||||
/* Show `name`, hide every other view, and write the single-writer
|
||||
head/nav state. `userInitiated` marks navbar-click / popstate
|
||||
switches: only those focus the target view (its tabindex="-1") and
|
||||
land the viewport at the top — a boot switch never steals focus. */
|
||||
async function switchTo(name, { userInitiated }) {
|
||||
const root = viewEls[name];
|
||||
if (!root) return;
|
||||
|
||||
/* Mount-once: the lazy module is imported on FIRST show only, then
|
||||
mounted into the view's section. The guard runs BEFORE the import
|
||||
(a re-show never re-imports) and is set only after mount resolves
|
||||
(a failed mount may retry on the next show). */
|
||||
if (!mounted[name]) {
|
||||
const load = VIEW_MODULES[name];
|
||||
if (load) {
|
||||
const mod = await load();
|
||||
await mod.mount(root);
|
||||
}
|
||||
mounted[name] = true;
|
||||
}
|
||||
|
||||
/* Show = drop hidden AND inert; hide = add BOTH (a hidden view must
|
||||
not receive focus or keyboard traversal — the inert pair makes the
|
||||
[hidden] contract hold in the a11y tree, not just the layout). */
|
||||
for (const [viewName, el] of Object.entries(viewEls)) {
|
||||
el.hidden = viewName !== name;
|
||||
el.inert = viewName !== name;
|
||||
}
|
||||
|
||||
/* SINGLE WRITER: the active nav link (is-active + aria-current),
|
||||
the document title, and the per-view meta description. */
|
||||
const path = VIEW_PATH[name];
|
||||
if (nav) {
|
||||
for (const a of nav.querySelectorAll("a.nav-link")) {
|
||||
const active = (a.getAttribute("href") || "") === path;
|
||||
a.classList.toggle("is-active", active);
|
||||
if (active) a.setAttribute("aria-current", "page");
|
||||
else a.removeAttribute("aria-current");
|
||||
}
|
||||
}
|
||||
document.title = titleFor(name);
|
||||
if (metaDesc) metaDesc.content = descFor(name);
|
||||
|
||||
current = name;
|
||||
|
||||
/* Focus the target view ONLY on user-initiated switches (navbar
|
||||
click / popstate) — never on initial boot (no focus steal on
|
||||
load). The top landing mirrors what the old per-view page loads
|
||||
did (user intent, not a streaming-frame autoscroll). */
|
||||
if (userInitiated) {
|
||||
window.scrollTo(0, 0);
|
||||
root.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- navbar click: same-shell links become view switches ----------
|
||||
* Delegated on the nav (covers the mobile dropdown too — it is the
|
||||
* same #app-nav element): a same-shell a.nav-link (href in VIEW) is
|
||||
* intercepted — preventDefault + history.pushState + switch, so the
|
||||
* click is a view switch, NEVER a document load. Every other link
|
||||
* (login, the document viewer, the not-yet-folded views in tasks
|
||||
* 02/03) keeps its real navigation untouched. */
|
||||
if (nav) {
|
||||
nav.addEventListener("click", (e) => {
|
||||
const a = e.target instanceof Element ? e.target.closest("a.nav-link") : null;
|
||||
if (!a) return;
|
||||
const href = a.getAttribute("href") || "";
|
||||
if (!(href in VIEW)) return; // not a same-shell view — real navigation
|
||||
e.preventDefault();
|
||||
const name = VIEW[href];
|
||||
if (name === current) return; // already visible (the menu still closes)
|
||||
history.pushState({ view: name }, "", href);
|
||||
switchTo(name, { userInitiated: true });
|
||||
});
|
||||
|
||||
/* Back / forward: popstate switches views (the history entries were
|
||||
written by the pushState above — same-document, no page load). */
|
||||
window.addEventListener("popstate", () => {
|
||||
const name = VIEW[window.location.pathname];
|
||||
if (name && name !== current) switchTo(name, { userInitiated: true });
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- boot: deep-link from the pathname, no focus steal ---------- */
|
||||
|
||||
/* A direct load of any shell path shows its view (chat for "/" and
|
||||
"/index.html", tuning for "/tuning.html"); an unexpected pathname
|
||||
falls back to chat (the shell's default view). userInitiated:false
|
||||
— boot never focuses (no focus steal on load). */
|
||||
const bootName = VIEW[window.location.pathname] ?? "chat";
|
||||
switchTo(bootName, { userInitiated: false });
|
||||
+539
-530
File diff suppressed because it is too large
Load Diff
@@ -404,6 +404,21 @@ html::after {
|
||||
padding-block: 1.25rem;
|
||||
}
|
||||
|
||||
/* Phase 76 (task 02): the shell's #view-chat wrapper sits between
|
||||
.app-main and .chat-shell — it must CONTINUE the full-height column
|
||||
chain (body's min-height: 100dvh flex → .app-main → #view-chat →
|
||||
.chat-shell, phase 52) or .chat-shell's flex:1 loses its flex
|
||||
parent and the column sizes to content: the composer's sticky pin
|
||||
(phases 43/55/65) then has no tall scroll range and the empty chat
|
||||
stops resting at the screen bottom. The folded document views
|
||||
(tuning/rag/git-sources) size to content in normal flow — they need
|
||||
no chain. */
|
||||
#view-chat {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Chat is a vertical conversation: a centered, capped column is the
|
||||
correct layout here (PLAN §UI/UX). The surrounding frame keeps it
|
||||
from collapsing into a hairline on wide screens. The cap is the
|
||||
|
||||
+300
-289
@@ -1,8 +1,9 @@
|
||||
/* Brain of Reese — Global Tuning page (phase 27, task 03).
|
||||
/* Brain of Reese — Global Tuning view (phase 27; phase 76 task 01:
|
||||
* shell view module).
|
||||
*
|
||||
* The standalone manager for steering notes: create / list / edit /
|
||||
* delete WITHOUT a chat conversation. This module is the single owner
|
||||
* of the page's behaviour:
|
||||
* of the view's behaviour:
|
||||
*
|
||||
* • loadNotes() — GET /api/steering → the newest-first note list
|
||||
* (#tune-list) + the empty state. A failed fetch (API down, or the
|
||||
@@ -25,317 +26,327 @@
|
||||
* announce a retry. The empty state is re-checked on every removal.
|
||||
* • announce(msg) — #tune-announcer (role=status, aria-live=polite),
|
||||
* the screen-reader confirmation for create / edit / delete.
|
||||
* • header boot (task 02) — initSharedHeader(): Sign in / Sign out,
|
||||
* the admin-only Sources link, and this page's own admin-only
|
||||
* "Tuning" nav link (#nav-tuning), all decided by the module's
|
||||
* cached whoami promise (exactly one /api/whoami request per
|
||||
* page). Phase 34 task 02: the New chat binding is module-owned
|
||||
* (assets/header.js, the SINGLE one) — on a non-chat page "new
|
||||
* chat" means going to the chat, fresh (the module clears the
|
||||
* phase-14 conversation key and navigates to "/").
|
||||
*
|
||||
* Anonymous-safe (task 03): the header already hides the "Tuning" nav
|
||||
* link for anonymous visitors; a DIRECT anonymous URL still gets a safe
|
||||
* page — loadNotes() only runs when the cached whoami says admin (the
|
||||
* Sources page gate pattern), the list stays on its empty state, and
|
||||
* the create form 403s gracefully on submit (the inline error carries
|
||||
* the API detail). Note text is always rendered with textContent —
|
||||
* never innerHTML (XSS-safe, like app.js's steering panel).
|
||||
* Phase 76 (task 01) — shell view module (the "Global Tuning" view of
|
||||
* the ONE-document shell; /tuning.html now serves the shell, and
|
||||
* assets/router.js lazy-imports THIS module on first show):
|
||||
*
|
||||
* • the top-level boot is now `export async function mount(root)` —
|
||||
* root is the view's <section id="view-tuning">, and every DOM
|
||||
* lookup scopes to root (the view ids stay unique across the
|
||||
* shell — scoped lookups keep the module honest and testable).
|
||||
* The router mounts a view ONCE (mount-once, hide-forever), so
|
||||
* the binding + state survive every switch.
|
||||
* • the initSharedHeader() call is DROPPED: in the shell the shared
|
||||
* header boots exactly once, via the chat module (app.js) at shell
|
||||
* boot — the view never re-boots it. The admin gate keeps
|
||||
* fetchIsAdmin() — the SAME cached /api/whoami promise header.js
|
||||
* exports (zero extra requests; the flag decides whether the note
|
||||
* list loads at all, the Sources-page gate pattern).
|
||||
*
|
||||
* Anonymous-safe (phase 27 task 03, unchanged in the shell): the
|
||||
* header hides the "Tuning" nav link for anonymous visitors; a DIRECT
|
||||
* anonymous URL still gets a safe view — loadNotes() only runs when
|
||||
* the cached whoami says admin, the list stays on its empty state,
|
||||
* and the create form 403s gracefully on submit (the inline error
|
||||
* carries the API detail). Note text is always rendered with
|
||||
* textContent — never innerHTML (XSS-safe, like app.js's steering
|
||||
* panel).
|
||||
*
|
||||
* The shared header module loads through this script's own relative
|
||||
* import ("./header.js") — a hoisted import evaluated before this body
|
||||
* runs (single-evaluation design: no direct <script> tag; esbuild
|
||||
* inlines it into the page bundle in the image build).
|
||||
* runs (single-evaluation design: no direct <script> tag; in the
|
||||
* image the Containerfile's esbuild stage inlines it — today into the
|
||||
* router bundle, phase 76 task 01).
|
||||
*/
|
||||
|
||||
import { fetchIsAdmin, initSharedHeader } from "./header.js";
|
||||
import { fetchIsAdmin } from "./header.js";
|
||||
|
||||
/* ---------- page elements (tuning.html, task 02) ---------- */
|
||||
const tuneForm = document.querySelector("#tune-form");
|
||||
const tuneNote = document.querySelector("#tune-note");
|
||||
const tuneSave = document.querySelector("#tune-save");
|
||||
const tuneList = document.querySelector("#tune-list");
|
||||
const tuneEmpty = document.querySelector("#tune-empty");
|
||||
const tuneAnnouncer = document.querySelector("#tune-announcer");
|
||||
export async function mount(root) {
|
||||
/* ---------- page elements (the view's section, scoped to root) ---------- */
|
||||
const tuneForm = root.querySelector("#tune-form");
|
||||
const tuneNote = root.querySelector("#tune-note");
|
||||
const tuneSave = root.querySelector("#tune-save");
|
||||
const tuneList = root.querySelector("#tune-list");
|
||||
const tuneEmpty = root.querySelector("#tune-empty");
|
||||
const tuneAnnouncer = root.querySelector("#tune-announcer");
|
||||
|
||||
/* The create form's inline error (role=alert) — created once, hidden
|
||||
by default, and kept between attempts: a failed POST keeps the form
|
||||
AND its message until the next submit. */
|
||||
const createError = document.createElement("p");
|
||||
createError.className = "tuning-error";
|
||||
createError.setAttribute("role", "alert");
|
||||
createError.hidden = true;
|
||||
if (tuneForm) tuneForm.appendChild(createError);
|
||||
/* The create form's inline error (role=alert) — created once, hidden
|
||||
by default, and kept between attempts: a failed POST keeps the
|
||||
form AND its message until the next submit. */
|
||||
const createError = document.createElement("p");
|
||||
createError.className = "tuning-error";
|
||||
createError.setAttribute("role", "alert");
|
||||
createError.hidden = true;
|
||||
if (tuneForm) tuneForm.appendChild(createError);
|
||||
|
||||
/* Polite live region: the screen-reader confirmation for create /
|
||||
edit / delete (task 03). */
|
||||
function announce(message) {
|
||||
if (tuneAnnouncer) tuneAnnouncer.textContent = message;
|
||||
}
|
||||
|
||||
/* Row-action icons — inline SVG constants (aria-hidden; the buttons
|
||||
carry their own labels), the same marks as app.js's steering panel. */
|
||||
const EDIT_ICON =
|
||||
'<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20l1.2-4.2L16.7 4.3a2.1 2.1 0 0 1 3 3L8.2 18.8 4 20Z"/><path d="M14.7 6.3l3 3"/></svg>';
|
||||
const DELETE_ICON =
|
||||
'<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M5 7h14M10 7V5h4v2M8.5 7l.7 12h5.6l.7-12"/></svg>';
|
||||
|
||||
/* FastAPI error bodies: a string detail or the validation-error array
|
||||
(the first entry's msg is the human line). Same extraction as app.js. */
|
||||
async function apiDetail(r, fallback) {
|
||||
try {
|
||||
const data = await r.json();
|
||||
if (Array.isArray(data.detail) && data.detail[0] && data.detail[0].msg) {
|
||||
return String(data.detail[0].msg);
|
||||
}
|
||||
if (typeof data.detail === "string" && data.detail) return data.detail;
|
||||
} catch {
|
||||
/* non-JSON error body */
|
||||
/* Polite live region: the screen-reader confirmation for create /
|
||||
edit / delete (task 03). */
|
||||
function announce(message) {
|
||||
if (tuneAnnouncer) tuneAnnouncer.textContent = message;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/* ---------- load / render (newest first — the API's list order) ---------- */
|
||||
/* Row-action icons — inline SVG constants (aria-hidden; the buttons
|
||||
carry their own labels), the same marks as app.js's steering panel. */
|
||||
const EDIT_ICON =
|
||||
'<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20l1.2-4.2L16.7 4.3a2.1 2.1 0 0 1 3 3L8.2 18.8 4 20Z"/><path d="M14.7 6.3l3 3"/></svg>';
|
||||
const DELETE_ICON =
|
||||
'<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M5 7h14M10 7V5h4v2M8.5 7l.7 12h5.6l.7-12"/></svg>';
|
||||
|
||||
/* GET /api/steering → render. A failed fetch (API down, or the 403 on
|
||||
an anonymous direct-URL visit) keeps the last rendered list —
|
||||
progressive enhancement, never a blanked panel. */
|
||||
async function loadNotes() {
|
||||
let r;
|
||||
try {
|
||||
r = await fetch("/api/steering");
|
||||
} catch {
|
||||
return; // API unreachable: keep the last rendered list
|
||||
}
|
||||
if (!r.ok) return; // e.g. anonymous 403: keep the last rendered list
|
||||
let notes;
|
||||
try {
|
||||
notes = (await r.json()).notes || [];
|
||||
} catch {
|
||||
return; // corrupt body: keep the last rendered list
|
||||
}
|
||||
renderNotes(notes);
|
||||
}
|
||||
|
||||
function renderNotes(notes) {
|
||||
if (!tuneList) return;
|
||||
tuneList.textContent = "";
|
||||
for (const n of notes) tuneList.appendChild(makeNoteRow(n));
|
||||
syncEmptyState(notes.length);
|
||||
}
|
||||
|
||||
/* The empty state tracks the list's rendered rows (the HTML ships on
|
||||
the "No tuning notes yet" text; it hides as soon as one row shows). */
|
||||
function syncEmptyState(count) {
|
||||
if (!tuneEmpty || !tuneList) return;
|
||||
const rows = typeof count === "number" ? count : tuneList.children.length;
|
||||
tuneEmpty.hidden = rows > 0;
|
||||
}
|
||||
|
||||
/* One list row: the note text (textContent — XSS-safe, never
|
||||
innerHTML) + the Edit and Delete buttons. */
|
||||
function makeNoteRow(n) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "tuning-note";
|
||||
|
||||
const text = document.createElement("span");
|
||||
text.className = "tuning-note-text";
|
||||
text.textContent = n.note; // rendered as text, never as HTML
|
||||
li.appendChild(text);
|
||||
|
||||
const editBtn = document.createElement("button");
|
||||
editBtn.type = "button";
|
||||
editBtn.className = "tuning-edit";
|
||||
editBtn.innerHTML = EDIT_ICON + "<span>Edit</span>";
|
||||
editBtn.addEventListener("click", () => openEditForm(li, n));
|
||||
|
||||
const delBtn = document.createElement("button");
|
||||
delBtn.type = "button";
|
||||
delBtn.className = "tuning-delete";
|
||||
delBtn.setAttribute("aria-label", `Delete tuning note: ${n.note}`);
|
||||
delBtn.innerHTML = DELETE_ICON + "<span>Delete</span>";
|
||||
delBtn.addEventListener("click", () => deleteNote(n.id, delBtn, li));
|
||||
|
||||
li.append(editBtn, delBtn);
|
||||
return li;
|
||||
}
|
||||
|
||||
/* ---------- create (POST /api/steering) ---------- */
|
||||
|
||||
if (tuneForm) {
|
||||
tuneForm.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
if (tuneSave) tuneSave.disabled = true; // one note per click
|
||||
createError.hidden = true;
|
||||
/* FastAPI error bodies: a string detail or the validation-error array
|
||||
(the first entry's msg is the human line). Same extraction as app.js. */
|
||||
async function apiDetail(r, fallback) {
|
||||
try {
|
||||
const r = await fetch("/api/steering", {
|
||||
method: "POST",
|
||||
const data = await r.json();
|
||||
if (Array.isArray(data.detail) && data.detail[0] && data.detail[0].msg) {
|
||||
return String(data.detail[0].msg);
|
||||
}
|
||||
if (typeof data.detail === "string" && data.detail) return data.detail;
|
||||
} catch {
|
||||
/* non-JSON error body */
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/* ---------- load / render (newest first — the API's list order) ---------- */
|
||||
|
||||
/* GET /api/steering → render. A failed fetch (API down, or the 403 on
|
||||
an anonymous direct-URL visit) keeps the last rendered list —
|
||||
progressive enhancement, never a blanked panel. */
|
||||
async function loadNotes() {
|
||||
let r;
|
||||
try {
|
||||
r = await fetch("/api/steering");
|
||||
} catch {
|
||||
return; // API unreachable: keep the last rendered list
|
||||
}
|
||||
if (!r.ok) return; // e.g. anonymous 403: keep the last rendered list
|
||||
let notes;
|
||||
try {
|
||||
notes = (await r.json()).notes || [];
|
||||
} catch {
|
||||
return; // corrupt body: keep the last rendered list
|
||||
}
|
||||
renderNotes(notes);
|
||||
}
|
||||
|
||||
function renderNotes(notes) {
|
||||
if (!tuneList) return;
|
||||
tuneList.textContent = "";
|
||||
for (const n of notes) tuneList.appendChild(makeNoteRow(n));
|
||||
syncEmptyState(notes.length);
|
||||
}
|
||||
|
||||
/* The empty state tracks the list's rendered rows (the HTML ships on
|
||||
the "No tuning notes yet" text; it hides as soon as one row shows). */
|
||||
function syncEmptyState(count) {
|
||||
if (!tuneEmpty || !tuneList) return;
|
||||
const rows = typeof count === "number" ? count : tuneList.children.length;
|
||||
tuneEmpty.hidden = rows > 0;
|
||||
}
|
||||
|
||||
/* One list row: the note text (textContent — XSS-safe, never
|
||||
innerHTML) + the Edit and Delete buttons. */
|
||||
function makeNoteRow(n) {
|
||||
const li = document.createElement("li");
|
||||
li.className = "tuning-note";
|
||||
|
||||
const text = document.createElement("span");
|
||||
text.className = "tuning-note-text";
|
||||
text.textContent = n.note; // rendered as text, never as HTML
|
||||
li.appendChild(text);
|
||||
|
||||
const editBtn = document.createElement("button");
|
||||
editBtn.type = "button";
|
||||
editBtn.className = "tuning-edit";
|
||||
editBtn.innerHTML = EDIT_ICON + "<span>Edit</span>";
|
||||
editBtn.addEventListener("click", () => openEditForm(li, n));
|
||||
|
||||
const delBtn = document.createElement("button");
|
||||
delBtn.type = "button";
|
||||
delBtn.className = "tuning-delete";
|
||||
delBtn.setAttribute("aria-label", `Delete tuning note: ${n.note}`);
|
||||
delBtn.innerHTML = DELETE_ICON + "<span>Delete</span>";
|
||||
delBtn.addEventListener("click", () => deleteNote(n.id, delBtn, li));
|
||||
|
||||
li.append(editBtn, delBtn);
|
||||
return li;
|
||||
}
|
||||
|
||||
/* ---------- create (POST /api/steering) ---------- */
|
||||
|
||||
if (tuneForm) {
|
||||
tuneForm.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
if (tuneSave) tuneSave.disabled = true; // one note per click
|
||||
createError.hidden = true;
|
||||
try {
|
||||
const r = await fetch("/api/steering", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ note: tuneNote ? tuneNote.value : "" }),
|
||||
});
|
||||
if (r.ok) {
|
||||
if (tuneNote) tuneNote.value = ""; // 201: the note is stored
|
||||
announce("Tuning note added. Future answers will follow it.");
|
||||
await loadNotes(); // the new note lands in the list, newest first
|
||||
} else {
|
||||
createError.textContent = await apiDetail(r, "Could not add the note — try again.");
|
||||
createError.hidden = false; // form kept — the instruction survives
|
||||
}
|
||||
} catch {
|
||||
createError.textContent = "Could not add the note — is the app reachable?";
|
||||
createError.hidden = false;
|
||||
} finally {
|
||||
if (tuneSave) tuneSave.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- edit (inline form → PUT /api/steering/{id}) ----------
|
||||
* The row swaps to the inline form — the is-editing class does the
|
||||
* visual swap (styles.css hides the text + the row buttons). One open
|
||||
* form view-wide: opening a new one reverts the others. Cancel reverts
|
||||
* to the text span; a failed save keeps the form + the inline error.
|
||||
*/
|
||||
let editSeq = 0; // unique ids for the edit forms' labeled textareas
|
||||
|
||||
function openEditForm(li, n) {
|
||||
if (li.classList.contains("is-editing")) return; // one per row
|
||||
// One open form view-wide: close any other row's first.
|
||||
root.querySelectorAll(".tuning-note.is-editing").forEach((other) => {
|
||||
other.classList.remove("is-editing");
|
||||
other.querySelector(".tuning-edit-form")?.remove();
|
||||
});
|
||||
li.querySelector(".tuning-saved")?.remove(); // a stale "Saved" pill
|
||||
li.classList.add("is-editing");
|
||||
|
||||
editSeq += 1;
|
||||
const inputId = `tuning-edit-input-${editSeq}`;
|
||||
const form = document.createElement("form");
|
||||
form.className = "tuning-edit-form";
|
||||
form.dataset.noteId = n.id; // the note id rides on the form
|
||||
|
||||
const label = document.createElement("label");
|
||||
label.className = "visually-hidden";
|
||||
label.htmlFor = inputId;
|
||||
label.textContent = `Edit tuning note: ${n.note}`;
|
||||
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.id = inputId;
|
||||
textarea.className = "tuning-edit-input";
|
||||
textarea.rows = 2;
|
||||
textarea.maxLength = 2000; // client-side 1–2000 contract (server re-validates)
|
||||
textarea.required = true;
|
||||
textarea.value = n.note; // prefilled with the current text
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "tuning-edit-form-actions";
|
||||
const saveBtn = document.createElement("button");
|
||||
saveBtn.type = "submit";
|
||||
saveBtn.className = "tune-save";
|
||||
saveBtn.textContent = "Save";
|
||||
const cancelBtn = document.createElement("button");
|
||||
cancelBtn.type = "button";
|
||||
cancelBtn.className = "tune-cancel";
|
||||
cancelBtn.textContent = "Cancel";
|
||||
actions.append(saveBtn, cancelBtn);
|
||||
|
||||
const error = document.createElement("p");
|
||||
error.className = "tuning-error";
|
||||
error.setAttribute("role", "alert");
|
||||
error.hidden = true;
|
||||
|
||||
form.append(label, textarea, actions, error);
|
||||
form.addEventListener("submit", (e) => handleEditSave(e, li, form, textarea, saveBtn, error));
|
||||
cancelBtn.addEventListener("click", () => {
|
||||
li.classList.remove("is-editing"); // revert to the text span
|
||||
form.remove();
|
||||
li.querySelector(".tuning-edit")?.focus();
|
||||
});
|
||||
|
||||
li.insertBefore(form, li.querySelector(".tuning-edit"));
|
||||
textarea.focus();
|
||||
}
|
||||
|
||||
async function handleEditSave(e, li, form, textarea, saveBtn, error) {
|
||||
e.preventDefault();
|
||||
saveBtn.disabled = true;
|
||||
error.hidden = true;
|
||||
const id = form.dataset.noteId;
|
||||
try {
|
||||
const r = await fetch(`/api/steering/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ note: tuneNote ? tuneNote.value : "" }),
|
||||
body: JSON.stringify({ note: textarea.value }),
|
||||
});
|
||||
if (r.ok) {
|
||||
if (tuneNote) tuneNote.value = ""; // 201: the note is stored
|
||||
announce("Tuning note added. Future answers will follow it.");
|
||||
await loadNotes(); // the new note lands in the list, newest first
|
||||
} else {
|
||||
createError.textContent = await apiDetail(r, "Could not add the note — try again.");
|
||||
createError.hidden = false; // form kept — the instruction survives
|
||||
let saved = textarea.value.trim();
|
||||
try {
|
||||
saved = (await r.json()).note ?? saved;
|
||||
} catch {
|
||||
/* keep the trimmed local text */
|
||||
}
|
||||
const textEl = li.querySelector(".tuning-note-text");
|
||||
if (textEl) textEl.textContent = saved; // the list shows the stored text
|
||||
const savedPill = document.createElement("p");
|
||||
savedPill.className = "tuning-saved";
|
||||
savedPill.setAttribute("role", "status");
|
||||
savedPill.textContent = "Saved";
|
||||
form.replaceWith(savedPill);
|
||||
li.classList.remove("is-editing"); // updated text + row buttons come back
|
||||
announce("Tuning note updated.");
|
||||
return;
|
||||
}
|
||||
error.textContent = await apiDetail(r, "Could not update the note — try again.");
|
||||
error.hidden = false; // form kept — the edit survives the failure
|
||||
saveBtn.disabled = false;
|
||||
} catch {
|
||||
createError.textContent = "Could not add the note — is the app reachable?";
|
||||
createError.hidden = false;
|
||||
} finally {
|
||||
if (tuneSave) tuneSave.disabled = false;
|
||||
error.textContent = "Could not update the note — is the app reachable?";
|
||||
error.hidden = false;
|
||||
saveBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- edit (inline form → PUT /api/steering/{id}) ----------
|
||||
* The row swaps to the inline form — the is-editing class does the
|
||||
* visual swap (styles.css hides the text + the row buttons). One open
|
||||
* form page-wide: opening a new one reverts the others. Cancel reverts
|
||||
* to the text span; a failed save keeps the form + the inline error.
|
||||
*/
|
||||
let editSeq = 0; // unique ids for the edit forms' labeled textareas
|
||||
|
||||
function openEditForm(li, n) {
|
||||
if (li.classList.contains("is-editing")) return; // one per row
|
||||
// One open form page-wide: close any other row's first.
|
||||
document.querySelectorAll(".tuning-note.is-editing").forEach((other) => {
|
||||
other.classList.remove("is-editing");
|
||||
other.querySelector(".tuning-edit-form")?.remove();
|
||||
});
|
||||
li.querySelector(".tuning-saved")?.remove(); // a stale "Saved" pill
|
||||
li.classList.add("is-editing");
|
||||
|
||||
editSeq += 1;
|
||||
const inputId = `tuning-edit-input-${editSeq}`;
|
||||
const form = document.createElement("form");
|
||||
form.className = "tuning-edit-form";
|
||||
form.dataset.noteId = n.id; // the note id rides on the form
|
||||
|
||||
const label = document.createElement("label");
|
||||
label.className = "visually-hidden";
|
||||
label.htmlFor = inputId;
|
||||
label.textContent = `Edit tuning note: ${n.note}`;
|
||||
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.id = inputId;
|
||||
textarea.className = "tuning-edit-input";
|
||||
textarea.rows = 2;
|
||||
textarea.maxLength = 2000; // client-side 1–2000 contract (server re-validates)
|
||||
textarea.required = true;
|
||||
textarea.value = n.note; // prefilled with the current text
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "tuning-edit-form-actions";
|
||||
const saveBtn = document.createElement("button");
|
||||
saveBtn.type = "submit";
|
||||
saveBtn.className = "tune-save";
|
||||
saveBtn.textContent = "Save";
|
||||
const cancelBtn = document.createElement("button");
|
||||
cancelBtn.type = "button";
|
||||
cancelBtn.className = "tune-cancel";
|
||||
cancelBtn.textContent = "Cancel";
|
||||
actions.append(saveBtn, cancelBtn);
|
||||
|
||||
const error = document.createElement("p");
|
||||
error.className = "tuning-error";
|
||||
error.setAttribute("role", "alert");
|
||||
error.hidden = true;
|
||||
|
||||
form.append(label, textarea, actions, error);
|
||||
form.addEventListener("submit", (e) => handleEditSave(e, li, form, textarea, saveBtn, error));
|
||||
cancelBtn.addEventListener("click", () => {
|
||||
li.classList.remove("is-editing"); // revert to the text span
|
||||
form.remove();
|
||||
li.querySelector(".tuning-edit")?.focus();
|
||||
});
|
||||
|
||||
li.insertBefore(form, li.querySelector(".tuning-edit"));
|
||||
textarea.focus();
|
||||
}
|
||||
|
||||
async function handleEditSave(e, li, form, textarea, saveBtn, error) {
|
||||
e.preventDefault();
|
||||
saveBtn.disabled = true;
|
||||
error.hidden = true;
|
||||
const id = form.dataset.noteId;
|
||||
try {
|
||||
const r = await fetch(`/api/steering/${encodeURIComponent(id)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ note: textarea.value }),
|
||||
});
|
||||
if (r.ok) {
|
||||
let saved = textarea.value.trim();
|
||||
try {
|
||||
saved = (await r.json()).note ?? saved;
|
||||
} catch {
|
||||
/* keep the trimmed local text */
|
||||
/* ---------- delete (DELETE /api/steering/{id}, optimistic) ----------
|
||||
* The row leaves the DOM the moment the server agrees (204); a 404
|
||||
* (already gone) also drops the row and reloads to resync; any other
|
||||
* failure re-enables the button and says to retry. */
|
||||
async function deleteNote(id, btn, li) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const r = await fetch(`/api/steering/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
if (r.status === 404) {
|
||||
li.remove(); // already gone on the server — drop it and resync
|
||||
syncEmptyState();
|
||||
announce("That note was already removed.");
|
||||
await loadNotes();
|
||||
return;
|
||||
}
|
||||
const textEl = li.querySelector(".tuning-note-text");
|
||||
if (textEl) textEl.textContent = saved; // the list shows the stored text
|
||||
const savedPill = document.createElement("p");
|
||||
savedPill.className = "tuning-saved";
|
||||
savedPill.setAttribute("role", "status");
|
||||
savedPill.textContent = "Saved";
|
||||
form.replaceWith(savedPill);
|
||||
li.classList.remove("is-editing"); // updated text + row buttons come back
|
||||
announce("Tuning note updated.");
|
||||
return;
|
||||
}
|
||||
error.textContent = await apiDetail(r, "Could not update the note — try again.");
|
||||
error.hidden = false; // form kept — the edit survives the failure
|
||||
saveBtn.disabled = false;
|
||||
} catch {
|
||||
error.textContent = "Could not update the note — is the app reachable?";
|
||||
error.hidden = false;
|
||||
saveBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- delete (DELETE /api/steering/{id}, optimistic) ----------
|
||||
* The row leaves the DOM the moment the server agrees (204); a 404
|
||||
* (already gone) also drops the row and reloads to resync; any other
|
||||
* failure re-enables the button and says to retry. */
|
||||
async function deleteNote(id, btn, li) {
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const r = await fetch(`/api/steering/${encodeURIComponent(id)}`, { method: "DELETE" });
|
||||
if (r.status === 404) {
|
||||
li.remove(); // already gone on the server — drop it and resync
|
||||
if (!r.ok) {
|
||||
announce("Could not delete the note — try again.");
|
||||
btn.disabled = false;
|
||||
return;
|
||||
}
|
||||
li.remove(); // 204: the server confirmed — the row goes now
|
||||
syncEmptyState();
|
||||
announce("That note was already removed.");
|
||||
await loadNotes();
|
||||
return;
|
||||
}
|
||||
if (!r.ok) {
|
||||
announce("Could not delete the note — try again.");
|
||||
announce("Tuning note deleted.");
|
||||
} catch {
|
||||
announce("Could not delete the note — is the app reachable?");
|
||||
btn.disabled = false;
|
||||
return;
|
||||
}
|
||||
li.remove(); // 204: the server confirmed — the row goes now
|
||||
syncEmptyState();
|
||||
announce("Tuning note deleted.");
|
||||
} catch {
|
||||
announce("Could not delete the note — is the app reachable?");
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- header boot (task 02) ---------- */
|
||||
|
||||
/* The New chat binding is module-owned (assets/header.js, phase 34
|
||||
* task 02 — the SINGLE binding): on this non-chat page it clears the
|
||||
* phase-14 conversation key and navigates to the chat's empty state.
|
||||
*
|
||||
* Boot: the shared header FIRST (Sign in/out + the admin-only nav
|
||||
* links — one cached whoami), then the note list — admin data only
|
||||
(the Sources page gate pattern): an anonymous visitor gets the page
|
||||
frame with the empty state, and the create form 403s gracefully on
|
||||
submit if one tries. */
|
||||
(async () => {
|
||||
await initSharedHeader(); // phase 19: whoami + Sign in/out + nav links
|
||||
/* ---------- view boot (phase 76 task 01) ----------
|
||||
* The New chat binding is module-owned (assets/header.js, phase 34
|
||||
* task 02 — the SINGLE binding) and lives in the chat view only.
|
||||
*
|
||||
* Boot: the shared header is NOT booted here — in the shell it runs
|
||||
* exactly once, via the chat module (app.js) at shell boot. The note
|
||||
* list is admin data (the Sources page gate pattern): the gate reads
|
||||
* fetchIsAdmin() — the SAME cached whoami promise the header uses
|
||||
* (zero extra requests). An anonymous visitor gets the view frame
|
||||
* with the empty state, and the create form 403s gracefully on
|
||||
* submit if one tries. */
|
||||
if (await fetchIsAdmin()) loadNotes(); // phase 27: the list is admin-only
|
||||
})();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user