mirror of
https://github.com/PerpetualSoftware/pad.git
synced 2026-09-24 19:32:10 +00:00
9b1a91ab0071f37bdb51645152b29bcdcd797bf3
287 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
9b1a91ab00 |
feat(collab): 5s-idle + on-disconnect markdown flush (TASK-1260) (#458)
* feat(collab): 5s-idle + on-disconnect markdown flush (TASK-1260) Replaces the temporary handleContentUpdate suppression introduced in TASK-1259 (PR #457) with a proper flush mechanism. Under collab, the Y.Doc + op-log are canonical for live state but items.content needs to stay reasonably fresh for downstream consumers (search index, share-page, exports, plain API readers). ## Mechanism 1. **5s idle timer.** Every editor onUpdate (local OR remote) resets a 5s timer. On fire, PATCHes items.content via the new `?source=collab-snapshot` query param. 2. **Server-side bypass.** handleUpdateItem inspects the source query param. When set, skips the applyContentViaCollab routing entirely and writes directly. Without the bypass, the PATCH would loop back through the applier protocol (the same tab gets asked to apply, acks, server strips input.Content) and leave items.content unchanged forever. The flag is trustworthy because the caller already has edit access. 3. **Dedupe across peers.** Track lastFlushedContent. If our last successful flush already landed this exact markdown, skip the PATCH. Multiple connected tabs would otherwise each fire a redundant flush after every shared edit converges, multiplying server load by the peer count. 4. **On-disconnect flush.** $effect cleanup (item swap or page unmount) calls flushCollabNow(true) BEFORE provider.destroy(). A separate beforeunload listener catches close-tab / reload / external-nav. Both use fetch keepalive: true so the request outlives the page lifecycle. 5. **Item-id race guards.** runCollabFlush captures reqItemId before await; ignores response if item swapped. loadData() clears collabFlushTimer + lastFlushedContent on navigation. ## Files - internal/server/handlers_items.go — accept `?source=collab-snapshot` - web/src/lib/api/client.ts — add api.items.flushCollabContent - web/src/routes/.../[slug]/+page.svelte — handleContentUpdate gains scheduleCollabFlush + runCollabFlush + flushCollabNow; wired to $effect cleanup + beforeunload + loadData reset. Parent: PLAN-1248 * fix(collab): capture ws+itemId at provider mount + apply unescapeDocLinks per Codex review (round 1) Two findings from round 1: 1) [P1] runCollabFlush resolved item.id and wsSlug at execution time, not at schedule time. During item navigation the timer could fire (or $effect cleanup could run) AFTER `item` was already updated to the new item, causing the OLD editor's markdown to be PATCHed against the NEW item's URL — cross-item content corruption. Fix: introduce activeCollabContext = { wsSlug, itemId }, captured at $effect-body time (when the provider is minted). scheduleCollabFlush, runCollabFlush, and flushCollabNow all take their target identity from this captured context, never from live reactive state. Cleared in the $effect's own cleanup (defensive `=== ctx` slot guard so a fast-navigation churn doesn't clobber a successor context). 2) [P2] The disconnect flush read raw editor.storage.markdown .getMarkdown() without unescapeDocLinks, unlike the regular onUpdate path. Closing/navigating before the idle flush could persist escaped wiki links like \[\[TASK-1\]\] which then wouldn't be converted by markdownToWikiLinks. Fix: apply unescapeDocLinks() at the start of runCollabFlush (covers both the timer-driven idle path and the unmount path). * fix(collab): gate UI mutations on foreground+current-item per Codex review (round 2) [P2] runCollabFlush mutated page-scoped state (saveStatus, editorStore.lastSaveTime, lastFlushedContent) before checking whether the captured itemId still matches the foreground item. On item navigation, the cleanup-driven keepalive flush could stamp 'saving' onto the NEW page's saveStatus, leaving it pinned indefinitely (and pollute lastFlushedContent for the new item's dedupe state). Fix: introduce isForegroundCurrent() = !keepalive && item.id === itemId. Gate saveStatus / setLastSaveTime / showSaved on it so background cleanup flushes never touch UI state. Gate lastFlushedContent on item.id === itemId regardless of keepalive so a stale flush can't seed the wrong item's dedupe. * fix(collab): skip cleanup flush on rich→raw transition per Codex review (round 3) [P1] $effect cleanup fires the keepalive flushCollabNow on every provider teardown, including rawMode toggles. The raw-button onclick already pre-populated rawPendingMarkdown with the live editor markdown (which the 1.2s raw debounce will land), so the keepalive PATCH from cleanup is redundant — and worse, can land AFTER the raw save and clobber newer raw edits with the older Y.Doc snapshot. Fix: gate the cleanup flush on `!rawMode`. If rawMode is true at cleanup time, the user just toggled to raw and the raw-mode codepath owns items.content from here. The other cleanup triggers (item nav, canEdit flip, page unmount) all keep firing the flush as before. Note: rawMode === true at cleanup time unambiguously means "transitioning into raw" — the inverse case (already in raw and the cleanup fires for some other reason) is impossible because collabKey gates on !rawMode, so the provider $effect never runs while rawMode is true. * fix(collab): synchronously flush Y.Doc state on rich→raw toggle per Codex review (round 4) [P1] Rich → raw → navigate-without-typing-or-toggling-back never PATCHed the live Y.Doc state to items.content. The previous seed mechanism only set rawPendingMarkdown, which only fires the 1.2s debounce on a subsequent handleRawContentUpdate call — which never happens if the user doesn't type. Fix: await runCollabFlush(ws, itemId, md, true) inside the raw button's async onclick BEFORE flipping rawMode = true. This: - Lands items.content with the live Y.Doc state synchronously (one PATCH, awaited, with keepalive: true so it survives a fast post-toggle navigation). - Seeds lastFlushedContent so any cleanup-driven re-flush is deduped. - Avoids populating rawPendingMarkdown — the raw debounce now only fires for actual user edits in raw mode, eliminating the race where a stale debounce fired after navigation could clobber state. The Round 3 cleanup-skip on rawMode is kept as defense-in-depth (also makes the no-op-when-already-flushed semantics explicit). * fix(collab): loop-flush until stable + cancel timer on rich→raw toggle per Codex review (round 5) Two HIGH findings from round 5: 1) Round 4's single-flush captured md BEFORE the await; concurrent peer edits (e.g. same user's other tab) during the await were lost from the seed and could be overwritten by subsequent raw-mode saves. Fix: loop-flush until stable. Re-read editor markdown after each PATCH; if it changed, flush again. Capped at 3 iterations to bound the transition under aggressive concurrent typing. 2) An onUpdate during the await could schedule a 5s collab flush timer that survived the rawMode flip. The cleanup skipped flushCollabNow on rawMode, but the timer fired its own runCollabFlush — which then PATCHed stale rich markdown on top of subsequent raw saves. Fix: explicitly clearTimeout(collabFlushTimer) at the end of the rich→raw onclick (after the loop-flush, before flipping rawMode). Belt-and-braces with the Round 3 cleanup skip. * fix(collab): seed raw mode from lastFlushed (not unflushed Y.Doc) per Codex review (round 6) [HIGH] Round 5's loop-flush could exit at the 3-iteration cap with md still differing from the last-PATCHed value, then seed rawSeedMarkdown with that unflushed md. An immediate navigation without typing would lose the unpersisted state. Fix: track lastFlushed inside the loop. After the loop, seed rawSeedMarkdown = lastFlushed (the markdown we actually PATCHed), NOT md (potentially a never-flushed in-memory value). If peer edits keep arriving past our cap, items.content lags Y.Doc briefly — but the peer's own 5s flush will catch up shortly, and at least raw mode shows state consistent with items.content rather than holding a value the server never received. * fix(collab): three corner-case fixes per Codex review (round 7) 1) [HIGH] lastFlushed = md was set unconditionally inside the loop-flush, even when runCollabFlush returned false (PATCH failed). rawSeedMarkdown could then be seeded with markdown the server never received. Fix: gate `lastFlushed = md` on runCollabFlush returning true. Failed PATCHes leave lastFlushed at its prior value. 2) [HIGH] lastFlushedContent (the collab-flush dedupe key) was never invalidated by raw-mode direct saves. Scenario: collab flushes A. Raw saves B. User returns to rich + edits back to A. Next collab flush dedupes (lastFlushedContent === A) and skips, leaving items.content stuck on B. Fix: reset lastFlushedContent = null after every successful raw save (both the regular handleRawContentUpdate path and the flushRawIfPending drain loop) so subsequent collab flushes always re-PATCH. 3) [MEDIUM] The async rich→raw onclick applied rawSeedMarkdown + rawMode = true after multiple awaits without verifying the user was still on the same item. A navigation during the loop-flush could let item A's handler resume and seed raw mode on item B. Fix: before mutating component state (rawSeedMarkdown, rawMode), check `item?.id === itemId` (the captured target). Bail with `return` if mismatched. * fix(collab): differentiate flush outcomes + foreground keepalive=false per Codex review (round 8) Two findings from round 8: 1) [P1] runCollabFlush returned `false` for both PATCH failure AND dedupe-skip. The rich→raw toggle treated `false` as "didn't flush" and didn't seed rawSeedMarkdown — but a dedupe means items.content already matches our markdown (the prior successful flush put it there). Raw mode then seeded from the page's stale `item.content` field, and a subsequent raw save could overwrite the current server content with the pre-collab snapshot. Fix: change runCollabFlush's return type to a discriminated string: 'flushed' | 'deduped' | 'failed'. The toggle treats 'flushed' and 'deduped' equivalently for seeding (both mean "server has this markdown") and only bails on 'failed'. 2) [P2] The toggle path used keepalive=true for the awaited flush. Browser keepalive requests can reject for bodies larger than the per-origin keepalive quota (~64KB). On reject, the catch silently fell through and raw mode activated with rawSeedMarkdown null. Fix: switch the toggle path to keepalive=false. The await is synchronous and user-initiated; navigation isn't imminent, so the keepalive escape hatch isn't needed (and risks losing the explicit save). Also added an `aborted` short-circuit so a 'failed' result returns early WITHOUT entering raw mode — user can retry. Cleanup-driven flushes (which DO need to survive page lifecycle) still use keepalive=true. |
||
|
|
5dc42b60df |
feat(collab): wire Yjs WebSocket provider + Y.Doc lifecycle (TASK-1259) (#457)
* feat(collab): wire Yjs WebSocket provider + Y.Doc lifecycle (TASK-1259)
Adds a thin y-websocket-style provider speaking the binary protocol
already implemented server-side in internal/collab/room.go. The
provider lives in a Svelte 5 .svelte.ts module so connection state
(`connected`, `synced`) can be consumed reactively by upcoming UX
tasks (TASK-1264 pending-sync indicator, TASK-1265 mobile reconnect).
Wire format mirrors the server's first-byte discriminator:
0x00 → y-protocols/sync (persisted to op-log + broadcast)
0x01 → y-protocols/awareness (broadcast only, ephemeral)
Lifecycle is bound to the item-detail page via $effect keyed on
`${item.id}:${canEdit}` — same key the <Editor> already re-mounts on,
so the Y.Doc and provider tear down in lockstep with the editor.
View-only viewers (canEdit === false) keep the legacy non-collab
editor; their read-only y-binding is deferred to TASK-1266.
Reconnect uses 1s/2s/4s/...30s exponential backoff. Sophisticated
mobile reconnect (visibility, network state) is TASK-1265.
KNOWN TEMPORARY REGRESSION: existing items with non-empty
items.content render an empty editor on first open under collab,
because the Y.Doc starts empty and TASK-1259 doesn't seed from
markdown. TASK-1261 (next in Phase 2) adds the lazy seed-after-
initial-sync path. New items + items already round-tripped through
collab are unaffected.
Drive-by lint cleanup of dead code that escaped Phase 1's
make-install-skips-lint loophole:
- gofmt -w on internal/collab/{applier,bus,manager}.go
- removed unused test/debug helpers Room.peerCount and
Room.applierConnCount (re-add with real callers when needed)
Parent: PLAN-1248
* fix(collab): gate Editor mount on ydoc + handle applier_request + catch-up state per Codex review (round 1)
Three findings from round 1:
1) [P1] $effect constructs ydoc AFTER Editor's onMount runs, so the
first mount on an editable item registered StarterKit history
instead of the Collaboration extension. The {#key} excluded ydoc,
so the editor never re-mounted when ydoc later became truthy →
editable users got a non-collab editor while the provider connected
to an unused Y.Doc.
Fix: gate the editable Editor mount on `ydoc` being ready
(`{#if !canEdit} ... {:else if ydoc} ...`). Adds at most one
reactive tick of delay; guarantees the first mount has the binding
registered.
2) [P1] Provider dropped non-binary WebSocket frames, but the server
sends `applier_request` as TextMessage. With TASK-1259 minting
active rooms, every concurrent CLI/MCP/API content PATCH would
sit blocked for 30s waiting for an ack, then fall back to a
direct write — and the in-memory Y.Doc would still hold stale
state and clobber it on the next 5s flush. Silent data loss.
Fix: parse TextMessage frames as JSON ControlMessage. On
`applier_request`, invoke an `onApplierRequest` callback (the
page passes `editor.commands.setContent(markdown)`) and send
`applier_ack` on success. The ExpiresAtMillis-driven late-apply
guard remains TASK-1262's full scope.
3) [P2] Local Y.Doc updates were silently dropped if the socket was
closed when handleDocUpdate fired. On reconnect the dumb-relay
server can't reconstruct missing updates from a state vector, so
any edits made before the first open or during a disconnect
could be lost.
Fix: after sending syncStep1 in onOpen, also send the current
doc state as a single update via `Y.encodeStateAsUpdate(ydoc)`.
CRDT idempotency makes this safe on initial open (server already
has these ops via op-log replay → sees a no-op update). Larger
docs incur a one-time cost on each connection; TASK-1265's
mobile-reconnect work can replace this with a buffered queue.
* fix(collab): destroy provider during rawMode + enforce ExpiresAtMillis on applier requests per Codex review (round 2)
Two findings from round 2:
1) [P1] collabKey ignored rawMode, leaving the WS provider connected
while the user edited via RawMarkdownEditor. Raw saves bypass the
y-binding (PATCH writes items.content directly), but the server
sees an active room → routes the PATCH through the applier flow
→ no editor mounted → 30s timeout fallback → direct write. The
stale Y.Doc still in memory then overwrote the raw save on the
next 5s flush after toggling back.
Fix: include rawMode in the collabKey derivation so toggling raw
destroys the provider (and the in-memory Y.Doc), and toggling back
mints a fresh pair that re-seeds from the op-log + TASK-1261's
lazy markdown seed.
2) [P1] Provider passed expires_at_millis to the handler but never
gated on it. A backgrounded tab that wakes after the server
retried or fell back could still apply setContent and overwrite
newer peer edits.
Fix: enforce the expiry in CollabProvider — check before
invoking the handler AND re-check before acking (handlers are
awaited and could span the deadline). Suppress the ack if either
gate trips; the server interprets "no ack" as "applier
unavailable" and falls back cleanly.
* fix(collab): prune op-log on direct-write fallback + pre-mutation expiry check per Codex review (round 3)
Two findings from round 3:
1) [P1] rawMode toggle to/from rich left a stale op-log: raw saves
wrote items.content directly while the destroyed provider's old
op-log persisted. Toggling back minted a fresh Y.Doc that
replayed the old log → showed pre-raw content → silently
overwrote the raw save on the next 5s flush.
Fix server-side: when ApplyExternalContent returns ErrNoActiveRoom
(no peers in memory, no in-flight Y.Doc state to corrupt), prune
the op-log alongside the direct items.content write so future
collab sessions start from a clean slate seeded by items.content
(TASK-1261's lazy seed). Pruning is intentionally NOT applied to
ErrNoApplierAvailable / ErrAllAppliersTimedOut — those paths
may have live peers whose Y.Doc state would diverge.
2) [P2] Provider's post-handler expiry check only suppressed the
ack, not the actual setContent mutation owned by the page
handler. An async handler that crossed the deadline could still
write stale markdown into the Y.Doc.
Fix: page handler now does its own pre-mutation expiry check
inside onApplierRequest before calling setContent. Documented
the contract on ApplierRequestHandler — handlers MUST honour
expiresAtMillis BEFORE mutating state.
* fix(collab): prune op-log on grace-TTL applier-unavailable + suppress autosave when collab active per Codex review (round 4)
Two findings from round 4:
1) [HIGH] op-log pruning still skipped ErrNoApplierAvailable. When
raw-mode destroys the in-tab provider, the room remains in its
60s grace TTL with zero conns, so the next direct-write PATCH
returns ErrNoApplierAvailable (not ErrNoActiveRoom). Stale op-log
rows persisted; toggling back within the grace window resurrected
pre-raw-save Y.Doc state.
Fix: prune op-log on ErrNoApplierAvailable too — the "no live
conns" condition makes pruning safe (no peers to corrupt).
ErrAllAppliersTimedOut still preserves op-log because peers may
still be alive there.
2) [HIGH] Once the WS provider is active the legacy 1.2s content
autosave PATCH gets intercepted by the applier path
(handleUpdateItem branch added in TASK-1252). On applier success
input.Content is nil'd out, so UpdateItem never writes the
markdown snapshot. The page's autosave was the only canonical
items.content flush in this diff — search / share-page / API
consumers would see stale content forever.
Fix: short-circuit handleContentUpdate when collabProvider is
set. The Y.Doc + op-log are canonical; items.content stays at
its pre-collab snapshot until TASK-1260 introduces the proper
5s idle flush with applier-bypass semantics. This is a known
Phase-2-internal regression closed by the very next task in
this run.
* fix(collab): tighten error classification + per-item lock + raw-mode flush per Codex review (round 5)
Three findings from round 5:
1) [HIGH] applier.go could return ErrAllAppliersTimedOut even when
no applier_request was ever successfully written (a row of write
failures followed by no remaining candidates). The handler-side
prune skipped that case, leaving stale op-log rows even though
no peer received the request.
Fix: track `anyWriteSucceeded` across the attempts and return
ErrNoApplierAvailable (which prunes) when the loop exits without
ever putting bytes on the wire.
2) [HIGH] Race between ApplyExternalContent's no-room classification
and the subsequent Prune/UpdateItem: a fresh Join could mint a
room and replay the soon-to-be-pruned op-log into a new client,
leaving it with stale Y.Doc state that overwrites the
freshly-written items.content on the next idle flush.
Fix: introduce per-item setup mutex on RoomManager. Join holds
the lock across addConn + replayTo and releases it before the
long-lived readLoop. New PruneAndApply method wraps the
prune+direct-write in the same per-item lock and re-verifies
"no live peers" under it (returns ErrRoomActiveDuringPrune if a
peer slipped in, in which case the caller falls through to a
plain direct write without pruning). Lock order: per-item lock
> m.mu > r.mu — Join and PruneAndApply both follow it.
3) [MEDIUM] Raw-mode 1.2s debounce timer could outlive the toggle
to rich mode: the deferred PATCH fired post-collab-mint and got
routed through the applier path (potentially overwriting newer
peer state).
Fix: track the latest pending raw markdown in
`rawPendingMarkdown`. The Rich-mode button is now an async
onclick that awaits a `flushRawIfPending()` synchronous PATCH
before flipping `rawMode = false` (which is what activates the
collab provider via the collabKey derivation).
* fix(collab): evict broken applier conn + retry on prune-race + retain raw pending on PATCH failure per Codex review (round 6)
Three findings from round 6:
1) [HIGH] When applier_request write failed, the broken roomConn
stayed in r.conns, defeating PruneAndApply's "no live peers"
check (which then returned ErrRoomActiveDuringPrune and the
handler skipped pruning). Net effect: the prune-safety
classification reverted to the round-5 hazard.
Fix: in the applier write-failure branch, force-close the conn
and call removeConn before continuing to the next applier. Both
are idempotent with the readLoop's natural cleanup path
(bus.Unsubscribe, conn map delete, conn.Close all tolerate
double-invocation).
2) [HIGH] On ErrRoomActiveDuringPrune the handler fell through to a
plain direct-write to items.content, bypassing the now-active
peer's applier. The peer's stale Y.Doc could still overwrite
items.content on the next idle flush.
Fix: surface ErrRoomActiveDuringPrune from
applyContentViaCollabOnce so the new applyContentViaCollab
wrapper can retry the full ApplyExternalContent flow against
the freshly-active room. Capped at applyContentMaxRetries=3 to
prevent runaway loops if joins keep landing during prune
attempts. After exhaustion, returns the same sentinel — the
handler's existing `if err == nil { input.Content = nil }`
gate falls through to direct write, which is the correct
degraded-mode behavior.
3) [MEDIUM] flushRawIfPending cleared rawPendingMarkdown before
the PATCH succeeded and the Rich-mode toggle always set
rawMode = false regardless of flush outcome. A failed flush
could activate collab with unsaved raw edits.
Fix: rework flushRawIfPending to return success bool, retain
rawPendingMarkdown on PATCH failure, and gate the Rich-button
transition on `ok`. Added a re-entrancy guard
(rawFlushInFlight) so a rapid double-click waits for the
in-flight flush to settle instead of issuing a duplicate PATCH.
* fix(collab): drain-loop flushRawIfPending to handle fast-typist edge per Codex review (round 7)
[P1] flushRawIfPending snapshotted rawPendingMarkdown then awaited
the PATCH; if the user typed during the await, the equality check
preserved the newer edit but the function still returned `true` and
the Rich-mode handler flipped collab on. The newly-active provider
then raced the un-flushed pending raw save — exactly the hazard
the guard is meant to close.
Fix: rework flushRawIfPending into a bounded drain loop. Each
iteration snapshots-PATCHes-clears (with the equality check). The
loop runs up to RAW_FLUSH_DRAIN_CAP=5 iterations, returning `true`
ONLY when rawPendingMarkdown is null on exit AND no PATCH failed.
A fast typist who keeps the queue non-null across the cap returns
`false`, leaving the user in raw mode (next click retries).
PATCH failure short-circuits with `false` so the toggle stays in
raw mode and the unsaved markdown is preserved for retry.
* fix(collab): atomic prune+content-write + preserve newer raw edit on stale PATCH response per Codex review (round 8)
Two findings from round 8:
1) [P1] PruneAndApply ran the op-log prune under the per-item lock
but the items.content write happened later in the post-loop
UpdateItem call, OUTSIDE the lock. A fresh Join landing in that
gap could replay the now-empty op-log, mint a peer with stale
Y.Doc state, and then overwrite the freshly-written
items.content on the next idle flush.
Fix: applyContentViaCollab now takes a `directWrite` callback
that the caller (handleUpdateItem) implements as a content-only
UpdateItem. PruneAndApply's applyFn invokes it AFTER the prune
so both run inside the same per-item critical section. The
trade-off is two DB round-trips when a PATCH carries content +
other fields together (rare): the content-only update happens
inside the lock; the rest (title, fields, status) flows through
the post-loop UpdateItem with input.Content nil'd to suppress
the duplicate write.
2) [P1] In flushRawIfPending's drain loop, `item = updated`
assigned the server-side snapshot from the just-PATCHed
markdown even when a newer raw edit had landed in the meantime.
RawMarkdownEditor mirrors `item.content` into its textarea
unconditionally (line 16), so the stale assignment would reset
the textarea mid-keystroke and lose the queued edit.
Fix: only swap in the full updated snapshot when
`rawPendingMarkdown === markdown` (no newer edit). Otherwise
keep our local content and adopt only the server-side metadata
(timestamps, version, modified_by) via spread.
* fix(collab): atomic mixed PATCH + raw autosave stale guard + rich→raw seeding per Codex review (round 9)
Three findings from round 9:
1) [P1] Toggling FROM rich+collab TO raw mode seeded
RawMarkdownEditor from items.content, which is intentionally
stale under collab (handleContentUpdate is suppressed while the
provider is connected; TASK-1260 closes that gap with a 5s
flush). Saving from raw mode would overwrite the live Y.Doc
state with a pre-collab snapshot.
Fix: when toggling to raw with a connected provider, capture
the editor's current Y.Doc-derived markdown via
`editor.storage.markdown.getMarkdown()` into a one-shot
`rawSeedMarkdown` slot and pre-populate `rawPendingMarkdown` so
the first auto-save persists it. RawMarkdownEditor seeds from
`rawSeedMarkdown ?? item.content`. Cleared on rich-mode toggle.
2) [P1] The regular debounced raw autosave still assigned
`item = updated` from a stale PATCH response. Same
stale-snapshot hazard the Round 8 fix closed in
flushRawIfPending.
Fix: equality-check `rawPendingMarkdown === toSave` before
swapping in the server snapshot. On stale, keep local content
and adopt only the server-side metadata via spread.
3) [P2] Round 8 split the items.content write (under per-item
lock) from the rest of UpdateItem (post-loop), losing
atomicity for mixed PATCHes (content + title) and breaking
Store.UpdateItem's content-versioning peek at Title.
Fix: directWrite callback now invokes the FULL UpdateItem
inside the per-item lock. A `fullWriteHandled` flag tells the
handler to skip the post-loop UpdateItem entirely (otherwise
we'd duplicate the write and create two version-history rows).
Mixed PATCHes are atomic again under the lock.
* fix(collab): clear raw seed/pending on item navigation per Codex review (round 10)
[P1] Navigating between items left rawSeedMarkdown,
rawPendingMarkdown, and the contentDebounceTimer set from the
previous item. This caused two concrete hazards:
(a) Item B's raw editor mounted with item A's live markdown via
`rawSeedMarkdown ?? item.content`.
(b) Clicking Rich on item B fired flushRawIfPending which
PATCHed A's queued markdown INTO item B (cross-item data
bleed).
Fix: at the top of loadData(), clear contentDebounceTimer,
rawSeedMarkdown, and rawPendingMarkdown so each navigation starts
from a clean slate. The collab provider's own lifecycle is
already keyed on item.id via $effect cleanup, so it doesn't need
the same explicit reset.
* fix(collab): item-id race guard on raw PATCH responses per Codex review (round 11)
[P1] In-flight raw PATCH responses (debounced autosave AND drain
loop) could clobber a newly navigated item. Clearing
contentDebounceTimer in loadData only cancels timers that have
not fired; an awaiting fetch keeps running and its `.then` /
`.catch` would assign back to the new page's `item` state.
Fix: mirror the existing TASK-754-style race guard pattern
(already used in the SSE / sync handlers above). Capture
`reqItemId = item.id` BEFORE the PATCH, then in the response
handler bail if `!item || item.id !== reqItemId`. Applied to
both handleRawContentUpdate's setTimeout body and
flushRawIfPending's drain loop.
* fix(collab): reset saveStatus on item navigation per Codex review (round 12)
[P2] After Round 11's race guard, a stale raw PATCH response that
matched a now-different item.id was correctly discarded — but
saveStatus had already been set to 'saving' before the await. With
loadData not resetting it, the next item could mount with
saveStatus pinned at 'saving' indefinitely, which then suppressed
all SSE/sync refreshes via the `if (saveStatus === 'saving')`
guards above.
Fix: in loadData's per-item state reset, clear saveStatusTimer
and reset saveStatus to 'idle' alongside the other transient
state. Cheap, scoped, no impact on the in-flight save's eventual
discard path.
|
||
|
|
b4904e0db9 |
feat(editor): wire optional ydoc + Collaboration extension (TASK-1258) (#456)
* feat(editor): wire optional ydoc + Collaboration extension into Editor.svelte (TASK-1258)
Productionizes the Yjs binding pattern verified in the
feat/yjs-tiptap-spike branch (TASK-1245 sandbox). Editor.svelte now
accepts an optional `ydoc?: Y.Doc` prop; when set, it registers the
Tiptap Collaboration extension and disables StarterKit's undoRedo
so the y-tiptap binding takes over document state + history.
Editor.svelte changes:
- Imports: `Collaboration` from `@tiptap/extension-collaboration`,
type-only `Y.Doc` from `yjs` (the actual constructor lives in the
caller route — TASK-1260 wires the WS provider).
- Props: new optional `ydoc?: Y.Doc`. When undefined the editor's
extension list and behaviour are byte-identical to today;
every existing call site stays backward-compatible.
- Extensions:
· StarterKit.configure now spreads `{ undoRedo: false }` IFF
ydoc is set (Yjs owns history when collab is active; v3's
option is `undoRedo`, the v2 `history` key was renamed).
· `...(ydoc ? [Collaboration.configure({ document: ydoc,
field: 'default' })] : [])` slot at the end of the extension
array — empty when ydoc is undefined, so existing single-Doc
usage is unaffected.
Dependencies added to web/package.json:
- `yjs@^13.6.30`
- `@tiptap/extension-collaboration@3.22.5` — EXACT pin (no caret)
because @tiptap/core is on 3.22.5 and the latest published
3.23.x of extension-collaboration requires a matching core. The
CLAUDE.md note in TASK-1269 codifies the multi-package coordinated
bump rule.
- `@tiptap/y-tiptap@^3.0.3`
Out of scope (per task spec): WS provider plumbing (TASK-1260),
lifecycle binding to item-detail page (TASK-1260), first-edit seed
from markdown (TASK-1262), CollaborationCursor extension
(TASK-1264).
Parent: PLAN-1248. Phase 1 — Backend foundation complete; Phase 2
is the next logical block to start.
* fix(editor): gate content-prop sync $effect when ydoc is active per Codex review (round 1)
P1: Editor.svelte's existing $effect that calls
editor.commands.setContent on prop-content changes (item switch,
external REST update) would route through the y-tiptap binding as a
LOCAL ProseMirror change when Collaboration is registered —
overwriting peers' Y.Doc state with stale REST markdown on every
content prop refresh.
Add an early return in the $effect when ydoc is set. Y.Doc is the
authoritative state under collab; markdown→Y.Doc seeding for the
first-edit-on-empty case lives in TASK-1262 and uses Y.Doc's own
primitives, NOT setContent.
The early return also captures `tracker.prev = content` so a future
host route that swapped ydoc on/off mid-editor wouldn't see the
non-collab branch's `prev === undefined` and accidentally skip its
first sync. In practice ydoc is set once per editor mount today,
but the cheap capture keeps the contract honest.
|
||
|
|
00d529d325 |
fix(editor): add NodeView update() hook to AttachmentChip (TASK-1251) (#449)
* fix(editor): add NodeView update() hook to AttachmentChip (TASK-1251) Audit confirmed the same gap pattern as BUG-1246 (mermaid) / TASK-1250 (attachment-image): closure-captured uuid + filename, no update() hook, so any attr change forces NodeView destroy+recreate. No in-tab attr-change source today (no rotate/crop on chips), but the upcoming Yjs collab work makes peer-driven uuid/filename swaps the common case — destroying the NodeView on every peer keystroke of a rename would jump the cursor and flicker the chip. Refactor closure state to be mutable, add update() that: - Returns false on type mismatch (defensive — should never fire for an attachmentChip). - On uuid change: refresh href + data-attachment-id, reset MIME + size pending re-probe, re-fire the HEAD metadata fetch (with in-flight guard so a stale probe doesn't trample fresher state). - On filename change: refresh data-filename, download attribute, visible name, and (only when MIME unknown) re-derive the filename-extension fallback icon. Click handler now reads currentUuid (mutable) so a peer-swapped chip target opens the new attachment, not the original. Parent: PLAN-1248. Phase 0 — Production prerequisites complete. * fix(editor): always refresh chip icon on rename per Codex review (round 1) P3: refreshIcon() falls back to the filename-extension heuristic whenever iconForMime() returns empty — both MIME-unknown and MIME-known-but-unmapped (e.g. application/octet-stream) hit the same fallback path. The previous `if (!currentMime) refreshIcon()` was too narrow; renaming foo.csv → foo.pdf after a generic MIME resolved would leave the stale .csv icon until the NodeView was recreated. Drop the conditional. refreshIcon() is idempotent for MIMEs that DO map to a specific icon (just rewrites the same emoji), so calling it on every filename change is correct and trivially cheap. |
||
|
|
530a2c05ba |
fix(editor): add NodeView update() hook to AttachmentImage (TASK-1250) (#448)
* fix(editor): add NodeView update() hook to AttachmentImage (TASK-1250) Same hazard pattern as BUG-1246 (mermaid) — the NodeView had no update() hook, so any attribute change forced ProseMirror to destroy + recreate the NodeView. Single-user rotate worked via that destroy + recreate path (invisible flicker + cursor jump), but under upcoming Yjs collab a remote peer's rotate would constantly remount the local image element. Add the hook and refactor closure state so attr changes refresh the live <img> in place: - update(updatedNode) returns false on type mismatch (defensive — should never fire for an attachmentImage), true otherwise. - uuid + alt promoted from const to let (currentUuid / currentAlt) so event handlers (click → lightbox, rotate, crop) read the latest value. - On uuid change: invalidate metadata cache for the OLD uuid, swap img.src + data-attachment-id, reset toolbar MIME gating, re-probe metadata for the NEW uuid (with a guard so a probe in flight doesn't trample a fresh swap). - On alt change: refresh img.alt. - swapNodeUuid loses its trailing invalidateAttachmentMetadata call — that lives in update() now so it fires regardless of source (local rotate, peer Yjs op, ...). Verifies single-user rotate still works AND lays groundwork for zero-flicker peer rotate under Phase 2 Yjs collab. Parent: PLAN-1248. * fix(editor): read live node attrs in swapNodeUuid per Codex review (round 1) P-LOW: with update() now keeping the AttachmentImage NodeView alive across attr changes, the closure-captured `node` is no longer guaranteed to reflect the document. Spreading its stale attrs in setNodeMarkup would clobber any concurrent edit to a non-uuid attr — e.g. a peer changes alt text, then a local rotate dispatches with the original alt and overwrites the peer's update. Resolve by reading node attrs from editor.state.doc.nodeAt(pos) at the moment of dispatch, so we always merge the new uuid onto the freshest known attrs. Bail if nodeAt returns null (edge: pos no longer points at this node — e.g. node was deleted in the same tick). * fix(editor): snapshot uuid in runRotate/runCrop per Codex review (round 2) P2: with the NodeView now surviving attr changes, currentUuid (mutable closure) can drift during the await on opts.transform() / openCropModal — a peer rotating or cropping the same image mid-flight would shift currentUuid out from under us. Crop is the worst case: the rect was chosen against the original image, but applying it to whatever uuid is live at completion time would crop the wrong image. Resolve by snapshotting currentUuid (and currentAlt for the crop modal) at the entry of each async handler, threading the snapshot through the transform call, and bailing if currentUuid drifted during any await. Same hazard surface in both functions; same fix shape applied to both. |
||
|
|
1ef7a21de2 |
fix(editor): add NodeView update() hook to MermaidCodeBlock (TASK-1249) (#447)
* fix(editor): add NodeView update() hook to MermaidCodeBlock (TASK-1249) Mermaid diagrams previously froze on the SVG generated when the NodeView was first created. ProseMirror only recreates a NodeView on node identity change; in-place text edits don't trigger that, and the existing factory had no `update()` hook to re-queue a render — so editing the source via the hover-revealed `< >` toggle silently mutated the code while the diagram showed stale output. Resolves BUG-1246. Implementation matches the pattern verified in the TASK-1245 spike (iteration 3, dev sandbox at /dev/yjs-sandbox) but with precise ProseMirror Node typing instead of `any`: - update(updatedNode) returns false on type mismatch or when the language attr flips into/out of `mermaid` — different DOM shape, so ProseMirror must tear down + recreate the NodeView. - Returns true (in-place update accepted) when same-node + same-lang; re-queues queueMermaidRender only when textContent actually changed. - Empty source clears the diagram element and the mermaid-error class. - Toggle state survives because we don't recreate the wrapper. Becomes a hard blocker once Yjs collab lands (PLAN-1248) since remote ops will constantly mutate mermaid source text mid-view. Parent: PLAN-1248. * fix(editor): serialize mermaid clear + drop error class on success per Codex review (round 1) Two issues raised in PR #447 review: P2 — Pending queueMermaidRender() could overwrite a synchronous diagram clear with a stale SVG, racing against a freshly-emptied source. Route the clear through the same renderQueue (queueMermaidClear) so it executes strictly after any in-flight render for the same target. P3 — A valid re-render after an invalid mermaid edit kept the .mermaid-error class on the diagram element. Drop the class in queueMermaidRender's success path now that successful render means the source compiled. Both fixes preserve TASK-1249's NodeView update() contract; no other behavior changed. |
||
|
|
07e47eba57 |
fix(web): subscribe item detail page to live SSE updates (TASK-1243) (#446)
* fix(web): subscribe item detail page to live SSE updates (TASK-1243)
The item detail page (+page.svelte under [collection]/[slug]) never
called sseService.onItemEvent, so live changes to the parent item's
title / fields / archive state didn't propagate from the server
until a manual refresh. Comments, reactions, timeline events, and
child-item updates all worked because their respective child
components (CommentThread, ItemTimeline, ChildItems) carry their
own SSE subscriptions — the gap was only on the parent item itself.
Discovered while manually verifying TASK-1242 (callback inversion):
two tabs on the same item showed divergent state until refresh.
Fix mirrors the existing onSync handler that lives a few lines below:
• Subscribe to sseService.onItemEvent in onMount, store the
unsubscriber alongside unsubscribeSync / unsubscribeBeforePrint
• Filter to event.item_id === item.id so cross-item navigation
inside the same component instance is handled cleanly (the
handler reads the *current* $state value of `item` on each fire,
no stale-closure bug)
• Same edit-conflict guards (saveStatus === 'saving' || editingTitle)
so SSE pushes don't clobber in-flight edits
• Same content-preservation pattern (`content: item.content`) — the
Tiptap editor owns the document state; replacing item.content
while it's mounted would clobber the user's local edits. Title,
fields, and metadata propagate; content stays put. This is a
deliberate conservative behavior identical to onSync's behavior
for the same reason.
• Handle item_archived (bounce back to collection list, matches
onSync's deletion path) and item_restored
• Tear down in onDestroy alongside the existing unsubscribers
Lifecycle: SvelteKit reuses the +page.svelte component instance when
navigating between items in the same collection, so onMount runs
once per route entry and onDestroy runs once per route exit. The
single subscription handles cross-item navigation correctly via the
`event.item_id !== item.id` filter; closure reads of $state /
$derived values pick up the new item on each event fire. No
re-subscription per navigation needed (collection page does that
because its closure captures wsSlug/collSlug as `const`s — different
pattern, same correctness).
KNOWN LIMITATION: live content sync is intentionally NOT handled.
For Pad's current "snapshot save on debounce" model, replacing the
editor's mounted document mid-edit would either drop user keystrokes
or fight the editor's internal state machine. A proper fix needs
either editor-dirty-state integration (acceptable for the "I'm
editing my own doc on two tabs" case) or a true CRDT-based collab-
edit refactor (Yjs + @tiptap/extension-collaboration) for the
"two users typing simultaneously" case. The CRDT direction is the
forward-looking plan; tracked separately.
* fix(web): guard SSE/sync handlers against stale-resolution race
Per Codex review on PR #446. The SSE handler I added in the previous
commit checks `event.item_id === item.id` *before* `await
api.items.get(...)`, but assigns to `item` *after* the resolution
without re-checking. If the user navigates to a different item while
the fetch is in flight, the resolved old-item data clobbers the
newly-loaded current item.
Same latent bug exists in the existing `onSync` handler's full-
refresh path, and Codex correctly flagged it as the same shape. The
loadData() function already guards against this same race in its
catch-block (TASK-754 round-2 race guard, see comment at line 224).
Fix mirrors that established pattern:
• Capture `item.id`, `wsSlug`, `itemSlug` into `reqItemId` /
`reqWsSlug` / `reqItemSlug` before the first await
• After every await (api.items.get, api.links.list), bail with
`if (!item || item.id !== reqItemId) return` before assigning
• Use the captured values for the requests themselves so cross-
navigation can't change which item we're fetching mid-flight
Applied to:
• SSE handler — item_updated and item_restored cases (item_archived
has no await, so it's already safe)
• onSync handler — incremental path (api.links.list was unguarded)
and full-refresh path (api.items.get was unguarded)
* fix(web): exempt destructive events from edit-conflict guard
Per Codex review round 2 on PR #446. The edit-conflict guard
(saveStatus === 'saving' || editingTitle) was placed BEFORE the
event-type switch, which meant `item_archived` (SSE) and the
`changes.deleted` branch (onSync) were also gated. Result: if
another client archived the item while the user was editing,
the destructive event was dropped and the user kept editing a
non-existent item until the next event or tab-resume sync.
Fix: hoist the destructive cases above the edit-conflict guard.
The user's in-flight save will fail against the archived row
anyway, so silently keeping them on a deleted item is strictly
worse than discarding the edit and bouncing them to the
collection list.
Applied to both handlers:
• SSE: `item_archived` runs before `saveStatus`/`editingTitle`
guard, exits early after `goto()`
• onSync: `result.changes.deleted.includes(item.id)` checked
before the guard for the same reason
|
||
|
|
578494dc43 |
fix(web): break sse↔sync circular dep via callback inversion (TASK-1242) (#445)
Rolldown's stricter import diagnostics (introduced in TASK-1238 via
Vite 8) flagged that `sync.svelte.ts` was both statically imported
from 5 routes/components AND dynamically imported from `sse.svelte.ts`.
Rolldown's warning:
[INEFFECTIVE_DYNAMIC_IMPORT] sync.svelte.ts is dynamically imported
by sse.svelte.ts but also statically imported by [5 files], dynamic
import will not move module into another chunk.
The original task body's first-cut fix ("convert the dynamic import
to static") was wrong: the dynamic import wasn't there for code-
splitting — the inline comment said "to avoid circular dependency",
and indeed sync.svelte.ts statically imports `sseService`, so a
reverse static import would close the cycle.
Real fix: callback inversion. Mirror the existing `onItemEvent`
pattern by adding `onSyncRequired(callback)` to sseService. Have
syncService subscribe in its `init()` instead of sseService calling
syncService directly. Net result:
Before: sse →(dynamic import)→ sync ──╮
sync ─(static import)─→ sse ←──╯ (circular, papered over)
After: sse exposes onSyncRequired()
sync subscribes on init(), receives sync_required pings
sse has zero imports of sync.svelte.ts (static or dynamic)
Behavior is identical:
• sse_required server event still triggers `syncService.triggerSync()`
• sync.svelte.ts still owns the sync coordination decision tree
• Init order is fine — both modules are evaluated as singletons at
module-load time; subscription happens during syncService.init()
which workspace +layout.svelte calls in onMount, well after both
modules have settled
Verified:
• `npm run build` — INEFFECTIVE_DYNAMIC_IMPORT warning is gone;
Rolldown bundle build went from 5.91s → 2.90s as a bonus
• `make check` — golangci-lint + go test + npm run build +
svelte-check, 0 errors, same 6 pre-existing warnings
• Manual UI verify — SSE still works (collection page real-time
updates, child item progress, comments/reactions, timeline)
Spawned [[TASK-1243]] for a separate pre-existing bug surfaced during
this manual verify: the item DETAIL page never subscribed to
sseService.onItemEvent, so live title/field updates from other clients
don't propagate until manual refresh. Out of scope for this PR.
|
||
|
|
1dabfd02ae |
chore(web)(deps): bump vite-plugin-svelte 6 → 7 + vite 7 → 8 (TASK-1238) (#444)
Coordinated bump of the Vite/Svelte build-tool stack:
• @sveltejs/vite-plugin-svelte 6.2.4 → 7.1.2
• vite 7.3.1 → 8.0.11
• @sveltejs/kit 2.59.0 → 2.59.1 (patch, free)
• @sveltejs/adapter-auto 7.0.0 → 7.0.1 (patch, free)
Smaller cascade than the deferred-bumps task body anticipated:
SvelteKit 2.59 already declared `^8.0.0` in its vite peer-dep range, so
no Kit major bump was needed. adapter-static is unaffected. svelte
itself (5.55.5) already meets the new vite-plugin-svelte v7 peer
constraint of ^5.46.4.
vite-plugin-svelte v7 integrated the inspector into the main package,
so the @sveltejs/vite-plugin-svelte-inspector subdep is gone — net 5
fewer packages in node_modules and a ~7KB smaller package-lock.json.
Vite 8 highlights:
• Rolldown replaces Rollup as the bundler — production build dropped
from ~12-16s to ~5.9s on this codebase
• Internally compiled with TypeScript 6 (matches our own TS 6 bump
from TASK-1236)
• npm audit moderate vulnerability count: 1 → 0 (the uuid advisory
was in a transitive that's no longer needed)
Configs reviewed:
• vite.config.ts is minimal (just sveltekit() plugin + dev proxy);
none of v7's removed options (vitePlugin.hot,
vitePlugin.ignorePluginPreprocessors, api.idFilter,
plugin.api.sveltePreprocess) are in use.
• svelte.config.js uses vitePlugin.dynamicCompileOptions (still
supported in v7).
Verified:
• Clean reinstall (rm -rf node_modules package-lock.json && npm i):
290 packages, 0 vulnerabilities
• npm run build: succeeds in 5.91s, output passes through
adapter-static
• make check (golangci-lint + go test + npm run build + svelte-check):
0 errors, same 6 pre-existing warnings
• Manual UI verify: dashboard, item list, item detail, editor (block
drag-handle, content edit/save), role board, share page all render
and function correctly
Rolldown surfaced one informational warning that's PRE-EXISTING in our
code, not introduced by the bump:
[INEFFECTIVE_DYNAMIC_IMPORT] sync.svelte.ts is both static- and
dynamic-imported. Filed as a follow-up task — fix is out of scope
for this PR.
Closes dependabot/npm_and_yarn/web/sveltejs/vite-plugin-svelte-7.0.0
(PR #215). Closes PLAN-1240 Tier 3 (5/5 ships).
|
||
|
|
1ac3f76478 |
chore(web)(deps): bump typescript 5.9.3 → 6.0.3 (TASK-1236) (#442)
The compiler bump itself is clean — svelte-check (TS 5.9 baseline) and
svelte-check (TS 6.0.3) both report 0 errors against the same 714-file
codebase. Confirms TypeScript 6's stricter inference doesn't surface
new errors in our Svelte 5 / SvelteKit / TipTap stack.
`tsc --noEmit` directly (which traverses standalone .ts files differently
than svelte-check) flagged 9 errors in one file — block-drag-handle.ts
calls TipTap chained commands (setParagraph, setHeading, toggleBulletList,
toggleOrderedList, toggleTaskList, toggleCodeBlock, toggleBlockquote)
that are added to `ChainedCommands` via TypeScript module augmentation
in the respective extension packages. TS 6 stopped propagating those
augmentations to files that don't import the augmenting modules
themselves, so each consumer must opt in.
Fix: add side-effect imports of `@tiptap/starter-kit` and
`@tiptap/extension-task-list` at the top of block-drag-handle.ts. The
modules are already loaded at runtime by Editor.svelte, so this adds
nothing to the bundle — it just re-registers the type augmentations
in this file's compilation context.
Verified:
• Manual: hover the drag handle, open the block context menu,
"Turn into" each block type (paragraph / H1-H3 / bullet / ordered /
task / code / quote), drag-reorder. All commands fire correctly.
• `make check` clean (golangci-lint + go test + npm run build +
svelte-check, 0 errors).
• Both `tsc --noEmit` and `svelte-check` return 0 errors after fix.
Closes dependabot/npm_and_yarn/web/typescript-6.0.3 (PR #213).
|
||
|
|
3ec3d6ec17 |
chore(web)(deps): bump marked 17.0.5 → 18.0.3 + drop @types/marked (TASK-1237) (#441)
v18.0.0 breaking changes are limited to (1) trimming trailing blank
lines from block tokens and (2) bumping the bundled-types compiler to
TypeScript 6. Our app calls `marked(content)` and overrides
`renderer.link` / `renderer.image` — neither path introspects the
intermediate token tree, and svelte-check (TS 5.9) consumes the
TS 6-emitted .d.ts cleanly.
Verified:
• Render snapshot of representative content (headings, code blocks,
tables, lists, task lists, blockquotes, links, images, autolinks,
strikethrough, multi-paragraph, escaped HTML) is byte-identical
between v17.0.5 and v18.0.3 — same 1847 bytes, zero diff lines.
• `make check` (golangci-lint + go test + npm run build + svelte-check)
passes with 0 errors.
• Manual UI spot-check: item body, wiki-links, code blocks, tables,
attachments, and the share-page route all render correctly.
Also drops @types/marked@5.0.2 — marked has shipped its own bundled
.d.ts since v9, so this devDep has been redundant and 12 majors stale.
Removing it eliminates type-resolution drift against the bundled types.
Mermaid retains its nested marked@16.4.2 — no transitive ripple. Closes
dependabot/npm_and_yarn/web/marked-18.0.2 (PR #212).
|
||
|
|
a1e7378d8e |
chore(web)(deps): bump diff 8.0.3 → 9.0.0 (TASK-1239) (#440)
v9.0.0 breaking changes are confined to patch parse/format functions (parsePatch, formatPatch, reversePatch, StructuredPatch). The only in-tree consumer is web/src/lib/components/versions/DiffView.svelte, which uses diffLines + the Change type — both unchanged in v9. ES5 support is dropped, which is irrelevant for our Vite/SvelteKit target. Verified via runtime smoke-test that diffLines() in v9 returns the same Change shape (value: string, added/removed: boolean) the DiffView consumer expects. Closes dependabot/npm_and_yarn/web/diff-9.0.0 (PR #214). |
||
|
|
06f8487d6b |
chore(deps)(deps): bump the npm-minor-and-patch group across 1 directory with 16 updates (#412)
Bumps the npm-minor-and-patch group with 15 updates in the /web directory: | Package | From | To | | --- | --- | --- | | [@tiptap/core](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/core) | `3.20.4` | `3.22.5` | | [@tiptap/extension-bubble-menu](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-bubble-menu) | `3.20.4` | `3.22.5` | | [@tiptap/extension-code-block-lowlight](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-code-block-lowlight) | `3.20.4` | `3.22.5` | | [@tiptap/extension-link](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-link) | `3.20.4` | `3.22.5` | | [@tiptap/extension-placeholder](https://github.com/ueberdosis/tiptap/tree/HEAD/packages-deprecated/extension-placeholder) | `3.20.4` | `3.22.5` | | [@tiptap/extension-table](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-table) | `3.20.4` | `3.22.5` | | [@tiptap/extension-task-item](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-task-item) | `3.20.4` | `3.22.5` | | [@tiptap/extension-task-list](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/extension-task-list) | `3.20.4` | `3.22.5` | | [@tiptap/starter-kit](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/starter-kit) | `3.20.4` | `3.22.5` | | [@tiptap/suggestion](https://github.com/ueberdosis/tiptap/tree/HEAD/packages/suggestion) | `3.20.4` | `3.22.5` | | [dompurify](https://github.com/cure53/DOMPurify) | `3.4.1` | `3.4.2` | | [mermaid](https://github.com/mermaid-js/mermaid) | `11.13.0` | `11.14.0` | | [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) | `2.57.1` | `2.59.0` | | [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) | `5.54.1` | `5.55.5` | | [svelte-check](https://github.com/sveltejs/language-tools) | `4.4.5` | `4.4.7` | Updates `@tiptap/core` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/core/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/core) Updates `@tiptap/extension-bubble-menu` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/extension-bubble-menu/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-bubble-menu) Updates `@tiptap/extension-code-block-lowlight` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/extension-code-block-lowlight/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-code-block-lowlight) Updates `@tiptap/extension-link` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/extension-link/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-link) Updates `@tiptap/extension-placeholder` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages-deprecated/extension-placeholder/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages-deprecated/extension-placeholder) Updates `@tiptap/extension-table` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/extension-table/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-table) Updates `@tiptap/extension-task-item` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-task-item) Updates `@tiptap/extension-task-list` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/extension-task-list) Updates `@tiptap/pm` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/pm/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/pm) Updates `@tiptap/starter-kit` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/starter-kit/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/starter-kit) Updates `@tiptap/suggestion` from 3.20.4 to 3.22.5 - [Release notes](https://github.com/ueberdosis/tiptap/releases) - [Changelog](https://github.com/ueberdosis/tiptap/blob/main/packages/suggestion/CHANGELOG.md) - [Commits](https://github.com/ueberdosis/tiptap/commits/v3.22.5/packages/suggestion) Updates `dompurify` from 3.4.1 to 3.4.2 - [Release notes](https://github.com/cure53/DOMPurify/releases) - [Commits](https://github.com/cure53/DOMPurify/compare/3.4.1...3.4.2) Updates `mermaid` from 11.13.0 to 11.14.0 - [Release notes](https://github.com/mermaid-js/mermaid/releases) - [Commits](https://github.com/mermaid-js/mermaid/compare/mermaid@11.13.0...mermaid@11.14.0) Updates `@sveltejs/kit` from 2.57.1 to 2.59.0 - [Release notes](https://github.com/sveltejs/kit/releases) - [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md) - [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.59.0/packages/kit) Updates `svelte` from 5.54.1 to 5.55.5 - [Release notes](https://github.com/sveltejs/svelte/releases) - [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md) - [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.55.5/packages/svelte) Updates `svelte-check` from 4.4.5 to 4.4.7 - [Release notes](https://github.com/sveltejs/language-tools/releases) - [Commits](https://github.com/sveltejs/language-tools/compare/svelte-check@4.4.5...svelte-check@4.4.7) --- updated-dependencies: - dependency-name: "@tiptap/core" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-bubble-menu" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-code-block-lowlight" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-link" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-placeholder" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-table" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-task-item" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/extension-task-list" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/pm" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/starter-kit" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@tiptap/suggestion" dependency-version: 3.22.5 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: dompurify dependency-version: 3.4.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: npm-minor-and-patch - dependency-name: mermaid dependency-version: 11.14.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: "@sveltejs/kit" dependency-version: 2.59.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: svelte dependency-version: 5.55.5 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: npm-minor-and-patch - dependency-name: svelte-check dependency-version: 4.4.7 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: npm-minor-and-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> |
||
|
|
a829d3a06d |
fix(web): ItemCard polish — nudge PR badge down, wrap long titles (BUG-1233) (#437)
* fix(web): ItemCard polish — nudge PR badge down, wrap long titles (BUG-1233)
Two small fixes on the item card:
1. PR badge vertical position: top: -6px → 8px. The previous offset
pushed the badge above the card edge; 8px sits the pill comfortably
inside the top of the card while keeping the right: -6px overhang
(sticker-on-edge feel). Cosmetic polish on TASK-1230.
2. Long-title overflow (BUG-1233). Item cards with unbreakable titles
(URLs, long identifiers, code-snippet titles) used to push the card
past its container — most visible on board view's narrow columns.
- `.item-card` → `min-width: 0` so it can shrink below its intrinsic
content width when it's a flex/grid child
- `.card-title` → `overflow-wrap: anywhere; min-width: 0` so any
character can be a break point when whitespace is absent
Deliberately NOT setting `overflow: hidden` on `.item-card` — the
PR badge protrudes at `right: -6px` and would be clipped.
Verification:
- golangci-lint -> 0 issues
- go test ./... -> all pass
- cd web && npm run build -> clean
- Manual: long-title item now wraps inside the card on board + list views;
PR badge still renders correctly at the new position.
* fix(web): reserve top-row right padding for PR badge per Codex review (round 1)
Codex flagged that moving the PR badge from top: -6px to top: 8px
brought it inside the card and on top of the .card-top-row content
(star button, optional collection badge, item ref). On dashboard
active-items panel and role board (both pass showCollection=true) or
items with long refs, the badge could cover that text and intercept
clicks.
Fix: add `class:has-pr={!!pullRequest}` to the card and reserve
padding-right: 52px on .card-top-row whenever a PR badge is present.
Width budget covers a 5-digit PR number worst case plus the badge's
right: -6px protrusion (~50px pill - 6px overhang = 44px inner gap;
rounded up to 52px for breathing room). Non-PR cards keep their full
top-row width.
|
||
|
|
e932fd4fcd |
feat(web): show PR state badge on item cards (TASK-1230) (#436)
Render a state-colored pill badge in the top-right corner of ItemCard
whenever an item has a linked GitHub PR. The badge overlaps the card
border ("sticker on card" feel), shows the PR number, and opens the PR
URL in a new tab on click without navigating to the item.
PR data is read from `item.code_context?.pull_request` which the server
already derives from `fields.github_pr` via ExtractItemCodeContext —
no new types, helpers, or API calls. State colors:
- OPEN -> var(--accent-green)
- MERGED -> var(--accent-purple, #8b5cf6)
- CLOSED -> var(--accent-red, #ef4444)
- DRAFT -> var(--text-muted)
- default -> var(--text-muted)
Implementation matches the existing star-btn pattern: a <button> (not
nested <a>) with preventDefault + stopPropagation, then window.open
with noopener,noreferrer. Visible in both default and compact card
variants; tooltip on hover surfaces the PR title + state.
Implements [[IDEA-1214]]. Stale-state refresh (badge may show OPEN
after PR is merged) is intentionally out of scope and tracked
separately under IDEA-1214 (sibling task).
Verification:
- golangci-lint run --timeout=5m ./... -> 0 issues
- go test ./... -> all pass
- cd web && npm run build -> clean
- svelte-check -> 0 errors
Note: `make check` also runs govulncheck which flags 4 pre-existing
Go stdlib vulnerabilities (GO-2026-4982 / 4980 / 4971 / 4918) on the
1.26.2 baseline. Tracked under TASK-1232 (Bump Go toolchain to 1.26.3).
Unrelated to this PR.
|
||
|
|
954c84d0bf |
refactor(e2e): extract demo data into shared module (TASK-1201) (#431)
Lift the static "realistic workspace" data out of seedRealisticContent
into web/e2e/lib/demo-data.ts so it can be consumed by pad-remotion (a
sibling repo) without dragging in Playwright as a dependency. Single
source of truth for what a real-feeling Pad demo looks like.
Wire-shape compatibility is preserved exactly:
- demoPlan: same title, status, content
- demoTasks: same 7 tasks in same order, same status/priority/effort,
same parent-to-plan linkage (now expressed via parentToPlan: boolean
rather than carrying the plan id inline — the seeder maps it back
to the freshly-created plan id at post time)
- demoIdeas: same 2 ideas, same fields
Behavior verified by running the gated screenshot spec:
PAD_SCREENSHOTS=1 npx playwright test e2e/screenshots.spec.ts \
--project=desktop-chromium
seedRealisticContent runs to completion and the dashboard / board /
list / table screenshots regenerate identically (reverted; not part
of this PR's diff).
demoConventions is also exported (4 representative entries) for the
pad-remotion ContextScene to render ghost-cards. demo-seed.ts itself
doesn't consume it — seedConventions takes caller-supplied input — but
the shape lives here so the shared data module is complete.
The companion pad-remotion file (src/data/demoItems.ts) lands as a
separate PR in PerpetualSoftware/pad-remotion. We chose copy-with-
manual-sync over a path import / symlink because pad-remotion is a
distinct git repo; a CI drift check is a possible follow-up if this
duplication starts to bite.
Parent: PLAN-1198.
|
||
|
|
40352a32e1 |
feat(auth): PAD_BYPASS_SETUP_TOKEN open-bootstrap escape hatch (#429)
Adds an env-var that lets self-host operators on trusted networks (Unraid behind a firewall, Tailscale-only deployments, homelabs) claim the first admin via the web UI without copying a bootstrap token out of the container logs. Behavior when PAD_BYPASS_SETUP_TOKEN=true: - handleBootstrap accepts non-loopback first-admin POSTs without an X-Bootstrap-Token header. The UserCount==0 invariant is unchanged, so the bypass auto-closes the moment the first admin claims the seat (subsequent bootstrap requests get 409 regardless of bypass). - handleSessionCheck returns setup_method=open so the /setup page skips the paste-token UI and renders the form directly. - Token generation is skipped at startup (no .bootstrap-token file written). A distinct WARN-flavored banner makes the open-mode trade-off obvious in operator logs. - Cloud mode (PAD_CLOUD/PAD_MODE=cloud) ignores the flag entirely. Three layers of defense: cmd/pad masks the env-var with !cfg.IsCloudServer(), Server.openBootstrapEnabled() checks !s.cloudMode, and the cloud branch in handleBootstrap never reads the bypass field. Unraid template gets a new "Bypass Setup Token" field (default false, Display="always") with a description that calls out the trust-the- network trade-off. Tests pin all the security-critical contracts: bypass admits non- loopback, bypass off keeps existing 403, cloud mode hard-ignores, loopback works either way, post-bootstrap gate stays closed, bypass wins over logs_token in session payload, cloud mode never advertises 'open' setup method. Codex review: CLEAN (round 1). |
||
|
|
05a9665f50 |
feat(auth): first-run logs-token bootstrap flow (TASK-1167) (#424)
One-time bootstrap token generated on first start with no users in self-host mode. Token is logged in a banner the operator can grab from `docker logs`, persists at <DataDir>/.bootstrap-token (mode 0600), and bypasses the loopback-only gate via the X-Bootstrap-Token header — letting the user claim the first admin from a remote browser at /setup#token=<x>. Header-only contract + URL-fragment (browser-only, never transmitted) + log-redaction middleware keeps the secret out of access logs, proxy logs, and browser history. Cloud mode unchanged: token never loaded, never honored. Validate → UserCount-check → CreateUser → consume sequence is mutex-serialized to prevent concurrent valid-token requests from creating multiple admins. Part of PLAN-1166 (Pad on Unraid — Community Apps launch). |
||
|
|
6c44291e78 |
fix(layout): let Cmd+F fall through to browser-native find on item views (BUG-986) (#423)
The layout's global keydown handler unconditionally intercepted Cmd+F and routed it through a `collectionSearchRequested` boolean that only the collection list page polled. On item / document views (and any non-collection page) nothing watched the flag, but `e.preventDefault()` had already blocked the browser's native find — leaving users with no way to search inside a document. Invert the model from "always intercept, broadcast a flag" to "only intercept when a page registers a handler": - ui.svelte.ts: replace `collectionSearchRequested` with a `collectionSearchHandler` registry exposing `registerCollectionSearch` / `unregisterCollectionSearch` / `triggerCollectionSearch` / `hasCollectionSearchHandler`. - +layout.svelte: only `e.preventDefault()` and dispatch when `uiStore.hasCollectionSearchHandler` is true; otherwise let Cmd+F pass through to the browser. - [collection]/+page.svelte: register the existing filters-open + focus-search behaviour in an `$effect` and unregister it via the effect's cleanup so it lives only while the page is mounted. Result: collection list view keeps its existing Cmd+F filter-search shortcut; item views and any other page get the browser's native find back. `make check` clean (Go tests, lint, web build, svelte-check 0 errors). |
||
|
|
50d04944c5 |
feat(sweep): gate role board + child reorder + run grep verification (TASK-1108) (#422)
* feat(sweep): gate role board + child reorder + run grep verification (TASK-1108)
Final sweep across PLAN-1100 (client-side permission audit). Confirms no
remaining open-coded permission checks and gates the few remaining surfaces
not covered by tasks 1102-1107.
Code-only acceptance grep results:
- `members.find(...)` outside workspaceStore: ZERO matches
- `m.role === 'owner' / 'editor'` open-codes outside permissions.ts: ZERO matches
- `isOwner = $derived(workspaceMembers...)` open-codes: ZERO matches
Surfaces gated in this PR:
- Role board (`/{workspace}/roles`):
- "+ New" item button gated on canEditAnyItem (owner|editor)
- "+ Add Role" column owner-only
- Lane edit button (✎) owner-only, lane drag handle owner-only
- Lane-header drag (column reorder) owner-only — handlers and draggable
attribute conditional on isOwner
- Lane-items dndzone receives dragDisabled: !canEditAnyItem (zone-level
library limitation, same constraint as TASK-1106)
- ChildItems component (used on item detail to render children):
- New canEdit prop (default true). Slug page passes canEdit (= canEditItem
of parent). dndzone receives dragDisabled: !canEdit so non-editors
can't drag-reorder children.
BUG-984 closure remains gated on HT-1157 (manual three-role smoke test),
which will sign off on real walks as owner / editor / viewer / guest.
Parent: PLAN-1100.
* fix(sweep): empty-state role create gate + grant-aware canEditAnyItem per Codex review (round 1)
Two findings from round 1:
1. Empty-state "Create your first role" button at roles/+page.svelte:530
wasn't gated. Now wrapped in {#if isOwner}.
2. canEditAnyItem was role-only (owner|editor). Server's reorder handler
is grant-aware per-item, so a viewer/guest with even one
CollectionGrant.edit or ItemGrant.edit can legitimately mutate via the
role board. Helper now ORs in any active edit grant — matches what
the server enforces.
Parent: PLAN-1100. Refs TASK-1108 PR #422.
* fix(sweep): align role-board create/lane-reorder gates with server per Codex review (round 2)
Two findings from round 2:
1. The role-board "+ New" item flow was gated on canEditAnyItem (any role
or any edit grant), but server's handleCreateItem requires collection-
level edit (collection grant or role+visibility), not item-only grant.
Item-grant-only users would see "+ New" but get a 403 on submit.
Filter eligibleCollections by workspaceStore.canEditCollection(coll.id)
and gate the button on eligibleCollections.length > 0.
2. Lane reorder was owner-only, but server's handleRoleBoardLaneReorder
uses requireMinRole "editor". Editors lost an allowed operation.
Introduced canReorderLanes (owner | editor) for lane drag handles +
ondrag handlers; role create/edit/delete remain owner-only.
Parent: PLAN-1100. Refs TASK-1108 PR #422.
|
||
|
|
7f06a9845a |
feat(comments): gate composer / replies / reactions / delete on canEditItem (TASK-1107) (#421)
Comment timeline previously rendered composer, reply, reaction picker,
and per-reaction toggle for all roles. Server enforces edit per-item on
comment writes; UI now matches.
Note on file paths: TASK-1107's original spec referenced
`web/src/lib/components/comments/CommentThread.svelte`, but that file is
unused anywhere in `web/src/`. Real comment UI lives in:
- `ItemTimeline.svelte` (composer + thread layout)
- `TimelineCommentCard.svelte` (per-comment delete, replies, reactions)
Changes:
- ItemTimeline: imports workspaceStore, accepts itemId + collectionId
props (optional with safe fallback), derives canEdit reactively. The
composer is hidden entirely when !canEdit.
- TimelineCommentCard: accepts canEdit prop. Delete / reply / reaction
picker / reply-comment delete / reply reaction picker all gated.
- Existing reactions still render with counts so read-only viewers see
who reacted; the chip's onclick is gated and disabled={!canEdit} so
toggling is blocked for them.
- Slug page passes item.id + item.collection_id so ItemTimeline can
resolve canEditItem itself (no prop-drilling of canEdit).
Parent: PLAN-1100.
|
||
|
|
fe9b76ab93 |
feat(views): gate drag/archive in ListView/BoardView on canEditCollection (TASK-1106) (#420)
The collection page's ListView and BoardView allowed all roles to drag
items, drag-status-change, reorder groups/columns, and archive groups.
Server enforces edit per-item and per-collection on these mutations
(handlers_items.go, handlers_role_board.go) — UI now matches.
Changes:
- ListView + BoardView accept a `canEdit?: boolean` prop (default true to
preserve behavior in existing callers).
- ListView: dndzone for groups + intra-group items receives
`dragDisabled: !canEdit`. Group drag handle and archive-group button
hidden when !canEdit.
- BoardView: column-cards dndzone receives `dragDisabled: isMobile || !canEdit`.
Column-header drag (column reorder) gated via `draggable={canEdit}` and
conditional drag handlers. Column-drag-handle indicator and
archive-column button hidden when !canEdit.
- Collection page passes `canEdit={canEditThisCollection}` to both views.
Scope note: per-item drag gating (e.g. a guest with ItemGrant.edit on one
item dragging just that one card) is not implemented — svelte-dnd-action
only supports zone-level dragDisabled. Achieving per-item would require
switching to dragHandleZone+dragHandle and shipping an explicit handle UI
for everyone, which is a larger UX change. Server already enforces per-item
edit on the resulting mutations, so no security gap. Documented as a
follow-up if needed.
TableView: excluded from drag/archive scope — no drag handlers to gate.
Status-cell editing is already gated via FieldEditor's readonly prop from
TASK-1105.
Parent: PLAN-1100.
|
||
|
|
a8b158829b |
feat(item-detail): gate write affordances on canEditItem (TASK-1105) (#419)
* feat(item-detail): gate write affordances on canEditItem (TASK-1105)
Item detail page hides title-edit, content editing, FieldEditor inputs,
delete button, and assignment dropdowns when the user lacks edit on this
specific item. Mirrors the server's per-item permission cascade so the UI
cannot show affordances the server would 403.
Per-item gate via workspaceStore.canEditItem(item) — owner → item grant →
collection grant → role + visibility → deny. Handles guests with single
ItemGrant.edit (full edit on that one item, read-only on siblings) and
the precedence regression where ItemGrant.view + CollectionGrant.edit on
the same item resolves to read-only (item grant wins per server cascade).
Changes:
- FieldEditor: new `readonly?: boolean` prop. When true, renders a unified
display block per field type (select / checkbox / date / number / url /
text) — same visual language as the editor's idle state, no inputs, no
dropdowns, no mutation handlers. Documented in the component header.
- RawMarkdownEditor: new `readonly?: boolean` prop, applied to the
underlying textarea.
- [slug]/+page.svelte: derived canEdit predicate. Title swaps from
click-to-edit button to plain h1 when read-only. Editor passes
editable=canEdit; EditorBubbleMenu / EditorLinkPopover only mount when
editable. RawMarkdownEditor passes readonly. Delete button hidden.
FieldEditor receives readonly={!canEdit}. Assignment + role dropdowns
swap to read-only display spans.
- New CSS: .title-readonly (no hover, default cursor),
.assignment-readonly (matches assignment-select height for layout
stability when the user gains/loses edit permission).
Parent: PLAN-1100.
* fix(item-detail): gate Editor toolbars + ?new=1 title bypass per Codex review (round 2)
Two read-only escape hatches found by Codex re-review:
1. Editor.svelte mobile toolbar (line 818) and table toolbar (line 846)
rendered without checking the `editable` prop. tiptap's editor instance
correctly refuses commands when editable=false, so the buttons would
no-op, but they still rendered and were visually misleading. Both
toolbars now gated on `editable`.
2. The slug page's auto-start-title-edit path for ?new=1 didn't check
canEdit. A read-only user appending ?new=1 would land on the title
textarea (which the visible-branch gate now hides). Added canEdit to
the auto-start condition AND to startEditTitle() itself as a defensive
second line.
Round 1 disagreements stand: Move-to / item-links / ChildItems are
explicitly TASK-1108 sweep scope and intentionally not addressed here.
Parent: PLAN-1100. Refs TASK-1105 PR #419.
* fix(item-detail): exclude BlockDragHandle in read-only + gate Move-to / links per Codex review (round 3)
Three findings from round 3:
1. Editor's BlockDragHandle ProseMirror plugin (registered in Editor's
extensions list) is not gated by tiptap's `editable` flag — its drag
handle is injected into the view DOM regardless. A read-only user
could drag blocks to dispatch transactions through onUpdate. Fix:
conditionally include the plugin in the extensions array based on
`editable`.
2 + 3. Move-to button and item-links add/delete affordances. These were
originally TASK-1108 sweep scope, but Codex re-flagged them in
round 3 despite the round-2 deferral. Absorbed into TASK-1105
rather than burn more review rounds — the gating is mechanical
(a few {#if canEdit} wrappers). TASK-1108 sweep will still grep
for any remaining open-coded patterns elsewhere.
Parent: PLAN-1100. Refs TASK-1105 PR #419.
* fix(item-detail): re-key Editor on canEdit change so BlockDragHandle reattaches per Codex review (round 4)
Round 3 excluded BlockDragHandle from the editor's extensions array when
editable=false. Round 4 caught the construction-time-only nature of that
gate: on cold/direct navigation /me resolves after the editor mounts, so
canEdit starts false → editor created without BlockDragHandle → /me
resolves → canEdit flips true but the existing $effect only calls
editor.setEditable(true) and does not re-register extensions.
Fix: add canEdit to the {#key} value so the editor is reconstructed when
permission flips. Cost is a brief loss of cursor/scroll position on the
flip — acceptable since the only path that flips canEdit mid-session is
a grant change while the page is open, which is rare.
Same approach is appropriate for any future extension whose registration
is gated on `editable`.
Parent: PLAN-1100. Refs TASK-1105 PR #419.
* fix(item-detail): handle ?new=1 auto-edit reactively for slow /me per Codex review (round 5)
* fix(item-detail): always reassign pendingNewItemEdit per Codex review (round 6)
|
||
|
|
d311245654 |
feat(collection-page): gate item-create affordances on canEditCollection (TASK-1104) (#418)
The collection list page renders multiple "create item" affordances — header "+ New" button, quick-create input, empty-state CTA, and view-level buttons via EmptyState — to all roles regardless of whether they can actually create items in this collection. Server rejects the writes; this hides the affordances entirely. Per-collection gate via workspaceStore.canEditCollection(collection.id) — not the binary canEdit. A viewer with a CollectionGrant.edit on Tasks sees "+ New" on /tasks but not on /ideas. A guest with only an ItemGrant sees no create affordance anywhere (server cascade: item grant doesn't promote to collection-wide write). Changes: - Header "+ New" button: hidden when !canEditThisCollection. - Quick-create input: only renders when both quickCreateOpen AND canEditThisCollection (defensive, since openQuickCreate is no longer callable through any visible affordance). - Empty-state-box CTA: hidden when !canEditThisCollection. Message also switches from "Create your first ..." to "This collection is empty." - View-level oncreate prop: undefined when !canEditThisCollection, so EmptyState (the shared empty-state component) hides its own create button automatically. Parent: PLAN-1100. |
||
|
|
0035a9dad9 |
feat(settings): gate collection management UI to owners (TASK-1103) (#417)
Settings → Collections currently shows "+ Create Collection" and clickable edit cards to all roles. The server already enforces owner-only on create, update, and delete (handlers_collections.go:48, :113, :164). UI now matches. Changes: - Collection cards remain clickable for owners (open EditCollectionModal); for non-owners they render as non-interactive divs with the same content visible. The "Edit" hint is hidden for non-owners. - "+ Create Collection" button hidden entirely for non-owners. - CreateCollectionModal / EditCollectionModal mount only for owners — a non-owner can't reach them via the UI. Note: TASK-1103 spec floated "create gated to editor+", but the server is owner-only. Aligned UI to server (server is the security boundary). Parent: PLAN-1100. |
||
|
|
3524a5ed92 |
feat(settings): gate Danger Zone tab + General write affordances on owner role (TASK-1102) (#416)
The presenting symptom of BUG-984: editors and viewers currently see the Danger Zone tab + workspace name/context/export controls. All of those are owner-only on the server. Gates them in the UI so the affordances aren't rendered to begin with. Changes: - Tabs are now derived: Danger Zone is filtered out for non-owners. Direct URL access to #danger as a non-owner snaps back to General. - Hash-driven tab restoration deferred to a validTabIds-aware $effect so owners deep-linking to #danger don't land on General because /me was still in flight at mount time. - General tab → Name input rendered readonly for non-owners; Save button hidden. - General tab → Context JSON textarea rendered readonly for non-owners; Save / Reset / Clear buttons hidden. - General tab → Export bundle gated to editor+ (canExport). Theme toggle remains available to all roles (personal preference, not workspace state). Owner experience unchanged. Non-owners now see a read-only General tab with workspace context visible (so they know what they're working in) but no controls that would 403. Parent: PLAN-1100. |
||
|
|
1ff6158468 |
feat(workspace): expose currentRole + resource-scoped permission helpers (TASK-1101) (#415)
* feat(workspace): expose currentRole + resource-scoped permission helpers (TASK-1101)
Foundation for PLAN-1100 (client-side permission audit). Lands the primitive
that every other task in the plan consumes, with no UI behavior changes.
Server:
- new GET /api/v1/workspaces/{ws}/me — returns role, collection_access,
visible_collection_ids (computed via VisibleCollectionIDs /
GuestVisibleCollectionIDs so it covers system collections, member access,
direct collection grants, and item-grant collections), plus the user's
direct collection_grants and item_grants.
- admins normalize to "owner"; legacy workspace-scoped tokens normalize to
"editor"; non-members with no grants are rejected upstream by
RequireWorkspaceAccess and never reach the handler.
Frontend:
- new $lib/utils/permissions module exporting pure cascade functions:
canEditWorkspace / canViewCollection / canEditCollection /
canViewItem / canEditItem.
- cascade mirrors server's ResolveUserPermission exactly:
owner → item grant → collection grant → membership role + visibility
so item grant beats collection grant beats role even when less permissive
(ItemGrant.view + CollectionGrant.edit on same item → effective view).
- workspaceStore wraps the pure functions with currentMembership state
fetched in setCurrent. New getters: currentRole, currentMembership,
isOwner, canEditWorkspace; new methods: canViewCollection /
canEditCollection / canViewItem / canEditItem.
- WorkspaceMembership type added.
- api.workspaces.me(slug) added.
Refactor:
- settings/+page.svelte, [collection]/+page.svelte,
[collection]/[slug]/+page.svelte: drop open-coded role derivation
(members.find + m.role open-codes), consume workspaceStore.isOwner.
members.list calls remain — still needed for assignee dropdowns / member
rows in settings — only the role-derivation path moves to the store.
Tests:
- server: handlers_me_test.go covers 6 scenarios
(admin, editor with all-access, viewer with collection grant,
restricted member, guest with item grant, non-member with no grants).
- frontend unit tests deferred — web/ has no unit-test runner today.
Pure-function module makes them trivial to add when the runner lands.
Cascade is independently covered by store/permissions_test.go and
store/grants_test.go on the server.
Parent: PLAN-1100.
* fix(workspace): per-item visibility uses strict full-access set + setCurrent race guard per Codex review (round 1)
P1: canViewItem fell back to canViewCollection, which uses the broad nav
set (visible_collection_ids — includes collections containing
item-granted items so they appear in nav). This meant a guest with one
ItemGrant on TASK-5 in Tasks would see canViewItem(any-other-task-in-Tasks)
return true, while the server only allows direct item grants or full
collection grants.
Fix: /me now also returns full_access_collection_ids — the strict set of
collections in which every item is accessible (collection grants +
member_collection_access + system collections; item-grant collections
intentionally excluded). This mirrors guestResourceFilter's fullCollIDs
in handlers. canViewItem and canEditItem now consult full_access_collection_ids
on the membership-fallthrough path, NOT the nav set.
Test added: TestMe_GuestWithItemGrant now asserts the item-grant collection
is in visible_collection_ids (nav) but NOT in full_access_collection_ids
(strict). TestMe_RestrictedMember updated to check both sets.
P2: workspaceStore.setCurrent had no guard against stale async /me responses.
A slow /me for workspace A could clobber a freshly-fetched membership
for workspace B if the user navigated mid-flight, briefly exposing
permission-gated UI for the wrong workspace.
Fix: monotonic membershipSeq counter incremented per setCurrent / create
call. Each /me response only writes back if its captured token still
matches at resolution time. Also clears currentMembership immediately on
setCurrent so helpers don't briefly answer "yes" using the previous
workspace's grants while /me is in flight.
Parent: PLAN-1100. Refs TASK-1101 PR #415.
* fix(workspace): canEditCollection uses strict full-access set per Codex review (round 2)
Same nav-vs-strict bug pattern as round 1's canViewItem fix, but in
canEditCollection. The editor-membership fallback path previously gated
on canViewCollection (broad nav predicate using visible_collection_ids),
which incorrectly returned true for a restricted editor whose only access
to a collection was an item grant. The collection appears in nav (correct)
but the editor must NOT see collection-wide write affordances like "+ New"
because the server rejects collection-level writes there.
Fix: editor membership fallback now requires either collection_access ===
"all" or the collection to be in full_access_collection_ids.
canEditItem already used full_access_collection_ids on its fallback path
(it was added in round 1) — verified unchanged.
Parent: PLAN-1100. Refs TASK-1101 PR #415.
|
||
|
|
504e22d7bc |
fix(console): add mobile hamburger menu + scrollable admin tabs (BUG-1118) (#414)
The /console navbar's horizontal pill row crammed/clipped on narrow viewports, and the admin sub-tab strip wrapped awkwardly. Add a hamburger menu that toggles a dropdown panel below the navbar on mobile, and make the admin tab strip horizontally scrollable on the same breakpoint. Console layout (web/src/routes/console/+layout.svelte): - Hamburger button (32x32) appears in .nav-left on mobile (<=640px), switches to an X when open. Same SVG/sizing as TopBar.svelte's .mobile-hamburger so the chrome stays consistent. - .nav-links becomes a full-width dropdown panel below the navbar when open. Visual style mirrors TopBar.svelte's .user-dropdown (--bg-secondary, border, --radius-lg, box-shadow, dropdown-in keyframe). - Closes on link click, Escape, outside-click, and route change. - Route-change auto-close kept as its own single-purpose $effect per CONVE-606. - a11y: aria-expanded, aria-controls, aria-label on toggle; role=menu on panel, role=menuitem on links. - Desktop layout (>640px) is unchanged. Admin layout (web/src/routes/console/admin/+layout.svelte): - On <=640px the .admin-tabs strip becomes overflow-x: auto with -webkit-overflow-scrolling: touch, scrollbar-width: none, and flex-wrap: nowrap so all tabs are reachable without clipping. - Tabs stay flex-shrink: 0 + nowrap to keep labels readable. - Active-tab underline + colors preserved. |
||
|
|
abf017c4e7 |
feat(onboarding): make banner + CLI hint template-aware (TASK-1150) (#409)
The IDEA-1 trigger phrase is no longer hardcoded — fresh scrum
workspaces surface "use pad to get BACK-1", product workspaces surface
"use pad to get FEAT-1", and any future template that ships an
agent-onboarding seed declares its primary ref once and gets the
banner / hint for free.
Mechanism:
1. WorkspaceTemplate gains an OnboardingPrimaryRef string field —
the canonical declaration of "this template's IDEA-1-style
primary entry." Set per template that ships the pattern
(startup → "IDEA-1", scrum → "BACK-1", product → "FEAT-1");
left empty for hiring/interviewing/demo where the agent-onboarding
pattern intentionally doesn't apply.
2. Server: handleGetDashboard identifies the seeded primary by
walking allItems looking for item_number=1 + source="template"
+ created_by="system" + collection_slug ∈ {ideas, backlog,
features}. The collection-slug whitelist is what keeps hiring's
REQ-1 (also seeded with item_number=1 + source=template) from
being flagged as an onboarding entry — those are example items,
not agent scripts. The dashboard response gains an
onboarding_seed field with ref/title/slug/collection_slug/status
plus a server-computed `active` boolean (true iff status equals
the schema initial value).
3. CLI: printOnboardingHints accepts the template name, looks up
the primary ref via collections.GetTemplate, and prints the
right "use pad to get X-1" line. Templates without a declared
primary skip the line entirely (so hiring's pad init success
doesn't promise a non-existent BACK-1 / IDEA-1).
4. Web frontend: dashboard reads dashboard.onboarding_seed,
gates the banner on `active=true`, passes ref/slug/collection
to OnboardingIdeaBanner. The component renders the trigger
phrase, copy button, and "Read it first" deep link from those
props — no more hardcoded IDEA-1.
ensureWorkspace's signature gains a returned templateName so init.go
+ main.go can pass it through to printOnboardingHints. The five
existing test call sites updated.
New tests:
internal/collections/templates_test.go
- TestTemplatesDeclareOnboardingPrimaryRef — locks the per-template
OnboardingPrimaryRef values (and the explicit emptiness of
hiring/interviewing/demo).
internal/server/handlers_dashboard_test.go
- TestDashboardOnboardingSeed_StartupTemplate
- TestDashboardOnboardingSeed_ScrumTemplate
- TestDashboardOnboardingSeed_ProductTemplate
- TestDashboardOnboardingSeed_HiringTemplate (asserts NO seed —
hiring's REQ-1 is example data, not an onboarding entry)
- TestDashboardOnboardingSeed_EmptyWorkspace (no template)
Removes the loadIdeaOne race-guard from +page.svelte — the dashboard
poll itself now carries the onboarding_seed.active flag so the banner
state lives entirely in the dashboard response. Drops ~50 lines of
frontend code.
Parent: PLAN-1146.
|
||
|
|
0a5eb777b9 |
feat(onboarding): surface IDEA-1 trigger phrase across CLI and web UI (TASK-1134) (#403)
* feat(onboarding): surface IDEA-1 trigger phrase across CLI and web UI (TASK-1134)
Make the seeded onboarding entry point discoverable without prior
knowledge. CONVE-191 calls for full-stack thinking on user-facing
features — this lands on every surface a fresh user might check.
CLI surfaces:
• `pad auth setup` success message gains a closing hint pointing at
`use pad to get IDEA-1` in a new agent session. New helper
printIdeaOneTriggerHint() so future templates can reuse the shape.
• `printOnboardingHints` (used after `pad init` / workspace creation)
now leads with the trigger phrase before the existing /pad prompt
suggestions. IDEA-1 is named because it's the seeded primary entry
in software-category templates; people-category templates will
seed REQ-1 / APP-1 etc. and need a template-aware version of this
hint — tracked under PLAN-1140.
Web UI surfaces:
• New OnboardingIdeaBanner component renders on the workspace
dashboard whenever IDEA-1 is in status=new. Shows the trigger
phrase verbatim with a copy button and a "Read it first" deep link
into the seeded item itself. Disappears the moment the user (or
agent) flips IDEA-1 out of `new`.
• Dashboard fetches IDEA-1 alongside its existing dashboard +
collections calls (cheap, indexed by ref) and re-checks on every
poll (default 30s) plus every sync signal so the banner is
self-correcting.
• Existing OnboardingChecklist gate (`totalItems === 0`) is left
alone. It still serves empty / non-templated workspaces; the new
banner is the templated-workspace surface.
No tests added — both surfaces are pure copy/render. Existing
dashboard + auth-setup tests still pass.
Parent: PLAN-1131. Origin: IDEA-1128.
* fix(onboarding): pin IDEA-1 lookup to exact prefix+number match per Codex review (round 1)
Server-side ResolveItem (via GetItemByRef) falls back from PREFIX-NUMBER
to a number-only lookup when the prefix doesn't match any collection in
the workspace. That fallback exists so an item moved between collections
is still resolvable by its old ref — but it has a bad interaction with
my new dashboard lookup:
In a non-software-category workspace (hiring, interviewing, …), there
is no Ideas collection. `api.items.get(ws, 'IDEA-1')` would silently
return whatever item has item_number=1 — typically REQ-1 (Requisition)
or APP-1 (Application). If that item happened to have status=new
(which the seeded Requisition / Application entries do), the dashboard
would render the IDEA-1 onboarding banner pointing at a /ideas/... URL
that 404s.
Fix: verify item.collection_prefix === 'IDEA' && item.item_number === 1
before trusting the result. Mismatch (or missing) → ideaOneStatus = null,
banner stays hidden. Software workspaces with a real IDEA-1 still match;
hiring / interviewing / interview-loop-style workspaces stop seeing the
banner entirely.
Caught by Codex on PR #403.
* fix(onboarding): guard IDEA-1 lookup against stale-workspace writes per Codex review (round 2)
Previous round addressed the wrong-collection match. This round fixes a
related race: rapid workspace navigation could let a slow loadIdeaOne()
from workspace A resolve after the user is already on workspace B and
write A's status into B's state, briefly rendering the IDEA-1 banner on
a workspace that doesn't have it.
Two-part fix:
1. The dashboard $effect that triggers load() now resets
ideaOneStatus = null synchronously when wsSlug changes, so any
leftover `new` status from the previous workspace can't briefly
render the banner during the window between navigation and the new
fetch resolving.
2. loadIdeaOne() now compares its captured slug against the current
wsSlug at every assignment point (success and error paths). If
they've diverged, the response is dropped — only the active
workspace's request can write ideaOneStatus.
Standard "was this still the active request" pattern. No behavior
change for the common case (single-workspace dashboard); the guard
only fires when navigation interleaves with an in-flight fetch.
Caught by Codex on PR #403.
|
||
|
|
95025793b9 |
feat(mobile): consolidate topbar + search palette UX (IDEA-1121) (#401)
Mobile chrome was previously split: a full <TopBar mobile /> (logo +
switcher + avatar) when the sidebar was open, and a slim inline
.mobile-header (hamburger + switcher) when it was closed. Every
mobile-chrome feature had to be added in two places, and the original
ask — a search button — surfaced the architectural debt.
Consolidated to a single always-rendered mobile chrome:
- TopBar.svelte mobile branch: PadLogo replaced with a hamburger that
toggles the sidebar; new search-icon button calls openSearch() AND
onNavigate() so the sidebar closes before navigating to a result
(caught by Codex review, mirrors the desktop sidebar pattern).
- +layout.svelte: dropped the &&sidebarOpen gate so TopBar always
renders on mobile; deleted the inline .mobile-header and its CSS;
added padding-top: var(--topbar-height) on .app-layout via @media
(max-width: 768px) so content doesn't slide under the fixed bar.
- [collection]/[slug]/+page.svelte: removed the now-stale 45px sticky
offset that was pushing the breadcrumb below the deleted slim
header.
Search palette mobile UX (CommandPalette.svelte, all in one
@media (max-width: 768px) block — desktop is byte-identical):
- Full-screen takeover (100dvh, no max-width / shadow / radius) so
input anchors at top instead of fighting a vertically-centered
layout against the on-screen keyboard.
- 16px input font to suppress iOS Safari focus-zoom.
- X close button (.mobile-close) replacing the useless 'esc' kbd hint.
- Body-scroll lock effect (overflow: hidden only — touch-action: none
would have killed child scroll).
- .results pinned as the sole scroll target with flex: 1; min-height: 0
so the search input stays at the top regardless of result-list size.
Editor toolbar leak fix (Editor.svelte): the .mobile-toolbar (z-index
100) rendered whenever the on-screen keyboard appeared for ANY input
— including the global search palette on a page with a tiptap editor
mounted. Gated the render condition on editorFocused (already tracked
via editor.on('focus')/on('blur')) so the toolbar only appears when
the editor itself is focused.
Refs: IDEA-1121, TASK-1122, TASK-1124
|
||
|
|
d6c0073409 |
chore(web): point ConnectMCPModal docs link at /mcp/remote (TASK-1117 follow-up) (#397)
The connect-MCP modal had DOCS_HREF set to a temporary fallback at getpad.dev/docs/mcp because the canonical /mcp/remote landing didn't exist yet (TODO comment noted that). pad-web PR #80 (TASK-1117) just shipped /mcp/remote as the proper sibling to /mcp/local. Update the link target to match. The previous URL /docs/mcp now 404s on getpad.dev (page <24h old when moved; redirect explicitly waived per the project owner). This commit ensures every Pad instance points at the live URL going forward. Parent: PLAN-1111. Companion to pad-web #80. |
||
|
|
78ec39daa2 |
feat(web): add ConnectMCPModal + wire into ConnectBanner (TASK-1115) (#396)
* feat(web): add ConnectMCPModal + wire it into ConnectBanner (TASK-1115)
Ships the Remote MCP onboarding modal that the MCP-mode banner has been
waiting for. With this PR, on any deployment that exposes a public MCP
URL (Pad Cloud + any self-host with PAD_MCP_PUBLIC_URL set), users with
an empty workspace see:
- A "Connect an AI agent — zero install →" banner (TASK-1114)
- Click → ConnectMCPModal with:
* The canonical MCP URL in a copy-block (sourced from
authStore.mcpPublicUrl, never hardcoded — works for self-hosted
deploys too)
* Four client cards (Claude Desktop, Cursor, Windsurf, ChatGPT) each
linking to the existing getpad.dev/docs/mcp/<client> page
* Footer links: Connected agents (in-app), Documentation
(getpad.dev/docs/mcp — TASK-1117 will swap to /mcp/remote when
that page lands), and "Prefer the CLI? →" which closes this modal
and opens the existing CLI install modal
ConnectBanner now mounts BOTH modals with independent open states; the
visibility predicate ORs them so the banner hides during interaction.
The "Prefer the CLI?" cross-link calls a parent callback so the banner
owns both states — ConnectMCPModal never directly mounts the CLI modal.
The transitional `mode === 'cli'` visibility gate from TASK-1114 is
removed (the gate's reason for existing — no MCP modal — is gone).
Validated:
- Svelte autofixer: 0 issues / 0 suggestions on the new component
- make check: 0 errors, 703 files (was 702 — confirms new file is
picked up by svelte-check)
Parent: PLAN-1111. Depends on TASK-1114 (banner refactor — shipped).
* fix(web): refetch on CLI-modal close regardless of banner mode (Codex round 1)
Codex caught a real bug: Effect C was gated on `mode === 'cli'`, but
the new MCP modal can flip the user to the CLI flow via "Prefer the
CLI? →". In that path, mode stays 'mcp' but the user runs `pad init`
and closes the CLI modal — and Effect C wouldn't refetch, leaving the
banner stale until a route change.
Fix: track `prevCliOpen` specifically and refetch on its true → false
transition, regardless of banner mode. The MCP-modal close transition
is still no-op (correct — user is off in a separate agent client).
|
||
|
|
393d8f1d7d |
feat(web): ConnectBanner two-mode refactor (CLI / MCP) (TASK-1114) (#395)
* feat(web): ConnectBanner two-mode refactor (CLI / MCP) (TASK-1114)
Adds mode-aware rendering to the connect banner. When the server exposes
a Remote MCP URL via /auth/session.mcp_public_url (Pad Cloud + any
self-host with PAD_MCP_PUBLIC_URL set), the banner renders in MCP mode:
- Plug icon (vs the historical terminal-arrow)
- Copy: "Connect an AI agent to this workspace — zero install →"
- CTA: "Connect" (vs "Get the CLI")
Self-hosted instances without an MCP public URL keep the existing
CLI-mode copy + flow (regression-safe — no behavior change there).
Effect C (refetch on modal close) now runs CLI-mode only. In MCP mode
the user leaves the page entirely — off to Claude Desktop / Cursor /
Windsurf to paste the URL — so refetching the dashboard right after
modal close doesn't help. Effect B (workspace-change refetch) and the
SSE feed catch the first MCP-sourced item on the next visit.
localStorage dismiss key migration: writes now go to
`pad-connect-banner-dismissed-{ws}` (was `pad-cli-banner-dismissed-{ws}`).
Reads OR the new and legacy keys for one release as a soft migration so
existing dismissals carry over without re-pestering. Legacy key is left
in localStorage as harmless dead state — we don't own the cleanup path.
Transitional state: MCP-mode banner currently routes to the existing
ConnectWorkspaceModal as a fallback. TASK-1115 ships ConnectMCPModal
and will swap the binding. Until then, MCP-mode users who click see the
CLI install flow — worse UX than the destination, but coherent (no
broken click). Clearly TODO'd in the markup.
Validated with the Svelte autofixer (0 issues; advisory suggestions
about $effect usage are justified — localStorage reads + async fetches
+ previous-value tracking can't be expressed as $derived).
Parent: PLAN-1111. Depends on TASK-1112 + TASK-1113 (both shipped).
* fix(web): suppress MCP-mode banner until ConnectMCPModal ships per Codex review (round 1)
Codex P1: the MCP-mode copy promises "zero install" but the click still
opens ConnectWorkspaceModal (CLI flow), which is misleading for users
who land in that state.
Fix: gate `visible` on `mode === 'cli'` for now. The mode-detection,
branched copy/icon/CTA, and dismiss-key migration all stay — they're
ready to light up when TASK-1115 mounts the new modal. The transitional
gate is removed in TASK-1115 along with the modal swap.
Net effect this PR: cloud / MCP-exposed deploys see no banner at all
(strictly safer than misleading); self-hosted deploys are unchanged
(same CLI banner + flow).
Codex finding addressed: PR #395 round 1.
|
||
|
|
a1179f1c07 |
feat(dashboard): broaden agent-activity signal to include MCP source (TASK-1112) (#394)
Renames the "has_cli_source" signal to "has_agent_activity" — semantically
the dashboard flag for "this workspace's agent loop is wired up." Existing
behavior is preserved (CLI activity still flips it on); the SQL widens to
match source IN ('cli', 'mcp') so the signal stays correct if attribution
is later split (today, all MCP-via-HTTPHandlerDispatcher activity persists
as source='cli' per dispatch_http_test.go's contract).
Renames:
- store: WorkspaceHasCLISource → WorkspaceHasAgentActivity
- dashboard struct: HasCLISource → HasAgentActivity
- JSON tag: has_cli_source → has_agent_activity
- Svelte state: hasCliSource → hasAgentActivity
- Svelte fn: refreshHasCliSource → refreshHasAgentActivity
- TS field: has_cli_source → has_agent_activity (DashboardData)
- Test: TestWorkspaceHasCLISource* → TestWorkspaceHasAgentActivity*
New test case in TestWorkspaceHasAgentActivity asserts that an item with
source='mcp' also flips the signal on, exercising the broadened SQL clause.
Comment updates explain today's "MCP attribution = source='cli'" reality
so future readers don't search in vain for source='mcp' writers.
The Svelte localStorage dismiss key (`pad-cli-banner-dismissed-`) is left
unchanged in this PR — TASK-1114 will rename it with a soft-migration
read of the old key for one release. This PR's goal is the rename + signal
broadening, not the banner UX refactor.
Unblocks TASK-1114 (banner two-mode refactor).
Parent: PLAN-1111.
|
||
|
|
92c05cb029 |
feat(auth): expose mcp_public_url on /auth/session (TASK-1113) (#393)
Adds mcp_public_url to the /auth/session response (and the parallel setupStatePayload for the pre-bootstrap state). Sourced from the existing s.mcpPublicURL field that SetMCPTransport populates from PAD_MCP_PUBLIC_URL at startup. Empty string when unset — never null, never absent — so the web UI can branch on `mcp_public_url !== ''` as the gate for "this Pad instance exposes a Remote MCP server." Frontend gets a parallel `authStore.mcpPublicUrl` getter mirroring the existing `cloudMode` pattern. AuthSession.mcp_public_url is typed as required (string), since the server always emits it. Tests cover both shapes: empty string when PAD_MCP_PUBLIC_URL is unset (both pre-setup and post-bootstrap), and verbatim echo when configured. Unblocks TASK-1114 (banner two-mode refactor) which gates on this field. Parent: PLAN-1111. Note: AuthSession lives in web/src/lib/api/client.ts, not types/index.ts — the task description had the wrong file. Type was edited in client.ts. |
||
|
|
f9d3244660 |
feat(connected-apps): user-facing OAuth connection management page (TASK-954) (#390)
* feat(connected-apps): user-facing OAuth connection management page (TASK-954)
Adds /console/connected-apps where a logged-in user can see every
OAuth grant chain they've authorized via the MCP consent flow
(Claude Desktop, Cursor, …) and revoke any of them. Joins to the
DCR client metadata for the display name + logo, and to the MCP
audit log (TASK-960) for the "last used" + "30-day calls" columns.
Pieces:
- internal/store/connected_apps.go — ListUserOAuthConnections walks
oauth_access_tokens + oauth_refresh_tokens, dedups by request_id,
hydrates client metadata, parses session_data for the workspace
allow-list, classifies granted_scopes into a coarse capability
tier. RevokeUserOAuthConnection verifies ownership (ErrConnection
NotFound for stranger's chains — anti-enumeration; same shape as
for unknown chains) then calls the existing RevokeRefreshTokenFamily
+ RevokeAccessTokenFamily so the next /mcp call gets 401.
- internal/models/connected_apps.go — OAuthConnection + CapabilityTier
models.
- internal/server/handlers_connected_apps.go — REST endpoints:
GET /api/v1/connected-apps (list) + DELETE /api/v1/connected-apps/{id}
(revoke, idempotent, 204). Wrapped in requireCloudMode group.
List enriches with MCPConnectionStatsForUser (audit aggregates) —
soft-fails on the audit lookup so a broken audit table degrades
to "no last-used data" instead of a broken page. Revoke records
an "oauth_connection_revoked" entry in audit_trail via the
existing CreateActivity path.
- web/src/routes/console/connected-apps/+page.svelte — list with
per-app card (logo, name, capability badge, workspace chips with
+N expander, connected/last-used relative times, 30-day count),
Details expander showing scope_string + workspace list + redirect
URIs, Revoke button → confirm modal → optimistic refresh, friendly
empty state linking to /connect.
- web/src/routes/console/+layout.svelte — Connected Apps nav link
(cloud-mode-gated, between Settings and Billing).
- web/src/lib/api/client.ts + types/index.ts — typed client +
ConnectedApp interface.
Tests cover:
- Store: chain dedup across rotation siblings, subject filtering
(Bob can't see Alice's), inactive chains excluded, ownership
check on revoke, idempotent re-revoke, capability tier mapping,
session-data allowed_workspaces parsing (both []string and JSON
[]interface{} round-trips).
- Handler: cloud-mode gate (404 outside), owner-only filtering,
DTO field shape + audit enrichment populating last_used_at +
calls_30d, revoke ownership 404 (not 403 — anti-enumeration),
idempotent 204, audit_trail row written.
`make check` clean (lint + go test ./... + svelte-kit build).
Parent: PLAN-943.
* fix(connected-apps): point empty-state link at getpad.dev (Codex review round 1)
Codex caught: the empty-state link to /connect 404s because /connect is a
pad-web (marketing site) route, not a docapp route. From inside the
authenticated console at app.getpad.dev, the right target is the
absolute https://getpad.dev/connect URL — same pattern the +error.svelte
page uses for its "Back to getpad.dev" + "/docs" links.
* fix(console nav): exclude /console/connected-apps from Workspaces active match (Codex round 2)
Codex caught: the Workspaces nav predicate `isActive('/console') && !isActive('/console/settings') && ...` was missing the new /console/connected-apps prefix, so both Workspaces AND Connected Apps lit up when viewing the connected-apps page.
Same shape as the existing exclusions for settings / billing / admin.
|
||
|
|
d8b1d98e08 |
feat(mcp): persistent audit log for /mcp tool calls (TASK-960) (#389)
* feat(mcp): persistent audit log for /mcp tool calls (TASK-960)
Adds a 90-day-retention audit log of every MCP request. Drives the
"last used" + "30-day calls" columns the connected-apps page (TASK-954)
will read, and gives ops + on-call a forensics surface via a new
admin /console/admin/mcp-audit page.
Schema deviation from the spec, documented in migration 049:
the original task body called for `token_id REFERENCES oauth_tokens(id)`
but pad has no `oauth_tokens` table — instead an OAuth grant chain is
identified by `request_id` (preserved across refresh-token rotations,
see migration 048), and PAT-authenticated MCP requests have no OAuth
identity at all. The audit row therefore carries `(token_kind,
token_ref)` — `oauth` + request_id for OAuth, or `pat` + api_tokens.id
for PATs. The connected-apps page in TASK-954 will filter on
token_kind='oauth' to surface third-party connections only.
Pieces:
- internal/store/migrations/049_mcp_audit.sql + pgmigrations/028 — table.
- internal/models/mcp_audit.go — typed entry + 30-day stats DTO.
- internal/store/mcp_audit.go — insert / list-by-user / list-by-connection
/ list-all / per-connection-stats aggregator / 90-day retention sweeper.
- internal/server/middleware_mcp_audit.go — async writer + sweeper +
middleware that wraps /mcp behind MCPBearerAuth. Hot path is
non-blocking enqueue with drop-on-overflow + atomic drop counter.
- internal/server/middleware_mcp_auth.go — both PAT + OAuth branches now
stash WithMCPTokenIdentity so the audit row attributes correctly.
- internal/server/handlers_mcp_audit.go — read endpoints:
GET /api/v1/connected-apps/{id}/audit (owner-scoped) +
GET /api/v1/admin/mcp-audit (admin-only).
- web/src/routes/console/admin/mcp-audit/+page.svelte + tab in admin layout.
- Tests cover required-field validation, round-trip, pagination,
owner-only filtering, last-used + 30-day aggregates, retention sweep,
body-sniff parser, canonical-JSON arg hashing, buffer-full drop path,
status-to-result classification, admin gate, DTO field shape.
`make check` clean (lint + go test ./... + svelte-kit build).
Parent: PLAN-943.
* fix(mcp-audit): emit denied row on rate-limit reject per Codex review (round 1)
PR #389 round 1 caught: MCPAuditLog is mounted INSIDE MCPBearerAuth, so
when bearer auth's per-token rate-limit fires (429) it returns before
next.ServeHTTP — and the wrapping audit middleware never sees the
response. classifyMCPResult mapped 401/403/429 with no path that could
actually reach it.
Fix: emitMCPAuditDenied helper called directly from the rate-limit
deny branches of both PAT + OAuth paths. Resolved user + token
identity are already in scope at that point, so the audit row gets
attributed correctly. Pre-auth rejections (no/invalid bearer) stay
un-audited because there's no user to attribute them to and the
audit_trail table covers those auth-event signals already.
Threading: handleMCPPATAuth + handleMCPOAuthAuth now take the entry
timestamp so the denied row carries real latency.
Test: TestMCPAudit_RateLimited_RecordsDeniedRow drives a real PAT
through the rate limiter, drains to 429, and asserts the audit row
lands with status="denied" + error_kind="rate_limited" + the right
tool_name from the request body.
|
||
|
|
8cdf582066 |
fix(auth): full-page navigation for server-owned post-auth redirect targets (BUG-1083) (#386)
Unauthenticated users hitting /oauth/authorize were 302'd through /login, but the post-login goto(redirectTarget) used SvelteKit's client-side router to navigate back to /oauth/authorize — a Go-server route with no SPA match. SvelteKit fell into the [username]/[workspace] catchall, parsed it as username="oauth" + workspace="authorize", and rendered "No dashboard data available." Add isServerOwnedPath() + navigateToRedirectTarget() helpers in web/src/lib/auth/redirect.ts. The helper picks window.location.replace for paths the Go server owns (/oauth/, /api/, /.well-known/, /mcp, /metrics) and goto() for genuine SPA routes. window.location.replace matches the prior replaceState: true semantics so back-button doesn't return to /login. Swap all 5 post-auth call sites in login/+page.svelte (onMount, password submit, 2FA verify) and register/+page.svelte (onMount, register submit) to use the helper. goto import is no longer needed in either file. |
||
|
|
cf04e16b5e |
chore(e2e): blog screenshot capture spec + shared seed helpers (TASK-1031) (#374)
Adds infrastructure for capturing Pad UI screenshots that ship inside
blog posts on getpad.dev.
* web/e2e/lib/demo-seed.ts (new) — extracts the realistic-content seed
(1 active plan + 7 tasks + 2 ideas) from screenshots.spec.ts into a
shared module, plus two new helpers:
- seedConventions(fixture, request, [...])
- activateLibraryConventions(fixture, request, titles)
Both consumers now share the same source of truth.
* web/e2e/blog-screenshots.spec.ts (new) — gated on
PAD_BLOG_SCREENSHOTS=1. One test.describe per blog post; each owns
its post-specific seed and captures into ../../pad-web/static/blog/
<slug>/. First consumer is BLOG-1007 (Conventions and Playbooks);
subsequent posts add a describe block per shot.
* web/e2e/screenshots.spec.ts — refactored to import seedRealisticContent
from the shared lib. No behavior change; PAD_SCREENSHOTS=1 README
capture still passes.
Companion publish helper lives in pad-web at scripts/blog-publish.mjs.
Capture command:
make build-go && cd web && PAD_BLOG_SCREENSHOTS=1 \
npx playwright test blog-screenshots --project=desktop-chromium
Refs TASK-1031, unblocks BLOG-1022 / BLOG-1004 / BLOG-1003 backfill
which all want screenshots.
|
||
|
|
12bd442711 |
feat(auth): contextual OAuth-intent banner on /login + /register (TASK-1001) (#368)
Add a small informational banner that renders when a user lands on
/login or /register mid-OAuth-flow (i.e. ?redirect=/oauth/authorize?...).
Tells them what they're in the middle of so the form doesn't read as a
non sequitur for first-touch users coming from the marketing site's
"Connect to Claude" CTA.
The banner is generic-only for now — once TASK-951 ships the OAuth
authorization server and the /api/v1/oauth/clients/{id}/public-info
endpoint, a follow-up will parse client_id from the inner query
string and substitute a friendly name ("connect Claude Desktop"
instead of "connect an AI agent"). Component contract is shaped to
allow that extension without consumer changes.
Detection is heuristic: redirectTarget.startsWith('/oauth/authorize').
False positives only mean a slightly more specific banner; false
negatives leave the user with the same UX they had before.
Mode prop drives the verb: signin ("signing in") on /login, signup
("creating an account") on /register.
Parent: PLAN-943.
|
||
|
|
a9ad767a45 |
feat(auth): extract <AuthOAuthButtons> + render on /register (TASK-1000) (#367)
* feat(auth): extract <AuthOAuthButtons> + render on /register (TASK-1000) Lift the cloud-mode SSO block (Continue with GitHub / Google) out of /login into a shared AuthOAuthButtons.svelte component, render it on both /login and /register, and extract redirect= validation + query-string helpers into $lib/auth/redirect so both pages compose the same encoding. Why: the marketing-site "Sign up to connect Claude" CTA lands new users on /register, which had no SSO buttons — first-touch users fell off the 30-second-onboard path. With this PR, /register exposes the same one-click SSO buttons as /login and preserves the ?redirect= query through the click so completing SSO returns to the original destination (e.g. /oauth/authorize?... once TASK-998 ships pad-cloud's redirect= honoring). Behavior changes: - /register reads the same `redirect` query param /login does and honors it on goto() after password registration. - /register populates the "Last used" pill from localStorage so returning users see the visual lift on their preferred provider. - /login is byte-identical: the inline SSO block is replaced with the component, the inline redirect helpers replaced with helper imports, and the now-unused CSS rules removed. Out of scope (separate tasks): pad-cloud's OAuth callback honoring ?redirect= (TASK-998), the OAuth-intent banner (TASK-1001). Parent: PLAN-943. * fix(auth): preserve redirect= across login↔register cross-links per Codex review (round 1) The "Don't have an account? Sign up" link on /login and the "Already have an account? Sign in" link on /register were dropping the current `redirect` query, breaking the OAuth/deep-link flow when a user mid-/oauth/authorize bounced between the two pages. Now both links append the encoded redirect target via redirectQueryFragment. Parent: PLAN-943, TASK-1000. |
||
|
|
4536892923 |
feat(brand): new tagline — Project Management for the agent era (#351)
Retire "Collaborate with your AI agents" in favor of "Project Management for the agent era". Companion change to PerpetualSoftware/pad-web#45 — they ship together so the brand reads consistently across the marketing site and the product. The phrasing leans into the moment without trend-chasing. "agent" carries more weight than "AI" — it points at *how* the technology shows up in your workflow (an autonomous teammate), not just *that* it exists. It's also the unit of change Pad is uniquely structured around (issue IDs, conventions, playbooks — things agents read). This commit only updates plain-text surfaces (README, goreleaser description, embedded PWA manifests, app meta tags). Visual accenting of the word "agent" lives in pad-web (homepage hero <h1> + OG card image), the only places that render the tagline to humans rather than to package managers / OG crawlers. ## Files - README.md — top-of-readme tagline. - .goreleaser.yaml — Homebrew formula description. - web/static/site.webmanifest — embedded PWA description. - web/static/manifest.json — duplicate PWA manifest in the same dir. - web/src/routes/+layout.svelte — <meta name="description"> and <meta property="og:description"> on every app page. ## Verification - make check: 0 errors. golangci-lint, go test ./..., govulncheck, and `cd web && npm run build` all pass. The 6 svelte-check warnings are all pre-existing in files this PR doesn't touch (NestedChildren, ChildItems, roles/+page, console/admin/+page). |
||
|
|
c4f7d243e6 |
fix(billing): gate Pro upgrade CTAs while Stripe is unwired (#324)
Stripe isn't configured on the cloud sidecar yet, so the "Upgrade to Pro" buttons on /console/billing dead-end at a 404 from /billing/checkout. Hide the Current-Plan CTA and replace the Compare-Plans CTA with a "Pro — coming soon" block plus a mailto:info@getpad.dev link to capture interest while we get the integration ready. The post-checkout polling/banners are left wired — they only fire on ?checkout=success, which can't happen until the gate flips back on. Flip the STRIPE_AVAILABLE constant (or thread it through a server flag like billing_enabled) once Stripe is live to restore the buttons. |
||
|
|
b783d06144 |
feat(web): last-used auth method banner on /login (TASK-923) (#323)
Returning users who are logged out land on /login with no context about how they signed in before. This adds a soft "last time, you used X to sign in" hint and visually elevates the matching CTA so the right next step reads at a glance — without overwhelming first-time visitors who still see all methods equally. Implementation -------------- - New helper `web/src/lib/auth/lastMethod.ts` reads/writes a `pad_last_auth_method` value (`'password' | 'github' | 'google'`) and a `pad_last_auth_at` timestamp in localStorage. Wrapped in try/catch so SSR, private mode, and disabled storage never break auth pages. - Login page records `password` on successful credential or 2FA login, and records the OAuth provider speculatively on button click. The OAuth handshake completes outside the SPA (provider → pad-cloud → pad backend session → redirect), so there's no JS callback to hang the write on. If the user bails at the consent screen the value still reflects "what the user tried last", which is the right answer for the next-visit banner. - Register page records `password` on successful registration so newly registered users see the same hint when they next return logged out. - Banner above the form names the method; matching OAuth button gets a border lift + "Last used" pill. Banner is suppressed when an OAuth error banner for the same provider is already showing — surfacing both at once muddles the message. Privacy ------- - Only the method *name* is stored — never an email, user ID, or token. - localStorage is per-origin and never sent over the wire. - No cookie, no URL param, no server log entry, no new endpoints. Parent: PLAN-776 (Post-launch Backlog). Promotes IDEA-922. |
||
|
|
f8ed3e10a7 |
fix(search): explicit selection on Enter + numeric go-to (BUG-864, BUG-910) (#320)
* fix(search): require explicit selection on Enter; add bare-number go-to (BUG-864, BUG-910) The command palette had two related issues: - BUG-864: Pressing Enter armed the first search result automatically — the user could close the modal and navigate without ever pressing an arrow key. selectedIdx now starts at -1 and only advances on ArrowDown/ArrowUp. - BUG-910: Typing a bare number (e.g. "843") returned no results because parseItemRef requires PREFIX-NUMBER and FTS doesn't index item_number. Backend (internal/store): - Add parseItemNumber() helper alongside parseItemRef. - In Search(), add a bare-numeric direct-lookup path that mirrors the existing ref-lookup block but without a collection prefix filter. item_number is unique per workspace (idx_items_workspace_number) so this resolves to at most one direct hit, prepended with rank=-1000. Frontend (CommandPalette.svelte): - selectedIdx defaults to -1; reset to -1 (not 0) on modal open and after every search. - Enter on a non-numeric query is a no-op unless the user has arrow-selected. - Numeric queries are a deliberate exception: Enter on a bare-number query flushes the debounce, navigates directly to the matching item, and lets the search palette double as a quick "go to item N" jump. Tests: - TestSearch_BareNumericQueryFindsItemByNumber covers the new path. - TestParseItemNumber covers helper edge cases. * fix(search): exclude direct hits from FTS WHERE to keep pagination correct Codex review (round 1) on PR #320: > Numeric direct hits are appended before the FTS query, but the later > pagination only removes duplicates after SQL LIMIT/OFFSET. If item #2 > also matches FTS for query "2" through its title/content, that > duplicate consumes an FTS slot, so page 1 can return fewer than `limit` > results and later pages can repeat/skip rows. Hoist the direct-hit (ref + numeric) snapshot to before the FTS query is built, then append `AND i.id NOT IN (...)` to both the SELECT and COUNT FTS queries. After a successful count, add refCount back so SearchResponse.Total still reflects the full result set (since FTS itself no longer counts those rows). The flaw also applied to the pre-existing parseItemRef path; this fix covers both. The post-LIMIT dedup loop is now defense-in-depth. New test TestSearch_BareNumericQueryDedupsAgainstFTS guards the case: an item whose title/content literally contains its own item_number (so it matches both the direct lookup and FTS) appears exactly once in Results and Total counts it exactly once. * fix(search): paginate direct hits properly across workspaces Codex review (round 2) on PR #320: > P1: Bare numeric direct hits break pagination in global search. > item_number is only unique per workspace, so q=1 with WorkspaceIDs > spanning N workspaces returns N direct hits — all appended without > being sliced to Limit. limit=1 with three workspaces each having #1 > returns three results on page 0, and offset=1 drops all direct hits > then returns FTS rows instead of the second direct hit. The same flaw applied to the pre-existing parseItemRef path: the global search "TASK-5" can match TASK-5 in multiple workspaces. Fix: - Add deterministic ORDER BY i.workspace_id, i.id to both ref and bare- numeric direct-hit lookups so pagination is stable across pages. - Replace the offset==0/offset>0 branching pagination with a uniform slice: directStart = min(Offset, refCount); directEnd = min(Offset+Limit, refCount); results = results[directStart:directEnd]; ftsLimit = Limit - directConsumed; ftsOffset = max(Offset - refCount, 0). This honours (offset, limit) whether direct hits, FTS, or both fill the page. Total stays correct because the FTS count was already excluding direct hits (round-1 fix) and we add refCount back unconditionally. New test TestSearch_BareNumericQueryPaginatesAcrossWorkspaces creates three workspaces each with item #1 and verifies that limit=1 with offsets 0/1/2 returns three different direct hits in stable order, and limit=10 returns all three. * chore: gofmt — column alignment in struct field declarations CI Go (SQLite) lint failed on two files: - internal/store/store_test.go (TestParseItemNumber, this PR's new test) — unaligned column widths and inconsistent comment spacing. - internal/config/config.go (drive-by) — pre-existing alignment regression in the Config struct that snuck in via an earlier landed PR; included here because it blocks merge. No semantic changes — `gofmt -w` only. |
||
|
|
94ebe5a83d |
test(screenshots): capture in dark mode (Pad's default theme) (#319)
The README screenshot capture script ran in light mode because Playwright's headless Chromium reports prefers-color-scheme: light by default. The Pad layout's onMount logic explicitly forces data-theme="light" when matchMedia matches 'light' — so the captures came out light-themed even though Pad defaults to dark when no user preference exists. Two effects made this misleading: 1. README screenshots showed a theme most Pad users never see by default. The first impression in the README didn't match the first impression of the running app. 2. The screenshots could not be reused in the getpad.dev marketing site (dark themed) without visible whiplash. TASK-918 (PLAN-911) needs them on the homepage; light-mode captures would have looked like screenshots of some other product. Fix: pass colorScheme: 'dark' via test.use(). Chromium then reports prefers-color-scheme: dark to the page; the layout's matchMedia check no longer matches 'light', so it leaves the document on the default theme — which is dark. Also fixed a typo in the re-run instruction in the docstring (the PAD_SCREENSHOTS=1 env var was attached to the wrong command). Re-captured all three screenshots (dashboard, board, list) under the new config. Docstring updated to call out the theme rationale so future maintainers don't accidentally flip it back. |
||
|
|
f122bec84a |
feat(layout): in-app Resources menu in user dropdown (TASK-905) (#316)
* feat(layout): in-app Resources menu in user dropdown (TASK-905) New UserMenuResources component adds a Resources block to the user-menu dropdown in TopBar, closing the product → marketing handoff seam. Logged-in users now have a clear path back out to Docs / Changelog / GitHub / Status / Support without having to remember getpad.dev URLs or visit the marketing site separately. Cloud-mode (cloudMode=true) shows: Docs / Changelog / GitHub / Status / Support. Replaces the prior inline Support/Status pair — that block became a special case of this unified Resources component. Self-hosted (cloudMode=false) shows the trimmed Docs / GitHub set. Changelog / Status are Cloud-specific surfaces; getpad.dev's support@getpad.dev mailbox isn't the operator's to direct people to. The Docs link still points at getpad.dev because that's the canonical project documentation regardless of deployment shape. Component is wired into BOTH the desktop and mobile branches of TopBar (the existing dropdown duplication). All links open in a new tab so a user mid-task doesn't lose state. Each entry has a small external-link icon so the off-property nature is visible without the user having to hover-and-read the title. The `:global(.user-dropdown)` selectors keep the new styles scoped to the existing dropdown surface in TopBar without forcing a CSS refactor of that component. Visual contract: docs/brand.md §6/§7. Companion to AuthHeader, AuthFooter, and +error.svelte from PLAN-900. Test plan: - web/npm run check — 0 errors (694 files, +1 new component) - web/npm run build — clean - Svelte autofixer — clean * fix(layout): UserMenuResources mirrors dropdown-item styles per Codex (round 2) Codex caught that .dropdown-item and .dropdown-divider rules in TopBar.svelte's <style> are scoped to that component — Svelte's scoped CSS attaches a per-component hash so the rules don't apply to DOM rendered by UserMenuResources.svelte (a separate component). The new resource links lost the dropdown padding/color/text-decoration/ hover styling, and the divider rendered as an unstyled empty 1px row. Mirror the base .dropdown-item / .dropdown-divider / .dropdown-item:hover rules inside UserMenuResources using :global(.user-dropdown) qualifiers so the dropdown surface remains the styling boundary — the rules apply to anything dropped into the menu but never leak outside it. Same scoping pattern that already worked for .resources-label and .external-icon in this component, just extended to the base classes. * fix(layout): respect canonical link order from brand spec per Codex (round 3) Codex caught that UserMenuResources rendered links in the order Docs / Changelog / GitHub / Status / Support, but docs/brand.md §7 defines a canonical relative order with GitHub before Docs and Changelog. The whole point of the brand spec is one canonical order across surfaces; violating it in the user menu undermines that. Reorder Cloud to GitHub / Docs / Changelog / Status / Support, and self-hosted to GitHub / Docs. Status and Support are user-menu-specific additions that don't appear in the marketing footer; they land at the end so the brand-spec subset stays in canonical position at the front. |
||
|
|
8f2be1b391 |
feat(error): branded 404 + 500 error pages with cloud-mode chrome (TASK-906) (#315)
* feat(error): branded 404 + 500 error pages with cloud-mode chrome (TASK-906)
New web/src/routes/+error.svelte renders for any unhandled error or
unmatched route in the SvelteKit tree. Friendly status-specific titles
+ hints (404, 401/403/500 covered explicitly; falls through to a
generic "An error occurred" + framework message for anything else).
Cloud mode wraps the error in marketing chrome — AuthHeader at the
top, AuthFooter at the bottom — and adds two extra escape CTAs ("Back
to getpad.dev" + "Open docs") in addition to the always-present "Go to
home" button. So a 404 doesn't drop the user out of the brand and they
always have somewhere to go.
Self-hosted (cloudMode=false) renders a minimal centered card with
just the status code, friendly title/hint, the inline Pad wordmark
(matching the auth-card pattern), and a single "Go to home" CTA. No
getpad.dev branding imposed on operators' deployments — same gating
philosophy as TASK-902/903.
The page hydrates authStore in onMount so cloudMode resolves on first
paint, fire-and-forget; if the session fetch fails we render the
self-hosted variant — safe fallback.
Reuses AuthHeader and AuthFooter from TASK-902/903; no need for
hand-rolled chrome since those components landed first.
Parent: PLAN-900.
Test plan:
- web/npm run check — 0 errors (693 files; +1 from new page)
- web/npm run build — clean
- Svelte autofixer — clean
* fix(error): context-aware chrome for in-app vs marketing routes per Codex (round 2)
Codex caught that +error.svelte unconditionally rendered the Cloud
marketing AuthHeader/AuthFooter, but the root +layout.svelte already
wraps workspace pages in the Sidebar/TopBar/main-content app shell.
On a workspace 404 the result would be both chromes stacked: app
shell underneath plus a fixed-position marketing header floating
over the top.
Fix: branch on the same paths the root layout uses to decide whether
to render bare children. "Marketing context" (auth/share/console
paths) keeps the full Cloud-mode AuthHeader + AuthFooter treatment;
"app-shell context" (everything else, i.e. workspace pages) renders a
minimal centered block inside the existing main-content area with no
fixed-position chrome of its own.
This means the user-facing experience in each context is correct:
- /this-does-not-exist (no auth): Cloud → branded marketing 404;
self-hosted → minimal centered card with Pad wordmark
- /login → same (auth-page family)
- /[user]/[ws]/some/missing/route: workspace shell stays intact
with a centered "Page not found" inside the main-content area
The marketing-context list mirrors the bare-render condition in
web/src/routes/+layout.svelte (isAuthPage || isSharePage ||
isConsolePage) plus the share-page prefix.
Verification: npm run check 0 errors; web build clean.
* test(e2e): wait for workspace heading before probing topbar trigger
The bundle-roundtrip test fired a synchronous isVisible() check on
the desktop topbar trigger immediately after `domcontentloaded`. The
workspace shell is fully client-rendered (adapter-static has no SSR
for app routes), so isVisible() raced hydration: on slower CI runners
the topbar wasn't in the DOM yet, the check returned false, the test
fell through to the mobile branch, and it then timed out waiting for
an element that doesn't exist on the desktop-chromium project.
Surfaced by TASK-906 (this PR), which adds ~8 KB of root-level JS
(error page + AuthHeader/AuthFooter chunks). That extra chunk-loading
shifted the hydration race past the test's check on GitHub Actions
runners; it had been winning consistently before. Locally the test
passes in ~4s either way — the race is real but tight.
Anchor the wait on the workspace heading ("E2E Workspace") which the
dashboard route renders the moment hydration completes. Keeps the
existing desktop/mobile branching intact and adds one toBeVisible()
gate so the rest of the flow runs against a fully-hydrated UI on any
runner speed.
Verified locally: 4.0s pass after the change.
|
||
|
|
2900a66861 |
feat(auth): footer parity with marketing site on auth-page family (TASK-903) (#314)
* feat(auth): footer parity with marketing site on auth-page family (TASK-903)
New <AuthFooter cloudMode={...} /> replaces the prior LegalFooter +
SupportFooter pair. Single component matches the brand spec
(docs/brand.md §7) which describes ONE footer pattern, not two
separate strips.
Cloud mode (cloudMode=true) carries the full getpad.dev marketing
footer: copyright line ("© <year> Pad · Perpetual Software") + the
nine-link list in canonical order — GitHub, Docs, Changelog,
Contribute, FAQ, Security, Privacy, Terms, Sub-processors. Visual
contract anchored on pad-web/src/routes/+layout.svelte (border-top,
max-w-6xl, flex-wrap, sm: breakpoint at 640px).
Self-hosted (cloudMode=false) renders the legal-essentials only —
Terms / Privacy / Sub-processors — preserving the visual treatment of
the prior LegalFooter exactly so existing self-hosted deployments see
no change after this PR. The Status / Support / GitHub / Changelog /
Contribute / FAQ / Security links were Cloud-only in the prior shape
too; that stays the case.
Wired the new AuthFooter into all five auth-family pages:
- /login (replaces LegalFooter + SupportFooter)
- /register (replaces LegalFooter + SupportFooter)
- /forgot-password (replaces LegalFooter + SupportFooter)
- /reset-password/[token] (NEW — was footer-less)
- /join/[code] (NEW — was footer-less)
LegalFooter.svelte and SupportFooter.svelte are deleted; they were
internal to the auth-pages feature and never used elsewhere
(grep-verified). AuthHeader's comment that referenced them is
updated to point at AuthFooter instead.
Year is computed once per page render via new Date().getFullYear()
— no auto-refresh needed since auth pages don't sit open across a
year boundary in any realistic flow.
Parent: PLAN-900.
Test plan:
- web/npm run check — 0 errors (692 files now, was 693; net -1 reflects
2 deletions + 1 addition)
- web/npm run build — clean
- go build ./... && go vet ./... && go test ./... — all pass
- Svelte autofixer — clean
* fix(auth): self-hosted AuthFooter renders nothing per Codex review (round 2)
Codex P1: the prior LegalFooter + SupportFooter both gated their entire
body on `{#if cloudMode}` — i.e. self-hosted rendered nothing at all.
The first draft of AuthFooter incorrectly assumed self-hosted should
get the legal-essentials subset (Terms / Privacy / Sub-processors
links), which would have rendered getpad.dev's hosted-service legal
links on someone else's deployment, misrepresenting the operator's
own legal terms.
Revert the self-hosted branch to render nothing. The brand spec
(docs/brand.md §7) already flags an operator-owned legal/footer
mechanism as deferred to the operator-branding follow-up plan, so
this restores the prior behavior exactly.
Removed the now-dead self-hosted link list, the .auth-footer-legal
CSS rules, and the $derived links computation.
* fix(auth): flex-direction on reset-password + join wrappers per Codex (round 3)
Codex P2: AuthFooter on /reset-password/[token] and /join/[code] sat
horizontally next to the auth card instead of below it because those
two page wrappers were `display: flex` without `flex-direction: column`.
The other three auth pages (login, register, forgot-password) already
had column layout so they were unaffected — only the two pages that
gained a footer in this PR were broken.
Add `flex-direction: column` to .page (reset-password) and .join-page
so the footer renders below the card on those routes too.
|