fix(desktop): every group chat storage writer keeps the whole room record
Three writers of the stored group chat map each rebuilt the room field by field, and each copy drifted from the others: - updateGroupChat (every room edit) wrote the full record. - durableGroupChatRooms, used by every gateway sync pull and publish, dropped holds and sessionOwners. After any sync, a window restart released a bot the user had stopped (#93129). - disbandGroupChat's rewrite of the rooms left behind dropped holds, heldMessages, holdDetection, stranded, externalCursors, pinned, rosterOrder and sectionId. Hydration on the read side also dropped holdDetection and heldMessages, so a room with stop detection turned off came back with it on. The same omission has been fixed one copy at a time before: roomId (fb7f0602), sectionId (609998718c), heldMessages (a273c2c031) and engine (51f600ae60). There is now one writer projection and one hydration reader, in group-chat-record.ts. All three writers go through persistGroupChatRooms. DurableGroupChat requires every GroupChat key except the runtime-only epoch/running/tombstone, so a field added to GroupChat, or dropped from either function, fails tsc.
This commit is contained in:
@@ -1,18 +1,10 @@
|
||||
/**
|
||||
* A Desktop-driven room's `engine: 'desktop'` reaches plugin storage through
|
||||
* every writer of the stored room map: a room write, the post-merge rewrite and
|
||||
* the rewrite of the rooms left after a disband. Hydration reads the field back
|
||||
* (group-chat-hydrate-engine.test.ts), so a writer that drops it hands an edited
|
||||
* all-local room back to the membership check after a reload.
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type * as groupChat from './group-chat'
|
||||
import type * as groupChatView from './group-chat-view'
|
||||
import { createGroupGateway, runTimersInline, scriptedStorage } from './group-test-utils'
|
||||
import { createGroupGateway, HELD_GROUP_ROOM, runTimersInline, scriptedStorage } from './group-test-utils'
|
||||
import type { ScriptedGateway } from './group-test-utils'
|
||||
import type { GroupChat } from './types'
|
||||
import type { DurableGroupChat } from './types'
|
||||
|
||||
const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))
|
||||
|
||||
@@ -44,7 +36,7 @@ async function loadRoom(): Promise<Room> {
|
||||
return { chat, gateway, view }
|
||||
}
|
||||
|
||||
const stored = (room: Room) => (room.gateway.storage.get('group-chats') || {}) as Record<string, GroupChat>
|
||||
const stored = (room: Room) => (room.gateway.storage.get('group-chats') || {}) as Record<string, DurableGroupChat>
|
||||
|
||||
function seed(room: Room) {
|
||||
for (const [name, engine] of [['Mixed', 'desktop'], ['Plain', undefined]] as const) {
|
||||
@@ -54,25 +46,43 @@ function seed(room: Room) {
|
||||
{ sync: false }
|
||||
)
|
||||
}
|
||||
|
||||
room.chat.updateGroupChat('Held', r => ({ ...r, ...structuredClone(HELD_GROUP_ROOM) }), { sync: false })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
runTimersInline()
|
||||
})
|
||||
|
||||
describe('engine reaches plugin storage', () => {
|
||||
describe('the durable room record reaches plugin storage', () => {
|
||||
it('through a room write and the post-merge rewrite', async () => {
|
||||
const room = await loadRoom()
|
||||
seed(room)
|
||||
|
||||
expect(stored(room).Mixed.engine).toBe('desktop')
|
||||
expect(stored(room).Plain.engine).toBeUndefined()
|
||||
expect(stored(room).Held).toEqual(HELD_GROUP_ROOM)
|
||||
|
||||
room.gateway.storage.delete('group-chats')
|
||||
await room.chat.persistGroupChatRooms()
|
||||
|
||||
expect(stored(room).Mixed.engine).toBe('desktop')
|
||||
expect(stored(room).Plain.engine).toBeUndefined()
|
||||
expect(stored(room).Held).toEqual(HELD_GROUP_ROOM)
|
||||
})
|
||||
|
||||
it('through the rewrite after a gateway sync pull', async () => {
|
||||
const room = await loadRoom()
|
||||
seed(room)
|
||||
room.gateway.uiMeta['hermes-bots-groups'] = room.chat.groupChatSyncSnapshot()
|
||||
room.gateway.storage.delete('group-chats')
|
||||
|
||||
expect(await room.chat.pullGroupChatServerState('')).toBe(true)
|
||||
|
||||
const { members, ...rest } = stored(room).Held
|
||||
const { members: heldMembers, ...heldRest } = HELD_GROUP_ROOM
|
||||
expect(rest).toEqual(heldRest)
|
||||
expect(members).toEqual(heldMembers?.map(member => ({ ...member, remoteSource: true })))
|
||||
})
|
||||
|
||||
it('through the rewrite of the rooms a disband leaves', async () => {
|
||||
@@ -82,7 +92,8 @@ describe('engine reaches plugin storage', () => {
|
||||
|
||||
await room.view.disbandGroupChat('Gone', [])
|
||||
|
||||
expect(Object.keys(stored(room)).sort()).toEqual(['Mixed', 'Plain'])
|
||||
expect(Object.keys(stored(room)).sort()).toEqual(['Held', 'Mixed', 'Plain'])
|
||||
expect(stored(room).Mixed.engine).toBe('desktop')
|
||||
expect(stored(room).Held).toEqual(HELD_GROUP_ROOM)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type * as GroupChatModule from './group-chat'
|
||||
import { HELD_GROUP_ROOM } from './group-test-utils'
|
||||
import type * as I18nModule from './i18n'
|
||||
import type { RosterRow } from './types'
|
||||
|
||||
@@ -142,4 +143,26 @@ describe('group-chat hydration', () => {
|
||||
expect($groupChats.get().Mixed.engine).toBe('desktop')
|
||||
expect($groupChats.get().Plain.engine).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores every stored durable field', async () => {
|
||||
$groupChats.set({})
|
||||
|
||||
try {
|
||||
plugin.register({
|
||||
i18n: { register: () => () => undefined },
|
||||
onDispose: () => undefined,
|
||||
register: () => () => undefined,
|
||||
storage: {
|
||||
get: async (key: string) => (key === 'group-chats' ? { Held: structuredClone(HELD_GROUP_ROOM) } : undefined),
|
||||
set: async () => undefined
|
||||
}
|
||||
} as never)
|
||||
} catch {
|
||||
// Registration walks UI surfaces the stub does not model.
|
||||
}
|
||||
|
||||
await vi.waitFor(() => expect($groupChats.get().Held).toBeDefined())
|
||||
|
||||
expect($groupChats.get().Held).toEqual({ ...HELD_GROUP_ROOM, epoch: 0, running: false })
|
||||
})
|
||||
})
|
||||
|
||||
48
apps/desktop/src/plugins/hermes-bots/group-chat-record.ts
Normal file
48
apps/desktop/src/plugins/hermes-bots/group-chat-record.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { stickyGroupEngine } from './group-engine'
|
||||
import type { DurableGroupChat, GroupChat } from './types'
|
||||
|
||||
export function durableGroupChatRoom(room: GroupChat): DurableGroupChat {
|
||||
return {
|
||||
log: room.log,
|
||||
holdDetection: room.holdDetection !== false,
|
||||
heldMessages: room.heldMessages || {},
|
||||
watermarks: room.watermarks || {},
|
||||
sessions: room.sessions || {},
|
||||
sessionOwners: room.sessionOwners || {},
|
||||
stranded: room.stranded || {},
|
||||
holds: room.holds || {},
|
||||
externalCursors: room.externalCursors || {},
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
engine: stickyGroupEngine(room).engine,
|
||||
image: room.image || null,
|
||||
rosterOrder: room.rosterOrder,
|
||||
pinned: room.pinned,
|
||||
sectionId: room.sectionId ?? null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0))
|
||||
}
|
||||
}
|
||||
|
||||
const objectOrEmpty = <T>(value: T) => (value && typeof value === 'object' ? value : {}) as NonNullable<T>
|
||||
|
||||
export function hydrateDurableGroupChatRoom(room: DurableGroupChat): DurableGroupChat {
|
||||
return {
|
||||
log: room.log,
|
||||
holdDetection: room.holdDetection !== false,
|
||||
heldMessages: objectOrEmpty(room.heldMessages),
|
||||
watermarks: objectOrEmpty(room.watermarks),
|
||||
sessions: objectOrEmpty(room.sessions),
|
||||
sessionOwners: objectOrEmpty(room.sessionOwners),
|
||||
stranded: objectOrEmpty(room.stranded),
|
||||
holds: objectOrEmpty(room.holds),
|
||||
externalCursors: objectOrEmpty(room.externalCursors),
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
engine: stickyGroupEngine(room).engine,
|
||||
image: typeof room.image === 'string' && room.image ? room.image : null,
|
||||
rosterOrder: Number.isFinite(room.rosterOrder) ? room.rosterOrder : undefined,
|
||||
pinned: Boolean(room.pinned),
|
||||
sectionId: room.sectionId ?? null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0))
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ import {
|
||||
$groupClarify,
|
||||
$groupNeedsYou,
|
||||
groupThreadOf,
|
||||
persistGroupChatRooms,
|
||||
rememberGroupChatTombstone,
|
||||
scheduleGroupChatServerSync,
|
||||
setGroupChatHoldDetection,
|
||||
@@ -93,7 +94,7 @@ import { focusComposerEnd, GroupClarifyCard, GroupImageControls, GroupMentionInp
|
||||
import type { GroupRoomPrompt } from './group-chat-parts'
|
||||
import { GroupMemberPicker } from './group-chat-view-members'
|
||||
import { compressGroupMemberHistory } from './group-compress'
|
||||
import { gatewayGroupEngine, type GatewayGroupEngine, stickyGroupEngine } from './group-engine'
|
||||
import { gatewayGroupEngine, type GatewayGroupEngine } from './group-engine'
|
||||
import { sweepExternalGroupWrites } from './group-external-writes'
|
||||
import { GroupHoldStatus } from './group-hold-status'
|
||||
import {
|
||||
@@ -125,7 +126,7 @@ import { clearGroupClarify, renameGroupClarify } from './group-turns'
|
||||
import { botsText, useBots } from './i18n'
|
||||
import { displayName, slugifyProfileName } from './labels'
|
||||
import { botRosterMeta, groupTranscriptSpeaker, groupTranscriptSpeakerMeta, setBotsWorkspaceOwner } from './routing'
|
||||
import { bumpBotOpenGeneration, getPluginCtx, ID } from './shared'
|
||||
import { bumpBotOpenGeneration, ID } from './shared'
|
||||
import type { Attachment, BotMeta, GroupChat, GroupMember, GroupMessage, RosterRow } from './types'
|
||||
|
||||
const Streamdown = typeof sdk === 'undefined' ? undefined : sdk.Streamdown
|
||||
@@ -220,29 +221,7 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
|
||||
|
||||
// Persist the room map WITHOUT the disbanded room so it can't come back
|
||||
// on the next window load.
|
||||
try {
|
||||
const durable: Record<string, GroupChat> = {}
|
||||
|
||||
for (const [name, room] of Object.entries($groupChats.get())) {
|
||||
if (name !== group && Array.isArray(room.log)) {
|
||||
durable[name] = {
|
||||
log: room.log,
|
||||
watermarks: room.watermarks,
|
||||
sessions: room.sessions || {},
|
||||
sessionOwners: room.sessionOwners || {},
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
...stickyGroupEngine(room),
|
||||
image: room.image || null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.resolve(getPluginCtx()?.storage?.set?.('group-chats', durable))
|
||||
} catch {
|
||||
/* storage unavailable — the atom reset above still empties the room */
|
||||
}
|
||||
await persistGroupChatRooms($groupChats.get())
|
||||
|
||||
scheduleGroupChatServerSync($groupChats.get(), {
|
||||
allowEmpty: true,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { atom, host, randomUuid } from '@hermes/plugin-sdk'
|
||||
|
||||
import { $botMeta, $lastRoster, botRosterKey } from './data'
|
||||
import { durableGroupChatRoom } from './group-chat-record'
|
||||
import type { GroupEngine } from './group-engine'
|
||||
import { gatewayGroupEngine, gatewayGroupIdentityConflicts, stickyGroupEngine } from './group-engine'
|
||||
import { groupMemberReferencesConnection, markOrphanedGroupMemberDescriptor } from './hygiene'
|
||||
@@ -20,6 +21,7 @@ import { botRosterMeta } from './routing'
|
||||
import { getPluginCtx } from './shared'
|
||||
import type {
|
||||
Attachment,
|
||||
DurableGroupChat,
|
||||
GroupChat,
|
||||
GroupHold,
|
||||
GroupMember,
|
||||
@@ -924,43 +926,15 @@ export function mergeRemoteGroupChatSnapshotIntoRooms(
|
||||
}
|
||||
|
||||
export function durableGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get()) {
|
||||
const durable: Record<string, GroupChat> = {}
|
||||
const durable: Record<string, DurableGroupChat> = {}
|
||||
|
||||
for (const [name, room] of Object.entries(all || {})) {
|
||||
if (!room || !Array.isArray(room.log)) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Disband tombstones are runtime-only coordination state (they hold the
|
||||
// epoch bump for an in-flight drive). Persisting one would resurrect the
|
||||
// room as an empty record on the next load AND keep its name "taken" for
|
||||
// same-name recreates. Mirrors updateGroupChat's inline durable map.
|
||||
if (room.tombstone) {
|
||||
continue
|
||||
}
|
||||
|
||||
durable[name] = {
|
||||
log: room.log,
|
||||
holdDetection: room.holdDetection !== false,
|
||||
heldMessages: room.heldMessages || {},
|
||||
watermarks: room.watermarks || {},
|
||||
sessions: room.sessions || {},
|
||||
stranded: room.stranded || {},
|
||||
externalCursors: room.externalCursors || {},
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
// Immutable room identity: without this, a room merged in via the
|
||||
// remote-sync path (the only caller of this function) loses its
|
||||
// roomId on the next cold hydrate and falls back to legacy
|
||||
// name-keyed identity — same field updateGroupChat's inline map
|
||||
// already carries.
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
...stickyGroupEngine(room),
|
||||
image: room.image || null,
|
||||
rosterOrder: room.rosterOrder,
|
||||
pinned: room.pinned,
|
||||
// Sidebar filing (user-sections) is room-local; keep it across sync.
|
||||
sectionId: room.sectionId ?? null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0))
|
||||
// same-name recreates.
|
||||
if (room && Array.isArray(room.log) && !room.tombstone) {
|
||||
durable[name] = durableGroupChatRoom(room)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -979,8 +953,6 @@ export function persistGroupChatRooms(all: Record<string, GroupChat> = $groupCha
|
||||
|
||||
/** Register-removed sweep: annotate (not delete) every persisted group-chat
|
||||
* member owned by the deleted connection, in the atom AND plugin storage.
|
||||
* Writes ride updateGroupChat so the durable record keeps its full shape
|
||||
* (sessionOwners, holds — durableGroupChatRooms would drop them).
|
||||
* Returns whether anything changed. */
|
||||
export function sweepGroupChatMembersForRemovedConnection(connectionId: string) {
|
||||
const id = String(connectionId || '').trim()
|
||||
@@ -1643,57 +1615,7 @@ export function updateGroupChat(
|
||||
all[group] = next
|
||||
$groupChats.set(all)
|
||||
|
||||
try {
|
||||
const durable: Record<string, GroupChat> = {}
|
||||
|
||||
for (const [name, room] of Object.entries(all)) {
|
||||
// Disband tombstones are runtime-only coordination state (they hold the
|
||||
// epoch bump for an in-flight drive). Persisting one would resurrect
|
||||
// the room as an empty record on the next load AND keep its name
|
||||
// "taken" for same-name recreates.
|
||||
if (room.tombstone) {
|
||||
continue
|
||||
}
|
||||
|
||||
durable[name] = {
|
||||
log: room.log,
|
||||
holdDetection: room.holdDetection !== false,
|
||||
heldMessages: room.heldMessages || {},
|
||||
watermarks: room.watermarks,
|
||||
sessions: room.sessions || {},
|
||||
sessionOwners: room.sessionOwners || {},
|
||||
// Timed-out turns awaiting a late reply — keyed by member, valued
|
||||
// with the pre-turn message baseline. Survives reloads so finished
|
||||
// work is still harvested after a window restart.
|
||||
stranded: room.stranded || {},
|
||||
// #93129: sticky per-member stop holds. Watermarks persist, so holds
|
||||
// must too — otherwise a window restart silently releases a bot the
|
||||
// user explicitly stopped.
|
||||
holds: room.holds || {},
|
||||
// #93813: per-member external-write reconcile cursors. Persisted so
|
||||
// external posts aren't re-mirrored after a window restart.
|
||||
externalCursors: room.externalCursors || {},
|
||||
// Source-qualified member descriptors keep the room whole when the
|
||||
// active connection changes and today's local members become remote.
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
// Immutable room identity: the member-session title for new rooms.
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
// A Desktop-driven room stays one across reloads (plugin.tsx hydration).
|
||||
...stickyGroupEngine(room),
|
||||
// Room picture (small data URL, same normalization as bot avatars).
|
||||
image: room.image || null,
|
||||
rosterOrder: room.rosterOrder,
|
||||
pinned: room.pinned,
|
||||
// Sidebar filing (user-sections) is room-local; keep it durable.
|
||||
sectionId: room.sectionId ?? null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0))
|
||||
}
|
||||
}
|
||||
|
||||
Promise.resolve(getPluginCtx()?.storage?.set?.('group-chats', durable)).catch(() => undefined)
|
||||
} catch {
|
||||
/* storage unavailable — room survives for this window only */
|
||||
}
|
||||
void persistGroupChatRooms(all)
|
||||
|
||||
if (sync) {
|
||||
scheduleGroupChatServerSync(all, {
|
||||
|
||||
@@ -23,6 +23,28 @@
|
||||
import type { PluginContext } from '@hermes/plugin-sdk'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
import type { DurableGroupChat } from './types'
|
||||
|
||||
export const HELD_GROUP_ROOM: DurableGroupChat = {
|
||||
log: [{ id: 'm1', thread: 't1', at: 1, from: { kind: 'user', name: 'You' }, text: '@alpha stop' }],
|
||||
holdDetection: false,
|
||||
heldMessages: { alpha: ['m1'] },
|
||||
watermarks: { 't1::alpha': 1 },
|
||||
sessions: { alpha: 'sid-alpha' },
|
||||
sessionOwners: { alpha: { name: 'alpha', connectionId: 'owner' } },
|
||||
stranded: { beta: 0 },
|
||||
holds: { alpha: { at: 1 } },
|
||||
externalCursors: { beta: 3 },
|
||||
members: [{ name: 'alpha' }, { name: 'beta' }],
|
||||
roomId: 'room-held',
|
||||
engine: 'desktop',
|
||||
image: 'data:image/png;base64,AA',
|
||||
rosterOrder: 2,
|
||||
pinned: true,
|
||||
sectionId: 'work',
|
||||
syncRevision: 4
|
||||
}
|
||||
|
||||
/** One message in a scripted session transcript, in the gateway's own shape. */
|
||||
export interface ScriptedMessage {
|
||||
content: string
|
||||
|
||||
@@ -66,7 +66,7 @@ import {
|
||||
sweepGroupChatMembersForRemovedConnection,
|
||||
updateGroupChat
|
||||
} from './group-chat'
|
||||
import { stickyGroupEngine } from './group-engine'
|
||||
import { hydrateDurableGroupChatRoom } from './group-chat-record'
|
||||
import { groupWorkspaceOwnerKey } from './group-membership'
|
||||
import { annotateOrphanedGroupChatMembers } from './hygiene'
|
||||
import { BOTS_LOCALES, botsText } from './i18n'
|
||||
@@ -284,27 +284,10 @@ export default {
|
||||
for (const [name, room] of Object.entries(value)) {
|
||||
if (room && Array.isArray(room.log)) {
|
||||
rooms[name] = {
|
||||
...hydrateDurableGroupChatRoom(room),
|
||||
// Pre-thread entries get synthetic thread ids on hydrate so
|
||||
// every UI/engine path can assume entry.thread exists.
|
||||
log: assignLegacyThreads(room.log),
|
||||
watermarks: room.watermarks && typeof room.watermarks === 'object' ? room.watermarks : {},
|
||||
sessions: room.sessions && typeof room.sessions === 'object' ? room.sessions : {},
|
||||
sessionOwners: room.sessionOwners && typeof room.sessionOwners === 'object' ? room.sessionOwners : {},
|
||||
stranded: room.stranded && typeof room.stranded === 'object' ? room.stranded : {},
|
||||
// #93129: rehydrate sticky stop holds with the same shape
|
||||
// guard as the other maps — a held bot stays held across
|
||||
// window restarts until explicitly released.
|
||||
holds: room.holds && typeof room.holds === 'object' ? room.holds : {},
|
||||
externalCursors:
|
||||
room.externalCursors && typeof room.externalCursors === 'object' ? room.externalCursors : {},
|
||||
members: Array.isArray(room.members) ? room.members : [],
|
||||
roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,
|
||||
...stickyGroupEngine(room),
|
||||
image: typeof room.image === 'string' && room.image ? room.image : null,
|
||||
rosterOrder: Number.isFinite(room.rosterOrder) ? room.rosterOrder : undefined,
|
||||
pinned: Boolean(room.pinned),
|
||||
sectionId: room.sectionId ?? null,
|
||||
syncRevision: Math.max(0, Number(room.syncRevision || 0)),
|
||||
epoch: 0,
|
||||
running: false
|
||||
}
|
||||
|
||||
@@ -258,6 +258,10 @@ export interface GroupChat {
|
||||
watermarks: Record<string, number>
|
||||
}
|
||||
|
||||
export type RuntimeGroupChatKey = 'epoch' | 'running' | 'tombstone'
|
||||
|
||||
export type DurableGroupChat = { [K in Exclude<keyof GroupChat, RuntimeGroupChatKey>]: GroupChat[K] }
|
||||
|
||||
/**
|
||||
* One sub-question of a batch clarify, straight off the wire. `choices` and
|
||||
* `question` stay unknown because the card re-validates them.
|
||||
|
||||
Reference in New Issue
Block a user