Skip to content

The agent that grows with you

fix(desktop): sync bot room previews through profiles

TheTom64d393cb7ef1
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index 51bdcb39697..867913881ad 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -307,6 +307,301 @@ function groupActivityTone(kind) {
return 'text-(--ui-text-tertiary)'
}
+const GROUP_CHAT_SYNC_META_KEY = 'hermes-bots-groups'
+// Gateway ui_meta is capped after Python JSON serialization. Keep a healthy
+// margin below that limit because Python escapes Unicode while JS does not.
+const GROUP_CHAT_SYNC_MAX_BYTES = 48000
+const GROUP_CHAT_SYNC_MESSAGES = 16
+const GROUP_CHAT_SYNC_TEXT_CHARS = 1200
+let groupChatSyncTimer = null
+let groupChatSyncRetryTimer = null
+let groupChatSyncPending = null
+let groupChatSyncInFlight = false
+let groupChatSyncRetryCount = 0
+let groupChatSyncDisposed = false
+
+/** Conservative byte count for the gateway's ensure_ascii JSON encoding.
+ * Python also inserts separator spaces, so reserve one extra byte per JS
+ * structural separator on top of escaped Unicode code-point widths. */
+function groupChatGatewayJsonSize(value) {
+ const json = JSON.stringify(value)
+ let bytes = 0
+
+ for (const character of json) {
+ const codePoint = character.codePointAt(0)
+
+ if (codePoint <= 0x7f) {
+ bytes += 1
+ if (character === ',' || character === ':') {
+ bytes += 1
+ }
+ } else {
+ bytes += codePoint <= 0xffff ? 6 : 12
+ }
+ }
+
+ return bytes
+}
+
+/** Compact, display-oriented copy of Desktop's room log for gateway clients.
+ * The live orchestration state stays in plugin storage; this bounded mirror
+ * rides the default profile's ui_meta so mobile can show the same messages.
+ * Newest rooms/messages win when the profile metadata size cap is reached. */
+function groupChatSyncSnapshot(all = $groupChats.get(), deleted = {}) {
+ const ranked = Object.entries(all || {})
+ // Empty runtime tombstones are used to stop an in-flight room after
+ // disband. They are not real rooms and must never reappear on mobile.
+ .filter(([, room]) => room && Array.isArray(room.log) && room.log.length > 0)
+ .sort(([, left], [, right]) => {
+ const leftAt = Number(left.log[left.log.length - 1]?.at || 0)
+ const rightAt = Number(right.log[right.log.length - 1]?.at || 0)
+ return rightAt - leftAt
+ })
+ const rooms = {}
+ const boundedDeleted = Object.fromEntries(
+ Object.entries(deleted)
+ .sort(([, left], [, right]) => Number(right || 0) - Number(left || 0))
+ .slice(0, 64)
+ )
+ const envelope = {
+ version: 1,
+ updatedAt: Date.now(),
+ rooms,
+ ...(Object.keys(boundedDeleted).length ? { deleted: boundedDeleted } : {})
+ }
+
+ for (const [name, room] of ranked) {
+ const log = room.log.slice(-GROUP_CHAT_SYNC_MESSAGES).map(entry => ({
+ from: {
+ kind: entry?.from?.kind === 'member' ? 'member' : 'user',
+ name: String(entry?.from?.name || (entry?.from?.kind === 'member' ? 'Bot' : 'You')).slice(0, 128),
+ ...(entry?.from?.source ? { source: String(entry.from.source).slice(0, 128) } : {})
+ },
+ text: String(entry?.text || '').slice(0, GROUP_CHAT_SYNC_TEXT_CHARS),
+ at: Number(entry?.at || 0),
+ ...(entry?.thread ? { thread: String(entry.thread).slice(0, 128) } : {})
+ }))
+ const compact = {
+ log,
+ members: (Array.isArray(room.members) ? room.members : []).slice(0, GROUP_CHAT_MAX_MEMBERS).map(member => ({
+ name: String(member?.name || '').slice(0, 128),
+ ...(member?.handle ? { handle: String(member.handle).slice(0, 128) } : {}),
+ ...(member?.connectionId ? { connectionId: String(member.connectionId).slice(0, 128) } : {}),
+ ...(member?.connectionKind ? { connectionKind: String(member.connectionKind).slice(0, 64) } : {}),
+ ...(member?.connectionLabel ? { connectionLabel: String(member.connectionLabel).slice(0, 128) } : {}),
+ ...(member?.sourceScoped ? { sourceScoped: true } : {})
+ }))
+ }
+
+ rooms[name] = compact
+ while (compact.log.length > 1 && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
+ compact.log.shift()
+ }
+ if (groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
+ delete rooms[name]
+ }
+ }
+
+ return envelope
+}
+
+function groupChatSyncEntryKey(entry) {
+ return JSON.stringify([
+ Number(entry?.at || 0),
+ String(entry?.from?.kind || ''),
+ String(entry?.from?.name || ''),
+ String(entry?.from?.source || ''),
+ String(entry?.thread || ''),
+ String(entry?.text || '')
+ ])
+}
+
+function groupChatSyncMemberKey(member) {
+ return JSON.stringify([
+ String(member?.source || ''),
+ String(member?.connectionId || ''),
+ String(member?.connectionLabel || ''),
+ String(member?.handle || ''),
+ String(member?.name || '')
+ ])
+}
+
+/** Merge two bounded projections without treating an absent room/message as
+ * deletion. Explicit tombstones win until a genuinely newer room message
+ * recreates the same name. */
+function mergeGroupChatSyncSnapshots(remote, local) {
+ const rooms = {}
+ const deleted = {}
+
+ for (const source of [remote, local]) {
+ for (const [name, at] of Object.entries(source?.deleted || {})) {
+ deleted[name] = Math.max(Number(deleted[name] || 0), Number(at || 0))
+ }
+ }
+
+ for (const source of [remote, local]) {
+ for (const [name, room] of Object.entries(source?.rooms || {})) {
+ if (!room || !Array.isArray(room.log)) {
+ continue
+ }
+ const current = rooms[name] || { log: [], members: [] }
+ const entries = new Map(current.log.map(entry => [groupChatSyncEntryKey(entry), entry]))
+ const members = new Map(current.members.map(member => [groupChatSyncMemberKey(member), member]))
+
+ for (const entry of room.log) {
+ entries.set(groupChatSyncEntryKey(entry), entry)
+ }
+ for (const member of Array.isArray(room.members) ? room.members : []) {
+ members.set(groupChatSyncMemberKey(member), member)
+ }
+ rooms[name] = {
+ log: [...entries.values()].sort((left, right) => {
+ const byTime = Number(left?.at || 0) - Number(right?.at || 0)
+ return byTime || groupChatSyncEntryKey(left).localeCompare(groupChatSyncEntryKey(right))
+ }),
+ members: [...members.values()]
+ }
+ }
+ }
+
+ for (const [name, deletedAt] of Object.entries(deleted)) {
+ const latestMessageAt = Math.max(0, ...(rooms[name]?.log || []).map(entry => Number(entry?.at || 0)))
+ if (Number(deletedAt || 0) >= latestMessageAt) {
+ delete rooms[name]
+ } else {
+ delete deleted[name]
+ }
+ }
+
+ return groupChatSyncSnapshot(rooms, deleted)
+}
+
+function groupChatSyncConnectionId() {
+ return String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || '')
+}
+
+/** Route a sync job back to the gateway that was active when it was queued.
+ * A foreground switch during debounce must not write the old snapshot into
+ * the newly active gateway. */
+async function groupChatSyncRequest(job, method, params) {
+ if (job.connectionId && typeof host.profileRoutes === 'function' && typeof host.requestProfile === 'function') {
+ const routes = await host.profileRoutes()
+ const route = (Array.isArray(routes) ? routes : []).find(candidate => {
+ const profile = String(candidate?.targetProfile || candidate?.profile || '')
+ return String(candidate?.connectionId || '') === job.connectionId && profile === 'default'
+ })
+
+ if (route) {
+ return host.requestProfile(route, method, params)
+ }
+ }
+
+ const currentConnectionId = groupChatSyncConnectionId()
+ if (job.connectionId && currentConnectionId && job.connectionId !== currentConnectionId) {
+ throw new Error('Group chat gateway changed before sync')
+ }
+ return host.request(method, params)
+}
+
+async function groupChatRemoteSnapshot(job) {
+ const result = await groupChatSyncRequest(job, 'profiles.list', { include_sessions: false })
+ const profile = (Array.isArray(result?.profiles) ? result.profiles : []).find(row => row?.name === 'default')
+ const snapshot = profile?.ui_meta?.[GROUP_CHAT_SYNC_META_KEY]
+ return snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) ? snapshot : null
+}
+
+function groupChatSyncBackoff() {
+ return Math.min(30000, 1000 * 2 ** Math.min(groupChatSyncRetryCount, 5))
+}
+
+async function flushGroupChatServerSync() {
+ if (groupChatSyncDisposed || groupChatSyncInFlight || !groupChatSyncPending) {
+ return
+ }
+ const job = groupChatSyncPending
+ groupChatSyncPending = null
+ groupChatSyncInFlight = true
+
+ try {
+ const remote = await groupChatRemoteSnapshot(job)
+ const snapshot = mergeGroupChatSyncSnapshots(remote, job.snapshot)
+ const result = await groupChatSyncRequest(job, 'profiles.configure', {
+ name: 'default',
+ ui_meta: { [GROUP_CHAT_SYNC_META_KEY]: snapshot }
+ })
+
+ if (result?.applied && result.applied.ui_meta !== true) {
+ throw new Error('Gateway rejected group chat ui_meta')
+ }
+
+ const confirmed = await groupChatRemoteSnapshot(job)
+ if (confirmed && Number(confirmed.updatedAt || 0) !== Number(snapshot.updatedAt || 0)) {
+ throw new Error('Group chat ui_meta changed before read-back')
+ }
+ groupChatSyncRetryCount = 0
+ } catch {
+ if (!groupChatSyncDisposed) {
+ groupChatSyncPending ||= job
+ groupChatSyncRetryCount += 1
+ if (typeof setTimeout === 'function' && groupChatSyncRetryTimer === null) {
+ groupChatSyncRetryTimer = setTimeout(() => {
+ groupChatSyncRetryTimer = null
+ void flushGroupChatServerSync()
+ }, groupChatSyncBackoff())
+ }
+ }
+ } finally {
+ groupChatSyncInFlight = false
+ if (groupChatSyncPending && groupChatSyncRetryTimer === null && !groupChatSyncDisposed) {
+ void flushGroupChatServerSync()
+ }
+ }
+}
+
+function stopGroupChatServerSync() {
+ groupChatSyncDisposed = true
+ groupChatSyncPending = null
+ if (groupChatSyncTimer !== null) {
+ clearTimeout(groupChatSyncTimer)
+ groupChatSyncTimer = null
+ }
+ if (groupChatSyncRetryTimer !== null) {
+ clearTimeout(groupChatSyncRetryTimer)
+ groupChatSyncRetryTimer = null
+ }
+}
+
+/** Debounced, pull-merge-write server mirror. Local storage keeps the complete
+ * orchestration log; ui_meta is a bounded cross-client projection. */
+function scheduleGroupChatServerSync(all = $groupChats.get(), { allowEmpty = false, deletedRooms = [] } = {}) {
+ // Browser shells provide timers; source-level VM tests and older embedded
+ // hosts may not. Room persistence must never break the surrounding gateway
+ // lifecycle when the optional mirror cannot be scheduled.
+ if (typeof setTimeout !== 'function') {
+ return
+ }
+ const deleted = Object.fromEntries(deletedRooms.map(name => [name, Date.now()]))
+ const snapshot = groupChatSyncSnapshot(all, deleted)
+ // A newly installed Desktop has no local room cache. Publishing that empty
+ // state on hydrate/reconnect would erase a valid mirror produced elsewhere.
+ // Only an explicit final-room disband is allowed to clear the projection.
+ if (Object.keys(snapshot.rooms).length === 0 && !allowEmpty) {
+ return
+ }
+ if (groupChatSyncTimer !== null) {
+ clearTimeout(groupChatSyncTimer)
+ }
+ if (groupChatSyncRetryTimer !== null) {
+ clearTimeout(groupChatSyncRetryTimer)
+ groupChatSyncRetryTimer = null
+ }
+ groupChatSyncPending = { snapshot, connectionId: groupChatSyncConnectionId() }
+ groupChatSyncTimer = setTimeout(() => {
+ groupChatSyncTimer = null
+ void flushGroupChatServerSync()
+ }, 350)
+}
+
function handleSessionsGatewayTransition() {
// A gateway swap invalidates any in-flight room drive: bump every room's
// epoch so running loops bail at their next member boundary.
@@ -317,6 +612,10 @@ function handleSessionsGatewayTransition() {
}
$groupChats.set(rooms)
+ // Re-publish the bounded room mirror after reconnects or gateway swaps.
+ // Local plugin storage remains authoritative, so a transient failure here
+ // is harmless and the next gateway transition or room update retries it.
+ scheduleGroupChatServerSync(rooms)
}
/** Per-bot appearance + display meta, persisted via ctx.storage:
@@ -4222,6 +4521,7 @@ function updateGroupChat(group, mutate) {
} catch {
/* storage unavailable — room survives for this window only */
}
+ scheduleGroupChatServerSync(all)
return next
}
@@ -4285,6 +4585,7 @@ async function disbandGroupChat(group, members) {
} catch {
/* storage unavailable — the atom reset above still empties the room */
}
+ scheduleGroupChatServerSync($groupChats.get(), { allowEmpty: true, deletedRooms: [group] })
// Remove this membership last. saveBotMeta never throws (local storage +
// best-effort profiles.configure per member), so a flaky gateway can't
@@ -5090,6 +5391,13 @@ function sendToGroupChat(group, members, text, thread, images) {
const target = thread || mintGroupThreadId()
$groupNeedsYou.set({ ...$groupNeedsYou.get(), [group]: false })
+ // Refresh the durable room roster on every send. This backfills rooms made
+ // by older Desktop builds and keeps the gateway mirror complete even when
+ // members overlap across multiple groups.
+ updateGroupChat(group, room => {
+ room.members = durableGroupChatMembers(members)
+ return room
+ })
appendGroupChatEntry(group, { kind: 'user', name: 'You' }, trimmed, target, attached)
const wasRunning = ($groupChats.get()[group] || {}).running === true
@@ -10768,6 +11076,7 @@ export default {
description: 'Bot Mode — a one-chat-per-agent roster with avatars, routines, group chats, and bot-to-bot messaging. Ships with the app; disable here if unwanted.',
register(ctx) {
pluginCtx = ctx
+ groupChatSyncDisposed = false
startFaceClock()
// Disabling the plugin (or a hot reload) must actually stop the clock —
// before this, the rAF loop + 1Hz document scan ran until app restart.
@@ -10908,6 +11217,7 @@ export default {
}
$groupChats.set({ ...rooms, ...$groupChats.get() })
+ scheduleGroupChatServerSync($groupChats.get())
}
})
.catch(() => undefined)
@@ -10928,6 +11238,7 @@ export default {
if (typeof ctx.onDispose === 'function') {
ctx.onDispose(() => {
+ stopGroupChatServerSync()
if (typeof unbindProfileListener === 'function') {
unbindProfileListener()
}
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
index 59cb23efafc..b69a2df3a16 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/group-chat.test.mjs
@@ -18,6 +18,7 @@ function load(turnScript, { busyUntilResumeCall, clarifyUntilResumeCall, approva
const calls = []
const clarifyResponds = []
const approvalResponds = []
+ const requests = []
const sessions = new Map()
const runtimeToStored = new Map()
const titleToStored = new Map()
@@ -45,6 +46,7 @@ function load(turnScript, { busyUntilResumeCall, clarifyUntilResumeCall, approva
document: { getElementById: () => null, createElement: () => ({}), head: { appendChild: () => undefined } },
host: {
request: async (method, params) => {
+ requests.push({ method, params })
if (method === 'session.create') {
sessionSequence += 1
const stored = `sid-${params.profile}-${sessionSequence}`
@@ -124,7 +126,7 @@ function load(turnScript, { busyUntilResumeCall, clarifyUntilResumeCall, approva
.replace(/^import .* from 'react\/jsx-runtime'\r?\n/m, '')
.replace('export default {', 'globalThis.plugin = {')
.concat(
- '\nglobalThis.__gc = { sendToGroupChat, runGroupChatRounds, harvestStrandedGroupReply, resolveGroupResponders, parseGroupChatMentions, rotateGroupSpeakers, isGroupPassText, formatGroupChatLine, buildGroupChatTurnPrompt, trimGroupChatLog, disbandGroupChat, updateGroupChat, ensureGroupChatSession, uniqueGroupChatName, liveGroupChatNames, openGroupChat, closeGroupChatMainTab, shouldRenderGroupChatInPane, syncGroupClarify, clearGroupClarify, answerGroupClarify, $groupClarify, $groupChats, $groupNeedsYou, $groupChatWorkspace, $groupMainTabsRev, $botMeta, GROUP_CHAT_MAX_ROUNDS, GROUP_CHAT_MAX_MESSAGES };\n'
+ '\nglobalThis.__gc = { sendToGroupChat, runGroupChatRounds, harvestStrandedGroupReply, resolveGroupResponders, parseGroupChatMentions, rotateGroupSpeakers, isGroupPassText, formatGroupChatLine, buildGroupChatTurnPrompt, trimGroupChatLog, groupChatSyncSnapshot, groupChatGatewayJsonSize, mergeGroupChatSyncSnapshots, scheduleGroupChatServerSync, disbandGroupChat, updateGroupChat, ensureGroupChatSession, uniqueGroupChatName, liveGroupChatNames, openGroupChat, closeGroupChatMainTab, shouldRenderGroupChatInPane, syncGroupClarify, clearGroupClarify, answerGroupClarify, $groupClarify, $groupChats, $groupNeedsYou, $groupChatWorkspace, $groupMainTabsRev, $botMeta, GROUP_CHAT_MAX_ROUNDS, GROUP_CHAT_MAX_MESSAGES };\n'
)
vm.runInNewContext(source, context, { filename: 'plugin.js' })
const storageWrites = new Map()
@@ -132,7 +134,7 @@ function load(turnScript, { busyUntilResumeCall, clarifyUntilResumeCall, approva
storage: { get: () => null, set: (key, value) => storageWrites.set(key, value) },
register: () => undefined
})
- return { ...context.__gc, approvalResponds, calls, clarifyResponds, host: context.host, sessions, storageWrites }
+ return { ...context.__gc, approvalResponds, calls, clarifyResponds, host: context.host, requests, sessions, storageWrites }
}
const MEMBERS = [{ name: 'research', title: '' }, { name: 'builder', title: '' }, { name: 'ops', title: 'The Ops' }]
@@ -446,6 +448,140 @@ test('log trimming keeps watermarks consistent', () => {
assert.equal(watermarks.builder, 0)
})
+test('group room messages and members mirror through bounded gateway profile metadata', async () => {
+ const gc = load(() => '(pass)')
+ const members = [
+ { name: 'research', handle: 'research' },
+ { name: 'builder', handle: 'builder' }
+ ]
+ gc.sendToGroupChat('Research', members, 'What changed?')
+ for (let i = 0; i < 200 && (gc.$groupChats.get().Research || {}).running; i++) {
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ const configure = gc.requests.filter(call => call.method === 'profiles.configure').at(-1)
+ assert.ok(configure, 'room updates are mirrored to the gateway')
+ assert.equal(configure.params.name, 'default')
+ const envelope = configure.params.ui_meta['hermes-bots-groups']
+ assert.equal(envelope.version, 1)
+ assert.equal(envelope.rooms.Research.log[0].text, 'What changed?')
+ assert.equal(JSON.stringify(envelope.rooms.Research.members.map(member => member.name)), JSON.stringify(['research', 'builder']))
+ assert.ok(gc.groupChatGatewayJsonSize(envelope) <= 48000)
+})
+
+test('group gateway mirror is size bounded and favors recent messages', () => {
+ const gc = load(() => '(pass)')
+ const long = 'x'.repeat(5000)
+ const snapshot = gc.groupChatSyncSnapshot({
+ Large: {
+ log: Array.from({ length: 100 }, (_, index) => ({
+ from: { kind: index % 2 ? 'member' : 'user', name: index % 2 ? 'research' : 'You' },
+ text: `${index}:${long}`,
+ at: index
+ }))
+ }
+ })
+
+ assert.ok(gc.groupChatGatewayJsonSize(snapshot) <= 48000)
+ assert.ok(snapshot.rooms.Large.log.length <= 16)
+ assert.match(snapshot.rooms.Large.log.at(-1).text, /^99:/)
+ assert.ok(snapshot.rooms.Large.log.at(-1).text.length <= 1200)
+})
+
+test('group gateway mirror preserves threads and budgets escaped Unicode', () => {
+ const gc = load(() => '(pass)')
+ const snapshot = gc.groupChatSyncSnapshot({
+ Unicode: {
+ log: Array.from({ length: 16 }, (_, index) => ({
+ from: { kind: 'member', name: 'research' },
+ text: `message ${index} ${'🧠'.repeat(1200)}`,
+ at: index,
+ thread: `thread-${index}`
+ }))
+ }
+ })
+
+ assert.ok(gc.groupChatGatewayJsonSize(snapshot) <= 48000)
+ assert.equal(snapshot.rooms.Unicode.log.at(-1).thread, 'thread-15')
+})
+
+test('empty runtime rooms are omitted from the gateway mirror', () => {
+ const gc = load(() => '(pass)')
+ const snapshot = gc.groupChatSyncSnapshot({
+ Disbanded: { log: [], members: [{ name: 'research' }] }
+ })
+
+ assert.deepEqual(Object.keys(snapshot.rooms), [])
+})
+
+test('an empty hydrate cannot erase a shared gateway room mirror', () => {
+ const gc = load(() => '(pass)')
+ const before = gc.requests.length
+
+ gc.scheduleGroupChatServerSync({})
+
+ assert.equal(gc.requests.length, before)
+})
+
+test('an explicit final-room disband may clear the gateway room mirror', async () => {
+ const gc = load(() => '(pass)')
+
+ gc.scheduleGroupChatServerSync({}, { allowEmpty: true, deletedRooms: ['Research'] })
+ await new Promise(resolve => setImmediate(resolve))
+
+ const configure = gc.requests.filter(call => call.method === 'profiles.configure').at(-1)
+ assert.deepEqual(Object.keys(configure.params.ui_meta['hermes-bots-groups'].rooms), [])
+ assert.ok(configure.params.ui_meta['hermes-bots-groups'].deleted.Research > 0)
+})
+
+test('pull-before-push merge preserves disjoint rooms, messages, and members', () => {
+ const gc = load(() => '(pass)')
+ const merged = gc.mergeGroupChatSyncSnapshots(
+ {
+ version: 1,
+ rooms: {
+ Shared: {
+ log: [{ from: { kind: 'user', name: 'You' }, text: 'remote', at: 1, thread: 'one' }],
+ members: [{ name: 'research', handle: 'research' }]
+ },
+ RemoteOnly: {
+ log: [{ from: { kind: 'member', name: 'ops' }, text: 'kept', at: 2 }],
+ members: [{ name: 'ops' }]
+ }
+ }
+ },
+ {
+ version: 1,
+ rooms: {
+ Shared: {
+ log: [{ from: { kind: 'member', name: 'builder' }, text: 'local', at: 3, thread: 'one' }],
+ members: [{ name: 'builder', handle: 'builder' }]
+ }
+ }
+ }
+ )
+
+ assert.equal(JSON.stringify(merged.rooms.Shared.log.map(entry => entry.text)), JSON.stringify(['remote', 'local']))
+ assert.equal(JSON.stringify(merged.rooms.Shared.members.map(member => member.name)), JSON.stringify(['research', 'builder']))
+ assert.equal(merged.rooms.RemoteOnly.log[0].text, 'kept')
+})
+
+test('room deletion tombstone wins over stale history but not a later recreation', () => {
+ const gc = load(() => '(pass)')
+ const stale = gc.mergeGroupChatSyncSnapshots(
+ { rooms: { Research: { log: [{ from: { kind: 'user', name: 'You' }, text: 'old', at: 10 }] } } },
+ { rooms: {}, deleted: { Research: 20 } }
+ )
+ assert.equal(stale.rooms.Research, undefined)
+ assert.equal(stale.deleted.Research, 20)
+
+ const recreated = gc.mergeGroupChatSyncSnapshots(stale, {
+ rooms: { Research: { log: [{ from: { kind: 'user', name: 'You' }, text: 'new', at: 30 }] } }
+ })
+ assert.equal(recreated.rooms.Research.log[0].text, 'new')
+ assert.equal(recreated.deleted, undefined)
+})
+
test('source contract: workspace + main-window door + prompt rules are wired', () => {
assert.match(pluginSource, /function GroupChatWorkspace\(/)
// Group rows open through the main-window door, feature-detected with the