Commit Graph

30 Commits

Author SHA1 Message Date
sulthan b20ecf1928 Add a redeploy runbook
DEPLOY.md covers standing the stack up from nothing and ends with a two-line
"Updating" section, which is the operation actually performed every time and
the one where the irreversible mistakes live. Redeploying has a required
order — back up before pulling, because a backup taken after a bad deploy is
a backup of the damage — and three traps that are invisible until they cost
data:

- The store runs in WAL mode, so copying bookmarks.db alone while the
  container is up can silently drop the newest bookmarks. VACUUM INTO folds
  the WAL in; the cold-copy fallback has to take the sidecar files.
- That backup needs the source volume mounted read-write, which looks wrong.
  Opening a WAL database creates the -shm file, so :ro fails outright.
- A restored file lands root-owned while the container runs as uid 65532.
  Reads succeed and writes do not, so the restore looks like it worked.

Backups go to ../mangabm-backups/, a sibling of the checkout rather than a
directory inside it, so no git operation or careless rm in the project dir
can take the backups along with it. Names carry a UTC timestamp so they sort
chronologically as plain text and cannot collide across a DST shift.

Also documents that a rebuild is mandatory for any UI change now that the
templates, CSS and fonts are //go:embed-ed, and ends at the phone smoke test:
no curl can tell you the panel works on the device.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:42:27 +07:00
sulthan a547cc9769 Write down the Cinder design system
The design lives in a Claude Design doc that an agent working in this repo
cannot see, so every future UI change would otherwise be a re-derivation
of the same rules from the CSS — and the rules that matter here are the
ones a stylesheet cannot state: that heat is reserved for an unread
chapter, that favourites get brass instead of borrowing it, that light mode
is a re-tuning rather than an inversion.

Records the token table for both colour branches, the three type roles,
the component anatomy of a row, the load-bearing details that look like
noise until they break something (the [hidden] override, the action
strip's flex-basis, the icon sprite, rebuilding the binary to see template
changes), and how to add a font weight.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:34:44 +07:00
sulthan ce7e93df53 Self-host the Cinder webfonts
The design depends on three specific families, and loading them from
fonts.googleapis.com means the UI silently loses its character exactly
where it is used most: Bromite is a de-googled browser whose users
routinely block Google's font domains, and the backend is reachable over a
LAN with no internet route. In both cases the page fell back to Georgia
and a system sans.

Five latin-subset woff2 files, ~120 KB total, in a binary already 27 MB —
the cost is noise, and //go:embed static picks them up with no build
change (backend/Dockerfile already copies static/). Latin only because the
UI is English; woff2 only because every browser that can run this app
supports it, so there is no second format to carry. DM Sans ships as one
variable file, which covers the whole 400-700 range the design uses for
the price of a single request.

staticHandler registers the .woff2 MIME type: Go's built-in table has no
entry for it and the scratch image has no /etc/mime.types, so the fonts
would otherwise be served as application/octet-stream. The two faces
above the fold are preloaded, since they are now discovered a stylesheet
late rather than from a preconnect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:34:26 +07:00
sulthan 686fcc19cc Repaint the userscript panel in Cinder
The panel and the web UI are the same product on the same phone, and the
old purple-on-charcoal panel read as a different application once the web
UI moved to Cinder. Same tokens, same rule that heat is typographic:
.item.hot mirrors the web UI's is-new, .item.dim mirrors is-dim, chips and
buttons become mono small-caps with hairline borders instead of pills, and
the loading spinner becomes the same burning hairline rather than a
rotating ring.

Tokens are declared on :host so the panel has one palette block to edit,
but the fonts stay system serif and mono — the web UI's webfonts cannot
follow, because an @import inside the shadow root is at the mercy of the
host site's CSP.

Structure, ids and classes are untouched: this is a restyle, and in
particular the edge tab keeps its geometry, touch-action and #hit sizing
(see docs/superpowers/specs/2026-07-28-edge-tab-hitbox-design.md).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:33:56 +07:00
sulthan e940b96eae Rebuild the web UI on the Cinder design
Replaces the card-and-chip visual language with the Cinder direction from
the design doc: editorial serif, containerless sheets divided by ash
hairlines, one 760px measure, no radii and no shadows.

The organising rule is that heat is typographic. Only a series with an
unread chapter is allowed to be crimson — title, cover foot rule, "Ch N
out", play icon — so the one thing worth acting on is the one thing that
draws the eye. Favourites get brass instead of borrowing the accent, which
is what made the old three-hue palette read as noise. Both states hang off
two classes on the article (is-new, is-dim), so a new sub-element inherits
the state rather than re-deriving it.

The action strip is flex-basis 100% inside the row, which is what lets the
same markup be a full-width six-cell strip under the row on a phone (46px
targets) and a group of 40px squares beside it on a desktop, with no
duplicate template branches. Icons move to a sprite in icons.html: cards
are swapped in by htmx and reference the page's symbols, so a row no
longer carries a screenful of inline SVG paths.

[hidden] gets a display:none override because every disclosure panel is
now a flex container and display beats the attribute. filter.js grows an
.open class alongside hidden so the strip can show which cell the open
panel belongs to.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:33:41 +07:00
sulthan 4d69e54c24 Count new chapters for the Updated tab badge
The tab strip needs to say how many series have an unread chapter without
the user opening the tab to find out, so listView carries the number
alongside the filtered items.

