diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f11424e5..9302d5e7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,7 +40,7 @@ jobs: # ad-hoc defaults (13.11). Diverges from ci.yml's test matrix by design. - os: macos arch: universal - runner: macos-14 + runner: macos-15 rust-target: aarch64-apple-darwin rust-extra: x86_64-apple-darwin napi-script: build:darwin-arm64 diff --git a/apps/bookmarks/src/index.html b/apps/bookmarks/src/index.html index c5fa30d5..1e97d002 100644 --- a/apps/bookmarks/src/index.html +++ b/apps/bookmarks/src/index.html @@ -4,7 +4,7 @@ Bookmarks diff --git a/apps/books/src/app.test.tsx b/apps/books/src/app.test.tsx index 287318d8..1069b6f3 100644 --- a/apps/books/src/app.test.tsx +++ b/apps/books/src/app.test.tsx @@ -182,6 +182,23 @@ describe("BooksApp shelf", () => { expect(el.querySelector(".books__page")?.textContent).toContain("Anchor"); }); + // The inspector read the stored fraction as a bare number ("45") while the + // footer showed the live one ("23% read"); both now come from the reader. + it("shows the reader's live progress in the inspector, as a percentage", async () => { + const el = await renderApp(); + const footer = /(\d+)%/.exec(el.querySelector(".books__progress")?.textContent ?? "")?.[1]; + expect(footer).toBeDefined(); + expect(Number(footer)).toBeGreaterThan(0); + expect(el.querySelector(".bs-cell-progress-text")?.textContent).toBe(`${footer}%`); + }); + + it("carries no Pages row for a reflowable book — the footer owns the page count", async () => { + const el = await renderApp(); + const labels = [...el.querySelectorAll(".bs-props__row-label")].map((n) => n.textContent); + expect(labels).toContain("Progress"); + expect(labels).not.toContain("Pages"); + }); + // F-487 — the shared `.bs-props` inspector is `position: fixed`, so it // takes no layout space. Books centres a full-bleed reading measure under // it, so with the panel open every line ran on underneath: paragraphs read diff --git a/apps/books/src/app.tsx b/apps/books/src/app.tsx index da964549..d41b17f4 100644 --- a/apps/books/src/app.tsx +++ b/apps/books/src/app.tsx @@ -65,7 +65,7 @@ import { } from "./logic/book-open"; import { makePositionPersister, removeBookEntity, writeBookPatch } from "./logic/book-writes"; import { parseEpub } from "./logic/epub-parser"; -import { booksFromEntities } from "./logic/library"; +import { type LiveProgress, booksFromEntities, withLiveProgress } from "./logic/library"; import { type PdfInfo, pdfEnrichmentPatch } from "./logic/pdf-metadata"; import { SAMPLE_BOOK_CONTENT, sampleBook } from "./logic/sample-book"; import { type TocEntry, tocFromContent, tocFromPdfOutline } from "./logic/toc"; @@ -283,6 +283,7 @@ export function BooksApp(): ReactElement { const [openNonce, setOpenNonce] = useState(0); const [status, setStatus] = useState(ReaderStatus.Idle); const [toc, setToc] = useState([]); + const [liveProgress, setLiveProgress] = useState(null); const [showLibrary, setShowLibrary] = useState(true); const libraryAutoHide = useAutoHidePanel({ side: PanelSide.Left, collapsed: !showLibrary }); const [showInspector, setShowInspector] = useState(readInspectorPref); @@ -380,10 +381,13 @@ export function BooksApp(): ReactElement { ); const isSample = selectedId === SAMPLE_BOOK_ID; + const shelf = useMemo(() => withLiveProgress(books, liveProgress), [books, liveProgress]); const selectedBook = useMemo(() => { - if (isSample) return sample.current; - return selectedId ? (books.find((b) => b.id === selectedId) ?? null) : null; - }, [isSample, selectedId, books]); + if (isSample) { + return sample.current ? (withLiveProgress([sample.current], liveProgress)[0] ?? null) : null; + } + return selectedId ? (shelf.find((b) => b.id === selectedId) ?? null) : null; + }, [isSample, selectedId, shelf, liveProgress]); // PRES-3 — who's-here on the open book (vault rows only; not the sample). const bookPeers = usePresence( isSample ? null : (selectedBook?.id ?? null), @@ -461,6 +465,7 @@ export function BooksApp(): ReactElement { if (!stage || !controls) return undefined; setToc([]); + setLiveProgress(null); if (selectedId === null) { stage.replaceChildren(); @@ -468,9 +473,14 @@ export function BooksApp(): ReactElement { return undefined; } + const reportProgress = (progress: number): void => { + if (seq === openSeqRef.current) setLiveProgress({ bookId: selectedId, progress }); + }; + if (selectedId === SAMPLE_BOOK_ID) { const handle = mountReader(stage, controls, SAMPLE_BOOK_CONTENT, { bookId: SAMPLE_BOOK_ID, + onProgressChange: reportProgress, }); readerRef.current = { dispose: handle.dispose, goTo: handle.goTo }; setToc(tocFromContent(SAMPLE_BOOK_CONTENT)); @@ -522,6 +532,7 @@ export function BooksApp(): ReactElement { bookId: book.id, initialPosition: book.reading.position, onPositionChange: persist, + onProgressChange: reportProgress, }); readerRef.current = { dispose: handle.dispose, goTo: handle.goTo }; setToc(tocFromContent(content)); @@ -543,6 +554,7 @@ export function BooksApp(): ReactElement { const handle = mountPdfReader(stage, controls, title, port, { initialPosition: book.reading.position, onPositionChange: persist, + onProgressChange: reportProgress, onOpenLink: (url) => { // Route page links through the `open` intent so web URLs land // in the browser app (the registered `https` opener) — Books @@ -880,7 +892,7 @@ export function BooksApp(): ReactElement { data-inspector-open={selectedBook && subject && showInspector ? "true" : "false"} > { - it("maps author / format label / pages / 0-100 progress", () => { + it("maps author / format label / pages / whole-percent progress fraction", () => { const values = bookToValues(fixtureBook()); expect(values[BOOK_PROP_KEY.author]).toBe("Cal Newport"); expect(values[BOOK_PROP_KEY.format]).toBe("PDF"); expect(values[BOOK_PROP_KEY.pages]).toBe(12); - expect(values[BOOK_PROP_KEY.progress]).toBe(42); + expect(values[BOOK_PROP_KEY.progress]).toBe(0.42); }); it("hides the page count for a book without a measured spine", () => { @@ -56,8 +57,23 @@ describe("applyBookPropertyValue", () => { }); describe("bookPropertyDefs", () => { + // The bare-number cell rendered "45" beside a footer reading "45% read". + it("formats progress as a percentage over a 0..1 range", () => { + const def = bookPropertyDefs(BookFormat.Pdf).find((d) => d.key === BOOK_PROP_KEY.progress); + expect(def?.format).toBe(PropertyFormat.Percent); + expect(def?.range).toEqual({ min: 0, max: 1 }); + }); + + // An EPUB's spine length is its chapter-file count; the reflow reader + // paginates to the viewport, so "Pages 1" sat beside "Page 2 of 8". + it("omits the page count for a reflowable EPUB", () => { + const keys = bookPropertyDefs(BookFormat.Epub).map((d) => d.key); + expect(keys).not.toContain(BOOK_PROP_KEY.pages); + expect(keys).toContain(BOOK_PROP_KEY.progress); + }); + it("declares every value-map key exactly once", () => { - const keys = bookPropertyDefs().map((d) => d.key); + const keys = bookPropertyDefs(BookFormat.Pdf).map((d) => d.key); expect([...keys].sort()).toEqual(Object.values(BOOK_PROP_KEY).sort()); const values = bookToValues(fixtureBook()); for (const key of keys) expect(key in values).toBe(true); diff --git a/apps/books/src/logic/book-properties.ts b/apps/books/src/logic/book-properties.ts index 84d447f8..fdb48c5f 100644 --- a/apps/books/src/logic/book-properties.ts +++ b/apps/books/src/logic/book-properties.ts @@ -7,7 +7,12 @@ * position-persistence path, never edited by hand). */ -import { type PropertyDef, PropertyView, ValueType } from "@brainstorm-os/sdk-types"; +import { + type PropertyDef, + PropertyFormat, + PropertyView, + ValueType, +} from "@brainstorm-os/sdk-types"; import { t } from "../i18n"; import { type Book, BookFormat } from "../types/book"; @@ -18,19 +23,32 @@ export const BOOK_PROP_KEY = { progress: "progress", } as const; -export function bookPropertyDefs(): readonly PropertyDef[] { - return [ +/** The rows for a book of `format`. A reflowable EPUB has no page count of + * its own — its `spineLength` counts chapter files and the reader paginates + * to the viewport — so only a fixed-layout PDF carries the Pages row. */ +export function bookPropertyDefs(format: BookFormat): readonly PropertyDef[] { + const defs: PropertyDef[] = [ { key: BOOK_PROP_KEY.author, name: t("prop.author"), icon: null, valueType: ValueType.Text }, { key: BOOK_PROP_KEY.format, name: t("prop.format"), icon: null, valueType: ValueType.Text }, - { key: BOOK_PROP_KEY.pages, name: t("prop.pages"), icon: null, valueType: ValueType.Number }, - { - key: BOOK_PROP_KEY.progress, - name: t("prop.progress"), + ]; + if (format === BookFormat.Pdf) { + defs.push({ + key: BOOK_PROP_KEY.pages, + name: t("prop.pages"), icon: null, valueType: ValueType.Number, - display: { view: PropertyView.ProgressBar }, - }, - ]; + }); + } + defs.push({ + key: BOOK_PROP_KEY.progress, + name: t("prop.progress"), + icon: null, + valueType: ValueType.Number, + format: PropertyFormat.Percent, + range: { min: 0, max: 1 }, + display: { view: PropertyView.ProgressBar }, + }); + return defs; } export const READONLY_BOOK_PROP_KEYS: ReadonlySet = new Set([ @@ -44,14 +62,14 @@ const FORMAT_LABEL_KEYS = { [BookFormat.Epub]: "prop.format.epub", } as const; -/** Cell values for a book. Progress is 0..100 (the ProgressBar cell's - * default range). */ +/** Cell values for a book. Progress is the 0..1 fraction snapped to a whole + * percent, so the cell reads the same number as the shelf row and footer. */ export function bookToValues(book: Book): Record { return { [BOOK_PROP_KEY.author]: book.author, [BOOK_PROP_KEY.format]: t(FORMAT_LABEL_KEYS[book.format]), [BOOK_PROP_KEY.pages]: book.spineLength > 0 ? book.spineLength : null, - [BOOK_PROP_KEY.progress]: Math.round(book.reading.progress * 100), + [BOOK_PROP_KEY.progress]: Math.round(book.reading.progress * 100) / 100, }; } diff --git a/apps/books/src/logic/library.test.ts b/apps/books/src/logic/library.test.ts index 59cfb67d..b6a5e5e4 100644 --- a/apps/books/src/logic/library.test.ts +++ b/apps/books/src/logic/library.test.ts @@ -11,6 +11,7 @@ import { filterLibrary, isInProgress, sortLibrary, + withLiveProgress, } from "./library"; const SECTION_LABELS: LibrarySectionLabels = { @@ -185,3 +186,22 @@ describe("booksFromEntities", () => { expect(books[0]?.format).toBe(BookFormat.Pdf); }); }); + +// The footer measures progress against the LIVE pagination; the stored +// fraction was measured against whatever viewport last turned a page. Shown +// side by side they disagreed ("45%" in the row, "23% read" in the footer). +describe("withLiveProgress", () => { + const shelf = [reading("a", "A", 0.45, 10), reading("b", "B", 0.8, 20)]; + + it("shows the open book at the reader's live progress", () => { + const out = withLiveProgress(shelf, { bookId: "a", progress: 0.23 }); + expect(out.map((b) => b.reading.progress)).toEqual([0.23, 0.8]); + expect(out[0]?.reading.lastReadAt).toBe(10); + }); + + it("returns the same list when nothing is live or nothing differs", () => { + expect(withLiveProgress(shelf, null)).toBe(shelf); + expect(withLiveProgress(shelf, { bookId: "a", progress: 0.45 })).toBe(shelf); + expect(withLiveProgress(shelf, { bookId: "zzz", progress: 0.1 })).toBe(shelf); + }); +}); diff --git a/apps/books/src/logic/library.ts b/apps/books/src/logic/library.ts index 03c539ad..43a51370 100644 --- a/apps/books/src/logic/library.ts +++ b/apps/books/src/logic/library.ts @@ -146,6 +146,27 @@ export function continueReading(books: readonly Book[]): Book[] { return sortLibrary(books.filter(isInProgress), LibrarySort.Recent); } +/** The open book's progress as its mounted reader currently measures it. */ +export type LiveProgress = { bookId: string; progress: number }; + +/** Overlay the open reader's live progress onto the shelf. Progress is + * measured to the END of the visible page, so it depends on the pagination + * (viewport × typography) — the stored fraction is only true for the layout + * that last turned a page. Every surface that shows the open book's progress + * reads through this, so they cannot disagree with the reader footer. */ +export function withLiveProgress( + books: readonly Book[], + live: LiveProgress | null, +): readonly Book[] { + if (live === null) return books; + const index = books.findIndex((b) => b.id === live.bookId); + const book = books[index]; + if (!book || book.reading.progress === live.progress) return books; + const next = [...books]; + next[index] = { ...book, reading: { ...book.reading, progress: live.progress } }; + return next; +} + /** The persistence seam for per-book reading state. The reader calls * `saveReadingPosition` whenever the parked locator changes; the preview * drop leaves it unset (in-memory only), and 9.21.2 wires it to a diff --git a/apps/books/src/render/pdf-reader.ts b/apps/books/src/render/pdf-reader.ts index 2bbb7a83..70961b2e 100644 --- a/apps/books/src/render/pdf-reader.ts +++ b/apps/books/src/render/pdf-reader.ts @@ -75,6 +75,9 @@ export type PdfReaderOptions = { * with the stable locator + progress (0..1), mirroring the reflow * reader's contract so the host persists both modes identically. */ onPositionChange?: (locator: Locator, progress: number) => void; + /** Fired with the progress the footer shows whenever it changes, + * including on mount — mirrors the reflow reader. Display-only. */ + onProgressChange?: (progress: number) => void; /** Fired when a link in the page is clicked — the host opens it (web links * go to the browser via the `open` intent). Absent = links render but do * nothing on click. */ @@ -215,6 +218,8 @@ export function mountPdfReader( return isSpread() ? 2 : 1; } + let reportedProgress: number | null = null; + function paint(): void { if (disposed) return; applyView(); @@ -231,9 +236,14 @@ export function mountPdfReader( : t("reader.pageStatus", { page: String(state.pageIndex + 1), total }); status.textContent = pageStatus; leftCanvas.setAttribute("aria-label", `${title} — ${pageStatus}`); + const fraction = pdfProgress(state); progress.textContent = t("reader.progress", { - percent: String(Math.round(pdfProgress(state) * 100)), + percent: String(Math.round(fraction * 100)), }); + if (fraction !== reportedProgress) { + reportedProgress = fraction; + options.onProgressChange?.(fraction); + } prev.disabled = !canGoPrevPdf(state); next.disabled = !canGoNextPdf(state); if (state.pageCount <= 0) return; diff --git a/apps/books/src/render/reader.test.ts b/apps/books/src/render/reader.test.ts index e71ec2f3..d6732d33 100644 --- a/apps/books/src/render/reader.test.ts +++ b/apps/books/src/render/reader.test.ts @@ -104,6 +104,35 @@ describe("reader render with a measured page box", () => { }); }); +describe("reader live progress", () => { + const footerPercent = (root: HTMLElement): number => + Number(/(\d+)%/.exec(root.querySelector(".books__progress")?.textContent ?? "")?.[1]); + + // The footer was the only surface that knew the live number; the shelf row + // and the inspector showed the stored one until the next page turn. + it("reports the footer's progress on mount, before any page turn", () => { + const { root, right } = scaffold(); + const seen: number[] = []; + handle = mountReader(root, right, SAMPLE_BOOK_CONTENT, { + onProgressChange: (p) => seen.push(p), + }); + expect(seen).toHaveLength(1); + expect(Math.round((seen[0] ?? -1) * 100)).toBe(footerPercent(root)); + }); + + it("reports again when a page turn moves it, and stays in step with the footer", () => { + const { root, right } = scaffold(); + const seen: number[] = []; + handle = mountReader(root, right, SAMPLE_BOOK_CONTENT, { + onProgressChange: (p) => seen.push(p), + }); + root.querySelector(".books__nav-btn:last-of-type")?.click(); + expect(seen).toHaveLength(2); + expect(seen[1]).toBeGreaterThan(seen[0] ?? 1); + expect(Math.round((seen[1] ?? -1) * 100)).toBe(footerPercent(root)); + }); +}); + describe("reader render", () => { it("paints the typography controls + the first page content + page status", () => { const { root, right } = scaffold(); diff --git a/apps/books/src/render/reader.ts b/apps/books/src/render/reader.ts index 2f4bf761..0a140218 100644 --- a/apps/books/src/render/reader.ts +++ b/apps/books/src/render/reader.ts @@ -126,6 +126,11 @@ export type ReaderOptions = { * it. The preview drop leaves it unset (in-memory only). Mirrors * `onTypographyChange`. */ onPositionChange?: (locator: Locator, progress: number) => void; + /** Fired with the progress the footer shows whenever it changes — + * including on mount and on a re-pagination that moves no locator + * (progress is measured to the end of the visible page, so a resize + * changes it). Display-only: nothing is persisted off this. */ + onProgressChange?: (progress: number) => void; /** The book whose highlights these are — the `Highlight/v1.bookId`. */ bookId?: string; /** The highlight persistence seam. 9.21.6 wires these to `Highlight/v1` @@ -231,6 +236,8 @@ export function mountReader( } } + let reportedProgress: number | null = null; + function paint(): void { applyTypographyVars(); const current = currentPage(state); @@ -255,9 +262,14 @@ export function mountReader( page: String(state.pageIndex + 1), total: String(total), }); + const fraction = readingProgress(state); progress.textContent = t("reader.progress", { - percent: String(Math.round(readingProgress(state) * 100)), + percent: String(Math.round(fraction * 100)), }); + if (fraction !== reportedProgress) { + reportedProgress = fraction; + options.onProgressChange?.(fraction); + } prev.disabled = !canGoPrev(state); next.disabled = !canGoNext(state); } diff --git a/apps/books/src/styles.css b/apps/books/src/styles.css index 3b19375e..97d22b42 100644 --- a/apps/books/src/styles.css +++ b/apps/books/src/styles.css @@ -84,14 +84,19 @@ body { * open each line ran on underneath it: every paragraph appeared hard-cut * mid-word at the panel edge, and the glass blur turned the occluded tail of * each line into a grey bar inside the panel that read as a stuck loading - * skeleton beside "Author — Empty". Reserving the panel's width on the stage - * fixes both: the column recentres in the width that is actually visible. */ + * skeleton beside "Author — Empty". Reserving the panel's width fixes both: + * the column recentres in the width that is actually visible. + * + * The reservation sits on the reader ROOT, not the stage: the footer is the + * stage's sibling, so a stage-only inset left it full-bleed and its + * next-page button (the trailing end of a space-between row) under the panel. + * Padding keeps the page background running beneath the glass. */ .books__layout { --books-inspector-width: 320px; } -.books__layout[data-inspector-open="true"] .books__stage { - padding-inline-end: calc(var(--space-4) + var(--books-inspector-width)); +.books__layout[data-inspector-open="true"] .books { + padding-inline-end: var(--books-inspector-width); } .books__content { @@ -387,6 +392,15 @@ body { padding-top: 0; } +/* The shared progress cell is `width: 100%` plus a -4px inline margin (a + * hover bleed for its editable face). As a growing flex item that makes it + * 8px wider than the value column, so its trailing number ran past the + * panel padding. Books' progress is read-only — no hover face to bleed. */ +:root .books__props .bs-cell-progress { + margin-inline: 0; + padding-inline: 0; +} + /* Separate the table of contents from the property rows with the same 1px divider the meta footer uses, so CONTENTS reads as its own section. */ .books__toc { @@ -451,6 +465,9 @@ body { flex-direction: column; flex: 1 1 auto; min-height: 0; + /* Matches the inspector's own slide transition so the column glides to + * its new centre instead of jumping. */ + transition: padding-inline-end var(--motion-duration-normal, 180ms) ease; background: var(--reader-bg, var(--bg)); color: var(--reader-text, var(--text)); --reader-font-family: var(--text-family-body, var(--text-family-ui)); @@ -547,9 +564,6 @@ body { display: flex; justify-content: center; padding: var(--space-6) var(--space-4); - /* Matches the inspector's own slide transition so the column glides to - * its new centre instead of jumping. */ - transition: padding-inline-end var(--motion-duration-normal, 180ms) ease; } .books__page { diff --git a/apps/books/src/ui/inspector.tsx b/apps/books/src/ui/inspector.tsx index 1642412c..2b5434ed 100644 --- a/apps/books/src/ui/inspector.tsx +++ b/apps/books/src/ui/inspector.tsx @@ -56,7 +56,7 @@ export function BookInspector({ onClose, }: BookInspectorProps): ReactElement { const values = bookToValues(book); - const rows: PropertiesPanelRow[] = bookPropertyDefs().map((def) => { + const rows: PropertiesPanelRow[] = bookPropertyDefs(book.format).map((def) => { const locked = readOnly || READONLY_BOOK_PROP_KEYS.has(def.key); const row: PropertiesPanelRow = { def, value: values[def.key], readOnly: locked }; if (!locked) { diff --git a/apps/browser/src/app-features.test.tsx b/apps/browser/src/app-features.test.tsx index 853a7243..0a53028c 100644 --- a/apps/browser/src/app-features.test.tsx +++ b/apps/browser/src/app-features.test.tsx @@ -22,7 +22,7 @@ import { BrowserApp } from "./app"; import { type HistoryVisit, historyRecordToProperties } from "./logic/history"; import { PERSIST_DEBOUNCE_MS, sessionRecordToProperties } from "./logic/persistence"; import type { EntityRecord } from "./runtime"; -import type { BrowsingSessionRecord } from "./types/browsing-session"; +import { type BrowsingSessionRecord, NEW_TAB_URL } from "./types/browsing-session"; const popupStateListeners = vi.hoisted(() => [] as Array<(open: boolean) => void>); vi.mock("@brainstorm-os/sdk/menus", async (importOriginal) => ({ @@ -326,6 +326,38 @@ describe("BrowsingSession/v1 restore", () => { expect(webView.bounds.some((b) => b.tabId === restoredOpen?.tabId)).toBe(true); }); + it("shows the start page when the restored ACTIVE tab is a blank new tab", async () => { + const stored = storedRecord(); + const record: BrowsingSessionRecord = { + ...stored, + tabs: [ + ...stored.tabs, + { + id: "old-3", + url: NEW_TAB_URL, + title: "", + faviconUrl: null, + pinned: false, + history: [], + historyIndex: -1, + }, + ], + activeTabId: "old-3", + }; + install([{ ...sessionRow(), properties: sessionRecordToProperties(record) }]); + await render(); + await act(async () => {}); + + expect(tabTitles()).toEqual(["Tab A", "Tab B", "New tab"]); + expect(container.querySelector(".browser-start")).not.toBeNull(); + const restoredOpen = webView.opened.at(-1); + expect(restoredOpen?.url).toBe(NEW_TAB_URL); + // The native view composites above the chrome, so it must be parked or + // it covers the start page. + const lastBounds = webView.bounds.filter((b) => b.tabId === restoredOpen?.tabId).at(-1); + expect(lastBounds?.rect).toEqual({ x: 0, y: 0, width: 0, height: 0 }); + }); + it("keeps a fresh session when nothing was stored", async () => { await render(); await act(async () => {}); diff --git a/apps/browser/src/logic/persistence.test.ts b/apps/browser/src/logic/persistence.test.ts index 6aa0dd7d..a29e4cab 100644 Binary files a/apps/browser/src/logic/persistence.test.ts and b/apps/browser/src/logic/persistence.test.ts differ diff --git a/apps/browser/src/logic/persistence.ts b/apps/browser/src/logic/persistence.ts index fb48a250..eda4efaf 100644 --- a/apps/browser/src/logic/persistence.ts +++ b/apps/browser/src/logic/persistence.ts @@ -16,7 +16,7 @@ import { sanitizeInlineText } from "@brainstorm-os/sdk/sanitize-text"; import type { BrowsingSessionRecord, TabSnapshot } from "../types/browsing-session"; -import { MAX_RECENTLY_CLOSED } from "../types/browsing-session"; +import { MAX_RECENTLY_CLOSED, NEW_TAB_URL } from "../types/browsing-session"; import { isWebUrl } from "./external-open"; /** Per-tab history bound in the persisted record — a long-lived tab's @@ -86,7 +86,11 @@ function parseTab(input: unknown): TabSnapshot | null { : currentEntry !== undefined && isWebUrl(currentEntry) ? Math.max(history.indexOf(currentEntry), 0) : history.length - 1; - const url = isWebUrl(raw.url) ? raw.url : (history[historyIndex] ?? ""); + // A tab with nothing web to restore IS a blank new tab: the chrome keys the + // start page (and parking the native view under it) on `NEW_TAB_URL`, so an + // empty string here restored a tab that showed neither a page nor the start + // page. + const url = isWebUrl(raw.url) ? raw.url : (history[historyIndex] ?? NEW_TAB_URL); return { id: raw.id, url, diff --git a/apps/browser/src/styles.css b/apps/browser/src/styles.css index cbe101a6..ba3d16aa 100644 --- a/apps/browser/src/styles.css +++ b/apps/browser/src/styles.css @@ -63,7 +63,10 @@ body { align-items: center; gap: var(--space-1, var(--space-1)); height: 30px; - min-width: 96px; + /* Floor sized for the chrome (12 + 14 favicon + 8 + 4 + 18 close + 4) plus a + * short title: at 96px only ~36px was left and "New tab" ellipsised to + * "Ne…" beside 190px neighbours. The strip scrolls, so a floor is safe. */ + min-width: 128px; max-width: 220px; padding: 0 var(--space-1, var(--space-1)) 0 var(--space-3, var(--space-3)); border-radius: var(--radius-md); diff --git a/apps/chat/src/app.test.tsx b/apps/chat/src/app.test.tsx index 8021fcf1..21c980c0 100644 --- a/apps/chat/src/app.test.tsx +++ b/apps/chat/src/app.test.tsx @@ -462,6 +462,254 @@ describe("ChatApp — agent proposal cards (Agent-Teams-3)", () => { }); }); +describe("ChatApp — @agent in a channel (Agent-13)", () => { + const AGENT_APP = "io.brainstorm.agent"; + const AGENT_REF = "app:io.brainstorm.agent"; + const SELF = "pk-self"; + const rosterFor = (pubkey: string) => ({ + self: () => Promise.resolve({ pubkey, fingerprint: "fp", displayName: "Ada" }), + members: () => Promise.resolve([]), + setSelf: vi.fn(), + }); + + const pendingTask = (invokedBy: string) => ({ + artifact: { + id: "prp-1", + kind: "task", + entityType: "brainstorm/Task/v1", + fields: { title: "Ship the release notes" }, + summary: "Ship the release notes", + }, + status: "pending", + invokedBy, + }); + + function agentRow(id: string, over: Partial & { props?: Record }) { + return { + id, + type: MESSAGE_TYPE, + ownerAppId: over.ownerAppId ?? AGENT_APP, + properties: { + conversation: "c1", + body: "Here is what I found.", + createdAt: "2026-06-20T10:00:00.000Z", + seq: Number(id.replace(/\D/g, "")) || 1, + sender: { kind: "assistant", personRef: AGENT_REF, displayName: "Agent" }, + agentInvoker: { pubkey: SELF, displayName: "Ada" }, + ...over.props, + }, + } satisfies StubEntity; + } + + const card = () => container.querySelector('[data-testid="chat-proposal"]'); + const approve = () => + container.querySelector('[data-testid="chat-proposal-approve"]'); + + it("renders the reply attributed to the agent, with who asked", async () => { + await mount([channel("c1", "general"), agentRow("m1", {})], undefined, { + roster: rosterFor(SELF), + }); + expect(container.querySelector(".chat__author")?.textContent).toBe("Agent"); + expect(container.querySelector('[data-testid="agent-asked-by"]')?.textContent).toBe( + "Asked by you", + ); + }); + + it("SECURITY (R5): a synced `agentInvoker` name cannot relabel a vouched reply", async () => { + // The property is ordinary synced data — a peer can overwrite it later. + await mount( + [ + channel("c1", "general"), + agentRow("m1", { props: { agentInvoker: { pubkey: "pk-x", displayName: "Mallory" } } }), + ], + undefined, + { roster: rosterFor(SELF) }, + ); + expect(container.textContent).not.toContain("Mallory"); + expect(container.querySelector('[data-testid="agent-asked-by"]')?.textContent).toBe( + "Asked by you", + ); + }); + + it("SECURITY (R5): a member cannot paint a fake 'Agent · asked by · approved' card", async () => { + // Everything on this row is attacker-chosen synced data; main vouches for + // none of it (the row was not written by this device's Agent app). + await mount( + [ + channel("c1", "general"), + agentRow("m1", { + ownerAppId: "brainstorm", + props: { + body: "Approved: wire the money", + agentInvoker: { pubkey: "pk-victim", displayName: "Victoria" }, + agentProposalPreview: { + kind: "task", + summary: "Wire the money", + fields: { title: "Wire the money" }, + status: "approved", + }, + }, + }), + ], + undefined, + { roster: rosterFor(SELF) }, + ); + // Not attributed to the real agent, and the victim's name appears nowhere. + expect(container.querySelector(".chat__author")?.textContent).toBe("Agent (unverified)"); + expect(container.textContent).not.toContain("Victoria"); + expect(container.querySelector('[data-testid="agent-asked-by"]')).toBeNull(); + expect(card()?.dataset.trust).toBe("unverified"); + expect(card()?.textContent).toContain("Shown from another member's device · not verified"); + // An unverified card never states an outcome as fact. + expect(container.querySelector('[data-testid="chat-proposal-outcome"]')?.textContent).toBe( + "Marked approved on their device", + ); + expect(card()?.textContent).not.toContain("saved to your vault"); + }); + + it("SECURITY (R5): a forged row never groups with the real agent's replies", async () => { + await mount( + [ + channel("c1", "general"), + agentRow("m1", {}), + agentRow("m2", { ownerAppId: "brainstorm", props: { body: "forged" } }), + ], + undefined, + { roster: rosterFor(SELF) }, + ); + const authors = [...container.querySelectorAll(".chat__author")].map((n) => n.textContent); + expect(authors).toEqual(["Agent", "Agent (unverified)"]); + expect(container.querySelector('[data-testid="agent-unverified"]')?.textContent).toBe( + "Shown from another member's device · not verified", + ); + }); + + it("SECURITY: model output is rendered as TEXT — markup in a reply never becomes elements", async () => { + const hostile = + '[x](javascript:alert(1))'; + await mount([channel("c1", "general"), agentRow("m1", { props: { body: hostile } })], undefined, { + roster: rosterFor(SELF), + }); + const line = container.querySelector(".chat__line"); + expect(line?.textContent).toBe(hostile); + expect(line?.children).toHaveLength(0); + expect(container.querySelector(".chat__messages img, .chat__messages script")).toBeNull(); + expect(container.querySelector('.chat__messages a[href^="javascript:"]')).toBeNull(); + expect((window as { __pwned?: number }).__pwned).toBeUndefined(); + }); + + it("SECURITY: markup in a proposal's fields is text too", async () => { + const proposal = pendingTask(SELF); + proposal.artifact.summary = "bold"; + proposal.artifact.fields.title = "x"; + await mount( + [channel("c1", "general"), agentRow("m1", { props: { agentProposal: proposal } })], + undefined, + { roster: rosterFor(SELF) }, + ); + expect(card()?.querySelector("b, i, img")).toBeNull(); + expect(card()?.textContent).toContain("bold"); + }); + + it("the INVOKER gets a live card and approves through the host", async () => { + await mount( + [channel("c1", "general"), agentRow("m1", { props: { agentProposal: pendingTask(SELF) } })], + undefined, + { roster: rosterFor(SELF) }, + ); + expect(card()?.dataset.readonly).toBe("false"); + expect(approve()?.disabled).toBe(false); + await act(async () => { + approve()?.click(); + }); + expect(approveProposal).toHaveBeenCalledWith({ messageId: "m1" }); + }); + + it("SECURITY: a non-invoker sees the card READ-ONLY — disabled, with whose it is — and cannot decide", async () => { + await mount( + [channel("c1", "general"), agentRow("m1", { props: { agentProposal: pendingTask(SELF) } })], + undefined, + { roster: rosterFor("pk-someone-else") }, + ); + expect(card()?.dataset.readonly).toBe("true"); + // Present and disabled — never hidden — with the reason on the control. + expect(approve()?.disabled).toBe(true); + expect(approve()?.title).toBe("Only the person who asked the agent can approve or discard this."); + expect(container.querySelector('[data-testid="chat-proposal-unavailable"]')?.textContent).toBe( + "Only the person who asked the agent can approve or discard this.", + ); + await act(async () => { + approve()?.click(); + container.querySelector('[data-testid="chat-proposal-discard"]')?.click(); + }); + expect(approveProposal).not.toHaveBeenCalled(); + expect(discardProposal).not.toHaveBeenCalled(); + }); + + it("SECURITY: before the viewer's identity resolves, the card is read-only (fail-closed)", async () => { + await mount([ + channel("c1", "general"), + agentRow("m1", { props: { agentProposal: pendingTask(SELF) } }), + ]); + expect(card()?.dataset.readonly).toBe("true"); + expect(approve()?.disabled).toBe(true); + }); + + it("another member's vault shows the synced PREVIEW as a read-only card", async () => { + // What arrives over sync: no reserved property, the row owned by the + // type's prefix, only the display-only preview. + await mount( + [ + channel("c1", "general"), + agentRow("m1", { + ownerAppId: "brainstorm", + props: { + agentProposalPreview: { + kind: "task", + summary: "Ship the release notes", + fields: { title: "Ship the release notes", bogus: "dropped" }, + status: "pending", + }, + }, + }), + ], + undefined, + { roster: rosterFor("pk-bo") }, + ); + expect(card()?.dataset.readonly).toBe("true"); + expect(card()?.dataset.trust).toBe("unverified"); + expect(approve()?.title).toBe( + "Only the person who asked the agent can decide this, on their own device.", + ); + expect(card()?.textContent).toContain("Ship the release notes"); + expect(card()?.textContent).not.toContain("dropped"); + expect(approve()?.disabled).toBe(true); + }); + + it("SECURITY: a synced row carrying a full reserved-shaped proposal is still not decidable", async () => { + await mount( + [ + channel("c1", "general"), + agentRow("m1", { + ownerAppId: "brainstorm", + props: { agentProposal: pendingTask("pk-victim") }, + }), + ], + undefined, + { roster: rosterFor("pk-victim") }, + ); + // No preview, and the author is not the Agent app: an ordinary message. + expect(card()).toBeNull(); + }); + + it("SECURITY: a preview on a message that does not present as the agent grows no card", async () => { + const row = message("m1", "c1", "Mallory", "hi"); + row.properties.agentProposalPreview = { kind: "task", summary: "pwned", status: "pending" }; + await mount([channel("c1", "general"), row], undefined, { roster: rosterFor(SELF) }); + expect(card()).toBeNull(); + }); +}); + describe("ChatApp — app-icon unread badge (7.14)", () => { function seededStorage(seed: Record): { kv: Map; diff --git a/apps/chat/src/app.tsx b/apps/chat/src/app.tsx index 06e71134..e98e3c8b 100644 --- a/apps/chat/src/app.tsx +++ b/apps/chat/src/app.tsx @@ -12,6 +12,7 @@ import { useVaultEntities } from "@brainstorm-os/react-yjs"; import { openEntity } from "@brainstorm-os/sdk"; import { AttachmentKind, + BUILTIN_AGENT_MENTION_REF, IconKind, type MessageAttachment, type RosterMember, @@ -61,11 +62,18 @@ import { formatDay, formatTime, navigatorLanguage } from "./format"; import { plural, t } from "./i18n"; import { useChatT } from "./i18n-hooks"; import { + agentMentionCandidate, + queryMayMatchAgent, + resolveAgentMentionTarget, +} from "./logic/agent-mention"; +import { + AgentRowTrust, CHANNEL_TYPE, type ChatChannel, type ChatMessage, MESSAGE_TYPE, type PanelMember, + UNVERIFIED_AGENT_REF, authorColor, buildChannelProperties, buildMessageProperties, @@ -143,6 +151,17 @@ function shareDialogLabels(): ShareDialogLabels { }; } +/** Agent-13 — the header name for a row that presents as the built-in agent. + * Never the row's own (synced) display name: the vouched agent is named by + * this app, and an unverified one is labelled as exactly that. */ +function agentAuthorLabel(authorRef: string): string | null { + if (authorRef === BUILTIN_AGENT_MENTION_REF) return t("agent.name"); + if (authorRef === UNVERIFIED_AGENT_REF) { + return t("agent.unverifiedAuthor", { name: t("agent.name") }); + } + return null; +} + export function ChatApp(): ReactElement { useChatT(); const services = getBrainstorm()?.services ?? null; @@ -172,6 +191,17 @@ export function ChatApp(): ReactElement { searchCandidates: async (query: string) => { const q = query.trim().toLowerCase(); const matches: ContextCandidate[] = []; + // Agent-13 — `@agent` leads the list. It is ALWAYS offered when it + // matches: unavailable means disabled with the reason as its caption, + // never absent (an option that vanishes cannot be discovered). + if (activeId && queryMayMatchAgent(query, t)) { + const target = await resolveAgentMentionTarget( + getBrainstorm()?.capabilities, + services?.agentProposals ?? null, + ); + const candidate = agentMentionCandidate(query, target, t); + if (candidate) matches.push(candidate); + } // People come from the channel roster (Collab-C6) — actual vault // members, keyed on the sovereign pubkey so the mention resolves to a // real identity, not an arbitrary Person/v1 contact. The stored @@ -183,6 +213,7 @@ export function ChatApp(): ReactElement { // (kind-tagged), so "@Researcher" works exactly like "@Ada": // mentioning an agent invites its loop into the channel. const people = await roster.members(activeId, { includeAgents: true }); + for (const m of people) { const name = m.displayName || m.fingerprint; if (q && !name.toLowerCase().includes(q)) continue; @@ -201,7 +232,7 @@ export function ChatApp(): ReactElement { return matches; }, }), - [roster, activeId], + [roster, activeId, services], ); // Documents / objects are pinned through their own search picker (anchored to @@ -432,9 +463,13 @@ export function ChatApp(): ReactElement { void badge.set({ count: unread }).catch(() => undefined); }, [unread, marksReady, services]); + // Agent-13 — a built-in-agent card is decidable only by its invoker, so the + // projection needs this viewer's key; until it resolves every such card is + // read-only (fail-closed). + const selfPubkey = selfStatus === SelfStatus.Resolved ? identity.personRef : undefined; const persisted = useMemo( - () => (activeId ? channelMessages(entities, activeId) : []), - [entities, activeId], + () => (activeId ? channelMessages(entities, activeId, selfPubkey) : []), + [entities, activeId, selfPubkey], ); // Merge persisted messages with this channel's optimistic echoes, dropping an @@ -865,7 +900,9 @@ export function ChatApp(): ReactElement { aria-haspopup="menu" onClick={openMore} > - + + + @@ -932,8 +969,8 @@ export function ChatApp(): ReactElement {
- {g.authorName} + {agentAuthorLabel(g.authorRef) ?? g.authorName}