feat(collab): selection soft-locks — remote-selected items can't be dragged locally (collab-presence 0007)

While a peer has an item selected, local users can still select it for
inspection but move/drag/rotate/delete skip it with an infobar naming the
holder (native locked-item UX; enforced via the fork's PCBJAM_REMOTE_LOCK
query — kicad 81f9cd80fd, the epic's first fork-touching phase). Overlapping
holds (both grabbed inside the awareness propagation window) tie-break
deterministically: lowest (user.id, clientID) keeps the item, every losing
client auto-releases it.

- lock-tiebreak.ts: pure policy — beats(), remoteLocks() (union of ALL other
  clients' selections incl. own user's other tabs, minus own-held-and-winning
  uuids so the winner isn't blocked mid-release), contestedReleases()
- presence.ts: clients() (per-client view, no user dedupe) + self(); FIX for
  a pre-existing flaky stack overflow — resolveCollision re-entered itself
  synchronously via its own patch's awareness 'change' and could ping-pong on
  stale same-user states (~1-in-3 unit runs); re-entrancy guard defers
  re-resolution to the next genuine delivery
- presence-kicad.ts: locks ride the kicadCollabSetRemote snapshot
  (`locks:[{uuid,name}]`); losing overlaps call kicadCollabReleaseSelection
- wasm bindings (both TUs + merged dispatch): g_locks map + fork query
  install; kicadCollabReleaseSelection (cancelInteractive only when a tool
  stack is live — bare ESC would clear the whole selection — then selective
  RemoveItemFromSel + infobar + forced re-emit); kicadCollabTestGetLocked
- tests: lock-tiebreak unit suite; presence-locks e2e for both editors (real
  move veto — pcbnew click+M hotkey since its default left-drag is
  rubber-band select, eeschema real drag — each with an unlocked control);
  two-tab tests/web/locks.spec.ts (lock propagation + deterministic tiebreak
  release + unlock on clear, passing vs real partykit)

Spec: docs/features/collab-presence/0007 (closed repo).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lg5jwWuhFH5dL8hEcBDuP2
This commit is contained in:
Gergő Törcsvári 2026-07-07 20:35:26 +02:00
commit c30bcd4531
No known key found for this signature in database
GPG key ID: 8E75F2CDE64E5322
14 changed files with 1221 additions and 7 deletions

View file

@ -30,10 +30,14 @@ async function join(projectId: string, userId: string, tool: string): Promise<Cr
return h;
}
afterEach(() => {
afterEach(async () => {
for (const h of handles) h.destroy();
handles = [];
resetPresenceColorClaims();
// Drain already-queued BroadcastChannel deliveries before vitest recycles
// the module registry — a late message otherwise trips the vite-node module
// proxy (flaky unhandled RangeError at the schema getter).
await new Promise((r) => setTimeout(r, 20));
});
describe("startCrossAppPresence", () => {

View file

@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { beats, contestedReleases, remoteLocks, type LockClient } from "./lock-tiebreak";
/** Soft-lock tiebreak policy unit tests (collab-presence 0007). */
function client(userId: string, clientId: number, selection: string[]): LockClient {
return { userId, clientId, name: userId, selection };
}
describe("beats", () => {
it("orders lexicographically on (userId, clientId)", () => {
expect(beats({ userId: "alice", clientId: 9 }, { userId: "bob", clientId: 1 })).toBe(true);
expect(beats({ userId: "bob", clientId: 1 }, { userId: "alice", clientId: 9 })).toBe(false);
// Same user's two tabs fall to clientId.
expect(beats({ userId: "alice", clientId: 1 }, { userId: "alice", clientId: 2 })).toBe(true);
expect(beats({ userId: "alice", clientId: 2 }, { userId: "alice", clientId: 1 })).toBe(false);
});
});
describe("remoteLocks", () => {
const self = { userId: "mid", clientId: 50, selection: [] as string[] };
it("unions every other client's selection with the winning holder's name", () => {
const locks = remoteLocks(self, [
client("zed", 9, ["u1", "u2"]),
client("alice", 1, ["u2"]), // alice beats zed → she is u2's holder
]);
expect(locks).toEqual([
{ uuid: "u1", name: "zed" },
{ uuid: "u2", name: "alice" },
]);
});
it("excludes uuids the local client holds AND wins, keeps ones it loses", () => {
const locks = remoteLocks({ userId: "mid", clientId: 50, selection: ["won", "lost"] }, [
client("zed", 9, ["won"]), // mid < zed → local wins → not locked for us
client("alice", 1, ["lost"]), // alice < mid → local loses → stays locked
]);
expect(locks).toEqual([{ uuid: "lost", name: "alice" }]);
});
it("is empty with no other clients", () => {
expect(remoteLocks(self, [])).toEqual([]);
});
});
describe("contestedReleases", () => {
it("releases only uuids a WINNING peer also holds, blaming the strongest", () => {
const self = { userId: "mid", clientId: 50, selection: ["a", "b", "c"] };
const release = contestedReleases(self, [
client("alice", 1, ["a"]), // wins → release a
client("zed", 9, ["b"]), // loses → keep b (zed releases, not us)
client("bob", 2, ["c"]), // wins → release c
]);
expect(release).toEqual({ uuids: ["a", "c"], holder: "alice" });
});
it("returns null when nothing is contested or every contest is won", () => {
const self = { userId: "alice", clientId: 1, selection: ["a"] };
expect(contestedReleases(self, [client("bob", 2, ["a"])])).toBeNull();
expect(contestedReleases(self, [client("bob", 2, ["other"])])).toBeNull();
expect(contestedReleases({ ...self, selection: [] }, [client("bob", 2, ["a"])])).toBeNull();
});
it("own-user other tab contests fall to clientId", () => {
const tab2 = { userId: "alice", clientId: 7, selection: ["a"] };
expect(contestedReleases(tab2, [client("alice", 3, ["a"])])).toEqual({
uuids: ["a"],
holder: "alice",
});
const tab1 = { userId: "alice", clientId: 3, selection: ["a"] };
expect(contestedReleases(tab1, [client("alice", 7, ["a"])])).toBeNull();
});
});

View file

@ -0,0 +1,89 @@
/**
* Selection soft-lock policy (collab-presence 0007) — pure logic, no I/O.
*
* Lock rule: an item selected by any OTHER awareness client (the same user's
* other tab included) is soft-locked locally — still selectable for
* inspection, filtered from move/drag acquisition (enforced C++-side via the
* fork's PCBJAM_REMOTE_LOCK query, fed from `remoteLocks`).
*
* Tiebreak rule (overlapping holds — both grabbed inside the awareness
* propagation window): lowest `(user.id, clientID)` lexicographic KEEPS the
* item; every losing client releases it (`contestedReleases` → the C++
* `kicadCollabReleaseSelection` entry point). Pure and computable from
* awareness state alone, so all clients agree with no coordination and no
* oscillation. Known accepted bias: alphabetically-early users win.
*/
export interface LockIdentity {
userId: string;
clientId: number;
}
export interface LockClient extends LockIdentity {
/** Display name for the infobar ("R5 is being edited by <name>"). */
name: string;
selection: string[];
}
/** True when `a` beats `b` in the deterministic (userId, clientId) order. */
export function beats(a: LockIdentity, b: LockIdentity): boolean {
if (a.userId !== b.userId) return a.userId < b.userId;
return a.clientId < b.clientId;
}
/**
* The soft-lock set to feed the C++ query: every uuid held by another client,
* EXCEPT uuids the local client holds and WINS — the winner must not be
* blocked from moving its own item while the loser's release is in flight.
* (Uuids the local client holds and LOSES stay locked: the release is about
* to strip them anyway, and moving them meanwhile would fight the winner.)
* Holder name = the winning holder when several clients hold the same uuid.
*/
export function remoteLocks(
self: LockIdentity & { selection: string[] },
others: LockClient[],
): Array<{ uuid: string; name: string }> {
const ownHeld = new Set(self.selection);
const byUuid = new Map<string, LockClient>();
for (const client of others) {
for (const uuid of client.selection) {
const current = byUuid.get(uuid);
if (!current || beats(client, current)) byUuid.set(uuid, client);
}
}
const out: Array<{ uuid: string; name: string }> = [];
for (const [uuid, holder] of byUuid) {
if (ownHeld.has(uuid) && beats(self, holder)) continue;
out.push({ uuid, name: holder.name });
}
return out.sort((a, b) => a.uuid.localeCompare(b.uuid));
}
/**
* The uuids the LOCAL client must release because a winning peer also holds
* them, plus the (single) name to blame in the infobar — the strongest
* winning holder when several are involved.
*/
export function contestedReleases(
self: LockIdentity & { selection: string[] },
others: LockClient[],
): { uuids: string[]; holder: string } | null {
const uuids: string[] = [];
let strongest: LockClient | null = null;
for (const uuid of self.selection) {
let winner: LockClient | null = null;
for (const client of others) {
if (!client.selection.includes(uuid)) continue;
if (beats(client, self) && (!winner || beats(client, winner))) winner = client;
}
if (winner) {
uuids.push(uuid);
if (!strongest || beats(winner, strongest)) strongest = winner;
}
}
return uuids.length && strongest ? { uuids, holder: strongest.name } : null;
}

View file

@ -27,8 +27,14 @@ function fakeModule() {
function stubPresence(peers: PresencePeer[] = []) {
const subscribers = new Set<(p: PresencePeer[]) => void>();
const handle: PresenceHandle & { firePeers(p: PresencePeer[]): void } = {
let clients: PresencePeer[] = peers;
const handle: PresenceHandle & {
firePeers(p: PresencePeer[]): void;
fireClients(c: PresencePeer[]): void;
} = {
peers: () => peers,
clients: () => clients,
self: () => ({ userId: "local", clientId: 100 }),
subscribe(cb) {
subscribers.add(cb);
return () => subscribers.delete(cb);
@ -39,8 +45,13 @@ function stubPresence(peers: PresencePeer[] = []) {
destroy: vi.fn(),
firePeers(p) {
peers = p;
clients = p;
for (const cb of subscribers) cb(p);
},
fireClients(c) {
clients = c;
for (const cb of subscribers) cb(peers);
},
};
return handle;
}
@ -195,6 +206,63 @@ describe("xselFromPeerState", () => {
});
});
describe("bindKicadPresence × soft-locks (0007)", () => {
it("pushes the locks set derived from ALL other clients", async () => {
const mod = fakeModule();
const presence = stubPresence();
bindKicadPresence({ mod, win: {}, presence });
presence.fireClients([
peer("bob", { clientId: 7, selection: ["u1"] }),
// Own user's other tab locks too (clients() is not user-deduped).
peer("local", { clientId: 8, selection: ["u2"] }),
]);
await new Promise((r) => setTimeout(r, 60));
const snapshot = JSON.parse(mod.kicadCollabSetRemote.mock.calls.at(-1)![0]);
expect(snapshot.locks).toEqual([
{ uuid: "u1", name: "bob" },
{ uuid: "u2", name: "local" },
]);
});
it("releases contested holds when the local client loses the tiebreak", async () => {
const release = vi.fn();
const mod = { ...fakeModule(), kicadCollabReleaseSelection: release };
const win: PresenceKicadWindow = {};
const presence = stubPresence(); // self = (local, 100)
bindKicadPresence({ mod, win, presence });
win.kicadCollab!.onSelection!('["contested","mine"]');
// alice (wins: "alice" < "local") also holds "contested".
presence.fireClients([peer("alice", { clientId: 3, selection: ["contested"] })]);
await new Promise((r) => setTimeout(r, 60));
expect(release).toHaveBeenCalledWith('["contested"]', "alice");
// The winner's snapshot keeps "contested" locked for us until we release.
const snapshot = JSON.parse(mod.kicadCollabSetRemote.mock.calls.at(-1)![0]);
expect(snapshot.locks).toEqual([{ uuid: "contested", name: "alice" }]);
});
it("does NOT release when the local client wins, and unlocks the won uuid", async () => {
const release = vi.fn();
const mod = { ...fakeModule(), kicadCollabReleaseSelection: release };
const win: PresenceKicadWindow = {};
const presence = stubPresence(); // self = (local, 100)
bindKicadPresence({ mod, win, presence });
win.kicadCollab!.onSelection!('["contested"]');
// zed loses ("local" < "zed") — we keep the item and it must not be
// locked against us while zed's release is in flight.
presence.fireClients([peer("zed", { clientId: 3, selection: ["contested"] })]);
await new Promise((r) => setTimeout(r, 60));
expect(release).not.toHaveBeenCalled();
const snapshot = JSON.parse(mod.kicadCollabSetRemote.mock.calls.at(-1)![0]);
expect(snapshot.locks).toEqual([]);
});
});
describe("bindKicadPresence × crossApp", () => {
it("forwards selection emits (uuids + fpPaths) into the cross-app room", () => {
const mod = fakeModule();

View file

@ -2,6 +2,7 @@ import { symbolUuidFromFootprintPath } from "@pcbjam/shared";
import { clog } from "./debug";
import type { PresenceHandle, PresencePeer } from "./presence";
import type { CrossAppHandle } from "./cross-app";
import { contestedReleases, remoteLocks, type LockClient } from "./lock-tiebreak";
/**
* Wire the C++ presence bridge (collab-presence 0002) to the awareness layer:
@ -28,6 +29,9 @@ export interface PresenceKicadModule {
/** 0006 (pcbnew builds): `{uuids, fpPaths}` — uuids plus the selected
* footprints' schematic paths. Absent on older wasm. */
kicadCollabGetSelectionFull?(): string;
/** 0007: tiebreak release — the local client lost an overlapping hold;
* the wasm side cancels an in-flight move and unselects exactly these. */
kicadCollabReleaseSelection?(uuidsJson: string, holder: string): void;
}
export interface PresenceKicadWindow {
@ -122,12 +126,17 @@ export function bindKicadPresence(opts: {
}): { destroy(): void } {
const { mod, win, presence, crossApp } = opts;
// The local selection as last emitted by C++ — the tiebreak (0007) compares
// it against every other client's published selection.
let ownSelection: string[] = [];
// C++ → awareness ------------------------------------------------------------
win.kicadCollab = {
...win.kicadCollab,
onSelection: (uuidsJson) => {
const parsed = parseSelectionEmit(uuidsJson);
if (!parsed) return; // malformed emit — keep the last published selection
ownSelection = parsed.uuids;
presence.setSelection(parsed.uuids);
crossApp?.setSelection(parsed.uuids, parsed.fpPaths);
},
@ -146,6 +155,7 @@ export function bindKicadPresence(opts: {
(mod.kicadCollabGetSelectionFull?.() ?? mod.kicadCollabGetSelection()) || "[]",
);
if (seed?.uuids.length) {
ownSelection = seed.uuids;
presence.setSelection(seed.uuids);
crossApp?.setSelection(seed.uuids, seed.fpPaths);
}
@ -165,6 +175,7 @@ export function bindKicadPresence(opts: {
selection: string[];
xsel?: string[];
}>;
locks?: Array<{ uuid: string; name: string }>;
} = {
peers: peers.map((p: PresencePeer) => ({
id: p.user.id,
@ -174,6 +185,22 @@ export function bindKicadPresence(opts: {
selection: p.selection,
})),
};
// Soft-locks (0007): every OTHER client's held uuids (own user's other
// tabs included — presence.clients(), not the user-deduped peers()),
// minus what we hold and win. Losing overlaps trigger a release.
const self = { ...presence.self(), selection: ownSelection };
const lockClients: LockClient[] = presence.clients().map((c) => ({
userId: c.user.id,
clientId: c.clientId,
name: c.user.name,
selection: c.selection,
}));
snapshot.locks = remoteLocks(self, lockClients);
const release = contestedReleases(self, lockClients);
if (release && mod.kicadCollabReleaseSelection) {
clog("presence-kicad: lost selection tiebreak to", release.holder, "—", release.uuids);
mod.kicadCollabReleaseSelection(JSON.stringify(release.uuids), release.holder);
}
// Cross-app peers (0006): rendered as ghost outlines on the mapped items.
// One entry per awareness CLIENT (own other tabs included — that's the
// single-user cross-probe), tagged with the source editor.

View file

@ -48,10 +48,14 @@ function client(channel: string): Client {
return c;
}
afterEach(() => {
afterEach(async () => {
for (const c of clients) c.destroy();
clients = [];
resetPresenceColorClaims();
// Drain already-queued BroadcastChannel deliveries before vitest recycles
// the module registry — a late message otherwise trips the vite-node module
// proxy (flaky unhandled RangeError at the schema getter).
await new Promise((r) => setTimeout(r, 20));
});
describe("presence over the BroadcastChannel awareness relay", () => {
@ -101,6 +105,14 @@ describe("presence over the BroadcastChannel awareness relay", () => {
// bob sees ONE alice (two tabs, one person); alice's tabs don't see each other.
expect(b.presence.peers().map((p) => p.user.id)).toEqual(["alice"]);
expect(a1.presence.peers().map((p) => p.user.id)).toEqual(["bob"]);
// clients() (0007 soft-locks) is per-CLIENT: no user dedupe, own-user
// other tabs included — alice's first tab sees her second tab AND bob.
expect(a1.presence!.clients().map((p) => p.user.id).sort()).toEqual(["alice", "bob"]);
expect(a1.presence!.self()).toEqual({
userId: "alice",
clientId: a1.awareness.clientID,
});
});
it("drops malformed peer states instead of crashing the roster", async () => {

View file

@ -31,6 +31,14 @@ export interface PresenceHandle {
* user in two tabs is one person — keep the freshest state).
*/
peers(): PresencePeer[];
/**
* Every OTHER awareness client in the room, validated but NOT deduped by
* user — the same user's other tab is its own entry. Soft-locks (0007) key
* on clients, not users: your own second tab must lock against you too.
*/
clients(): PresencePeer[];
/** This client's identity for tiebreaks: (user.id, awareness clientID). */
self(): { userId: string; clientId: number };
/** Fires with the new roster on every awareness change. Returns unsubscribe. */
subscribe(cb: (peers: PresencePeer[]) => void): () => void;
/** 0002: publish the local pointer's world position (null = off canvas). */
@ -167,7 +175,24 @@ export function createPresence(opts: {
// holds our color, we yield and re-claim the lowest free slot — exactly one
// side of any collision yields, so this converges without coordination.
// Same-user tabs converge the other way: adopt the lower clientID's color.
//
// Re-entrancy guard: patch() fires the awareness 'change' event
// SYNCHRONOUSLY on the local instance, which re-enters this resolver — with
// two stale conflicting states in view (e.g. mid-propagation same-user
// tabs) the adopt/re-claim branches can ping-pong until the stack blows.
// Patches made HERE don't need immediate re-resolution; the next genuine
// (async) awareness delivery re-runs the resolver with fresher states.
let resolvingCollision = false;
const resolveCollision = () => {
if (resolvingCollision) return;
resolvingCollision = true;
try {
resolveCollisionOnce();
} finally {
resolvingCollision = false;
}
};
const resolveCollisionOnce = () => {
for (const [clientId, raw] of awareness.getStates()) {
if (clientId === awareness.clientID) continue;
const parsed = presenceStateSchema.safeParse(raw);
@ -194,13 +219,20 @@ export function createPresence(opts: {
}
};
function peers(): PresencePeer[] {
const byUser = new Map<string, PresencePeer>();
function clients(): PresencePeer[] {
const out: PresencePeer[] = [];
for (const [clientId, raw] of awareness.getStates()) {
if (clientId === awareness.clientID) continue;
const parsed = presenceStateSchema.safeParse(raw);
if (!parsed.success) continue;
const peer: PresencePeer = { ...parsed.data, clientId };
out.push({ ...parsed.data, clientId });
}
return out.sort((a, b) => a.clientId - b.clientId);
}
function peers(): PresencePeer[] {
const byUser = new Map<string, PresencePeer>();
for (const peer of clients()) {
// Another tab of the SAME user isn't a peer — the roster shows other people.
if (peer.user.id === user.id) continue;
const existing = byUser.get(peer.user.id);
@ -231,6 +263,10 @@ export function createPresence(opts: {
let destroyed = false;
return {
peers,
clients,
self() {
return { userId: user.id, clientId: awareness.clientID };
},
subscribe(cb) {
subscribers.add(cb);
return () => subscribers.delete(cb);