collab-buckets: exclusive locks, server-enforced, with editor takeover
The previous lock implementation was advisory only — the relay's lock table PK was (bucket_uid, card_uid, holder_id), so multiple users could "hold" the same card simultaneously and the plugin only used the locks to draw a small badge. Concurrent writers raced through LWW, and an unsaved editor on User A could be silently overwritten when User B saved (the symptom: cards appearing to "disappear" from User A's view once their version was clobbered by an LWW pull). Now an exclusive, server-enforced lock: * relay schema: collab_card_locks PK is (bucket_uid, card_uid). One lock per card. Migration drops the old 3-column-PK table on the next bootstrap (locks are 60s ephemeral, no data to preserve). * /api/collab-locks POST: returns 409 + holder info when another tenant already holds it. Same holder refreshes the TTL. * /api/collab-cards POST/DELETE: refuse with 423 + locked_by when a foreign tenant holds the lock. The plugin's local edit is preserved — the push just stays queued and retries on the next poll until the lock expires or is released. Tombstones are gated the same way so a card can't be deleted under the holder's editor. * Plugin push phase: tracks blocked count + holder names, surfaces them in the poll response so the frontend can toast the user. Frontend lock-on-first-keystroke flow: * The lock is no longer acquired on editor-open — opening for read doesn't lock anything. On the FIRST input event in #inp-title or #editor-body the plugin tries to acquire. On success, heartbeat every 30 s; on 409, immediately enter editor takeover. * Takeover mode: title + body inputs disabled, all three save buttons get a capture-phase click blocker (stopImmediatePropagation to defeat the editor's own listener), a window-level capture-phase keydown blocker swallows Ctrl/Cmd+S (app.js binds save directly to the shortcut, bypassing the buttons), and a banner inside the modal explains the situation. The user can still copy their unsaved text out before closing. * If a foreign lock arrives via the regular poll while the editor is already open on that card, the same takeover engages mid-session. * Opening the editor on a card whose lock is *already* known to be foreign starts in takeover mode without arming the input listeners at all. * Self-detection: poll response now carries `self` (the relay username), cached as window._collabSelf, so we don't take ourselves over and the board decoration ignores our own lock. Visual: * Board cards held by a foreign lock now get a frosted overlay + centered lock icon + holder name (replaces the small corner badge). * Editor takeover banner uses the danger accent. Save buttons get a .collab-save-blocked dim style. * New `.collab-lock-toast` variant of the existing conflict toast, used for both "your push is queued because X is editing" and "this card just got locked by X" notifications. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c8fe15b0c9
commit
f6cf7b4358
6 files changed
+407
-48
No files matched your search
@@ -27,11 +27,12 @@ let collabByUid = new Map();
|
||||
let pollHandle = null;
|
||||
const POLL_INTERVAL_MS = 30000;
|
||||
|
||||
// Phase 4: edit locks
|
||||
// Phase 4: edit locks (now exclusive — server-enforced)
|
||||
// card_uid -> { bucket_uid, holder_username, expires_at }
|
||||
let collabLocks = new Map();
|
||||
// Active heartbeat for the currently open editor (if editing a collab card)
|
||||
let activeLock = null; // { bucket_uid, card_uid, timer }
|
||||
// Tracks the editor session: { bucket_uid, card_uid, cardId, hbTimer,
|
||||
// inputCleanup, acquired, takeover }
|
||||
let editorSession = null;
|
||||
const LOCK_HEARTBEAT_MS = 30000;
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────
|
||||
@@ -61,6 +62,7 @@ async function pollOnce() {
|
||||
try {
|
||||
const res = await hyprcrd.api('api/collab-buckets/poll', { method: 'POST' });
|
||||
if (!res?.ok) return;
|
||||
if (res.self) window._collabSelf = res.self;
|
||||
// Reload if:
|
||||
// * a bucket changed (metadata / members)
|
||||
// * the bucket set shrunk or grew
|
||||
@@ -90,6 +92,25 @@ async function pollOnce() {
|
||||
collabLocks = next;
|
||||
window._collabLocks = collabLocks;
|
||||
decorateBoardLocks();
|
||||
// If the editor is currently open on a card that just got
|
||||
// locked by someone else, take over immediately. Covers the
|
||||
// race where two users started typing nearly simultaneously
|
||||
// and the relay arbitration only resolves on the next poll.
|
||||
if (editorSession && !editorSession.takeover) {
|
||||
const lock = collabLocks.get(editorSession.card_uid);
|
||||
const self = window._collabSelf || null;
|
||||
if (lock && lock.holder_username && lock.holder_username !== self) {
|
||||
enterEditorTakeover(lock.holder_username);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The push phase couldn't deliver because someone else holds an
|
||||
// exclusive lock on a dirty card. Surface so the user knows their
|
||||
// edit isn't lost — it's just queued.
|
||||
const blocked = res.card_stats?.blocked || 0;
|
||||
if (blocked > 0) {
|
||||
const by = Array.isArray(res.card_stats?.blocked_by) ? res.card_stats.blocked_by : [];
|
||||
showBlockedToast(by);
|
||||
}
|
||||
} catch { /* silent */ }
|
||||
}
|
||||
@@ -597,10 +618,13 @@ function decorateBoardLocks() {
|
||||
if (!badge) {
|
||||
badge = document.createElement('div');
|
||||
badge.className = 'collab-lock-badge';
|
||||
badge.innerHTML = '<i class="ph ph-lock-simple text-xs"></i>';
|
||||
el.appendChild(badge);
|
||||
}
|
||||
badge.title = `Being edited by ${lock.holder_username}`;
|
||||
badge.innerHTML = `
|
||||
<i class="ph ph-lock-simple-fill"></i>
|
||||
<span>${escapeHtml(lock.holder_username)}</span>
|
||||
`;
|
||||
badge.title = `Locked by ${lock.holder_username}`;
|
||||
} else if (badge) {
|
||||
badge.remove();
|
||||
}
|
||||
@@ -630,13 +654,22 @@ function collabIdentityOf(card) {
|
||||
return { bucket_uid: bucket.collab_uid, card_uid: card.relay_uid };
|
||||
}
|
||||
|
||||
async function acquireLock(bucket_uid, card_uid) {
|
||||
/** Acquire (or refresh) the exclusive lock. Returns:
|
||||
* { ok: true } on success
|
||||
* { ok: false, locked_by: '…' } when another tenant already holds it (409)
|
||||
* { ok: false } on transport / unknown error */
|
||||
async function tryAcquireLock(bucket_uid, card_uid) {
|
||||
try {
|
||||
await hyprcrd.api('api/collab-locks', {
|
||||
const res = await hyprcrd.api('api/collab-locks', {
|
||||
method: 'POST',
|
||||
body: { bucket_uid, card_uid },
|
||||
});
|
||||
} catch { /* silent */ }
|
||||
if (res?.ok) return { ok: true };
|
||||
if (res?.locked_by) return { ok: false, locked_by: res.locked_by };
|
||||
return { ok: false };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
|
||||
async function releaseLock(bucket_uid, card_uid) {
|
||||
@@ -648,41 +681,203 @@ async function releaseLock(bucket_uid, card_uid) {
|
||||
} catch { /* silent */ }
|
||||
}
|
||||
|
||||
function startHeartbeat(bucket_uid, card_uid) {
|
||||
stopHeartbeat();
|
||||
activeLock = { bucket_uid, card_uid, timer: null };
|
||||
acquireLock(bucket_uid, card_uid);
|
||||
activeLock.timer = setInterval(() => acquireLock(bucket_uid, card_uid), LOCK_HEARTBEAT_MS);
|
||||
/** First-keystroke lock: sets up one-shot input listeners on the editor
|
||||
* inputs. The first input event tries to acquire the exclusive lock; on
|
||||
* success we start the heartbeat, on failure we slap the editor into
|
||||
* takeover mode. */
|
||||
function armFirstKeystrokeLock() {
|
||||
if (!editorSession) return;
|
||||
const inputs = [document.getElementById('inp-title'), document.getElementById('editor-body')].filter(Boolean);
|
||||
let fired = false;
|
||||
const onInput = async () => {
|
||||
if (fired) return;
|
||||
fired = true;
|
||||
// Drop the listeners — heartbeat or takeover takes over from here
|
||||
for (const el of inputs) el.removeEventListener('input', onInput);
|
||||
if (!editorSession) return;
|
||||
const { bucket_uid, card_uid } = editorSession;
|
||||
const res = await tryAcquireLock(bucket_uid, card_uid);
|
||||
if (!editorSession) return; // editor closed during the await
|
||||
if (res.ok) {
|
||||
editorSession.acquired = true;
|
||||
editorSession.hbTimer = setInterval(() => tryAcquireLock(bucket_uid, card_uid), LOCK_HEARTBEAT_MS);
|
||||
} else {
|
||||
enterEditorTakeover(res.locked_by || 'someone');
|
||||
}
|
||||
};
|
||||
for (const el of inputs) el.addEventListener('input', onInput);
|
||||
editorSession.inputCleanup = () => {
|
||||
for (const el of inputs) el.removeEventListener('input', onInput);
|
||||
};
|
||||
}
|
||||
|
||||
function stopHeartbeat() {
|
||||
if (!activeLock) return;
|
||||
const { bucket_uid, card_uid, timer } = activeLock;
|
||||
if (timer) clearInterval(timer);
|
||||
releaseLock(bucket_uid, card_uid);
|
||||
activeLock = null;
|
||||
/** Switch the editor to read-only takeover mode. The user can still see /
|
||||
* copy their text but the inputs are disabled and save is blocked. */
|
||||
function enterEditorTakeover(holder) {
|
||||
if (!editorSession || editorSession.takeover) return;
|
||||
editorSession.takeover = true;
|
||||
const modal = document.getElementById('modal');
|
||||
const title = document.getElementById('inp-title');
|
||||
const body = document.getElementById('editor-body');
|
||||
if (title) title.disabled = true;
|
||||
if (body) body.disabled = true;
|
||||
modal?.classList.add('collab-readonly-modal');
|
||||
|
||||
// Block save buttons by capturing clicks before the editor handler.
|
||||
// stopImmediatePropagation also blocks any sibling listeners registered
|
||||
// on the same element (the editor's own click handler) and skips both
|
||||
// target + bubble phases for ancestors.
|
||||
const saveIds = ['modal-save', 'modal-save-view', 'modal-save-close'];
|
||||
const blockers = saveIds.map(id => {
|
||||
const btn = document.getElementById(id);
|
||||
if (!btn) return null;
|
||||
const handler = (e) => {
|
||||
e.stopImmediatePropagation();
|
||||
e.preventDefault();
|
||||
};
|
||||
btn.addEventListener('click', handler, true); // capture phase
|
||||
btn.setAttribute('disabled', 'disabled');
|
||||
btn.classList.add('collab-save-blocked');
|
||||
return { btn, handler };
|
||||
}).filter(Boolean);
|
||||
editorSession.saveBlockers = blockers;
|
||||
|
||||
// Also intercept Ctrl/Cmd+S — app.js binds this directly to saveCard/
|
||||
// saveOnly without going through the buttons we just disabled.
|
||||
const keyBlocker = (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 's' || e.key === 'S')) {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', keyBlocker, true);
|
||||
editorSession.keyBlocker = keyBlocker;
|
||||
|
||||
// Banner inside the modal explaining the situation
|
||||
let banner = document.getElementById('collab-takeover-banner');
|
||||
if (!banner) {
|
||||
banner = document.createElement('div');
|
||||
banner.id = 'collab-takeover-banner';
|
||||
banner.className = 'collab-takeover-banner';
|
||||
const inner = document.querySelector('#modal .modal-inner') || document.querySelector('#modal > div') || modal;
|
||||
inner?.prepend(banner);
|
||||
}
|
||||
banner.innerHTML = `
|
||||
<i class="ph ph-lock-simple-fill"></i>
|
||||
<span><b>Locked by ${escapeHtml(holder)}.</b> This card was locked by another user while you were typing. Copy your text out — saving is disabled.</span>
|
||||
`;
|
||||
|
||||
// Also show a one-off toast so the user can't miss it
|
||||
showLockToast(holder);
|
||||
}
|
||||
|
||||
function exitEditorTakeover() {
|
||||
const modal = document.getElementById('modal');
|
||||
const title = document.getElementById('inp-title');
|
||||
const body = document.getElementById('editor-body');
|
||||
if (title) title.disabled = false;
|
||||
if (body) body.disabled = false;
|
||||
modal?.classList.remove('collab-readonly-modal');
|
||||
document.getElementById('collab-takeover-banner')?.remove();
|
||||
if (editorSession?.saveBlockers) {
|
||||
for (const { btn, handler } of editorSession.saveBlockers) {
|
||||
btn.removeEventListener('click', handler, true);
|
||||
btn.removeAttribute('disabled');
|
||||
btn.classList.remove('collab-save-blocked');
|
||||
}
|
||||
editorSession.saveBlockers = null;
|
||||
}
|
||||
if (editorSession?.keyBlocker) {
|
||||
window.removeEventListener('keydown', editorSession.keyBlocker, true);
|
||||
editorSession.keyBlocker = null;
|
||||
}
|
||||
}
|
||||
|
||||
function showLockToast(holder) {
|
||||
const existing = document.getElementById('collab-lock-toast');
|
||||
if (existing) existing.remove();
|
||||
const toast = document.createElement('div');
|
||||
toast.id = 'collab-lock-toast';
|
||||
toast.className = 'collab-conflict-toast collab-lock-toast';
|
||||
toast.innerHTML = `
|
||||
<i class="ph ph-lock-simple-fill"></i>
|
||||
<span><b>Locked by ${escapeHtml(holder)}.</b> Copy your text — saving is blocked.</span>
|
||||
<button class="collab-conflict-close" aria-label="dismiss">✕</button>
|
||||
`;
|
||||
toast.querySelector('.collab-conflict-close').addEventListener('click', () => {
|
||||
toast.classList.add('fade-out');
|
||||
setTimeout(() => toast.remove(), 400);
|
||||
});
|
||||
document.body.appendChild(toast);
|
||||
setTimeout(() => { toast.classList.add('fade-out'); setTimeout(() => toast.remove(), 400); }, 8000);
|
||||
}
|
||||
|
||||
function showBlockedToast(by) {
|
||||
const existing = document.getElementById('collab-blocked-toast');
|
||||
if (existing) existing.remove();
|
||||
const toast = document.createElement('div');
|
||||
toast.id = 'collab-blocked-toast';
|
||||
toast.className = 'collab-conflict-toast collab-lock-toast';
|
||||
const who = by.length ? by.join(', ') : 'another user';
|
||||
toast.innerHTML = `
|
||||
<i class="ph ph-lock-simple-fill"></i>
|
||||
<span>Your edit is queued — <b>${escapeHtml(who)}</b> is currently editing. It'll sync when they're done.</span>
|
||||
<button class="collab-conflict-close" aria-label="dismiss">✕</button>
|
||||
`;
|
||||
toast.querySelector('.collab-conflict-close').addEventListener('click', () => {
|
||||
toast.classList.add('fade-out');
|
||||
setTimeout(() => toast.remove(), 400);
|
||||
});
|
||||
document.body.appendChild(toast);
|
||||
setTimeout(() => { toast.classList.add('fade-out'); setTimeout(() => toast.remove(), 400); }, 6000);
|
||||
}
|
||||
|
||||
/** Tear down everything we own for the active editor session. Called both
|
||||
* on editor-close and on plugin reload. */
|
||||
function endEditorSession() {
|
||||
if (!editorSession) return;
|
||||
const { hbTimer, inputCleanup, acquired, bucket_uid, card_uid } = editorSession;
|
||||
if (hbTimer) clearInterval(hbTimer);
|
||||
if (typeof inputCleanup === 'function') inputCleanup();
|
||||
if (acquired) releaseLock(bucket_uid, card_uid);
|
||||
exitEditorTakeover();
|
||||
editorSession = null;
|
||||
}
|
||||
|
||||
window.addEventListener('hyprcrd:editor-open', (e) => {
|
||||
endEditorSession();
|
||||
const card = e.detail?.card;
|
||||
const id = collabIdentityOf(card);
|
||||
if (id) startHeartbeat(id.bucket_uid, id.card_uid);
|
||||
if (!id) return;
|
||||
editorSession = {
|
||||
bucket_uid: id.bucket_uid,
|
||||
card_uid: id.card_uid,
|
||||
cardId: card?.id,
|
||||
hbTimer: null,
|
||||
inputCleanup: null,
|
||||
acquired: false,
|
||||
takeover: false,
|
||||
saveBlockers: null,
|
||||
};
|
||||
// If a foreign lock is already known from the last poll, take over
|
||||
// immediately — no point letting the user type into a doomed editor.
|
||||
const existing = collabLocks.get(id.card_uid);
|
||||
const self = window._collabSelf || null;
|
||||
if (existing && existing.holder_username && existing.holder_username !== self) {
|
||||
enterEditorTakeover(existing.holder_username);
|
||||
return;
|
||||
}
|
||||
armFirstKeystrokeLock();
|
||||
});
|
||||
window.addEventListener('hyprcrd:editor-close', () => {
|
||||
stopHeartbeat();
|
||||
endEditorSession();
|
||||
});
|
||||
// Graceful release on tab close
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (activeLock) {
|
||||
// Best-effort sync release; browsers may block regular fetch, so
|
||||
// use sendBeacon when available.
|
||||
if (editorSession?.acquired) {
|
||||
try {
|
||||
if (navigator.sendBeacon) {
|
||||
const url = 'api/collab-locks/' + encodeURIComponent(activeLock.bucket_uid) + '/' + encodeURIComponent(activeLock.card_uid);
|
||||
// sendBeacon only supports POST; use fetch keepalive as the
|
||||
// DELETE fallback. Both are best-effort at unload time.
|
||||
fetch(url, { method: 'DELETE', keepalive: true }).catch(() => {});
|
||||
}
|
||||
const url = 'api/collab-locks/' + encodeURIComponent(editorSession.bucket_uid) + '/' + encodeURIComponent(editorSession.card_uid);
|
||||
fetch(url, { method: 'DELETE', keepalive: true }).catch(() => {});
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user