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:
thandClaude Opus 4.6 committed 2026-04-11 19:36:57 +02:00
1 parent c8fe15b0c9
commit f6cf7b4358
6 files changed
+407 -48

No files matched your search

+13 -1
View File
@@ -227,6 +227,18 @@ $db->exec('CREATE INDEX IF NOT EXISTS idx_collab_cards_bucket_updated ON collab_
// 60s TTL. Other clients poll the list and show a lock indicator on the
// card. The lock is purely advisory — force-editing is still allowed and
// LWW remains the authoritative conflict resolver.
// Exclusive lock: PRIMARY KEY is (bucket_uid, card_uid). The first writer
// to acquire holds it; everyone else gets a 409 Locked. The previous schema
// had holder_id in the PK, which let multiple users "lock" the same card
// simultaneously — locks were advisory only, and concurrent writers could
// silently overwrite each other through LWW.
//
// Migration: if the existing table still has the 3-column PK, drop it.
// Locks are ephemeral (60s TTL) so dropping discards nothing important.
$lockTableInfo = $db->query("SELECT sql FROM sqlite_master WHERE type='table' AND name='collab_card_locks'")->fetchColumn();
if ($lockTableInfo && stripos($lockTableInfo, 'PRIMARY KEY (bucket_uid, card_uid, holder_id)') !== false) {
$db->exec('DROP TABLE collab_card_locks');
}
$db->exec('CREATE TABLE IF NOT EXISTS collab_card_locks (
bucket_uid TEXT NOT NULL,
card_uid TEXT NOT NULL,
@@ -234,7 +246,7 @@ $db->exec('CREATE TABLE IF NOT EXISTS collab_card_locks (
holder_username TEXT NOT NULL,
acquired_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT NOT NULL,
PRIMARY KEY (bucket_uid, card_uid, holder_id),
PRIMARY KEY (bucket_uid, card_uid),
FOREIGN KEY (holder_id) REFERENCES tenants(id) ON DELETE CASCADE
)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_collab_card_locks_expires ON collab_card_locks(expires_at)');
+34
View File
@@ -27,6 +27,21 @@ function collabCardsIsMember(PDO $db, string $bucketUid, int $tenantId): bool {
return (bool)$stmt->fetchColumn();
}
/** If a foreign tenant currently holds a non-expired lock on this card,
* return the lock row; otherwise null. Used to gate writes / deletes. */
function collabCardsForeignLock(PDO $db, string $bucketUid, string $cardUid, int $tenantId): ?array {
$stmt = $db->prepare("
SELECT holder_id, holder_username, expires_at
FROM collab_card_locks
WHERE bucket_uid = :b AND card_uid = :c
AND holder_id != :t
AND expires_at > datetime('now')
");
$stmt->execute(['b' => $bucketUid, 'c' => $cardUid, 't' => $tenantId]);
$row = $stmt->fetch();
return $row ?: null;
}
// ── POST: upsert a card ──────────────────────────────────────────
if ($route === '/api/collab-cards' && $method === 'POST') {
@@ -42,6 +57,16 @@ if ($route === '/api/collab-cards' && $method === 'POST') {
if (!collabCardsIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
jsonResponse(['error' => 'not a member of this bucket'], 403);
}
// Exclusive lock enforcement: if another tenant holds the lock,
// refuse the write. Plugin retries on the next poll until the lock
// expires or is released. The local edit is preserved either way.
$foreign = collabCardsForeignLock($db, $bucketUid, $cardUid, (int)$clientTenant['id']);
if ($foreign) {
jsonResponse([
'error' => 'card is being edited by ' . $foreign['holder_username'],
'locked_by' => $foreign['holder_username'],
], 423);
}
if (empty($clientTenant['secret_encrypted'])) {
jsonResponse(['error' => 'sender has no client secret set — log into the relay UI and configure one in your account'], 400);
}
@@ -148,6 +173,15 @@ if (preg_match('#^/api/collab-cards/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$#', $route
if (!collabCardsIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
jsonResponse(['error' => 'not a member of this bucket'], 403);
}
// Same lock enforcement on delete: if another user has the editor
// open on this card, deleting it under their feet would be rude.
$foreign = collabCardsForeignLock($db, $bucketUid, $cardUid, (int)$clientTenant['id']);
if ($foreign) {
jsonResponse([
'error' => 'card is being edited by ' . $foreign['holder_username'],
'locked_by' => $foreign['holder_username'],
], 423);
}
// Mark as tombstone rather than actually deleting. Late pollers see it,
// bootstrap.php cleanup prunes after 7 days.
$db->prepare('
+27 -3
View File
@@ -30,18 +30,42 @@ if ($route === '/api/collab-locks' && $method === 'POST') {
if (!collabLocksIsMember($db, $bucketUid, (int)$clientTenant['id'])) {
jsonResponse(['error' => 'not a member of this bucket'], 403);
}
// Drop expired before checking — bootstrap cleanup runs every request
// but this protects against a stale lock blocking acquisition in the
// narrow window between cleanup and this query.
$db->prepare("DELETE FROM collab_card_locks WHERE bucket_uid = :b AND card_uid = :c AND expires_at <= datetime('now')")
->execute(['b' => $bucketUid, 'c' => $cardUid]);
// Existing live lock? If a different tenant holds it, refuse.
$cur = $db->prepare('SELECT holder_id, holder_username, expires_at FROM collab_card_locks WHERE bucket_uid = :b AND card_uid = :c');
$cur->execute(['b' => $bucketUid, 'c' => $cardUid]);
$existing = $cur->fetch();
if ($existing && (int)$existing['holder_id'] !== (int)$clientTenant['id']) {
jsonResponse([
'error' => 'card is being edited by ' . $existing['holder_username'],
'locked_by' => $existing['holder_username'],
'locked_by_id' => (int)$existing['holder_id'],
'expires_at' => $existing['expires_at'],
], 409);
}
// Acquire / refresh — same holder bumps the expiry
$db->prepare("
INSERT INTO collab_card_locks (bucket_uid, card_uid, holder_id, holder_username, acquired_at, expires_at)
VALUES (:b, :c, :hid, :hu, datetime('now'), datetime('now', '+60 seconds'))
ON CONFLICT(bucket_uid, card_uid, holder_id) DO UPDATE SET
expires_at = datetime('now', '+60 seconds')
ON CONFLICT(bucket_uid, card_uid) DO UPDATE SET
holder_id = excluded.holder_id,
holder_username = excluded.holder_username,
expires_at = excluded.expires_at
")->execute([
'b' => $bucketUid,
'c' => $cardUid,
'hid' => $clientTenant['id'],
'hu' => $clientTenant['username'],
]);
jsonResponse(['ok' => true, 'expires_at' => (string)$db->query("SELECT datetime('now', '+60 seconds')")->fetchColumn()]);
jsonResponse([
'ok' => true,
'holder_id' => (int)$clientTenant['id'],
'expires_at' => (string)$db->query("SELECT datetime('now', '+60 seconds')")->fetchColumn(),
]);
}
// ── DELETE: release own lock ─────────────────────────────────────