The count is taken over the whole reading set rather than the rendered
items, so it means the same thing on every tab instead of collapsing to
len(Items) on Updated and 0 everywhere else. Archived and finished are
excluded, matching what the Updated tab itself shows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 09:32:58 +07:00
sulthan 1dc5b2ab65 Widen the edge-tab tap target, split scroll from reposition (#9)
The 7px edge tab is well below a usable touch target on a phone. This widens
only its *hit* area — the visible sliver still measures exactly 7 × 44 and
`offsetWidth`/`offsetHeight` still report it, so `placeFab`, `applyFabPos` and
the edge-snap maths are untouched.

- An invisible `#hit` child extends the tappable box inward to `28 × 72`.
  `overflow: hidden` had to go (it would clip `#hit`), so the rounded-corner
  clip for the dwell-progress fill moves onto `#fill` via `border-radius: inherit`.
- `touch-action` is resolved by the browser at gesture start, so the strip
  cannot be both browser-scrolled and script-dragged. `#fab` keeps
  `touch-action: none`, owns every gesture, and `makeDraggable` splits by
  intent: a plain swipe from `#hit` scrolls the page via `window.scrollBy`, a
  ~400ms hold arms a reposition drag (tab brightens and grows a ring), and the
  visible sliver still drags immediately with no hold.
- Adds the previously missing `pointercancel` reset, and snaps + saves on
  cancel so an OS-claimed gesture (Android's swipe-back starts in exactly this
  screen region) cannot strand the tab mid-screen.
- Clears a stale `dataset.dragged` on pointerdown, so a scroll or drag that
  produces no trailing click cannot swallow the *next* tap.

## Testing

`node --check` clean, `node --test userscript/test/logic.test.js` 14/14 pass.
The gesture code has no unit test — `logic.test.js` runs under node with no DOM
and this branch deliberately does not add a DOM harness. Manual device checks
(tap / swipe-to-scroll / hold-to-arm / sliver-drag on a chapter page) are the
real verification and are pending.

## Known ceilings

- The scroll is hand-rolled: no momentum or fling, and it assumes the document
  is the scroller rather than a nested container. Flagged in a `ponytail:`
  comment with the upgrade path.
- Gesture state is not keyed by `pointerId`, so a second finger corrupts an
  in-progress gesture. Pre-existing, not a regression.
- A >400ms still press on the *visible* sliver shows the armed ring even though
  the sliver never needs a hold. Cosmetic only.

Reviewed-on: #9
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-28 20:36:25 +07:00
sulthan 0416354c06 Serve the userscript from the backend; card + loading fixes (#8)
Serves the userscript from the backend so Violentmonkey auto-updates it, plus two panel fixes.

## Backend: `GET /u/{token}/manga-bookmark.user.js`

The script is read off disk per request from `USERSCRIPT_PATH` and streamed back with its `@version` line rewritten.

- **Token in the path, not a header.** Violentmonkey's update poll sends no `Authorization` header, and the script embeds `API_TOKEN` in plain text — an open URL would hand that token to anyone who guessed it. Compare is constant-time.
- **404, never 401**, for both a wrong token and a missing file: a prober learns nothing about whether the route exists.
- Registered outside `withAuth` and outside the `WEB_PASSWORD` gate, so the script is installable on a deployment that never enabled the web UI.
- Stdlib only (`crypto/subtle`, `os`, `regexp`) — no new Go dependencies.

**The served `@version` is derived from the file's mtime** (`YYYY.MM.DD.HHMM`, UTC), discarding whatever the file body says. Violentmonkey only updates when the served version sorts higher than the installed one, so a body-derived version means one typo or accidental downgrade freezes updates forever. An mtime-derived version is monotonic by construction. A file with no `@version` line is served byte-identical. `os.Stat` runs before `os.ReadFile`, so a concurrent edit can only serve new content under an old stamp — which self-heals on the next poll — never the reverse.

## Bindmount

`./userscript` is bindmounted read-only at `/userscript`. The script is deliberately **not** copied into the image: the build context stays `./backend`, and widening it would churn every `COPY` path for a file the mount always supplies. Editing the file on the VPS is live on the next poll — no rebuild, no restart. `git pull` restores the committed version, so a redeploy always ships the repo's script; checkout sets mtime to now, so even a rollback serves a *higher* version and is adopted. Without the mount the endpoint 404s and logs it; bookmark sync is unaffected.

`@downloadURL` / `@updateURL` are literal URLs in the metadata block — it is parsed before any JS runs, so `API_BASE`/`API_TOKEN` cannot be interpolated. The token was already committed in this file, so this adds no new exposure.

## Userscript UI

- **Card actions moved under the subtitle.** Only the cover and the title continue reading now; the subtitle and the action row are inert siblings in the text column. A thumb that misses ★ lands on nothing, and Remove is never inside a link.
- **Loading spinner** while the first fetch is in flight — the panel used to read as frozen on the first open after a cold start. It draws only when there is nothing cached to draw instead, so a populated list never flaps.

## Verification

- `go test -count=1 ./...` — ok, 7.070s
- `node --check` clean; `node --test userscript/test/logic.test.js` — 14/14
- Live `docker compose` smoke: `/healthz` 200, wrong token 404, script served with a stamped `@version 2026.07.28.1057` and both metadata URLs present; `touch`ing the file advanced the served version to `2026.07.28.1100` with no restart.

Layout and spinner are verified on-device — there is deliberately no DOM test harness.

Reviewed-on: #8
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-28 18:28:27 +07:00
sulthan 324b2efad6 Leaner userscript: edge tab, card-click continue, test harness (#7)
Drops the Continue and Edit buttons, makes the card body the continue target, adds a confirm to Remove, replaces the view-blocking circular FAB with a 7x44 edge tab plus a two-finger long-press, and adds a zero-dependency node:test harness for the adapter logic. Fixes a latent offsetWidth/offsetHeight bug in the FAB placement math. No backend or API change.

Verified live against real asurascans.com and demonicscans.org series and chapter pages: edge tab does not cover artwork, card-body click navigates, action buttons do not, Remove confirms and cancel preserves the row, the 25s dwell fill records progress, and the tab drags/snaps/clamps correctly.

Known and accepted: a deliberately slow two-finger pinch that stays inside the 15px slop for the full 500ms opens the panel. A normal-speed pinch (240px in ~240ms) cancels well before the timer. An absolute per-finger drift threshold cannot separate a slow pinch from two fingers resting, which is the gesture being detected.

Reviewed-on: #7
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-28 16:21:01 +07:00
sulthan 206c447f36 Stable Asura series IDs: strip rotating build hash (#6)
Asura series slugs carry a site-wide build hash (-059befe1) that rotates on every redeploy, silently orphaning all asura bookmarks (old-hash URLs 302 to new-hash ones, so detect() yields keys that never match stored rows).

Backend:
- migrateAsuraKeys in OpenStore: one-off idempotent migration rewriting hashed asura keys to the stable hashless ID, merging collisions to newest updated_at; losers deleted before winner rewrite (PK-collision safe) — regression tests included
- poller latestChapterFrom: build hash made optional in chapter-scoping regex so latest_chapter survives redeploys

Userscript:
- stripBuildHash(/-[0-9a-f]{8}$/) applied to seriesId in both asura detect branches; URLs keep full slug (stale hashes 302)
- load-time migration rewrites cached + retry-queued asura keys to the stripped form so a queued PUT cannot resurrect an orphaned row

Docs: AGENTS.md + CLAUDE.md URL-shape notes; design spec at docs/superpowers/specs/2026-07-28-asura-stable-series-id-design.md

Verified: go test -count=1 ./... green (new rotation + collision tests), node --check green, regex verified against live asurascans.com slugs.

Deploy order: backend first (migration runs at OpenStore). Orphan rows created by not-yet-updated userscripts self-heal on next backend restart.

Reviewed-on: #6
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-28 07:21:10 +07:00
sulthan 6dce9fc481 Offline retry queue for userscript writes (#5)
## The bug

Every mutation in the userscript is optimistic: it writes `state.list` and the `mangabm:cache` copy, re-renders, then PUTs. **If the PUT fails, nothing rolls back and nothing retries.** The cache now asserts something the server has never heard of, until the next successful `GET /bookmarks` silently overwrites it.

Walked end to end: phone loses signal mid-read, user taps **Archive**, the card moves to Archived and looks saved. `apiPut` throws. Local state is not rolled back. Signal returns, a later navigation calls `refresh()` → `apiGet()` → `setList()`, which replaces `state.list` wholesale. The series is back in All. No toast, no explanation, minutes later.

Four of the five call sites already toasted a promise of a retry that did not exist. This makes the existing copy honest rather than adding a new promise.

## The shape

**Markers, not payloads.** Every mutation already builds and PUTs the *whole* desired row, and `state.list` (mirrored into `mangabm:cache`) already *is* the desired state. So the queue stores only `{key, op, sendStatus, attempts}` in `localStorage` under `mangabm:queue`; the body is read from `state.byKey` at send time. That collapses four hard questions at once:

- **Ordering** — one entry per key, so two writes to the same series cannot replay out of order.
- **Coalescing** — archive-then-unarchive is not two writes, it is "the cache now says `reading`". Nothing to merge.
- **DELETE after PUT** — the delete entry *replaces* the put entry, so a replay cannot resurrect the row.
- **Staleness** — no snapshot can drift from the cache, because there is no snapshot.

**One write path.** `pushBookmark` / `pushDelete` are the only way a user-facing mutation reaches the API — not a fallback bolted onto each `catch`. That distinction is the whole point; see below.

**Drain triggers**, all cheap when the queue is empty (`drain()` returns on its first line): head of `refresh()`, `onNavigate` (drain only, *not* a full refresh — Asura is client-routed and an extra GET per route change is not wanted), a `window` `online` listener, and tapping the pending chip.

**Visibility.** A `⟳ N pending` chip in the existing `#nav` row, hidden entirely when the queue is empty. Silent convergence in the happy path; honest the moment something is stuck.

**Failure classes:** a `400` drops the entry and says so; a `401` aborts the whole pass and keeps the queue intact (fixing the token fixes everything); a `404` on DELETE is treated as success; network errors and `5xx` retry to a cap of 10 attempts. Every dropped write is announced — a queue that fails permanently and says nothing is the same class of bug being fixed.

## The sticky-`sendStatus` hole this closes

An empty `status` on the wire means "keep the stored bucket" server-side. A queue bolted onto each mutation's `catch` has a hole:

1. Offline. User archives X → entry `{X, put, sendStatus: true}` is queued.
2. Signal returns. No drain trigger has fired yet.
3. User reads a chapter of X → `syncUpsert` PUTs with `sendStatus: false` → **succeeds** → `upsertLocal(saved)` adopts a server row that still says `reading`.
4. The archive is gone from local state, and the pending entry now replays a row that no longer carries the intent. Silent un-archive.

Routing every write through `pushBookmark` — which ORs in any pending `sendStatus` and only ever *widens* it, never narrows it — is what closes that. A replayed progress write still omits `status`; a replayed archive still carries it.

`refresh()` drains before it fetches, then `overlayPending()` re-applies anything still pending over the fetched list before `setList` replaces `state.byKey`, so the card the user just changed never flaps back.

`applyLatestChapterIfChanged` deliberately stays **out** of the queue: it is background information the user never asked for, the server-side poller learns the same fact independently, and `backgroundRefreshLatest` already retries on a 4h throttle. Queueing it would let a stale local `latest_chapter` overwrite a fresher poller value on replay.

## Fixes from the final review (commits 6-8)

The whole-branch review found one Critical and two Important defects that only appear across commit boundaries:

- **Critical — the un-archive hole reopened through the latest-chapter exclusion.** `applyLatestChapterIfChanged` PUTs without `sendStatus`, so the server strips `status`, returns the stored `reading`, and `upsertLocal(saved)` writes that over a pending archive. `onNavigate` runs `maybeCaptureLatestOnSeriesPage()` *before* `drain()` with no await between them, so this was deterministic on any series-page visit, not a race — and the drain then sent `status:"reading"` explicitly, making it permanent. Fixed with a single `if (queueGet(bm.key)) return;` guard: the write stays unqueued as designed, it just no longer adopts a server row while a write is pending. `latest_chapter` still reaches the server via the drain, carrying the correct bucket.
- **Important — `draining` guarded drain-vs-drain but not drain-vs-mutation.** A tap during an in-flight same-key PUT started a second concurrent write; whichever response landed second won, and the loser's `queueDrop` could delete the entry the tap had just parked. Fixed with per-key in-flight tracking: a write for a key already in flight defers (parks a queue entry, sends nothing, returns `false` so the caller still toasts), and the landing flight suppresses its own `upsertLocal`/`queueDrop` when superseded — including on its failure path, so a failing flight cannot clobber a parked `op:"delete"` and resurrect a removed bookmark.
- **Important — `drain()` returned `undefined` while already draining**, so `refresh()`'s `await drain()` was a silent no-op and could adopt a pre-write list, flapping the card at boot. It now returns the in-flight promise. The empty-queue fast path is unchanged and still an immediate return.

Also: `render()` moved out of `pushBookmark`'s `try` (a render throw was re-queueing an already-successful write), and unawaited `drain()` rejections are swallowed.

## The backend is untouched

No file under `backend/` is in this diff. The `updated_at` rule and the empty-status keep rule stay solely in `Store.Upsert`; nothing client-side duplicates or works around them. A replayed PUT is an ordinary late write under the project's existing last-write-wins model. Regression check: `go test ./...` is `ok`, `CGO_ENABLED=0 go build ./...` succeeds.

Two accepted losses, marked with `ponytail:` comments at the replay site: a `latest_chapter` the poller learned while the client was offline can be overwritten by the client's older value (self-healing on the poller's next cooldown), and read progress made on another device between the failed write and the replay can be overwritten (single-user deployment).

## Verification status — read this before merging

`node --check` passes and every commit was reviewed, but **the 15-row manual DevTools checklist has NOT been run.** There is no test infrastructure for the userscript, and by design it gains none here — a pasted copy of the logic in a scratch node script would drift from the real file the moment either changed. The author is shipping to prod and verifying there.

The rows most worth checking first, because each maps to a specific defect the review caught:

- Offline → archive X → online → open X's **series page** and nothing else → X must stay Archived. *(the Critical above; nothing else exercises it)*
- Slow 3G → queue a write → tap the pending chip → immediately archive the same series → final state must match the last tap.
- Queue a write → reload on a slow link → the card must not flap back during `init`.
- Offline → archive X, then remove X → one entry, `op:"delete"` → after reconnecting, X must not reappear.
- Empty queue → navigate for a minute → no chip and **no extra network requests** from `onNavigate`.

## Known limitations, deliberately not fixed here

- A `400` drops the entry and toasts, but local state keeps asserting the lost change until the next successful `GET`.
- A `401` on a live tap toasts "will sync when online" rather than the auth message; the user learns the truth on the next drain.
- Two same-origin tabs clobber each other's `mangabm:queue` — the queue is read once at boot and each save writes the whole array. Same idiom as the pre-existing `saveCache`; low risk on mobile Bromite.
- A pending favourite floats to the top of the list until it syncs, then settles back. Consistent with how optimistic writes already behaved.

Reviewed-on: #5
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-27 17:52:16 +07:00
sulthan 6af49e6790 Archived and finished buckets, userscript nav chips (#4)
Gives every bookmark a lifecycle bucket — `reading`, `archived`, or `finished` — so on-hold series leave the main list while still being polled for new chapters, completed series get a web-only bucket, and the userscript panel gains quick links to the web UI and both manga sites.

Design: `docs/superpowers/specs/2026-07-27-status-buckets-design.md`

## Data model

One additive column through the existing `addedColumns` migration list:

```sql
ALTER TABLE bookmarks ADD COLUMN status TEXT NOT NULL DEFAULT 'reading'
```

The `DEFAULT` backfills every pre-existing row as `reading`, so there is no separate migration step. `favorite` is unchanged and orthogonal — a series can be an archived favourite.

Rollback is safe: an old binary against the new database omits `status` from its INSERT (it gets the DEFAULT) and never mentions it in the conflict clause, so buckets survive.

## The write rule

`PUT /bookmarks/{key}` decodes a whole `Bookmark` and `Upsert` writes every column it knows about. `latest_checked_at` escaped this by staying out of `bookmarkColumns` entirely — `status` cannot, because the userscript must be able to archive and restore.

So an empty incoming status means **"no opinion"**, not a value, and resolves on the `VALUES` side of the upsert:

```sql
COALESCE(NULLIF(?, ''), (SELECT status FROM bookmarks WHERE key = ?), 'reading')
```

with `DO UPDATE SET status = excluded.status`.

It has to be this way round. `excluded.*` is the row *after* the `VALUES` expressions are evaluated, so applying the default there and then reading `excluded.status` in the conflict clause would see `'reading'` rather than the empty string — and would overwrite an archived row on every progress PUT from a client that knows nothing about the column. One expression, evaluated once, covers insert and update alike. The subquery runs inside the transaction, so it sees the row the statement is about to conflict with.

`TestUpsertEmptyStatusPreservesStored` is the guard on this.

`updated_at` behaviour is unchanged: it moves only when `last_chapter_num` changes, so archiving, finishing, restoring, and favouriting never reorder the list.

## Validation

`PUT /bookmarks/{key}` returns 400 for any status outside `{"", "reading", "archived", "finished"}`, and for `"finished"` specifically. Finishing a series is a web-UI decision, enforced server-side rather than by trusting every client to leave the value alone. The `/ui/*` endpoints have their own session-guarded route and are unaffected.

## Visibility

| Surface | All | Updated | Favourites | Archived | Finished |
|---|---|---|---|---|---|
| Web | reading | reading | reading | archived | finished |
| Userscript | reading | — | reading | archived | not shown |

Archived and finished appear in their own tab and nowhere else — including the web UI's "Continue reading" strip, which is now built from reading-only rows before tab filtering. An archived favourite shows up under Archived only: Favourites means "favourites I am currently reading".

## Backend

- **`store.go`** — `Bookmark.Status`, the column in `schema` / `addedColumns` / `bookmarkColumns` / `scanBookmark` / `Upsert`. `scanBookmark` normalises anything outside the three known buckets to `reading`, so no row can land in no list at all.
- **`store.go`** — `DueForLatestCheck` gains `AND status IS NOT 'finished'`. Archived series keep being polled; that is the whole point of archiving rather than deleting. Finished ones have nothing coming, so polling them only burns fetches and risks a spurious "new chapter" badge. `IS NOT` is null-safe, so a hand-edited NULL still qualifies.
- **`handlers.go`** — status validation on `PUT`, before any write.
- **`web.go`** — `buildListView` filters the new tabs and excludes both buckets from `all` / `new` / `fav` and the recent strip; new `POST /ui/bookmarks/{key}/status`, session-guarded like its siblings, read-modify-writing through `Store.Get` + `Store.Upsert` so the `updated_at` rule stays in one place.
- **`templates/`** — two more tabs; per-card controls (reading → Archive + Finish, archived → Restore + Finish, finished → Restore); empty-state copy for both new tabs.
- **`static/style.css`** — five tabs no longer divide a phone's width legibly, so the row scrolls sideways instead of squeezing.

## Userscript (1.3.0)

- Third tab **Archived** beside All and Favourites. A missing `status` reads as `reading`, so a list cached by the previous version still renders. `finished` matches no tab and is invisible everywhere.
- Per-item **Archive / Unarchive** button on the existing optimistic path: mutate local state and cache, `apiPut`, adopt the server's returned row.
- Header chip row linking the web UI and both manga sites, each `target="_blank" rel="noopener"`.
- `apiPut` now omits `status` unless the caller opts in — see below.

Still free of every `GM_*` API: plain `fetch`, page `localStorage`, on-page UI only.

## One bug worth calling out

The userscript's other mutations (`updateToCurrentChapter`, `setChapterManual`, `toggleFavorite`, `applyLatestChapterIfChanged`) build their payload with `Object.assign({}, existing, …)`, so they echoed the cached `status` back to the server. `GET /bookmarks` has no status filter — finished rows are in `state.list` and only hidden at render time — which made two failures reachable:

1. Reading a chapter of a series marked finished sent `"status":"finished"`, which the API rejects with 400. Progress never synced, behind a misleading "Offline — saved locally, will retry" toast, permanently.
2. Archiving on desktop and then reading on a phone whose cache predated the archive sent `"status":"reading"` and silently un-archived the series — contradicting the README's "reading an archived series leaves it archived".

Fixed at the single choke point: `apiPut(key, obj, { sendStatus = false })` strips `status` from a copy of the body unless the caller opts in, and only `toggleArchive` opts in. Only an explicit archive/restore has an opinion about the bucket; everything else omits the field so the server's keep-on-empty rule applies. Stripping merely the *invalid* values would not have been enough — a stale cached `"reading"` still clobbers a remote archive.

Also: the userscript's `backgroundRefreshLatest` now skips finished series, matching the server poller, instead of spending batch slots fetching pages for a series that has nothing coming.

## Known limitations, deliberate

Both are marked in-code with `ponytail:` comments naming the ceiling and the upgrade path:

- The poller's `Store.Get` + `Store.Upsert` is not wrapped in a transaction, so a client PUT that commits between the two is lost to the stale re-read. Already documented for read progress in `CLAUDE.md`; it now costs a status change too. Accepted for a single-user deployment.
- A card whose new status no longer matches the active tab stays on screen until the next list load. The alternative is an out-of-band swap or a full list refresh per toggle, and the card visibly showing its new state is enough feedback.

## Testing

`go test ./...` passes; `CGO_ENABLED=0 go build ./...` clean.

- **`store_test.go`** — a fresh row defaults to `reading`; a legacy database gains the column with every row `reading`; an `Upsert` carrying `""` preserves the stored bucket while a value replaces it; a status change does not move `updated_at`; `DueForLatestCheck` returns archived and skips finished; the poller's `Get` → `Upsert` round trip preserves `archived`.
- **`main_test.go`** — `PUT` with `finished` or garbage is 400, `""` / `reading` / `archived` round-trip; a PUT that omits the `status` key entirely (what a pre-1.3.0 userscript sends) preserves an archived bucket *and* applies the chapter progress in the same request.
- **`web_test.go`** — each tab returns only its bucket; the recent strip excludes archived and finished; the status endpoint requires a session, rejects unknown values, and does not move `updated_at`; the card renders the right controls per bucket.

Userscript has no automated harness, so it was checked against a live `https://asurascans.com` page: the chips resolve, Archive moves a series out of All and Favourites into Archived, the state survives a full reload (so it came from the server, not local optimism), Unarchive returns it, a series marked finished in the web UI appears in no tab, and — captured on the wire — the archive PUT carries `"status":"archived"` while a favourite toggle on that same archived series carries no `status` key at all.

Reviewed-on: #4
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-27 16:58:05 +07:00
sulthan a587b16423 Web UI: Updated tab, inline errors, mobile card fixes (#3)
Third pass on the password-gated web UI, on top of #1 and #2.

## Updated tab
New `?tab=new` tab listing only series with an unread published chapter, plus per-tab empty states for Favourites and Updated. Covered by `TestUIListNewTab`.

## Inline error feedback
htmx does not swap on a non-2xx response, so a failed favourite/chapter/delete looked like an ignored tap. Errors now render in a `.error-inline` slot on the card and clear after 5s. The chapter-edit form and delete-confirm row also close each other — only one per-card panel open at a time.

## Mobile fixes (P0)
`.chapter-form` held three children on one unwrapped flex row, pushing Save off screen: **97px of page overflow at 390px, 127px at 360px**. That broke correcting a chapter number on the primary device class.

- `.chapter-form` and `.confirm-row` wrap; hint and prompt take their own full-width row
- `.chapter-form input` uses `flex: 1 1 0; min-width: 0` — with `flex: 1` (basis auto) a number input holds its ~20ch intrinsic width and refused to shrink, which pushed Save to a third row
- `white-space: nowrap` on the confirm prompt alone reintroduced 26px of overflow; the full-width row is what actually fixes it

Verified live: `document.body.scrollWidth <= window.innerWidth` with every chapter-form and confirm-row open, at 360/390/768/1280, light and dark.

## Icons
`☆ ✎ 🗑 ▶` replaced with hand-authored inline SVG on `currentColor` — the emoji font rendered each in a different face, weight, and colour, ignoring the card's own type and colour system. `.icon.on` / `.icon.danger` / `.primary` keep driving colour. No icon font or library added.

## No-cover empty state
Series whose source site gave no `og:image` render a title-initial monogram (`Bookmark.Initial()`) instead of a blank `--surface-2` rectangle that read as a cover still loading. Shared between the card cover and the Continue-reading strip.

## Verification
- `go build ./... && go test ./...` — pass
- Live interaction run: favourite toggle round-trips, chapter save 210.5→211, All/Updated/Favourites swap, delete-confirm removes the card, no console errors

Reviewed-on: #3
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-27 00:42:19 +07:00
sulthan 62772e1eaa feat: server-side latest-chapter polling (#2)
Adds a background goroutine to the backend that re-checks each bookmarked series' newest published chapter on its own schedule, so `latest_chapter` stays fresh even when the manga sites are never opened in a browser.

This is a *second, parallel* signal, not a replacement: the userscript keeps its own `maybeCaptureLatestOnSeriesPage` / `backgroundRefreshLatest` logic, unchanged. `userscript/manga-bookmark.user.js` is byte-identical to `main`.

## How it works

One ticker goroutine in the same binary. Each wake it asks SQLite for bookmarks whose `latest_checked_at` has aged past a per-bookmark cooldown, fetches those series pages through a Chrome-fingerprinted HTTP client, extracts the max chapter number with a per-site regex, and writes it back through `Store.Get` + `Store.Upsert`. Every failure path logs and moves on.

Two independent clocks:

- **cooldown** — how long one bookmark rests between checks, enforced by the `WHERE` clause in `Store.DueForLatestCheck`, not by a timer.
- **interval** — how often the goroutine wakes and looks.

Shortening the interval therefore cannot shorten anyone's cooldown; it only makes the poller wake and find nothing due more often.

The row is stamped **before** the fetch, so an error, a timeout, or a shutdown mid-request still consumes the cooldown — a renamed or challenged series waits out a full cooldown instead of being retried every tick.

## Design decisions worth reviewing

**`latest_checked_at` is deliberately absent from the `Bookmark` struct and from `bookmarkColumns`.** `PUT /bookmarks/{key}` decodes a whole `Bookmark` and `Upsert` writes every column it knows about, so a userscript PUT — which has no idea this field exists — would write a zero and reset the cooldown, making the poller re-fetch that series on every tick for as long as the user kept reading it. Two tests guard this: `TestUpsertPreservesLatestCheckedAt` and `TestPutDoesNotClobberLatestCheckedAt`, the latter driving a real router PUT with a userscript-shaped body.

**`updated_at` never moves on a latest-chapter bump.** All chapter writes go through `Store.Get` + `Store.Upsert`, so the existing `CASE` keeps the stored timestamp when only `latest_chapter_num` changes and the bookmark list does not reorder. `TestRunOnceDoesNotReorderList` asserts both the timestamp and the `List()` head position.

**Fetches use `bogdanfinn/tls-client` with a Chrome profile.** Plain `net/http` was verified working against both sites on 2026-07-26, so this is not fixing an observed block — it is deliberate defence-in-depth against a future fingerprint-based one. The library is pure Go, so `CGO_ENABLED=0`, the static binary, and the distroless image are all unaffected. It does require the Go floor to move 1.23 → 1.24.

**`checkOne` validates before spending a request.** `series_url` is entirely client-supplied through `PUT /bookmarks/{key}`, so without a guard the poller would issue GETs from the server's own network position to any URL a token holder writes. The check requires a known site and an `https` URL with a non-empty host, and sits *after* the cooldown stamp so an unfetchable row is retried at cooldown pace rather than hot-looping.

## Config

Five new env vars, all with defaults sized for this deployment, all wired through `docker-compose.yml`:

| Variable | Default | Meaning |
| --- | --- | --- |
| `LATEST_CHAPTER_POLL_ENABLED` | `1` | Kill switch |
| `LATEST_CHAPTER_POLL_COOLDOWN` | `1h` | Per series, floored at `15m` |
| `LATEST_CHAPTER_POLL_INTERVAL` | `10m` | How often to wake |
| `LATEST_CHAPTER_POLL_BATCH` | `14` | Series per wake |
| `LATEST_CHAPTER_POLL_STAGGER` | `20s` | Delay between fetches in a batch |

`batch × (cooldown / interval)` = 84 series hold a true cooldown cadence at these defaults. Past that nothing breaks: the cadence stretches uniformly and the oldest-checked-first ordering keeps it fair. Bad values log and fall back rather than failing startup — the poller is an enhancement, and a typo in one of its knobs must not stop bookmark sync.

## Known limitation (accepted, documented)

The poller's `Store.Get` + `Store.Upsert` is not wrapped in a single transaction. If a userscript `PUT` commits in the sub-millisecond window between the two, the poller writes back its stale re-read — reverting that progress and, since the stored `last_chapter_num` now differs, tripping the `updated_at` `CASE` and reordering the list.

Accepted rather than fixed for a single-user deployment: the window is one SELECT wide, the poller only writes when a chapter number actually changed, and the next read self-heals it. The alternative — a transactional read-modify-write — means moving or duplicating the `updated_at` `CASE` that four tests and the whole list-ordering invariant depend on. Recorded in `CLAUDE.md` next to the poller's architecture bullet so it is not a silent trap.

## Testing

- Full suite green, including `-race`; `go vet` clean; `CGO_ENABLED=0` static build and `docker compose build` both pass on the bumped `golang:1.24-alpine`.
- No test touches the network: the `fetcher` interface exists so tests inject a fake, and no test imports `tls-client` or reaches either manga site.
- Extraction is fixture-driven against markup trimmed from real pages (2026-07-26), including a Cloudflare challenge page, cross-series chapter links, decimal chapters, and both raw `&` and `&amp;` forms.
- Poller tests cover the no-reorder invariant, cooldown enforcement across passes, batch limiting, one bad series not stalling a batch, downward correction on a retracted chapter, cancelled contexts, and all four failure shapes still consuming the cooldown.
- Migration from a pre-column database has its own test — `newTestStore` takes the `CREATE TABLE` path, so the `ALTER TABLE` path would otherwise be untested.
- **Live smoke test:** real server, real fetch of asurascans.com. Log showed `latest is now Chapter 181` and `due=1 checked=1`; `GET /bookmarks` returned `latest_chapter_num: 181` with `updated_at` byte-identical to the PUT that created the row — the no-reorder invariant confirmed against a live site, not just a fake.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #2
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-26 18:54:42 +07:00
sulthan c601ef54d5 chore: untrack plans and docs/superpowers dirs
Keep local planning docs out of the repo; add to .gitignore.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-26 13:56:34 +07:00
sulthan ebc7a546c5 feat: password-gated web UI on the same backend (#1)
Adds a password-gated browser UI for the bookmark list, served by the same Go
binary and container as the userscript API.

## What

- `GET /` — list page, or the login page when there is no session (200, no redirect).
- `POST /login`, `POST /logout` — stateless HMAC session cookie, 60-day Max-Age.
- `GET /ui/list?tab=all|fav`, `POST /ui/bookmarks/{key}/favorite`,
  `POST /ui/bookmarks/{key}/chapter`, `DELETE /ui/bookmarks/{key}` — htmx fragments.
- `GET /static/*` — embedded `style.css`, `htmx.min.js`, `filter.js`.

Mobile-first dark CSS, 2–3 column grid at ≥900px, "Continue reading" strip of the
five most recent series, NEW badge, client-side title search, no build step.

## Stack

Go `html/template` + htmx 2.0.4 (vendored, 50 KB) + plain CSS. No npm, no bundler.
Templates and assets are `go:embed`-ed, so `CGO_ENABLED=0` and the distroless
image still hold.

## Auth

`WEB_PASSWORD` gates the UI; unset means the web routes are never registered and
`/` returns 404. Session cookie is `HttpOnly`, `SameSite=Lax`, `Secure` when the
request is HTTPS. The signing key derives from `API_TOKEN` + `WEB_PASSWORD`, so
rotating either logs every browser out. Login is rate-limited to 10 failures per
20 minutes per client IP, keyed on the **rightmost** `X-Forwarded-For` entry
(Traefik appends the observed peer, so the leftmost is client-spoofable). CGNAT
lockout is a known, accepted limitation — the window self-heals.

## Invariants preserved

- A session cookie never authenticates `/bookmarks*`. That API stays JSON +
  bearer token, unchanged, as does the userscript.
- `Store.Upsert` is byte-for-byte unmodified. Every UI write goes
  read-modify-write through the new `Store.Get`, so the conditional-`updated_at`
  rule (favouriting must not reorder the list, a chapter override must) lives in
  exactly one function.

## Deployment

`docker-compose.prod.yml` gains a second Traefik router on `MANGA_WEB_HOST`
pointing at the same service — one container, one certificate resolver, no second
service. Both `MANGA_API_HOST` and `MANGA_WEB_HOST` are required (`:?`), with no
example fallback in `.env.example`: a placeholder there would make Traefik
silently publish the UI on a domain you do not own. Needs a DNS A/AAAA record for
`manga.<domain>`. See `DEPLOY.md` §1b.

## Docs

- Design: `docs/superpowers/specs/2026-07-25-web-ui-design.md`
- Plan: `plans/2026-07-25-web-ui-implementation-plan.md`

## Verification

`gofmt` clean, `go vet`, `go test -race ./...`, `CGO_ENABLED=0 go build`, a real
`docker build` + curl smoke test, and a Playwright pass covering login
reject/accept, favourite-without-reorder, chapter edit, delete-with-confirm,
search, tab switch + back button, 390px with no horizontal overflow, and zero JS
console errors.

Reviewed-on: #1
Co-authored-by: Sulthan Zaki <sultankiki05@gmail.com>
Co-committed-by: Sulthan Zaki <sultankiki05@gmail.com>
2026-07-26 03:59:58 +07:00
sulthan c2914d0b5a docs: record conditional updated_at, latest-chapter tracking, favourites
Documents why updated_at moves only on reading progress and why PUT therefore
returns the stored row, why "latest chapter" is found from the browser rather
than the backend, and its limits — a bookmark is as current as its last check,
and nothing here can be instant.

Also corrects two stale claims: asurascans.com is the current domain, and
asuracomic.net deep links now 301 to its root rather than the matching path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 12:12:12 +07:00
sulthan 6df8836334 feat(userscript): latest-chapter tracking, favourites, All/Favourites tabs
Bookmarks now show the newest chapter a site has published alongside the one
the user has read. A series page carries its whole chapter list, so standing on
one records it directly; everything else is learned by fetching series pages in
the background, one per navigation and at most every four hours per series.
Those fetches are same-origin on purpose — they ride the browsing session that
gets past the sites' bot checks, which a request from the backend could not.
Freshness is tracked per device in localStorage rather than synced, since each
device checks independently.

Favourites are a synced flag with a star toggle and a second tab. Filtering
happens at render time, so a favourited series still appears under All.

Neither favouriting nor recording a new chapter reorders the list: both send
updated_at only as a candidate, and the server keeps the stored value unless
reading progress moved.

Also corrects the asuracomic.net comment — those deep links now 301 to the
asurascans.com root, dropping the path, before any script runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 12:10:40 +07:00
sulthan 01301805fb feat(backend): favorite + latest-chapter fields, conditional updated_at
Adds favorite, latest_chapter and latest_chapter_num to the bookmark record,
with an idempotent ALTER TABLE migration so the already-deployed database
picks them up.

updated_at now moves only when a bookmark is new or last_chapter_num changes.
Clients order their list by updated_at, so favoriting a series or recording a
newly published chapter must not disturb that order. Upsert consequently
returns the row as stored and the handler echoes that rather than the request
payload, since the candidate timestamp it sends is often discarded.

Scanning also tolerates NULL in the optional columns, which a database created
before this code can legitimately contain.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-25 12:06:44 +07:00
sulthan 053355d0c6 docs: add implementation plan for bookmark reorder/latest-chapter/favorites
Concrete backend + userscript plan against the approved design doc, including
the Store.Upsert return-value fix needed to keep ordering correct once
updated_at becomes conditional, and background-refresh triggering on both
init() and SPA navigation per user preference.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 12:01:10 +07:00
sulthan 83c3ffe3ad docs: add background opportunistic refresh to latest-chapter design
Same-origin fetch() from the userscript, throttled per-bookmark, to reduce
the "only fresh when you open the exact series page" gap without server-side
polling (still blocked by Cloudflare). Also documents that no JSON API or
RSS feed exists on either site, ruling out a more stable poll target.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 11:40:17 +07:00
sulthan 0f7d611a60 docs: design for bookmark reorder-by-progress, latest-chapter display, favorites
Covers list reordering (already implemented, no-op confirmed), latest-available-chapter
capture on series-page visits, favorites synced via backend, a required backend change
to make updated_at conditional on progress advance, and the asuracomic.net redirect
regression found while verifying feasibility live.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 11:28:54 +07:00
sulthan d1e0d7bf19 docs: add graphify knowledge graph integration
Ignore graphify-out/ (local graph data) and document query/update
workflow in CLAUDE.md for future codebase questions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-25 11:05:22 +07:00
sulthan 2e4a4519f0 feat(userscript): 25s dwell before auto-update + draggable edge-snap FAB
Auto-update no longer fires the instant a newer chapter opens (guards against
a misclick on "latest chapter"). Instead a 25s dwell timer arms, shown by a
countdown ring filling around the FAB; the manual "Update to X" button still
fires immediately. Timer is keyed to the chapter, not the URL, so turning
pages within the same chapter (Demonic /chapter/N/<page>) keeps it counting
rather than resetting.

FAB is now draggable: drag anywhere, release snaps it to the nearer left/right
edge keeping its vertical position, persisted in localStorage across sessions
and re-clamped on rotation. A drag no longer opens the panel; a tap still does.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 20:07:39 +07:00
sulthan c597bb5d5b fix(userscript): move boot after TEMPLATE/CSS consts to avoid TDZ crash
init() ran at line 514 (document.body exists at @run-at document-idle),
but buildUI() reads the TEMPLATE/CSS consts declared lower in the IIFE.
Accessing them before initialization threw ReferenceError: Cannot access
'CSS' before initialization, so the script died before mounting the FAB
and no UI appeared in Cromite. Move the boot invocation to the end of the
IIFE, after both consts are initialized.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 18:46:10 +07:00
sulthan 0ef528648d change the domain and add the api key to the script 2026-07-24 18:18:22 +07:00
claude cb95cef763 docs: add DEPLOY.md step-by-step (Traefik + Bromite)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:12:34 +07:00
claude 894a421a9d feat: Traefik router labels for prod deploy
Add traefik.enable + Host/entrypoints/tls/certresolver/service labels to the
prod override, driven by MANGA_API_HOST / PROXY_NETWORK / TRAEFIK_ENTRYPOINT /
TRAEFIK_CERTRESOLVER env vars (documented in .env.example).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 17:04:31 +07:00
claude f58d113934 feat: manga bookmark sync backend + Bromite userscript
Backend (Go, stdlib net/http + modernc.org/sqlite, CGO-free static binary):
- GET/PUT/DELETE /bookmarks{,/key} + /healthz
- bearer auth (constant-time), CORS origin reflection + 204 preflight
- SQLite store keyed <site>:<series_id>, last-write-wins, server-set updated_at
- httptest + temp-sqlite tests (auth, CORS, round-trip); go vet clean
- multi-stage Dockerfile (distroless static nonroot) + compose (base + prod proxy override)

Userscript (single Bromite-compatible IIFE, no GM_* APIs):
- Asura + Demonic adapters, URL-regex ids + og: title/cover
- Shadow-DOM floating UI, localStorage cache, optimistic sync
- auto-progress (no regress) + manual override; framework-agnostic nav watcher

Live-verified adapters (Playwright, 2026-07-24): asurascans.com /comics/<slug-hash>,
demonicscans.org /manga/<slug> + /title/<slug>/chapter/<n> — corrects the plan's
assumed /series/ paths and asuracomic.net domain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-24 16:48:28 +07:00
claude d47a07af46 chore: initial plan 2026-07-24 16:23:24 +07:00