Compare commits

...
5 Commits
Author SHA1 Message Date
Andrew S Erwin 549c8108ea release 1.2.9: bump federated service VERSION, installer image version and mcp package version
release gate / check (push) Failing after 6m35s
release / smoke (push) Successful in 10m41s
release / publish (push) Failing after 10m0s
2026-11-11 15:05:28 -06:00
Andrew S Erwin 4914661d06 CHANGELOG: 1.2.9 page-URLs-become-bookmarks entry
release gate / check (push) Canceled after 4m20s
2026-11-11 15:01:00 -06:00
Andrew S Erwin 76a090995a Revive both browser suites and cover the URL→bookmark invariant
The regression suite had been dead since 4e421f6 removed the Next
/api/auth/login route: every run died on the first assertion. The auth
preamble now speaks the live protocol — NextAuth CSRF + credentials
callback for login, proxy Origin/Sec-Fetch-Site barriers and a fixture
mirror of Go's 415 content-type rule for the CSRF checks. Fixtures
match the current pageView projection (backlinks/links/embeds), Go's
addBookmarkId/removeBookmarkId link ops and the sidebar's link rows;
editor reads use textContent on the contenteditable.

New coverage: Link-button and bare-URL paste create a page bookmark,
re-pasting the same URL reuses the existing bookmark instead of
duplicating, and the raw Markdown text is never rewritten. e2e's pages
section drives the WYSIWYG editor properly (insertText/slash menu, no
fill() on contenteditable) and verifies paste→bookmark against the real
Go API.
2026-11-11 15:00:56 -06:00
Andrew S Erwin 3f86214cf5 Page URLs become bookmarks: paste, Link button and popover create-or-reuse a page bookmark
Product invariant: every URL a user adds to a page now becomes a bookmark
linked to that page. Bare-URL pastes and the editor Link button announce
the URL through PageEditor's new onAddUrl; the workspace reuses an
existing same-URL bookmark (normalized: scheme implied, hash dropped,
trailing slash trimmed) instead of minting duplicates, and attaches via
addBookmarkId without refetching — so an editor-triggered attach can
never reset the caret mid-typing. Pasted Markdown stays untouched; the
titled-link upgrade keeps its explicit-click rule.

