Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Apply each saved mark to what other windows saved

Fei2411a0448ef883e8
diff --git a/ds-bot/client.js b/ds-bot/client.js
index 9b5e894a..279c2c6e 100644
--- a/ds-bot/client.js
+++ b/ds-bot/client.js
@@ -12695,6 +12695,60 @@ ${marked}
var readPageScript = (limits = READ_LIMITS) => `(${readPage})(${JSON.stringify(limits)})`;
var READ_PAGE_SCRIPT = readPageScript();
+// src/client/shared-map.js
+function sharedMap(key, storage = globalThis.localStorage) {
+ const read = (fallback = {}) => {
+ if (!storage) return fallback;
+ try {
+ const value = JSON.parse(storage.getItem(key) ?? "{}");
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
+ } catch {
+ return fallback;
+ }
+ };
+ const update = (change, fallback = {}) => {
+ const base = read(fallback);
+ const next = change(base);
+ if (next === base) return next;
+ try {
+ storage?.setItem(key, JSON.stringify(next));
+ } catch {
+ }
+ return next;
+ };
+ return { key, read, update };
+}
+function setEntry(map, id, value) {
+ if (value === void 0) {
+ if (!Object.hasOwn(map, id)) return map;
+ const { [id]: _, ...rest } = map;
+ return rest;
+ }
+ return { ...map, [id]: value };
+}
+function toggleReaction(reactions, key, index, emoji) {
+ const entry = { ...reactions[key] };
+ const list = entry[index] ?? [];
+ entry[index] = list.includes(emoji) ? list.filter((item) => item !== emoji) : [...list, emoji];
+ if (entry[index].length === 0) delete entry[index];
+ const next = { ...reactions };
+ if (Object.keys(entry).length) next[key] = entry;
+ else delete next[key];
+ return next;
+}
+function setUnread(unread, id, value) {
+ if (Boolean(unread[id]) === value) return unread;
+ const next = { ...unread };
+ if (value) next[id] = true;
+ else delete next[id];
+ return next;
+}
+function noteLeft(seen, ids, now) {
+ const next = { ...seen };
+ for (const id of ids) next[id] = Math.max(Number(next[id]) || 0, now);
+ return next;
+}
+
// src/client/bot-browsers.js
var STORE_KEY = STORAGE.browsers;
var MAX_LIVE = 6;
@@ -12728,12 +12782,8 @@ function createBotBrowsers({ bridge, createSource: createSource2, storage = glob
const owner = /* @__PURE__ */ new Map();
const tabs = createSource2({});
const pages = createSource2({});
- let saved = {};
- try {
- saved = JSON.parse(storage?.getItem(STORE_KEY) ?? "{}") ?? {};
- } catch {
- saved = {};
- }
+ const store = sharedMap(STORE_KEY, storage);
+ let saved = store.read();
let layer;
let shown = null;
let rect = null;
@@ -12746,29 +12796,16 @@ function createBotBrowsers({ bridge, createSource: createSource2, storage = glob
const botId = owner.get(tabId);
return { ...state, [tabId]: { ...EMPTY, ...savedTab(botId, tabId), ...state[tabId], ...patch } };
});
- const writeSaved = () => {
- try {
- storage?.setItem(STORE_KEY, JSON.stringify(saved));
- } catch {
- }
+ const save = (botId, entry) => {
+ saved = store.update((stored) => setEntry(stored, botId, entry), saved);
};
const persist = (botId) => {
const state = tabs.getSnapshot()[botId];
- if (state === void 0) {
- if (saved[botId] === void 0) return;
- const { [botId]: _, ...rest } = saved;
- saved = rest;
- } else {
- const snapshot = pages.getSnapshot();
- saved = {
- ...saved,
- [botId]: {
- tabs: state.ids.map((id) => ({ id, url: snapshot[id]?.url ?? "", title: snapshot[id]?.title ?? "" })),
- active: state.active
- }
- };
- }
- writeSaved();
+ const snapshot = pages.getSnapshot();
+ save(botId, state && {
+ tabs: state.ids.map((id) => ({ id, url: snapshot[id]?.url ?? "", title: snapshot[id]?.title ?? "" })),
+ active: state.active
+ });
};
const ensureTabs = (botId) => {
if (tabs.getSnapshot()[botId] !== void 0) return;
@@ -13024,11 +13061,7 @@ function createBotBrowsers({ bridge, createSource: createSource2, storage = glob
const { [botId]: _, ...rest } = snapshot;
return rest;
});
- if (saved[botId] !== void 0) {
- const { [botId]: _, ...rest } = saved;
- saved = rest;
- writeSaved();
- }
+ save(botId, void 0);
}
return {
tabs,
@@ -13353,28 +13386,11 @@ function apply(ctx) {
ctx.effect(() => installLocale(ctx.get("locale")), "ds-bot: interface copy");
const roster = createSource(EMPTY_ROSTER);
migrateStorage();
- const UNREAD_KEY = STORAGE.unread;
- let savedUnread = {};
- try {
- savedUnread = JSON.parse(localStorage.getItem(UNREAD_KEY) ?? "{}") ?? {};
- } catch {
- savedUnread = {};
- }
- const REACTIONS_KEY = STORAGE.reactions;
- let savedReactions = {};
- try {
- savedReactions = JSON.parse(localStorage.getItem(REACTIONS_KEY) ?? "{}") ?? {};
- } catch {
- savedReactions = {};
- }
- const SEEN_KEY = STORAGE.seen;
- let seenAt = {};
- try {
- seenAt = JSON.parse(localStorage.getItem(SEEN_KEY) ?? "{}") ?? {};
- } catch {
- seenAt = {};
- }
- const ui2 = createSource({ details: null, view: "details", renaming: false, tab: null, newChat: null, exchange: null, menu: null, voice: null, palette: null, quote: null, settings: null, memory: null, toast: null, signIn: null, renameAgent: null, unread: savedUnread, reactions: savedReactions, visits: {} });
+ const unreadStore = sharedMap(STORAGE.unread);
+ const reactionStore = sharedMap(STORAGE.reactions);
+ const seenStore = sharedMap(STORAGE.seen);
+ let seenAt = seenStore.read();
+ const ui2 = createSource({ details: null, view: "details", renaming: false, tab: null, newChat: null, exchange: null, menu: null, voice: null, palette: null, quote: null, settings: null, memory: null, toast: null, signIn: null, renameAgent: null, unread: unreadStore.read(), reactions: reactionStore.read(), visits: {} });
const surface = createSource({ mode: readMode(), plain: false });
let agentSessionCache = /* @__PURE__ */ new Set();
try {
@@ -13395,18 +13411,23 @@ function apply(ctx) {
const dropPanels = () => ui2.set((state) => state.details || state.renaming ? { ...state, details: null, view: "details", renaming: false, tab: null } : state);
const seenKey = (id) => roster.getSnapshot().byId?.[id]?.id ?? id;
const leaveVisits = (ids) => {
- const now = Date.now();
- for (const id of ids) seenAt[seenKey(id)] = now;
- try {
- localStorage.setItem(SEEN_KEY, JSON.stringify(seenAt));
- } catch {
- }
+ seenAt = seenStore.update((seen) => noteLeft(seen, ids.map(seenKey), Date.now()), seenAt);
};
ctx.effect(() => {
const onPageHide = () => leaveVisits(Object.keys(ui2.getSnapshot().visits ?? {}));
window.addEventListener("pagehide", onPageHide);
return () => window.removeEventListener("pagehide", onPageHide);
}, "ds-bot: remember visits on page hide");
+ ctx.effect(() => {
+ const onStorage = (event) => {
+ if (event.storageArea !== localStorage) return;
+ if (event.key === null || event.key === unreadStore.key) ui2.set((state) => ({ ...state, unread: unreadStore.read(state.unread) }));
+ if (event.key === null || event.key === reactionStore.key) ui2.set((state) => ({ ...state, reactions: reactionStore.read(state.reactions) }));
+ if (event.key === null || event.key === seenStore.key) seenAt = seenStore.read(seenAt);
+ };
+ window.addEventListener("storage", onStorage);
+ return () => window.removeEventListener("storage", onStorage);
+ }, "ds-bot: follow other windows");
const activity = createSource({});
const work = createSource({ bots: {}, approvals: [] });
let workKey = "";
@@ -13433,17 +13454,10 @@ function apply(ctx) {
} catch {
savedPrefs = {};
}
- const setUnread = (id, value) => ui2.set((state) => {
- if (Boolean(state.unread[id]) === value) return state;
- const unread = { ...state.unread };
- if (value) unread[id] = true;
- else delete unread[id];
- try {
- localStorage.setItem(UNREAD_KEY, JSON.stringify(unread));
- } catch {
- }
- return { ...state, unread };
- });
+ const writeUnread = (id, value) => {
+ const unread = unreadStore.update((marks) => setUnread(marks, id, value), ui2.getSnapshot().unread);
+ ui2.set((state) => JSON.stringify(state.unread) === JSON.stringify(unread) ? state : { ...state, unread });
+ };
const refreshed = /* @__PURE__ */ new Set();
let pulls = 0;
let applied = 0;
@@ -13851,7 +13865,7 @@ function apply(ctx) {
});
}
},
- markUnread: (id) => setUnread(id, true),
+ markUnread: (id) => writeUnread(id, true),
beginVisit: (id) => {
const made = roster.getSnapshot().byId[id] ?? roster.getSnapshot().roomsById[id];
const seen = seenAt[seenKey(id)] ?? (made?.createdBy && Number.isFinite(made.createdAt) ? made.createdAt : null);
@@ -13866,23 +13880,13 @@ function apply(ctx) {
return { ...state, visits };
});
},
- toggleReaction: (key, index, emoji) => ui2.set((state) => {
- const entry = { ...state.reactions?.[key] ?? {} };
- const list = entry[index] ?? [];
- entry[index] = list.includes(emoji) ? list.filter((item) => item !== emoji) : [...list, emoji];
- if (entry[index].length === 0) delete entry[index];
- const reactions = { ...state.reactions };
- if (Object.keys(entry).length) reactions[key] = entry;
- else delete reactions[key];
- try {
- localStorage.setItem(REACTIONS_KEY, JSON.stringify(reactions));
- } catch {
- }
- return { ...state, reactions };
- }),
+ toggleReaction: (key, index, emoji) => {
+ const reactions = reactionStore.update((saved) => toggleReaction(saved, key, index, emoji), ui2.getSnapshot().reactions);
+ ui2.set((state) => ({ ...state, reactions }));
+ },
quote: (sessionId, text) => ui2.set((state) => ({ ...state, quote: { sessionId, text, token: Date.now() } })),
clearQuote: (token) => ui2.set((state) => state.quote?.token === token ? { ...state, quote: null } : state),
- clearUnread: (id) => setUnread(id, false),
+ clearUnread: (id) => writeUnread(id, false),
setFlags: (id, flags) => after(call("set-flags", { id, ...flags })),
deleteRoom: (id) => after(call("delete-room", { id })),
openMenu: (menu) => {
diff --git a/ds-bot/src/client/bot-browsers.js b/ds-bot/src/client/bot-browsers.js
index e23b8648..e18b003b 100644
--- a/ds-bot/src/client/bot-browsers.js
+++ b/ds-bot/src/client/bot-browsers.js
@@ -8,6 +8,7 @@
// stays the same) but hidden.
import { READ_PAGE_SCRIPT } from './read-page.js'
+import { setEntry, sharedMap } from './shared-map.js'
import { STORAGE } from './storage.js'
export { READ_PAGE_SCRIPT }
@@ -67,9 +68,10 @@ export function createBotBrowsers({ bridge, createSource, storage = globalThis.l
const tabs = createSource({})
// Per tab: { url, title, favicon, loading, canGoBack, canGoForward, error, live, readAt?, excerpt }
const pages = createSource({})
- // Per Bot, what survives a reload: { tabs: [{id,url,title}], active }.
- let saved = {}
- try { saved = JSON.parse(storage?.getItem(STORE_KEY) ?? '{}') ?? {} } catch { saved = {} }
+ // Per Bot, what survives a reload: { tabs: [{id,url,title}], active }. Another window
+ // saves its own Bots' tabs into the same object.
+ const store = sharedMap(STORE_KEY, storage)
+ let saved = store.read()
let layer
let shown = null
// The last panel rectangle sizes every guest, shown or not; `visible` says whether the
@@ -85,26 +87,14 @@ export function createBotBrowsers({ bridge, createSource, storage = globalThis.l
const botId = owner.get(tabId)
return { ...state, [tabId]: { ...EMPTY, ...savedTab(botId, tabId), ...state[tabId], ...patch } }
})
- const writeSaved = () => {
- try { storage?.setItem(STORE_KEY, JSON.stringify(saved)) } catch { /* storage unavailable */ }
- }
+ const save = (botId, entry) => { saved = store.update(stored => setEntry(stored, botId, entry), saved) }
const persist = (botId) => {
const state = tabs.getSnapshot()[botId]
- if (state === undefined) {
- if (saved[botId] === undefined) return
- const { [botId]: _, ...rest } = saved
- saved = rest
- } else {
- const snapshot = pages.getSnapshot()
- saved = {
- ...saved,
- [botId]: {
- tabs: state.ids.map(id => ({ id, url: snapshot[id]?.url ?? '', title: snapshot[id]?.title ?? '' })),
- active: state.active,
- },
- }
- }
- writeSaved()
+ const snapshot = pages.getSnapshot()
+ save(botId, state && {
+ tabs: state.ids.map(id => ({ id, url: snapshot[id]?.url ?? '', title: snapshot[id]?.title ?? '' })),
+ active: state.active,
+ })
}
// Saved tabs come back as placeholders: they show in the strip and open their
@@ -390,11 +380,7 @@ export function createBotBrowsers({ bridge, createSource, storage = globalThis.l
const { [botId]: _, ...rest } = snapshot
return rest
})
- if (saved[botId] !== undefined) {
- const { [botId]: _, ...rest } = saved
- saved = rest
- writeSaved()
- }
+ save(botId, undefined)
}
return {
diff --git a/ds-bot/src/client/index.js b/ds-bot/src/client/index.js
index 203345b2..5ae49f6a 100644
--- a/ds-bot/src/client/index.js
+++ b/ds-bot/src/client/index.js
@@ -25,6 +25,7 @@ import { FOLDER_CSS } from './folder-menu.js'
import { USAGE_CSS } from './usage-page.js'
import { SCHEDULE_CSS } from './schedules.js'
import { STORAGE, migrateStorage } from './storage.js'
+import { noteLeft, setUnread, sharedMap, toggleReaction } from './shared-map.js'
import { groupsFor, readMode, surfaceGroups, writeMode } from './surface.js'
import { installLocale, language } from './i18n.js'
import { noteClientError, quietly } from './diagnostics.js'
@@ -40,19 +41,14 @@ export function apply(ctx) {
ctx.effect(() => installLocale(ctx.get('locale')), 'ds-bot: interface copy')
const roster = createSource(EMPTY_ROSTER)
migrateStorage()
- const UNREAD_KEY = STORAGE.unread
- let savedUnread = {}
- try { savedUnread = JSON.parse(localStorage.getItem(UNREAD_KEY) ?? '{}') ?? {} } catch { savedUnread = {} }
- const REACTIONS_KEY = STORAGE.reactions
- let savedReactions = {}
- try { savedReactions = JSON.parse(localStorage.getItem(REACTIONS_KEY) ?? '{}') ?? {} } catch { savedReactions = {} }
+ const unreadStore = sharedMap(STORAGE.unread)
+ const reactionStore = sharedMap(STORAGE.reactions)
// When each conversation was last left; a visit compares new turns against it.
- const SEEN_KEY = STORAGE.seen
- let seenAt = {}
- try { seenAt = JSON.parse(localStorage.getItem(SEEN_KEY) ?? '{}') ?? {} } catch { seenAt = {} }
+ const seenStore = sharedMap(STORAGE.seen)
+ let seenAt = seenStore.read()
// `details` is the panel's subject (a Session id); `view` picks details or the
// subject Bot's browser inside it.
- const ui = createSource({ details: null, view: 'details', renaming: false, tab: null, newChat: null, exchange: null, menu: null, voice: null, palette: null, quote: null, settings: null, memory: null, toast: null, signIn: null, renameAgent: null, unread: savedUnread, reactions: savedReactions, visits: {} })
+ const ui = createSource({ details: null, view: 'details', renaming: false, tab: null, newChat: null, exchange: null, menu: null, voice: null, palette: null, quote: null, settings: null, memory: null, toast: null, signIn: null, renameAgent: null, unread: unreadStore.read(), reactions: reactionStore.read(), visits: {} })
// Bot mode paints the whole team surface; Agent mode withdraws every slot and
// style so the shell's own interface returns. `plain` stays false until a Bot-mode
// view hosts a plain session, which drops only the conversation replacements.
@@ -80,15 +76,25 @@ export function apply(ctx) {
// A Bot's chat spans several parts, so when it was last left is kept per Bot.
const seenKey = id => roster.getSnapshot().byId?.[id]?.id ?? id
const leaveVisits = (ids) => {
- const now = Date.now()
- for (const id of ids) seenAt[seenKey(id)] = now
- try { localStorage.setItem(SEEN_KEY, JSON.stringify(seenAt)) } catch { /* storage unavailable */ }
+ seenAt = seenStore.update(seen => noteLeft(seen, ids.map(seenKey), Date.now()), seenAt)
}
ctx.effect(() => {
const onPageHide = () => leaveVisits(Object.keys(ui.getSnapshot().visits ?? {}))
window.addEventListener('pagehide', onPageHide)
return () => window.removeEventListener('pagehide', onPageHide)
}, 'ds-bot: remember visits on page hide')
+ // Unread marks, reactions and visits are shared by every window; one saved elsewhere
+ // shows here at once. A `null` key is a cleared storage.
+ ctx.effect(() => {
+ const onStorage = (event) => {
+ if (event.storageArea !== localStorage) return
+ if (event.key === null || event.key === unreadStore.key) ui.set(state => ({ ...state, unread: unreadStore.read(state.unread) }))
+ if (event.key === null || event.key === reactionStore.key) ui.set(state => ({ ...state, reactions: reactionStore.read(state.reactions) }))
+ if (event.key === null || event.key === seenStore.key) seenAt = seenStore.read(seenAt)
+ }
+ window.addEventListener('storage', onStorage)
+ return () => window.removeEventListener('storage', onStorage)
+ }, 'ds-bot: follow other windows')
const activity = createSource({})
// Per Bot, the turn it runs and its tool; and the approvals waiting for the user.
const work = createSource({ bots: {}, approvals: [] })
@@ -117,14 +123,10 @@ export function apply(ctx) {
const PREFS_KEY = STORAGE.prefs
let savedPrefs = {}
try { savedPrefs = JSON.parse(localStorage.getItem(PREFS_KEY) ?? '{}') ?? {} } catch { savedPrefs = {} }
- const setUnread = (id, value) => ui.set((state) => {
- if (Boolean(state.unread[id]) === value) return state
- const unread = { ...state.unread }
- if (value) unread[id] = true
- else delete unread[id]
- try { localStorage.setItem(UNREAD_KEY, JSON.stringify(unread)) } catch { /* storage unavailable */ }
- return { ...state, unread }
- })
+ const writeUnread = (id, value) => {
+ const unread = unreadStore.update(marks => setUnread(marks, id, value), ui.getSnapshot().unread)
+ ui.set(state => (JSON.stringify(state.unread) === JSON.stringify(unread) ? state : { ...state, unread }))
+ }
const refreshed = new Set()
// Pulls can overlap (the poll and a navigation); an older answer never wins.
let pulls = 0
@@ -480,7 +482,7 @@ export function apply(ctx) {
})
}
},
- markUnread: id => setUnread(id, true),
+ markUnread: id => writeUnread(id, true),
beginVisit: (id) => {
// A conversation a Bot started, never opened here, is unread from its start.
const made = roster.getSnapshot().byId[id] ?? roster.getSnapshot().roomsById[id]
@@ -496,20 +498,13 @@ export function apply(ctx) {
return { ...state, visits }
})
},
- toggleReaction: (key, index, emoji) => ui.set((state) => {
- const entry = { ...(state.reactions?.[key] ?? {}) }
- const list = entry[index] ?? []
- entry[index] = list.includes(emoji) ? list.filter(item => item !== emoji) : [...list, emoji]
- if (entry[index].length === 0) delete entry[index]
- const reactions = { ...state.reactions }
- if (Object.keys(entry).length) reactions[key] = entry
- else delete reactions[key]
- try { localStorage.setItem(REACTIONS_KEY, JSON.stringify(reactions)) } catch { /* storage unavailable */ }
- return { ...state, reactions }
- }),
+ toggleReaction: (key, index, emoji) => {
+ const reactions = reactionStore.update(saved => toggleReaction(saved, key, index, emoji), ui.getSnapshot().reactions)
+ ui.set(state => ({ ...state, reactions }))
+ },
quote: (sessionId, text) => ui.set(state => ({ ...state, quote: { sessionId, text, token: Date.now() } })),
clearQuote: token => ui.set(state => (state.quote?.token === token ? { ...state, quote: null } : state)),
- clearUnread: id => setUnread(id, false),
+ clearUnread: id => writeUnread(id, false),
setFlags: (id, flags) => after(call('set-flags', { id, ...flags })),
deleteRoom: id => after(call('delete-room', { id })),
openMenu: (menu) => { ui.set(state => ({ ...state, menu })) },
diff --git a/ds-bot/src/client/shared-map.js b/ds-bot/src/client/shared-map.js
new file mode 100644
index 00000000..54a613db
--- /dev/null
+++ b/ds-bot/src/client/shared-map.js
@@ -0,0 +1,65 @@
+// A JSON object in browser storage that every open window of DSH edits, one entry at a
+// time. Each change applies to what is stored at that moment, never to the window's own
+// copy, so a window does not undo what another window saved after it loaded. Other
+// windows learn of a change from the `storage` event and read the object again.
+
+export function sharedMap(key, storage = globalThis.localStorage) {
+ // `fallback` stands in when storage cannot be read, so the window keeps its own copy.
+ const read = (fallback = {}) => {
+ if (!storage) return fallback
+ try {
+ const value = JSON.parse(storage.getItem(key) ?? '{}')
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
+ } catch {
+ return fallback
+ }
+ }
+ // A change that returns what it was given changes nothing, and nothing is written.
+ const update = (change, fallback = {}) => {
+ const base = read(fallback)
+ const next = change(base)
+ if (next === base) return next
+ try { storage?.setItem(key, JSON.stringify(next)) } catch { /* storage unavailable */ }
+ return next
+ }
+ return { key, read, update }
+}
+
+// Sets one entry, or drops it for `undefined`; an entry already so leaves the map as it is.
+export function setEntry(map, id, value) {
+ if (value === undefined) {
+ if (!Object.hasOwn(map, id)) return map
+ const { [id]: _, ...rest } = map
+ return rest
+ }
+ return { ...map, [id]: value }
+}
+
+// reactions: { [message key]: { [bubble index]: [emoji…] } }
+export function toggleReaction(reactions, key, index, emoji) {
+ const entry = { ...reactions[key] }
+ const list = entry[index] ?? []
+ entry[index] = list.includes(emoji) ? list.filter(item => item !== emoji) : [...list, emoji]
+ if (entry[index].length === 0) delete entry[index]
+ const next = { ...reactions }
+ if (Object.keys(entry).length) next[key] = entry
+ else delete next[key]
+ return next
+}
+
+// unread: { [Bot or group id]: true }
+export function setUnread(unread, id, value) {
+ if (Boolean(unread[id]) === value) return unread
+ const next = { ...unread }
+ if (value) next[id] = true
+ else delete next[id]
+ return next
+}
+
+// seen: { [Bot or group id]: when it was last left }. A time never goes back, so a window
+// that closes late with an old copy cannot make seen messages new again.
+export function noteLeft(seen, ids, now) {
+ const next = { ...seen }
+ for (const id of ids) next[id] = Math.max(Number(next[id]) || 0, now)
+ return next
+}
diff --git a/ds-bot/test/shared-map.test.js b/ds-bot/test/shared-map.test.js
new file mode 100644
index 00000000..12d84145
--- /dev/null
+++ b/ds-bot/test/shared-map.test.js
@@ -0,0 +1,87 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { createBotBrowsers } from '../src/client/bot-browsers.js'
+import { noteLeft, setUnread, sharedMap, toggleReaction } from '../src/client/shared-map.js'
+import { STORAGE } from '../src/client/storage.js'
+
+// One browser storage that two windows (tabs of DSH Web, or Desktop windows) share.
+function sharedStorage() {
+ const items = new Map()
+ return {
+ items,
+ getItem: key => items.get(key) ?? null,
+ setItem: (key, value) => { items.set(key, String(value)) },
+ removeItem: (key) => { items.delete(key) },
+ }
+}
+// A window as index.js keeps one: a copy read at load, updated by its own changes.
+function windowOn(storage, key) {
+ const store = sharedMap(key, storage)
+ let copy = store.read()
+ return { change: (edit) => { copy = store.update(edit, copy); return copy }, get copy() { return copy } }
+}
+
+// #215: each window wrote its whole copy back, so the window that wrote last erased what
+// the others had saved since it loaded.
+test('reactions made in two windows are both kept, and one taken back leaves the other', () => {
+ const storage = sharedStorage()
+ const a = windowOn(storage, STORAGE.reactions)
+ const b = windowOn(storage, STORAGE.reactions)
+ a.change(saved => toggleReaction(saved, 'writer:3:step3', 0, '👍'))
+ b.change(saved => toggleReaction(saved, 'writer:4:step4', 1, '❤️'))
+ assert.deepEqual(JSON.parse(storage.getItem(STORAGE.reactions)), { 'writer:3:step3': { 0: ['👍'] }, 'writer:4:step4': { 1: ['❤️'] } })
+ // A window learns of the other's change through the storage event and reads again.
+ assert.deepEqual(sharedMap(STORAGE.reactions, storage).read(a.copy), JSON.parse(storage.getItem(STORAGE.reactions)))
+ a.change(saved => toggleReaction(saved, 'writer:3:step3', 0, '👍'))
+ assert.deepEqual(JSON.parse(storage.getItem(STORAGE.reactions)), { 'writer:4:step4': { 1: ['❤️'] } })
+})
+
+test('unread marks set in two windows are both kept', () => {
+ const storage = sharedStorage()
+ const a = windowOn(storage, STORAGE.unread)
+ const b = windowOn(storage, STORAGE.unread)
+ a.change(marks => setUnread(marks, 'viewer', true))
+ b.change(marks => setUnread(marks, 'umber', true))
+ assert.deepEqual(JSON.parse(storage.getItem(STORAGE.unread)), { viewer: true, umber: true })
+ b.change(marks => setUnread(marks, 'viewer', false))
+ assert.deepEqual(JSON.parse(storage.getItem(STORAGE.unread)), { umber: true })
+})
+
+test('a window that closes with an old copy does not move a visit time back', () => {
+ const storage = sharedStorage()
+ const a = windowOn(storage, STORAGE.seen)
+ a.change(seen => noteLeft(seen, ['writer', 'coder'], 100))
+ const b = windowOn(storage, STORAGE.seen)
+ b.change(seen => noteLeft(seen, ['writer'], 300))
+ // A closes later, but its clock read is older than B's.
+ a.change(seen => noteLeft(seen, ['writer', 'coder'], 250))
+ assert.deepEqual(JSON.parse(storage.getItem(STORAGE.seen)), { writer: 300, coder: 250 })
+})
+
+test('storage that cannot be read leaves the window its own copy, and nothing unchanged is written', () => {
+ const storage = sharedStorage()
+ const store = sharedMap(STORAGE.unread, { ...storage, getItem: () => { throw new Error('blocked') }, setItem: () => { throw new Error('blocked') } })
+ assert.deepEqual(store.update(marks => setUnread(marks, 'umber', true), { viewer: true }), { viewer: true, umber: true })
+ assert.deepEqual(sharedMap(STORAGE.unread, undefined).read({ viewer: true }), { viewer: true })
+ storage.setItem(STORAGE.unread, 'not json')
+ assert.deepEqual(sharedMap(STORAGE.unread, storage).read({ kept: true }), { kept: true })
+
+ let writes = 0
+ const counted = sharedMap(STORAGE.unread, { ...storage, getItem: () => '{"umber":true}', setItem: () => { writes += 1 } })
+ counted.update(marks => setUnread(marks, 'umber', true))
+ assert.equal(writes, 0)
+})
+
+test('Bot browser tabs saved by two windows are both kept', () => {
+ const storage = sharedStorage()
+ const createSource = (initial) => {
+ let value = initial
+ return { getSnapshot: () => value, set: (next) => { value = typeof next === 'function' ? next(value) : next }, subscribe: () => () => {} }
+ }
+ const open = () => createBotBrowsers({ bridge: {}, createSource, storage, document: { body: { append() {} }, createElement: () => ({ style: {}, append() {}, remove() {} }) } })
+ const first = open()
+ const second = open()
+ first.openTab('writer')
+ second.openTab('coder')
+ assert.deepEqual(Object.keys(JSON.parse(storage.getItem(STORAGE.browsers))).sort(), ['coder', 'writer'])
+})