Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep a connected pin that could not be written (#11269)

Michael Hanc2fc78d3045c
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts b/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
index a83b753db09..4d0d9f6d7a6 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pinned-connected-models.ts
@@ -2,8 +2,8 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
// Pinned `external::<connectionId>::<modelId>` ids for the Connected list, in localStorage.
-// NOT the On Device store in pinned-models.ts: an external id contains "::", which that store
-// reads as its repoId/quant separator and surfaces as a phantom pinned quant on the On Device tab.
+// NOT pinned-models.ts: "::" is that store's repoId/quant separator, so an external id lands on the
+// On Device tab as a phantom pinned quant.
import { create } from "zustand";
@@ -20,65 +20,126 @@ function readPinned(): string[] {
}
}
-/** The stored list, or null for "nothing to read". Distinct from []: a toggle falling back to []
- * would drop this window's own pins where every write has failed. */
-function storedPinned(): string[] | null {
+/** `absent` is a peer's reset and unpins what the record held; `unreadable` (access revoked, or an
+ * unparseable value) is this window losing its eyes and must change nothing. A single null for
+ * both made a revoked read unpin everything. */
+type StoredRecord =
+ | { readonly kind: "list"; readonly ids: string[] }
+ | { readonly kind: "absent" }
+ | { readonly kind: "unreadable" };
+
+function storedRecord(): StoredRecord {
+ let raw: string | null;
try {
- const raw = localStorage.getItem(KEY);
- if (raw === null) return null;
- const parsed = JSON.parse(raw);
+ raw = localStorage.getItem(KEY);
+ } catch {
+ return { kind: "unreadable" };
+ }
+ if (raw === null) return { kind: "absent" };
+ try {
+ const parsed: unknown = JSON.parse(raw);
return Array.isArray(parsed)
- ? parsed.filter((v): v is string => typeof v === "string")
- : null;
+ ? {
+ kind: "list",
+ ids: parsed.filter((v): v is string => typeof v === "string"),
+ }
+ : { kind: "unreadable" };
} catch {
- return null;
+ return { kind: "unreadable" };
}
}
-function writePinned(pinned: string[]): void {
+// Ids this window pinned and could not persist. The record stays authoritative for everything
+// else, peer removals included, so these are tracked rather than inferred from what it lacks.
+let storageWritable = true;
+let unpersisted = new Set<string>();
+
+/** `added` is the id this edit introduced, or null for a reorder, an unpin or a drag commit. */
+function writePinned(pinned: string[], added: string | null = null): void {
try {
localStorage.setItem(KEY, JSON.stringify(pinned));
+ storageWritable = true;
+ unpersisted.clear();
+ return;
} catch {
- // Ignore unavailable storage; pins stay session-only.
+ storageWritable = false;
}
+ // Only `added` is certainly unpublished: re-reading the record here instead claimed ids a peer
+ // removed between that read and this failed write, and the next write that landed undid them.
+ // The intersection is the undo rule, so unpinning while writes fail takes the id back out.
+ const carried = new Set([...unpersisted].filter((id) => pinned.includes(id)));
+ if (added !== null) carried.add(added);
+ unpersisted = carried;
+}
+
+/** Read from the set, not the caller's list: a peer's storage event replaces this window's array
+ * wholesale, so by the next edit the list no longer carries them. */
+function ourPins(stored: readonly string[], present: readonly string[]): string[] {
+ if (storageWritable) return [];
+ return [...unpersisted].filter(
+ (id) => !stored.includes(id) && !present.includes(id),
+ );
+}
+
+function isOurs(id: string): boolean {
+ return !storageWritable && unpersisted.has(id);
+}
+
+/** An id the record carries is no longer ours to re-add, whoever wrote it, else a peer pinning then
+ * unpinning it resurrects the pin. From every read, not just the handler: an unchanged drag sees a
+ * peer's write before its event arrives. */
+function retirePersisted(stored: readonly string[]): void {
+ if (unpersisted.size === 0) return;
+ for (const id of stored) unpersisted.delete(id);
+}
+
+/** The record to apply an edit to. It is FRESH for other windows and stale only for our own
+ * unpersisted pins, so it is merged rather than dropped. */
+function persistedBase(fallback: readonly string[]): string[] {
+ const record = storedRecord();
+ if (record.kind !== "list") {
+ return record.kind === "absent" ? fallback.filter(isOurs) : [...fallback];
+ }
+ const stored = record.ids;
+ retirePersisted(stored);
+ // With nothing of ours unwritten the record wins outright: storageWritable describes OUR writes,
+ // and holding the rendered order past a peer's reorder would overwrite it on the next toggle.
+ if (storageWritable || unpersisted.size === 0) return stored;
+ return rebaseOnStored(fallback);
}
// movePinnedConnected runs on every dragenter: writing each would make a cancelled drag permanent.
-// Snapshot, move in memory, commit on drop. Mirrors pinned-models.ts.
let dragSnapshot: string[] | null = null;
-// Keep remote updates for cancellation without replacing the drag's live order.
-let dragExternalOrder: string[] | null = null;
-
function sameOrder(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((key, index) => key === b[index]);
}
-/** A dragged order over the stored membership: this window owns row ORDER, the record owns which
- * ids are pinned, since another window's storage event may still be in flight at the drop.
- * Its additions arrive at the front; null storage leaves the order alone. */
+/** A rendered order over the stored membership: this window owns row ORDER, the record owns which
+ * ids are pinned. Its additions arrive at the front. */
function rebaseOnStored(order: readonly string[]): string[] {
- const stored = storedPinned();
- if (stored === null) return [...order];
- const kept = order.filter((id) => stored.includes(id));
+ // A reset unpins what the record held, and only pins nothing else ever recorded survive it.
+ const record = storedRecord();
+ if (record.kind !== "list") {
+ return record.kind === "absent" ? order.filter(isOurs) : [...order];
+ }
+ const stored = record.ids;
+ retirePersisted(stored);
const added = stored.filter((id) => !order.includes(id));
- return [...added, ...kept];
+ // Survives if the record carries it or it is ours; a peer's removal is honoured either way.
+ const kept = order.filter((id) => stored.includes(id) || isOurs(id));
+ return [...ourPins(stored, [...added, ...kept]), ...added, ...kept];
}
interface PinnedConnectedModelsState {
pinned: string[];
- /** Pin or unpin one external model id. */
togglePinnedConnected: (modelId: string) => void;
- /**
- * Move `fromId` into `toId`'s slot. Both must already be pinned; anything else is a no-op.
- * Outside a drag session the new order persists immediately, inside one it is held until
- * `endPinnedConnectedDrag`.
- */
+ /** Move `fromId` into `toId`'s slot; anything not already pinned is a no-op. Inside a drag the
+ * new order is held until `endPinnedConnectedDrag`. */
movePinnedConnected: (fromId: string, toId: string) => void;
- /** Snapshot the current order so a cancelled drag can be undone. */
beginPinnedConnectedDrag: () => void;
- /** End a drag session. `commit` persists the reordered list; otherwise the snapshot is
- * restored. Idempotent, because drop is followed by dragend and only the first may decide. */
+ /** `commit` persists the reordered list, else the snapshot is restored. Idempotent: drop is
+ * followed by dragend and only the first may decide. */
endPinnedConnectedDrag: (commit: boolean) => void;
}
@@ -87,16 +148,16 @@ export const usePinnedConnectedModelsStore = create<PinnedConnectedModelsState>(
pinned: readPinned(),
togglePinnedConnected: (modelId) =>
set((state) => {
- // Applied to the stored list, not to this window's copy of it, since a write replaces the
- // whole list: another window's pin can be newer than the storage event this one has
- // processed, and rewriting our own array would drop it for good.
- const base = storedPinned() ?? state.pinned;
- // Newest pin first, as On Device does, so "Pin to top" literally lands on top of the
- // pinned group rather than under earlier pins.
- const next = base.includes(modelId)
- ? base.filter((id) => id !== modelId)
- : [modelId, ...base];
- writePinned(next);
+ // A write replaces the whole list, so the edit applies to the record: rewriting this
+ // window's array would drop a peer's pin newer than the event we have processed.
+ const base = persistedBase(state.pinned);
+ // Direction from the ROW, which draws state.pinned. A base that no longer holds the model
+ // turns an unpin into a pin and writes back what the user was removing.
+ const unpinning = state.pinned.includes(modelId);
+ const without = base.filter((id) => id !== modelId);
+ // Newest first, as On Device does, so "Pin to top" lands on top of the pinned group.
+ const next = unpinning ? without : [modelId, ...without];
+ writePinned(next, unpinning ? null : modelId);
return { pinned: next };
}),
movePinnedConnected: (fromId, toId) =>
@@ -112,28 +173,24 @@ export const usePinnedConnectedModelsStore = create<PinnedConnectedModelsState>(
beginPinnedConnectedDrag: () =>
set((state) => {
dragSnapshot = [...state.pinned];
- dragExternalOrder = null;
return state;
}),
endPinnedConnectedDrag: (commit) =>
set((state) => {
const snapshot = dragSnapshot;
- const external = dragExternalOrder;
dragSnapshot = null;
- dragExternalOrder = null;
if (snapshot === null) return state;
- // Read storage too, since its event may still be pending.
- const base = storedPinned() ?? external ?? snapshot;
+ // The PRE-DRAG rendered order: only it holds this window's unpersisted pins where they are
+ // drawn, and the record is read live below rather than stashed from an event.
+ const base = persistedBase(snapshot);
if (commit && !sameOrder(snapshot, state.pinned)) {
if (sameOrder(base, state.pinned)) return state;
- // The write replaces the whole list and nothing echoes it back to this window, so a
- // plain write of the dragged order would erase a pin another window added mid-drag
- // with no event left to restore it.
+ // Nothing echoes the write back here, so a plain write of the dragged order would erase
+ // a pin another window added mid-drag with no event left to restore it.
const next = rebaseOnStored(state.pinned);
writePinned(next);
return sameOrder(next, state.pinned) ? state : { pinned: next };
}
- // Cancellation and unchanged drags use the latest persisted order.
if (sameOrder(base, state.pinned)) return state;
return { pinned: base };
}),
@@ -143,12 +200,18 @@ export const usePinnedConnectedModelsStore = create<PinnedConnectedModelsState>(
if (typeof window !== "undefined") {
window.addEventListener("storage", (event) => {
if (event.key === KEY || event.key === null) {
+ // The RECORD retires a pin, never event.newValue: a peer pinning and unpinning B before our
+ // failed attempt and after it deliver the same payloads, and on that tie the pin the user
+ // just made is the one worth keeping.
const next = readPinned();
- if (dragSnapshot !== null) {
- dragExternalOrder = next;
- return;
- }
- usePinnedConnectedModelsStore.setState({ pinned: next });
+ retirePersisted(next);
+ // A drag owns the rendered order until it ends, and reads the record live then.
+ if (dragSnapshot !== null) return;
+ // The toggle's rule: merging unconditionally instead lost a peer's pure REORDER, which adds
+ // no ids and so changed nothing on a window with nothing unwritten.
+ usePinnedConnectedModelsStore.setState({
+ pinned: persistedBase(usePinnedConnectedModelsStore.getState().pinned),
+ });
}
});
}
diff --git a/studio/frontend/tests/connected-model-row-actions.test.ts b/studio/frontend/tests/connected-model-row-actions.test.ts
index 5764615f3dd..1720dd0f287 100644
--- a/studio/frontend/tests/connected-model-row-actions.test.ts
+++ b/studio/frontend/tests/connected-model-row-actions.test.ts
@@ -128,18 +128,11 @@ test("connected pins are a separate list from the On Device ones", () => {
assert.doesNotMatch(pickers, /togglePinned\(model\.id\)/);
assert.doesNotMatch(pickers, /pinKey\(model\.id\)/);
assert.match(pickers, /onToggle: \(\) => togglePinnedConnected\(model\.id\)/);
- // A toggle applies its one change to the STORED list. The write replaces the whole list, so two
- // windows pinning different models before the storage event lands would otherwise keep only the
- // second pin. Null, not [], when there is nothing to read: a toggle on an install whose writes
- // all fail has to keep the session's own pins rather than drop them.
- assert.match(
- connectedPins,
- /const base = storedPinned\(\) \?\? state\.pinned;/,
- );
- assert.match(
- connectedPins,
- /const raw = localStorage\.getItem\(KEY\);\s*if \(raw === null\) return null;/,
- );
+ // A toggle applies its one change to the STORED list, since the write replaces the whole list
+ // and two windows pinning different models before the storage event lands would otherwise keep
+ // only the second pin. Asserted as behaviour in pinned-connected-models-reorder.test.ts, which
+ // also covers the storage-unavailable case; a regex here pinned the expression and broke on a
+ // rename that moved nothing.
// A drag commit rebases too, for the same reason and one more: nothing echoes this window's own
// write back to it, so a pin another window added mid-drag would be erased with no event left
// to restore it. The dragged order is this window's; which ids are pinned is the record's.
@@ -147,10 +140,9 @@ test("connected pins are a separate list from the On Device ones", () => {
connectedPins,
/const next = rebaseOnStored\(state\.pinned\);\s*writePinned\(next\);/,
);
- assert.match(
- connectedPins,
- /const kept = order\.filter\(\(id\) => stored\.includes\(id\)\);\s*const added = stored\.filter\(\(id\) => !order\.includes\(id\)\);\s*return \[\.\.\.added, \.\.\.kept\];/,
- );
+ // The rebase itself is asserted as behaviour in pinned-connected-models-reorder.test.ts,
+ // including the failed-write case where the record is fresh for other windows and stale only
+ // for this one. A regex over the expression broke on a rename that moved nothing.
});
test("a pin moves the row out of its provider group", () => {
diff --git a/studio/frontend/tests/pinned-connected-models-reorder.test.ts b/studio/frontend/tests/pinned-connected-models-reorder.test.ts
index 53a26d549da..ec77cdd59b5 100644
--- a/studio/frontend/tests/pinned-connected-models-reorder.test.ts
+++ b/studio/frontend/tests/pinned-connected-models-reorder.test.ts
@@ -10,11 +10,18 @@ const { usePinnedConnectedModelsStore: pins } = await import(
"../src/features/model-picker/components/model-selector/pinned-connected-models.ts"
);
const KEY = "unsloth_pinned_connected_models";
-const [A, B, C, D] = ["a", "b", "c", "d"].map((id) => `external::connection::${id}`);
+const [A, B, C, D, E] = ["a", "b", "c", "d", "e"].map(
+ (id) => `external::connection::${id}`,
+);
+const RESET_PROBE = "external::connection::__reset__";
function reset(order = [A, B]) {
pins.getState().endPinnedConnectedDrag(false);
storage.clear();
+ // Two toggles that WRITE, to clear module-private failure state: resetting only storage and the
+ // zustand state left a leaked `unpersisted` making the next test pass without testing anything.
+ pins.getState().togglePinnedConnected(RESET_PROBE);
+ pins.getState().togglePinnedConnected(RESET_PROBE);
storage.set(KEY, JSON.stringify(order));
pins.setState({ pinned: order });
}
@@ -91,3 +98,404 @@ test("storage events outside a drag apply immediately", () => {
externalWrite([C, A]);
assert.deepEqual(pins.getState().pinned, [C, A]);
});
+
+test("a pin that could not be written survives the next toggle", () => {
+ // Quota exhausted with the key present: reads still return the OLDER list, so basing the next
+ // edit on the record dropped the pin that never persisted.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ assert.deepEqual(pins.getState().pinned, [B, A]);
+ pins.getState().togglePinnedConnected(C);
+ assert.deepEqual(pins.getState().pinned, [C, B, A]);
+ } finally {
+ storage.set = realSet;
+ }
+ // A write succeeding again hands the record back its authority.
+ pins.getState().togglePinnedConnected(D);
+ assert.deepEqual(storedOrder(), [D, C, B, A]);
+});
+
+test("a drag after a failed write keeps both sides' pins", () => {
+ // The record stays FRESH for other windows, so it is merged: ignoring it let the drop overwrite
+ // another window's additions once storage recovered.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B); // session-only, never persisted
+ assert.deepEqual(pins.getState().pinned, [B, A]);
+ } finally {
+ storage.set = realSet;
+ }
+ pins.getState().beginPinnedConnectedDrag();
+ pins.getState().movePinnedConnected(B, A); // reorder locally
+ externalWrite([D, A]); // another window pins D mid-drag
+ pins.getState().endPinnedConnectedDrag(true);
+ const after = pins.getState().pinned;
+ assert.ok(after.includes(B), `this session's unpersisted pin was lost: ${JSON.stringify(after)}`);
+ assert.ok(after.includes(D), `the other window's pin was overwritten: ${JSON.stringify(after)}`);
+});
+
+test("a peer removal survives a failed write", () => {
+ // Treating everything the record lacks as local re-added what a peer had just unpinned.
+ reset([A, C]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B); // ours, never persisted
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([A]); // a peer unpins C
+ pins.getState().togglePinnedConnected(D); // this one lands
+ const after = pins.getState().pinned;
+ assert.ok(!after.includes(C), `the peer's removal was undone: ${JSON.stringify(after)}`);
+ assert.ok(after.includes(B), `this session's unpersisted pin was lost: ${JSON.stringify(after)}`);
+ assert.deepEqual(storedOrder(), after);
+});
+
+test("undoing a failed pin does not resurrect it", () => {
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ assert.deepEqual(pins.getState().pinned, [B, A]);
+ pins.getState().togglePinnedConnected(B); // undo, still failing
+ assert.deepEqual(pins.getState().pinned, [A]);
+ } finally {
+ storage.set = realSet;
+ }
+ pins.getState().togglePinnedConnected(D);
+ const after = pins.getState().pinned;
+ assert.ok(!after.includes(B), `an undone pin came back: ${JSON.stringify(after)}`);
+});
+
+test("a failed pin stays on screen when a peer writes", () => {
+ // The rendered list decides which way the row toggles, so it must agree with the merge.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([C, A]);
+ assert.ok(
+ pins.getState().pinned.includes(B),
+ `the row would render unpinned while the merge still holds it: ${JSON.stringify(pins.getState().pinned)}`,
+ );
+});
+
+test("a peer persisting our failed pin hands it back to the record", () => {
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([B, A]); // a peer pins the same model, so the record carries it now
+ externalWrite([A]); // and later unpins it
+ assert.ok(
+ !pins.getState().pinned.includes(B),
+ `a peer's removal was undone by a stale unpersisted entry: ${JSON.stringify(pins.getState().pinned)}`,
+ );
+});
+
+test("a record read outside the storage handler retires a pin too", () => {
+ // An unchanged drag sees the peer's write before its event, so retiring only in the handler
+ // left the id classified as ours.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([B, A], false); // a peer persists the same model, event still pending
+ pins.getState().beginPinnedConnectedDrag();
+ pins.getState().endPinnedConnectedDrag(false); // unchanged drag: reads the record synchronously
+ externalWrite([A]); // the peer then unpins it
+ assert.ok(
+ !pins.getState().pinned.includes(B),
+ `a synchronously observed pin stayed classified as ours: ${JSON.stringify(pins.getState().pinned)}`,
+ );
+});
+
+test("a queued payload does not retire a pin the record never carried", () => {
+ // The mirror of the test above and INDISTINGUISHABLE from it: the same two payloads over the
+ // same final record. Retiring on the payload is right there and drops the user's own pin here,
+ // so only the record retires and this pin survives session-only.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ storage.set(KEY, JSON.stringify([B, A]));
+ storage.set(KEY, JSON.stringify([A]));
+ fireWindowEvent("storage", { key: KEY, newValue: JSON.stringify([B, A]) });
+ fireWindowEvent("storage", { key: KEY, newValue: JSON.stringify([A]) });
+ assert.ok(
+ pins.getState().pinned.includes(B),
+ `the pin the user just made was dropped: ${JSON.stringify(pins.getState().pinned)}`,
+ );
+ assert.deepEqual(storedOrder(), [A]);
+});
+
+test("a newer peer pin sits above an older unpersisted one", () => {
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([C, A]); // a peer pins C after B was attempted
+ assert.deepEqual(pins.getState().pinned, [C, B, A]);
+});
+
+test("a later successful toggle persists the rendered order", () => {
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([C, A]);
+ assert.deepEqual(pins.getState().pinned, [C, B, A]);
+ pins.getState().togglePinnedConnected(D); // this one lands
+ assert.deepEqual(pins.getState().pinned, [D, C, B, A]);
+ assert.deepEqual(storedOrder(), [D, C, B, A]);
+});
+
+test("a peer reorder wins once nothing of ours is unwritten", () => {
+ // `storageWritable` is about OUR writes, not the record: with nothing of ours left to carry,
+ // holding the rendered order let the next toggle that landed overwrite a peer's reorder.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([B, A]); // a peer persists the same pin, so nothing of ours is unwritten now
+ externalWrite([A, B], false); // and reorders, event not yet delivered
+ pins.getState().togglePinnedConnected(D); // this one lands
+ assert.deepEqual(storedOrder(), [D, A, B]);
+ assert.deepEqual(pins.getState().pinned, [D, A, B]);
+});
+
+test("interleaved local and peer pins keep one newest-first order", () => {
+ // Two blocks is an order neither window produced: it lifts every pin we could not write above
+ // every peer pin on screen, and the next write that lands freezes that.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ const failing = () => {
+ throw new Error("QuotaExceededError");
+ };
+ storage.set = failing;
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalWrite([C, A]);
+ assert.deepEqual(pins.getState().pinned, [C, B, A]);
+ storage.set = failing;
+ try {
+ pins.getState().togglePinnedConnected(D);
+ } finally {
+ storage.set = realSet;
+ }
+ assert.deepEqual(pins.getState().pinned, [D, C, B, A]);
+ externalWrite([E, C, A]);
+ assert.deepEqual(pins.getState().pinned, [E, D, C, B, A]);
+});
+
+function externalRemove() {
+ storage.delete(KEY);
+ assert.equal(fireWindowEvent("storage", { key: KEY, newValue: null }), 1);
+}
+
+test("a peer clearing the record unpins everything it held", () => {
+ reset([A, B]);
+ externalRemove();
+ assert.deepEqual(pins.getState().pinned, []);
+ pins.getState().togglePinnedConnected(D);
+ // The pins the peer cleared must not come back with the next write that lands.
+ assert.deepEqual(storedOrder(), [D]);
+});
+
+test("a peer clearing the record keeps a pin that was never written", () => {
+ // Only this window ever held it, so a reset of the record says nothing about it.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ externalRemove();
+ assert.deepEqual(pins.getState().pinned, [B]);
+});
+
+test("an unchanged drag keeps a peer pin above an older failed one", () => {
+ // Ending on the list the event carried re-added the unpersisted pin at the front, above a
+ // newer peer pin.
+ reset([A]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ } finally {
+ storage.set = realSet;
+ }
+ pins.getState().beginPinnedConnectedDrag();
+ externalWrite([C, A]); // a peer pins C mid-drag
+ pins.getState().endPinnedConnectedDrag(false);
+ assert.deepEqual(pins.getState().pinned, [C, B, A]);
+});
+
+test("a peer reordering the same pins reorders this window too", () => {
+ // Nothing added or removed, so a merge carrying only our unwritten pins left the old order.
+ reset([A, B]);
+ externalWrite([B, A]);
+ assert.deepEqual(pins.getState().pinned, [B, A]);
+});
+
+test("a record this window cannot read changes nothing on screen", () => {
+ // Revoked access reads like a deleted key and means the opposite: as a reset it unpinned
+ // everything, on a window whose writes still land.
+ reset([A]);
+ const realGet = storage.get.bind(storage);
+ storage.get = () => {
+ throw new Error("SecurityError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(B);
+ assert.deepEqual(pins.getState().pinned, [B, A]);
+ } finally {
+ storage.get = realGet;
+ }
+ assert.deepEqual(storedOrder(), [B, A]);
+});
+
+test("an event arriving while the record is unreadable leaves the list alone", () => {
+ reset([A, B]);
+ const realGet = storage.get.bind(storage);
+ storage.get = () => {
+ throw new Error("SecurityError");
+ };
+ try {
+ externalWrite([C]);
+ assert.deepEqual(pins.getState().pinned, [A, B]);
+ } finally {
+ storage.get = realGet;
+ }
+});
+
+test("an unpin stays an unpin when a peer cleared the record first", () => {
+ // The row draws itself pinned, so the click means unpin; the emptied base wrote it back in.
+ reset([A, B]);
+ storage.delete(KEY); // a peer clears, its event not yet delivered
+ pins.getState().togglePinnedConnected(A);
+ assert.ok(
+ !pins.getState().pinned.includes(A),
+ `an unpin was turned into a pin: ${JSON.stringify(pins.getState().pinned)}`,
+ );
+ assert.deepEqual(storedOrder(), []);
+});
+
+test("an unpin stays an unpin when a peer unpinned it first", () => {
+ // The quiet version of the same thing: one model gone from the record rather than all of them.
+ reset([A, B]);
+ storage.set(KEY, JSON.stringify([B])); // a peer unpins A, its event not yet delivered
+ pins.getState().togglePinnedConnected(A);
+ assert.deepEqual(storedOrder(), [B]);
+ assert.deepEqual(pins.getState().pinned, [B]);
+});
+
+test("a record we cannot read does not make older pins ours", () => {
+ // Blind both ways, the only id known unpublished is the one just added: claiming the screen
+ // made stored pins ours, so a peer unpinning one was undone by the next write that landed.
+ reset([A, B]);
+ const realSet = storage.set.bind(storage);
+ const realGet = storage.get.bind(storage);
+ storage.set = () => {
+ throw new Error("QuotaExceededError");
+ };
+ storage.get = () => {
+ throw new Error("SecurityError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(C);
+ assert.deepEqual(pins.getState().pinned, [C, A, B]);
+ } finally {
+ storage.set = realSet;
+ storage.get = realGet;
+ }
+ externalWrite([A]); // a peer unpinned B while this window was blind
+ pins.getState().togglePinnedConnected(D); // this one lands
+ assert.deepEqual(storedOrder(), [D, C, A]);
+});
+
+test("a peer removing a pin as the write fails does not make it ours", () => {
+ // The peer's write lands between the read this edit was built on and the setItem that failed,
+ // so reading ownership off the difference claimed B and undid the removal.
+ reset([A, B]);
+ const realSet = storage.set.bind(storage);
+ storage.set = () => {
+ realSet(KEY, JSON.stringify([A])); // the peer unpins B, and then our write throws
+ throw new Error("QuotaExceededError");
+ };
+ try {
+ pins.getState().togglePinnedConnected(C);
+ } finally {
+ storage.set = realSet;
+ }
+ assert.equal(fireWindowEvent("storage", { key: KEY }), 1);
+ assert.deepEqual(pins.getState().pinned, [C, A]);
+ pins.getState().togglePinnedConnected(D); // this one lands
+ assert.deepEqual(storedOrder(), [D, C, A]);
+});