Fix found by the revived suites: loadPage now repaints the uncontrolled
editor on every load, so discard/recovery no longer leaves stale draft
text on screen.
2026-11-11 15:00:48 -06:00
Andrew S Erwin 8203b8b512 CHANGELOG: 1.2.8 notifications phase 2 entry
release gate / check (push) Failing after 7m19s
2026-11-09 17:44:02 -06:00
9 changed files with 290 additions and 60 deletions
+46
View File
@@ -6,6 +6,52 @@ Versions correspond to git tags and to the published image set
(`service` VERSION, installer image version) move in lockstep from 1.2.0 on. (`service` VERSION, installer image version) move in lockstep from 1.2.0 on.
Dates are tag dates. Dates are tag dates.
## 1.2.9 — 2026-11-11
### Added
- **Page URLs become bookmarks** (product invariant): every URL a user
adds to a page — the links popover's "Save & add", the editor Link
button, or a bare-URL pasted straight into the text — now creates a
bookmark linked to that page (`POST /api/bookmarks` + `addBookmarkId`).
An existing same-URL bookmark (after normalization) is **reused** rather
than duplicated. Pasted Markdown text is never rewritten — the
titled-link upgrade keeps its explicit-click rule.
- Browser regressions and e2e cover the new invariant, including the
duplicate-URL reuse path.
### Fixed
- Discarding a conflict draft (or reloading onto a recovered page) now
repaints the editor with the fresh server content; the uncontrolled
TipTap document previously kept the discarded draft on screen.
- The browser regression suite had been dead since `4e421f6` removed the
Next `/api/auth/login` route — every run died on the very first
assertion. The auth preamble now speaks the live protocol (NextAuth
CSRF + credentials callback; proxy Origin/Sec-Fetch-Site barriers; the
415 content-type mirror of Go), the fixtures match the current
`pageView` projection and sidebar links, and the e2e pages section
drives the WYSIWYG editor the way the product actually works.
## 1.2.8 — 2026-11-09
### Added
- **Notifications phase 2** (the old Gitea #10 ask): `share_received`
trigger (bookmark/tag/collection shared with you); targeted recipients
via `config.targetUserIds` (same tenant, ≤20) delivered through each
target's **own** enabled channel of the rule's kind, gated by the
target's plan, with `recipientId` in history (which now lists rows you
own *or* were targeted on); `signal` channel kind via a signal-cli REST
bridge (sender account encrypted + masked like every credential);
Settings → Notifications gained the trigger option, a same-tenant target
picker and the Signal fields.
- **Managed-by footer**: deliveries for tenants on the free hosted plan
carry "Managed by David's Superbrain."; paying plans, core and
self-hosted never do. Plan data (`entitlements.ManagedFooter`, override
key `managed_footer`), appended at delivery time.
### Changed
- Entitlement catalog: `signal` joins the standard/premium/core/selfhosted
channel allowlists.
## 1.2.7 — 2026-11-09 ## 1.2.7 — 2026-11-09
### Added ### Added
+1 -1
View File
@@ -48,7 +48,7 @@ SUPERBRAIN_APP_IP="192.168.0.94"
SUPERBRAIN_MIGRATE_IP="192.168.0.95" SUPERBRAIN_MIGRATE_IP="192.168.0.95"
# Release to install; the generic `upgrade` flow keeps .env in step with the # Release to install; the generic `upgrade` flow keeps .env in step with the
# service file's VERSION afterwards. # service file's VERSION afterwards.
SUPERBRAIN_IMAGE_VERSION="1.2.8" SUPERBRAIN_IMAGE_VERSION="1.2.9"
# render_superbrain_compose writes the app-dir compose file. Called by # render_superbrain_compose writes the app-dir compose file. Called by
# config_superbrain (install) and by deploy/federated/update.sh after a lib # config_superbrain (install) and by deploy/federated/update.sh after a lib
+1 -1
View File
@@ -2,7 +2,7 @@ NAME=superbrain
DESCRIPTION="Bookmark & Knowledge Base" DESCRIPTION="Bookmark & Knowledge Base"
DOCS=https://github.com/andrew/superbrain DOCS=https://github.com/andrew/superbrain
CONTAINER=federatedcomputer/superbrain-app CONTAINER=federatedcomputer/superbrain-app
VERSION=1.2.8 VERSION=1.2.9
INTERNAL_IP=192.168.0.93 INTERNAL_IP=192.168.0.93
DEPENDS="postgresql" DEPENDS="postgresql"
PORTS=3000 PORTS=3000
+1 -1
View File
@@ -7,7 +7,7 @@ name = "superbrain-mcp"
# Versioned in lockstep with the Superbrain release it speaks to (house # Versioned in lockstep with the Superbrain release it speaks to (house
# tooling tracks one version per app); the federated mcpserver gateway # tooling tracks one version per app); the federated mcpserver gateway
# installs this package and spawns `superbrain-mcp` per linked instance. # installs this package and spawns `superbrain-mcp` per linked instance.
version = "1.2.8" version = "1.2.9"
description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API" description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API"
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
+1 -1
View File
@@ -1,3 +1,3 @@
"""Superbrain MCP server — bookmarks, tags and pages for AI tooling.""" """Superbrain MCP server — bookmarks, tags and pages for AI tooling."""
__version__ = "1.2.8" __version__ = "1.2.9"
+38 -13
View File
@@ -135,27 +135,52 @@ try {
const moved = await json(await context.request.delete(`${base}/api/kanban/columns/${custom.id}`)) const moved = await json(await context.request.delete(`${base}/api/kanban/columns/${custom.id}`))
assert.equal(moved.moved, 1) assert.equal(moved.moved, 1)
await page.goto(`${base}/pages`) await page.goto(`${base}/pages`)
await page.locator('main').getByRole('button', { name: 'New page', exact: true }).click() await page.getByRole('button', { name: 'New page', exact: true }).click()
await page.getByRole('textbox', { name: 'Page title' }).waitFor() await page.getByRole('textbox', { name: 'Page title' }).waitFor()
await page.getByPlaceholder('Write Markdown notes… type / for blocks, paste links, lists, thoughts.').fill('# QA page\n\nAutosaved markdown.') // TipTap contenteditable: drive it with keyboard.insertText (fill() does
// not work on contenteditable) and watch the workspace save badge.
const editor = page.locator('[data-page-editor]')
await editor.click()
await page.keyboard.insertText('Autosaved markdown from browser QA.')
await page.getByText('Saved', { exact: true }).waitFor() await page.getByText('Saved', { exact: true }).waitFor()
const pages = await json(await context.request.get(`${base}/api/pages`)) const pages = await json(await context.request.get(`${base}/api/pages`))
const detail = await json(await context.request.get(`${base}/api/pages/${pages[0].id}`)) let created = null
assert.equal(detail.content, '# QA page\n\nAutosaved markdown.') for (const p of pages) {
const detail = await json(await context.request.get(`${base}/api/pages/${p.id}`))
if (detail.content.includes('Autosaved markdown from browser QA.')) { created = detail; break }
}
assert.ok(created, 'autosaved page content never reached the API')
// Notion-style slash menu: "/h2" at the start of a line inserts a heading. // Notion-style slash menu: "/h2" at the start of a line inserts a heading.
const editor = page.getByPlaceholder('Write Markdown notes… type / for blocks, paste links, lists, thoughts.')
await editor.click() await editor.click()
await page.keyboard.press('Control+End') await page.keyboard.press('End')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await page.keyboard.type('/h2') await page.keyboard.type('/h2')
await page.getByRole('option', { name: /Heading 2/ }).click() await page.getByRole('option', { name: /Heading 2/ }).click()
await editor.evaluate((el, suffix) => new Promise((resolve, reject) => { await page.keyboard.type('QA heading')
const timeout = setTimeout(() => reject(new Error(`slash command did not insert heading: ${JSON.stringify(el.value)}`)), 5000) await page.getByText('Saved', { exact: true }).waitFor()
const check = setInterval(() => { if (el.value.endsWith(suffix)) { clearTimeout(timeout); clearInterval(check); resolve() } }, 25) const slashed = await json(await context.request.get(`${base}/api/pages/${created.id}`))
}), '\n## ') assert.ok(slashed.content.includes('## QA heading'), `slash command did not insert heading: ${JSON.stringify(slashed.content)}`)
console.log('PASS: slash command menu inserts Markdown blocks') console.log('PASS: pages autosave and slash commands insert Markdown headings')
await json(await context.request.patch(`${base}/api/pages/${pages[0].id}`, { data: { addBookmarkId: bookmark.id } })) await json(await context.request.patch(`${base}/api/pages/${created.id}`, { data: { addBookmarkId: bookmark.id } }))
const markdown = await context.request.get(`${base}/api/pages/${pages[0].id}/markdown`) // Product invariant: a URL added to the page (paste) becomes a bookmark.
// insertText does not fire ProseMirror's paste handler, so dispatch a real
// ClipboardEvent; arm both network waits before the event.
const bookmarkPost = page.waitForResponse(r => r.url().includes('/api/bookmarks') && r.request().method() === 'POST')
const linkPatch = page.waitForResponse(r => r.request().method() === 'PATCH' && r.url().includes('/api/pages/') && Boolean(r.request().postDataJSON()?.addBookmarkId))
await editor.click()
await page.keyboard.press('Control+a')
await page.evaluate(() => {
const dt = new DataTransfer()
dt.setData('text/plain', 'https://e2e-url.test/qa-page-link')
document.querySelector('[data-page-editor]')
.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
})
const created2 = await (await bookmarkPost).json()
await linkPatch
const linked = await json(await context.request.get(`${base}/api/pages/${created.id}`))
assert.ok(created2.url === 'https://e2e-url.test/qa-page-link', 'paste created a bookmark for the wrong URL')
assert.ok(linked.bookmarks.some(b => b.bookmark.url === 'https://e2e-url.test/qa-page-link'), 'pasted URL did not become a page bookmark')
const markdown = await context.request.get(`${base}/api/pages/${created.id}/markdown`)
assert.equal(markdown.status(), 200) assert.equal(markdown.status(), 200)
assert.ok((await markdown.text()).includes('Browser QA bookmark')) assert.ok((await markdown.text()).includes('Browser QA bookmark'))
// Collections (Notion-like upgrades phase 2, validation scenario): an // Collections (Notion-like upgrades phase 2, validation scenario): an
+116 -24
View File
@@ -5,7 +5,10 @@ import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright' import { chromium } from 'playwright'
// The real built Next server/UI with isolated API fixtures: no app users or DB writes. // The real built Next server/UI with isolated API fixtures: no app users or DB writes.
const pages = new Map(['a', 'b'].map((id, position) => [id, { id, title: `Page ${id.toUpperCase()}`, content: '', version: 1, position, pinned: false, bookmarks: [] }])) // The real Go projection (pageView) always carries these arrays; the fixture
// must too, or client code reading them crashes exactly as the tests prove.
const newPageFixture = (id, position) => ({ id, title: `Page ${id.toUpperCase()}`, content: '', version: 1, position, pinned: false, bookmarks: [], backlinks: [], links: [], embeds: [] })
const pages = new Map(['a', 'b'].map((id, position) => [id, newPageFixture(id, position)]))
const tags = [{ id: 'one', name: 'First tag', color: '#123456' }, { id: 'two', name: 'Second tag', color: '#654321' }] const tags = [{ id: 'one', name: 'First tag', color: '#123456' }, { id: 'two', name: 'Second tag', color: '#654321' }]
const kanbanColumns = [ const kanbanColumns = [
{ id: 'inbox', label: 'Inbox', color: '#123456', key: 'INBOX', position: 0 }, { id: 'inbox', label: 'Inbox', color: '#123456', key: 'INBOX', position: 0 },
@@ -43,6 +46,15 @@ const api = http.createServer(async (req, res) => {
try { try {
let raw = '' let raw = ''
for await (const chunk of req) raw += chunk for await (const chunk of req) raw += chunk
// Mirror Go's content-type discipline (internal/http security_test):
// mutating requests carrying a non-JSON Content-Type are rejected
// outright — the body is never JSON-sniffed.
const ctype = (req.headers['content-type'] || '').split(';')[0].trim().toLowerCase()
if (!['GET', 'HEAD', 'DELETE'].includes(req.method) && req.headers['content-type'] && ctype !== 'application/json') {
res.writeHead(415, { 'Content-Type': 'application/json' })
res.end('{"error":"Content-Type must be application/json"}')
return
}
const body = raw ? JSON.parse(raw) : {} const body = raw ? JSON.parse(raw) : {}
const url = new URL(req.url, 'http://fixture') const url = new URL(req.url, 'http://fixture')
let result = [] let result = []
@@ -81,15 +93,35 @@ const api = http.createServer(async (req, res) => {
activeSaves++ activeSaves++
maxConcurrentSaves = Math.max(maxConcurrentSaves, activeSaves) maxConcurrentSaves = Math.max(maxConcurrentSaves, activeSaves)
await new Promise(resolve => setTimeout(resolve, delaySaves)) await new Promise(resolve => setTimeout(resolve, delaySaves))
const { version, ...data } = body const { version, addBookmarkId, removeBookmarkId, ...data } = body
Object.assign(target, data) Object.assign(target, data)
// Mirrors Go's page PATCH link ops: add is visibility-checked and
// idempotent (ON CONFLICT DO NOTHING), remove just detaches.
if (removeBookmarkId) target.bookmarks = target.bookmarks.filter(x => x.bookmark.id !== removeBookmarkId)
if (addBookmarkId && !target.bookmarks.some(x => x.bookmark.id === addBookmarkId)) {
const bookmark = bookmarks.find(b => b.id === addBookmarkId)
if (bookmark) target.bookmarks.push({ pageId: id, bookmarkId: bookmark.id, position: target.bookmarks.length, bookmark })
}
if ('content' in body) target.version++ if ('content' in body) target.version++
activeSaves-- activeSaves--
} }
result = pages.get(id) result = pages.get(id)
} else if (url.pathname === '/api/bookmarks' && req.method === 'POST') {
const bookmark = {
id: `bookmark-${bookmarks.length}`, ownerId: 'fixture-user', title: body.url, url: body.url,
description: '', notes: '', tags: [], sharedWith: [], kanbanStatus: 'INBOX', kanbanColumnId: null, kanbanPosition: null,
isPublic: false, imapWatchEnabled: false, alertAt: null, dueDate: null, version: 0,
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
}
bookmarks.push(bookmark)
result = bookmark
} else if (url.pathname === '/api/bookmarks') { } else if (url.pathname === '/api/bookmarks') {
const shared = url.searchParams.get('shared') === 'true' const shared = url.searchParams.get('shared') === 'true'
const matching = shared ? [] : bookmarks.filter(b => b.title.includes(url.searchParams.get('search') || '')) const q = (url.searchParams.get('search') || '').toLowerCase()
// Go's search matches title, url, notes and tags (bookmarks.go); the
// url match is what lets the pages workspace reuse an existing bookmark
// for a URL instead of creating a duplicate.
const matching = shared ? [] : bookmarks.filter(b => !q || b.title.toLowerCase().includes(q) || b.url.toLowerCase().includes(q))
const offset = Number(url.searchParams.get('cursor') || 0) const offset = Number(url.searchParams.get('cursor') || 0)
const limit = Number(url.searchParams.get('limit') || 200) const limit = Number(url.searchParams.get('limit') || 200)
// Mirror the Go permission-specific projections (PRIV-02): shared // Mirror the Go permission-specific projections (PRIV-02): shared
@@ -192,7 +224,7 @@ for (let attempt = 1; attempt <= 3; attempt++) {
} }
const attacker = http.createServer((req, res) => { const attacker = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html') res.setHeader('Content-Type', 'text/html')
res.end(`<form method="POST" action="${base}/api/auth/login" enctype="text/plain"><input name='{"email":"attacker@superbrain.test","password":"password","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`) res.end(`<form method="POST" action="${base}/api/pages" enctype="text/plain"><input name='{"title":"forged","extra":"' value='"}'></form><script>document.forms[0].submit()</script>`)
}) })
await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve)) await new Promise(resolve => attacker.listen(0, '127.0.0.1', resolve))
async function eventually(check, label) { async function eventually(check, label) {
@@ -202,6 +234,19 @@ async function eventually(check, label) {
} }
assert.fail(label) assert.fail(label)
} }
// The UI logs in through NextAuth's credentials callback (app/login/client.tsx
// signIn('credentials')); the standalone Next /api/auth/login route was removed
// as dead in 4e421f6, so the tests must speak the same protocol as the browser:
// fetch a CSRF token, POST the callback, and prove the session landed.
async function fixtureLogin(context) {
const { csrfToken } = await context.request.get(`${base}/api/auth/csrf`).then(r => r.json())
await context.request.post(`${base}/api/auth/callback/credentials`, {
headers: { Origin: base },
form: { csrfToken, email: 'fixture@superbrain.test', password: 'password', callbackUrl: `${base}/pages` },
})
const session = await context.request.get(`${base}/api/auth/session`).then(r => r.json())
assert.equal(session?.user?.id, 'fixture-user', 'fixture login did not establish a NextAuth session')
}
let browser let browser
try { try {
await eventually(async () => { try { return (await fetch(`${base}/login`)).ok } catch { return false } }, `Next server did not start: ${logs}`) await eventually(async () => { try { return (await fetch(`${base}/login`)).ok } catch { return false } }, `Next server did not start: ${logs}`)
@@ -212,17 +257,25 @@ try {
page.on('pageerror', error => errors.push(error.message)) page.on('pageerror', error => errors.push(error.message))
page.on('dialog', dialog => dialog.accept()) page.on('dialog', dialog => dialog.accept())
await page.goto(`http://127.0.0.1:${attacker.address().port}`) await page.goto(`http://127.0.0.1:${attacker.address().port}`)
await page.waitForURL(`${base}/api/auth/login`) await page.waitForURL(`${base}/api/pages`)
await page.getByText('Invalid request origin').waitFor()
assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined) assert.equal((await context.request.get(`${base}/api/auth/session`).then(r => r.json()))?.user, undefined)
for (const headers of [{ Origin: 'https://attacker.invalid' }, {}]) { // Proxy CSRF barriers (web/app/api/[...path]/route.ts): a present attacker
const response = await context.request.post(`${base}/api/auth/login`, { headers, data: { email: 'attacker@superbrain.test', password: 'password' } }) // Origin is rejected, and a stripped Origin cannot bypass the check for a
assert.equal(response.status(), 403) // cross-site Sec-Fetch-Site mutation.
for (const headers of [{ Origin: 'https://attacker.invalid' }, { 'sec-fetch-site': 'cross-site' }]) {
const response = await fetch(`${base}/api/pages`, {
method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: '{"title":"forged"}',
})
assert.equal(response.status, 403, `mutating proxy request survived ${JSON.stringify(headers)}`)
} }
const plain = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base, 'Content-Type': 'text/plain' }, data: '{"email":"attacker@superbrain.test"}' }) // Go rejects non-JSON bodies with 415 (internal/http security_test); the
assert.equal(plain.status(), 415) // fixture mirrors that discipline so the Next proxy's content-type
const login = await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } }) // passthrough is exercised end to end.
assert.equal(login.status(), 200) const plain = await fetch(`${base}/api/pages`, { method: 'POST', headers: { Origin: base, 'Content-Type': 'text/plain' }, body: '{"title":"forged"}' })
console.log('PASS: forged logins rejected; legitimate login works') assert.equal(plain.status, 415)
await fixtureLogin(context)
console.log('PASS: cross-site form posts and forged mutations rejected; fixture login works through NextAuth')
// Review CR-14: an oversized chunked body (no usable Content-Length) must // Review CR-14: an oversized chunked body (no usable Content-Length) must
// be rejected by the proxy's streaming limit — counted while read and // be rejected by the proxy's streaming limit — counted while read and
@@ -251,7 +304,7 @@ try {
} }
await page.goto(`${base}/pages?id=a`) await page.goto(`${base}/pages?id=a`)
await setEditorText('A edits before switching') await setEditorText('A edits before switching')
await page.getByRole('button', { name: 'Page B', exact: true }).click() await page.getByRole('link', { name: 'Page B', exact: true }).click()
await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page B'), 'Page B not selected') await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page B'), 'Page B not selected')
await setEditorText('B edits') await setEditorText('B edits')
await eventually(() => pages.get('b').content === 'B edits', 'Page B not saved') await eventually(() => pages.get('b').content === 'B edits', 'Page B not saved')
@@ -270,11 +323,14 @@ try {
failSaves = true failSaves = true
await setEditorText('Recover this failed draft') await setEditorText('Recover this failed draft')
await page.getByRole('button', { name: 'Page A', exact: true }).click() await page.getByRole('link', { name: 'Page A', exact: true }).click()
await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor()
assert.equal(await page.getByRole('textbox', { name: 'Page title' }).inputValue(), 'Page B') assert.equal(await page.getByRole('textbox', { name: 'Page title' }).inputValue(), 'Page B')
await page.reload() // The sidebar row is a <Link>, so the URL may move to ?id=a even while the
await eventually(() => editor.inputValue().then(value => value === 'Recover this failed draft'), 'Draft not recovered after reload') // workspace keeps its unsaved B draft. Recovery lives per page — reload
// where the draft actually is.
await page.goto(`${base}/pages?id=b`)
await eventually(() => editor.textContent().then(value => value === 'Recover this failed draft'), 'Draft not recovered after reload')
failSaves = false failSaves = false
await page.getByRole('button', { name: 'Save now', exact: true }).click() await page.getByRole('button', { name: 'Save now', exact: true }).click()
await eventually(() => pages.get('b').content === 'Recover this failed draft', 'Retry did not persist draft') await eventually(() => pages.get('b').content === 'Recover this failed draft', 'Retry did not persist draft')
@@ -312,7 +368,7 @@ try {
pages.get('b').version++ pages.get('b').version++
failSaves = false failSaves = false
await page.reload() await page.reload()
await eventually(() => editor.inputValue().then(value => value === 'Draft with an older base'), 'Draft not recovered after reload') await eventually(() => editor.textContent().then(value => value === 'Draft with an older base'), 'Draft not recovered after reload')
await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() await page.getByText('This page was changed elsewhere', { exact: true }).waitFor()
// Snapshot AFTER recovery: the reload itself lets the departing page flush // Snapshot AFTER recovery: the reload itself lets the departing page flush
// its dirty draft once (the fixture rejects it with a 409 against the newer // its dirty draft once (the fixture rejects it with a 409 against the newer
@@ -322,7 +378,7 @@ try {
assert.equal(patchAttempts, attemptsAfterRecovery, 'Recovered draft saved without an explicit resolution') assert.equal(patchAttempts, attemptsAfterRecovery, 'Recovered draft saved without an explicit resolution')
assert.equal(pages.get('b').content, 'Remote saved while draft failed', 'Recovery rebased onto and clobbered the newer version') assert.equal(pages.get('b').content, 'Remote saved while draft failed', 'Recovery rebased onto and clobbered the newer version')
await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click()
await eventually(() => editor.inputValue().then(value => value === 'Remote saved while draft failed'), 'Discard did not load the remote content') await eventually(() => editor.textContent().then(value => value === 'Remote saved while draft failed'), 'Discard did not load the remote content')
console.log('PASS: recovered drafts keep their original base and conflict instead of rebasing') console.log('PASS: recovered drafts keep their original base and conflict instead of rebasing')
// Unknown-provenance draft (review DATA-06): a legacy plain-string draft // Unknown-provenance draft (review DATA-06): a legacy plain-string draft
@@ -334,13 +390,13 @@ try {
await page.evaluate(() => sessionStorage.setItem('superbrain:page-draft:a', JSON.stringify('Legacy draft of unknown origin'))) await page.evaluate(() => sessionStorage.setItem('superbrain:page-draft:a', JSON.stringify('Legacy draft of unknown origin')))
const attemptsBeforeLegacy = patchAttempts const attemptsBeforeLegacy = patchAttempts
await page.reload() await page.reload()
await eventually(() => editor.inputValue().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered') await eventually(() => editor.textContent().then(value => value === 'Legacy draft of unknown origin'), 'Legacy draft not recovered')
await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() await page.getByText('This page was changed elsewhere', { exact: true }).waitFor()
await new Promise(resolve => setTimeout(resolve, 1000)) await new Promise(resolve => setTimeout(resolve, 1000))
assert.equal(patchAttempts, attemptsBeforeLegacy, 'Unknown-base draft saved without review') assert.equal(patchAttempts, attemptsBeforeLegacy, 'Unknown-base draft saved without review')
assert.equal(pages.get('a').content, 'Typing must not overwrite', 'Unknown-base draft clobbered the remote content') assert.equal(pages.get('a').content, 'Typing must not overwrite', 'Unknown-base draft clobbered the remote content')
await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click()
await eventually(() => editor.inputValue().then(value => value === 'Typing must not overwrite'), 'Discard did not load the remote content') await eventually(() => editor.textContent().then(value => value === 'Typing must not overwrite'), 'Discard did not load the remote content')
console.log('PASS: unknown-base legacy drafts pause for review instead of saving') console.log('PASS: unknown-base legacy drafts pause for review instead of saving')
// Envelope refresh (review DATA-07): when a later save in the same serial // Envelope refresh (review DATA-07): when a later save in the same serial
@@ -356,7 +412,7 @@ try {
await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor()
assert.equal(pages.get('b').content, 'Envelope part one', 'First save of the loop did not land') assert.equal(pages.get('b').content, 'Envelope part one', 'First save of the loop did not land')
await page.reload() await page.reload()
await eventually(() => editor.inputValue().then(value => value === 'Envelope part two'), 'Newest loop content not recovered') await eventually(() => editor.textContent().then(value => value === 'Envelope part two'), 'Newest loop content not recovered')
assert.equal(await page.getByText('This page was changed elsewhere', { exact: true }).count(), 0, assert.equal(await page.getByText('This page was changed elsewhere', { exact: true }).count(), 0,
'Recovery hit a spurious conflict — the stored base was not refreshed after the successful save') 'Recovery hit a spurious conflict — the stored base was not refreshed after the successful save')
delaySaves = 0 delaySaves = 0
@@ -380,7 +436,7 @@ try {
await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() await page.getByText('This page was changed elsewhere', { exact: true }).waitFor()
assert.equal(pages.get('a').content, 'Remote content stays', 'Metadata response rebased the stale draft over the remote content') assert.equal(pages.get('a').content, 'Remote content stays', 'Metadata response rebased the stale draft over the remote content')
await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click()
await eventually(() => editor.inputValue().then(value => value === 'Remote content stays'), 'Discard did not load the remote content') await eventually(() => editor.textContent().then(value => value === 'Remote content stays'), 'Discard did not load the remote content')
console.log('PASS: metadata mutations do not rebase stale content drafts') console.log('PASS: metadata mutations do not rebase stale content drafts')
await page.goto(`${base}/bookmarks`) await page.goto(`${base}/bookmarks`)
@@ -442,6 +498,42 @@ try {
await inboxColumn.locator('[data-bookmark-id="bookmark-3"]').waitFor() await inboxColumn.locator('[data-bookmark-id="bookmark-3"]').waitFor()
console.log('PASS: kanban drag reorders within a column and moves cards between columns') console.log('PASS: kanban drag reorders within a column and moves cards between columns')
// URLs added to a page become bookmarks (product invariant): the editor's
// Link button and a bare-URL paste each create — or reuse — a bookmark and
// attach it under "Links on this page". The pasted Markdown itself is
// never rewritten without an explicit click.
await page.goto(`${base}/pages?id=a`)
await page.locator('[data-page-editor]').waitFor()
await page.evaluate(() => { window.prompt = () => 'https://pages-url.test/report' })
await page.getByRole('button', { name: 'Link', exact: true }).click()
await eventually(() => bookmarks.some(b => b.url === 'https://pages-url.test/report'), 'Link button did not save the URL as a bookmark')
await eventually(() => pages.get('a').bookmarks.some(x => x.bookmark.url === 'https://pages-url.test/report'), 'Link button bookmark was not attached to the page')
await page.getByText('pages-url.test').first().waitFor()
// Re-adding the same URL attaches nothing new: no duplicate bookmark row,
// no second link.
const urlsBefore = bookmarks.length
await page.evaluate(() => { window.prompt = () => 'https://pages-url.test/report/' })
await page.getByRole('button', { name: 'Link', exact: true }).click()
await new Promise(resolve => setTimeout(resolve, 600))
assert.equal(bookmarks.length, urlsBefore, 'Re-adding the same URL created a duplicate bookmark')
assert.equal(pages.get('a').bookmarks.filter(x => x.bookmark.url.startsWith('https://pages-url.test')).length, 1, 'Duplicate URL attached twice')
// A bare-URL paste reuses the EXISTING library bookmark whose url matches
// (search covers urls server-side) instead of POSTing a new one, and the
// raw text stays in the document.
const pasteTarget = bookmarks.find(b => b.url === 'https://127.0.0.1/changed')
await page.locator('[data-page-editor]').click()
await page.evaluate((url) => {
const dt = new DataTransfer()
dt.setData('text/plain', url)
document.querySelector('[data-page-editor]')
.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
}, 'https://127.0.0.1/changed')
await eventually(() => pages.get('a').bookmarks.some(x => x.bookmark.id === pasteTarget.id), 'Pasted URL did not attach the existing bookmark')
await eventually(() => pages.get('a').content.includes('https://127.0.0.1/changed'), 'Pasted URL text was not inserted and saved')
assert.equal(bookmarks.length, urlsBefore, 'Pasted URL created a duplicate bookmark instead of reusing the existing one')
assert.ok(!pages.get('a').content.includes('[https://127.0.0.1/changed]'), 'Pasted URL was rewritten without an explicit click')
console.log('PASS: URLs added to a page (Link button and paste) become page bookmarks, reusing existing rows')
// The sidebar persists the complete order permutation (PUT /api/pages); // The sidebar persists the complete order permutation (PUT /api/pages);
// drag b above a. Reset the pin from the earlier metadata test so both // drag b above a. Reset the pin from the earlier metadata test so both
// pages are in one reorder group. // pages are in one reorder group.
@@ -480,7 +572,7 @@ try {
// backstop) posts to Go /api/auth/signout with a signed assertion, so the // backstop) posts to Go /api/auth/signout with a signed assertion, so the
// tokenVersion bump kills Go cookie sessions and any previously minted // tokenVersion bump kills Go cookie sessions and any previously minted
// assertions — not just the local NextAuth JWT. // assertions — not just the local NextAuth JWT.
await context.request.post(`${base}/api/auth/login`, { headers: { Origin: base }, data: { email: 'fixture@superbrain.test', password: 'password' } }) await fixtureLogin(context)
await page.goto(`${base}/pages`) await page.goto(`${base}/pages`)
const revoked = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST') const revoked = page.waitForResponse(r => r.url().includes('/api/session/revoke') && r.request().method() === 'POST')
await page.getByRole('button', { name: 'Sign out', exact: true }).click() await page.getByRole('button', { name: 'Sign out', exact: true }).click()
+68 -18
View File
@@ -35,6 +35,20 @@ type PageRevisionDetail = PageRevisionSummary & { content: string; icon: string
const notify = notifyPagesChanged const notify = notifyPagesChanged
const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } } const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } }
// Canonical form for URL identity: https:// implied, host lowercased, hash
// dropped, trailing slash trimmed — so a re-pasted URL matches the bookmark
// already in the library instead of minting a duplicate.
const normalizeUrl = (raw: string) => {
const trimmed = raw.trim()
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
try {
const u = new URL(withScheme)
u.hash = ''
return u.toString().replace(/\/$/, '')
} catch {
return withScheme
}
}
export function PagesClient({ initialId }: { initialId: string | null }) { export function PagesClient({ initialId }: { initialId: string | null }) {
const router = useRouter() const router = useRouter()
const [pages, setPages] = useState<PageSummary[]>([]) const [pages, setPages] = useState<PageSummary[]>([])
@@ -134,7 +148,10 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
setTitle(data.title) setTitle(data.title)
setContent(draft ?? data.content) setContent(draft ?? data.content)
notifyActivePage(data.title) notifyActivePage(data.title)
if (draft !== undefined) editorRef.current?.resetContent(draft) // The editor is uncontrolled (TipTap owns its document): every load must
// explicitly paint what the user should see — the recovered draft, or the
// fresh server content after a discard — or stale text stays on screen.
editorRef.current?.resetContent(draft ?? data.content)
}, [autosave]) }, [autosave])
useEffect(() => { useEffect(() => {
@@ -377,23 +394,54 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
}, [linkQuery, linkOpen]) }, [linkQuery, linkOpen])
const addBookmark = async (bookmarkId: string) => { const addBookmark = async (bookmarkId: string) => {
if (activeId && !await autosave.flush(activeId)) return if (!activeId) return false
if (await patch({ addBookmarkId: bookmarkId })) { if (!await autosave.flush(activeId)) return false
setLinkOpen(false); setLinkQuery('') const res = await patch({ addBookmarkId: bookmarkId })
if (activeId) await loadPage(activeId) if (!res) return false
await loadPages() // Reflect the server's fresh link list straight from the PATCH response
// (pageView carries bookmarks/backlinks/embeds). No loadPage refetch:
// an attach triggered from inside the editor must never risk resetting
// content and moving the caret mid-typing, and per CR-17 the metadata
// response must not feed its version into autosave anyway.
const updated: PageDetail | null = await res.json().catch(() => null)
if (updated && updated.id === activeId) setPage(updated)
setLinkOpen(false); setLinkQuery('')
await loadPages()
return true
}
// Product invariant: a URL added to a page becomes a bookmark. Reuse the
// bookmark that already carries this URL — attached to the page, or in the
// library (search matches url server-side) — instead of minting a duplicate.
const urlInFlight = useRef(new Set<string>())
const saveUrlAsBookmark = async (raw: string) => {
if (!page || page.id !== activeId) return
const url = normalizeUrl(raw)
if (page.bookmarks.some((x) => normalizeUrl(x.bookmark.url) === url)) return
if (urlInFlight.current.has(url)) return
urlInFlight.current.add(url)
try {
let existingId: string | undefined
try {
const found = await fetch(`/api/bookmarks?search=${encodeURIComponent(url)}&limit=8`)
const rows: LinkedBookmark[] = found.ok ? await found.json() : []
existingId = rows.find((r) => normalizeUrl(r.url) === url)?.id
} catch { /* transient; creating a fresh bookmark is the safe fallback */ }
if (existingId) {
if (await addBookmark(existingId)) toast.success('Link added')
return
}
const res = await fetch('/api/bookmarks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) })
if (!res.ok) { toast.error('Could not save URL'); return }
const created: { id: string } = await res.json()
if (await addBookmark(created.id)) toast.success('Link added')
} finally {
urlInFlight.current.delete(url)
} }
} }
const addUrl = async () => { const addUrl = () => {
let url = linkQuery.trim() if (linkQuery.trim()) void saveUrlAsBookmark(linkQuery)
if (!url) return
if (!/^https?:\/\//i.test(url)) url = `https://${url}`
const res = await fetch('/api/bookmarks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) })
if (!res.ok) { toast.error('Could not save URL'); return }
const b = await res.json()
await addBookmark(b.id)
toast.success('Link added')
} }
const removeBookmark = async (bookmarkId: string) => { const removeBookmark = async (bookmarkId: string) => {
@@ -403,9 +451,10 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
} }
} }
// Notion-style paste: a bare URL lands in the textarea untouched, and once // Notion-style paste (see PageEditor): a bare URL lands in the document
// its preview resolves we offer to upgrade it to a titled Markdown link. // untouched and its preview offers a titled-link upgrade — nothing is
// Nothing is rewritten without an explicit click, so undo stays intact. // rewritten without an explicit click, so undo stays intact. The URL still
// becomes a bookmark on this page via saveUrlAsBookmark.
const looksLikeUrl = /^(https?:\/\/)?[\w-]+(\.[\w-]+)+/i.test(linkQuery.trim()) const looksLikeUrl = /^(https?:\/\/)?[\w-]+(\.[\w-]+)+/i.test(linkQuery.trim())
// A page may move under any page except itself or one of its descendants // A page may move under any page except itself or one of its descendants
@@ -505,6 +554,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
embeds={page.embeds} embeds={page.embeds}
onContentChange={onContentChange} onContentChange={onContentChange}
onNavigatePage={(id) => { void select(id) }} onNavigatePage={(id) => { void select(id) }}
onAddUrl={(url) => { void saveUrlAsBookmark(url) }}
/> />
<div className="mt-10 mb-3 flex items-center justify-between"> <div className="mt-10 mb-3 flex items-center justify-between">
+18 -1
View File
@@ -13,6 +13,10 @@
// - superbrain:page/ links navigate on click instead of editing the href. // - superbrain:page/ links navigate on click instead of editing the href.
// - A bare-URL paste stays plain text and offers a titled-link upgrade once // - A bare-URL paste stays plain text and offers a titled-link upgrade once
// the preview resolves (nothing is rewritten without an explicit click). // the preview resolves (nothing is rewritten without an explicit click).
// - Any external http(s) URL the user adds to the page — a bare-URL paste or
// the Link button — is also announced via onAddUrl, so the page workspace
// can create (or reuse) a bookmark for it. Product invariant: a URL added
// to a page becomes a bookmark on the page.
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react' import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
@@ -51,6 +55,10 @@ type Props = {
embeds: PageEmbed[] embeds: PageEmbed[]
onContentChange: (markdown: string) => void onContentChange: (markdown: string) => void
onNavigatePage: (id: string) => void onNavigatePage: (id: string) => void
// Fired when the user adds an external http(s) URL to the page (bare-URL
// paste or the Link button). The page workspace turns it into a bookmark;
// the editor never rewrites the Markdown itself.
onAddUrl?: (url: string) => void
} }
// Mutable embed lookup the paragraph node view reads at render time. // Mutable embed lookup the paragraph node view reads at render time.
@@ -103,7 +111,7 @@ const SLASH_BLOCKS = [
] as const ] as const
export const PageEditor = forwardRef<PageEditorHandle, Props>(function PageEditor( export const PageEditor = forwardRef<PageEditorHandle, Props>(function PageEditor(
{ content, embeds, onContentChange, onNavigatePage }, { content, embeds, onContentChange, onNavigatePage, onAddUrl },
ref, ref,
) { ) {
const [slash, setSlash] = useState<{ query: string; from: number; to: number; index: number; x: number; y: number } | null>(null) const [slash, setSlash] = useState<{ query: string; from: number; to: number; index: number; x: number; y: number } | null>(null)
@@ -116,6 +124,8 @@ export const PageEditor = forwardRef<PageEditorHandle, Props>(function PageEdito
onChange.current = onContentChange onChange.current = onContentChange
const navigate = useRef(onNavigatePage) const navigate = useRef(onNavigatePage)
navigate.current = onNavigatePage navigate.current = onNavigatePage
const addUrl = useRef(onAddUrl)
addUrl.current = onAddUrl
const editor = useEditor({ const editor = useEditor({
content, content,
@@ -168,6 +178,10 @@ export const PageEditor = forwardRef<PageEditorHandle, Props>(function PageEdito
handlePaste: (view, event) => { handlePaste: (view, event) => {
const text = event.clipboardData?.getData('text/plain').trim() ?? '' const text = event.clipboardData?.getData('text/plain').trim() ?? ''
if (!/^https?:\/\/\S+$/i.test(text)) return false if (!/^https?:\/\/\S+$/i.test(text)) return false
// The URL lands in the page, so it becomes a bookmark (parent creates
// or reuses one and links it to the page). The pasted text itself is
// still left untouched — this only adds a link, never rewrites.
addUrl.current?.(text)
const from = view.state.selection.from const from = view.state.selection.from
pasteOffer.current = { from, to: from + text.length, url: text } pasteOffer.current = { from, to: from + text.length, url: text }
void fetchLinkPreview(text).then((p) => { void fetchLinkPreview(text).then((p) => {
@@ -285,6 +299,9 @@ export const PageEditor = forwardRef<PageEditorHandle, Props>(function PageEdito
const url = window.prompt('Link URL (https://… or superbrain:page/<id>)') const url = window.prompt('Link URL (https://… or superbrain:page/<id>)')
if (!url) return if (!url) return
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run() editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
// A real web URL on the page must also become a bookmark; internal
// superbrain: links stay page-to-page edges instead.
if (/^https?:\/\/\S+$/i.test(url)) onAddUrl?.(url)
}}><Link2 className="h-3.5 w-3.5" /></Button> }}><Link2 className="h-3.5 w-3.5" /></Button>
<span className="mx-1 h-4 w-px bg-border" aria-hidden /> <span className="mx-1 h-4 w-px bg-border" aria-hidden />
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('heading', { level: 1 }) && active)} aria-label="Heading 1" title="Heading 1" onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}><Heading1 className="h-3.5 w-3.5" /></Button> <Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('heading', { level: 1 }) && active)} aria-label="Heading 1" title="Heading 1" onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}><Heading1 className="h-3.5 w-3.5" /></Button>