feat(desktop): file group chats into user-made roster sections

Group chats now file into user-made sidebar sections exactly like bots:
drag the group row onto a section, pick one from its context menu, or
create a section straight from the group's menu. Unfiling (drop on
Unassigned, Remove from section, or deleting the section) returns the
group to the roster's group-chat bucket.

The membership model stays membership-on-the-item, with the one
difference the two row kinds force: a bot's sectionId is a field on its
profile meta (profile sync carries it), while a group has no profile —
its room record is its only durable identity — so the assignment is a
field on the room and rides the room's own plugin-storage persistence
(updateGroupChat + durableGroupChatRooms + hydrate). It is deliberately
absent from the bounded gateway sync projection, which mirrors
conversations to other clients, not this machine's sidebar layout — the
same local scope the section list itself has.

- user-sections.ts: groupDragKey / groupChatSectionId /
  moveGroupChatsToSection; groupRowsBySection seats group rows per
  their room record (dangling ids fall to Unassigned, never vanish)
- bot-row.tsx: GroupRow gains draggable + the same Move-to-section
  submenu a bot row gets
- roster-pane.tsx: drop zones accept the group drag key; the automatic
  group-chat bucket renders through the user-section blocks too
- GroupChat.sectionId carried by all three durable room writers
This commit is contained in:
tobenwarrior
2026-09-08 11:18:56 +08:00
committed by Teknium
parent d7c791c64c
commit 609998718c
9 changed files with 294 additions and 29 deletions

View File

@@ -73,7 +73,16 @@ import {
workerActiveAt
} from './row-helpers'
import type { GroupMember, RosterRow, SidebarRowLabels } from './types'
import { $botSections, $draggingBot, BOT_DRAG_MIME, botSectionId, moveBotsToSection } from './user-sections'
import {
$botSections,
$draggingBot,
BOT_DRAG_MIME,
botSectionId,
groupChatSectionId,
groupDragKey,
moveBotsToSection,
moveGroupChatsToSection
} from './user-sections'
// ── bot row ──────────────────────────────────────────────────────────────────
@@ -454,13 +463,17 @@ interface GroupRowProps {
members: GroupMember[]
needsYou: boolean
onDisband: (room: { members: GroupMember[]; name: string }) => void
/** Opens the New section dialog; the group is filed into it on create. */
onNewSection: (group: string) => void
onOpen: (group: string) => void
}
export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }: GroupRowProps) {
export function GroupRow({ active, group, members, needsYou, onOpen, onDisband, onNewSection }: GroupRowProps) {
const { t } = useI18n()
const b = useBots()
const rooms = useValue($groupChats)
const sections = useValue($botSections)
const currentSectionId = groupChatSectionId(group, rooms)
const room = rooms[group] || {
log: []
@@ -485,18 +498,31 @@ export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }
const availableMembers = members.filter(member => botSourceStatus(member).available).length
const availabilityLabel = `${availableMembers} of ${members.length} available`
// Same drag contract as a bot row, under the group's own key shape so a
// drop zone can tell which kind landed without decoding roster keys.
const dragKey = groupDragKey(group)
const dragging = useValue($draggingBot) === dragKey
const row = (
<RowButton
aria-label={`${group}, ${members.length} bots, ${availabilityLabel}`}
className={cn(
'flex w-full min-w-0 max-w-full items-center gap-2.5 overflow-hidden rounded-md px-2 py-2 text-left transition-colors',
'hover:bg-(--chrome-action-hover)',
active && 'bg-(--ui-row-active-background)'
active && 'bg-(--ui-row-active-background)',
dragging && 'opacity-40'
)}
draggable
onClick={() => {
haptic('tap')
onOpen(group)
}}
onDragEnd={() => $draggingBot.set(null)}
onDragStart={event => {
event.dataTransfer.setData(BOT_DRAG_MIME, dragKey)
event.dataTransfer.effectAllowed = 'move'
$draggingBot.set(dragKey)
}}
>
<div className="relative flex w-[34px] shrink-0 items-center justify-center">
{room.image ? (
@@ -554,6 +580,35 @@ export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }
<ContextMenuContent>
<ContextMenuItem onSelect={() => onOpen(group)}>Open Group Chat</ContextMenuItem>
<ContextMenuSeparator />
{/* Filing — the same submenu a bot row gets, driving the room-record
assignment instead of profile meta. */}
<ContextMenuSub>
<ContextMenuSubTrigger>{b.sections.moveTo}</ContextMenuSubTrigger>
<ContextMenuSubContent>
{sections.map(section => (
<ContextMenuItem
disabled={section.id === currentSectionId}
key={section.id}
onSelect={() => moveGroupChatsToSection([group], section.id)}
>
<Codicon className="mr-1.5" name="folder" />
{section.name}
</ContextMenuItem>
))}
{sections.length ? <ContextMenuSeparator /> : null}
<ContextMenuItem onSelect={() => onNewSection(group)}>
<Codicon className="mr-1.5" name="new-folder" />
{b.sections.newSectionEllipsis}
</ContextMenuItem>
{currentSectionId ? (
<ContextMenuItem onSelect={() => moveGroupChatsToSection([group], null)}>
<Codicon className="mr-1.5" name="inbox" />
{b.sections.removeFromSection}
</ContextMenuItem>
) : null}
</ContextMenuSubContent>
</ContextMenuSub>
<ContextMenuSeparator />
<ContextMenuItem
className="text-destructive focus:text-destructive"
onSelect={() =>

View File

@@ -755,6 +755,8 @@ export function durableGroupChatRooms(all: Record<string, GroupChat> = $groupCha
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))
}
}
@@ -1356,6 +1358,8 @@ export function updateGroupChat(
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))
}
}

View File

@@ -248,6 +248,7 @@ export default {
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

View File

@@ -8,7 +8,7 @@ import { disbandGroupChat, openGroupChat } from './group-chat-view'
import type { useBots } from './i18n'
import { deleteBot } from './profile-ops'
import type { GroupMember, RosterRow } from './types'
import { createBotSection, renameBotSection } from './user-sections'
import { createBotSection, moveGroupChatsToSection, renameBotSection, type SectionDialogState } from './user-sections'
import { SectionNameDialog } from './user-sections-ui'
interface renderRosterDialogsProps {
@@ -26,10 +26,8 @@ interface renderRosterDialogsProps {
setDeletingGroup: (value: { members: GroupMember[]; name: string } | null) => void
grouping: RosterRow | null
setGrouping: (value: RosterRow | null) => void
sectionDialog: null | { bot?: RosterRow; mode: 'create' } | { id: string; mode: 'rename'; name: string }
setSectionDialog: (
value: null | { bot?: RosterRow; mode: 'create' } | { id: string; mode: 'rename'; name: string }
) => void
sectionDialog: SectionDialogState
setSectionDialog: (value: SectionDialogState) => void
roster: RosterRow[]
activeSourceRoster: RosterRow[]
refetch: ReturnType<typeof useRoster>['refetch']
@@ -85,7 +83,11 @@ export function renderRosterDialogs({
if (sectionDialog?.mode === 'rename') {
renameBotSection(sectionDialog.id, name)
} else {
createBotSection(name, sectionDialog?.bot ? [sectionDialog.bot] : [])
const section = createBotSection(name, sectionDialog?.bot ? [sectionDialog.bot] : [])
if (section && sectionDialog?.group) {
moveGroupChatsToSection([sectionDialog.group], section.id)
}
}
}}
open={Boolean(sectionDialog)}

View File

@@ -6,13 +6,16 @@ import type { useBots } from './i18n'
import type { RosterGroupRow } from './roster-pane-derivation'
import { GatewayKindGlyph, GatewaySectionHeading, RosterSectionHeader } from './roster-sections'
import type { ResolvedRosterGatewaySection } from './roster-sections'
import type { BotMeta, GroupMember, RosterRow } from './types'
import type { $botSections } from './user-sections'
import type { BotMeta, GroupChat, GroupMember, RosterRow } from './types'
import type { $botSections, SectionDialogState } from './user-sections'
import {
deleteBotSection,
GROUP_DRAG_PREFIX,
groupDragKey,
groupRowsBySection,
moveBotSection,
moveBotsToSection,
moveGroupChatsToSection,
UNASSIGNED_SECTION_KEY
} from './user-sections'
import { SectionDropZone, UserSectionHeader } from './user-sections-ui'
@@ -22,12 +25,11 @@ interface RosterSectionRenderersProps {
userSections: ReturnType<typeof $botSections.get>
roster: RosterRow[]
allMeta: Record<string, BotMeta>
groupRooms: Record<string, GroupChat>
dragging: string | null
rosterSectionCollapsed: (id: string) => boolean
toggleRosterSection: (id: string) => void
setSectionDialog: (
value: null | { bot?: RosterRow; mode: 'create' } | { id: string; mode: 'rename'; name: string }
) => void
setSectionDialog: (value: SectionDialogState) => void
renderBotRow: (bot: RosterRow, keyPrefix?: string) => ReactNode
renderGroupRow: (row: { members: GroupMember[]; name: string }) => ReactNode
sortedGroupRows: RosterGroupRow[]
@@ -38,6 +40,7 @@ export function rosterSectionRenderers({
userSections,
roster,
allMeta,
groupRooms,
dragging,
rosterSectionCollapsed,
toggleRosterSection,
@@ -76,7 +79,7 @@ export function rosterSectionRenderers({
}
const nested = Boolean(keyPrefix)
const blocks = groupRowsBySection(rows, userSections, allMeta)
const blocks = groupRowsBySection(rows, userSections, allMeta, groupRooms)
return (
blocks
@@ -95,15 +98,24 @@ export function rosterSectionRenderers({
return (
<SectionDropZone
isSource={
Boolean(dragging) && block.rows.some(row => row.kind !== 'group' && botRosterKey(row.bot) === dragging)
Boolean(dragging) &&
block.rows.some(row =>
row.kind === 'group' ? groupDragKey(row.name) === dragging : botRosterKey(row.bot) === dragging
)
}
key={key}
nested={nested}
onDropBot={rosterKey => {
// `block.id` is null for Unassigned, which is exactly the value
// both movers want for "clear the assignment".
if (rosterKey.startsWith(GROUP_DRAG_PREFIX)) {
moveGroupChatsToSection([rosterKey.slice(GROUP_DRAG_PREFIX.length)], block.id)
return
}
const bot = roster.find(row => botRosterKey(row) === rosterKey)
// `block.id` is null for Unassigned, which is exactly the value
// moveBotsToSection wants for "clear the assignment".
if (bot) {
void moveBotsToSection([bot], block.id)
}
@@ -173,7 +185,9 @@ export function rosterSectionRenderers({
onToggle={() => toggleRosterSection(sectionId)}
tip={`${sortedGroupRows.length} global group chat${sortedGroupRows.length === 1 ? '' : 's'}`}
/>
{collapsed ? null : <div className="grid min-w-0 gap-0.5">{sortedGroupRows.map(renderGroupRow)}</div>}
{collapsed ? null : (
<div className="grid min-w-0 gap-0.5">{renderUserSections(sortedGroupRows, 'groups:')}</div>
)}
</div>
)
}

View File

@@ -51,7 +51,7 @@ import { botNeedsHandleLabel, rosterGatewayOptions } from './roster-sections'
import { botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './routing'
import { activeBots, useTurnBusy } from './row-helpers'
import type { BotMeta, GatewaySource, GroupMember, RosterActivityFilter, RosterKindFilter, RosterRow } from './types'
import { $botSections, $draggingBot } from './user-sections'
import { $botSections, $draggingBot, type SectionDialogState } from './user-sections'
import { useEscapeCancelsBotDrag } from './user-sections-ui'
// ── roster pane ──────────────────────────────────────────────────────────────
@@ -244,10 +244,8 @@ export function BotsPane() {
useEscapeCancelsBotDrag()
// The one name dialog serves both New section (optionally filing the bot
// whose menu opened it) and Rename.
const [sectionDialog, setSectionDialog] = useState<
null | { bot?: RosterRow; mode: 'create' } | { id: string; mode: 'rename'; name: string }
>(null)
// or group whose menu opened it) and Rename.
const [sectionDialog, setSectionDialog] = useState<SectionDialogState>(null)
const [grouping, setGrouping] = useState<null | RosterRow>(null)
const [query, setQuery] = useState('')
@@ -431,6 +429,7 @@ export function BotsPane() {
key={`group:${row.name}`}
members={row.members}
onDisband={setDeletingGroup}
onNewSection={target => setSectionDialog({ group: target, mode: 'create' })}
onOpen={openGroupChat}
sortedGroupRows={sortedGroupRows}
/>
@@ -442,6 +441,7 @@ export function BotsPane() {
userSections,
roster,
allMeta,
groupRooms,
dragging,
rosterSectionCollapsed,
toggleRosterSection,

View File

@@ -180,6 +180,13 @@ export interface GroupChat {
rosterOrder?: number
/** Read when ordering rooms; no write site in the plugin today. */
pinned?: boolean
/** Which user-made sidebar section this group chat is filed under
* (`user-sections.ts`). Like a bot's `sectionId` it is membership on the
* item, but a group's only durable identity is its room record, so the
* field rides the room's plugin-storage persistence — local, like the
* section list itself, and deliberately absent from the bounded gateway
* sync projection, which carries conversations, not sidebar layout. */
sectionId?: null | string
/** How far each `<thread>::<member>` has read into `log`. Required: unlike
* the gateway-sourced shapes above, a room record is plugin-owned — every
* writer (hydrate, server-sync merge, updateGroupChat, room reset) seeds

View File

@@ -0,0 +1,123 @@
/**
* Group chats file into user-made sections exactly like bots — with the one
* structural difference the model encodes: a bot's membership is a field on
* its profile meta (profile sync carries it), while a group's is a field on
* its room record, because that record is the only durable identity a group
* has. Filing must ride the room's own durable persistence path, never a
* parallel list.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { saveBotMeta, storage } = vi.hoisted(() => ({
saveBotMeta: vi.fn<(bot: { name: string }, patch: Record<string, unknown>) => Promise<unknown>>(),
storage: new Map<string, unknown>()
}))
vi.mock('@hermes/plugin-sdk', async () => {
const { atom } = await import('nanostores')
return { atom, host: {} }
})
vi.mock('./data', async () => {
const { atom } = await import('nanostores')
const $botMeta = atom<Record<string, { sectionId?: null | string }>>({})
const $lastRoster = atom<unknown[]>([])
saveBotMeta.mockImplementation(async (bot: { name: string }, patch: Record<string, unknown>) => {
$botMeta.set({ ...$botMeta.get(), [bot.name]: { ...$botMeta.get()[bot.name], ...patch } })
return { serverOutcome: 'persisted', serverPersisted: true }
})
return {
$botMeta,
$lastRoster,
botRosterKey: (bot: { connectionId?: string; name?: string }) => `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`,
saveBotMeta
}
})
vi.mock('./routing', () => ({
botRosterMeta: (bot: { name: string }, meta: Record<string, unknown>) => meta[bot.name]
}))
vi.mock('./shared', () => ({
getPluginCtx: () => ({
storage: {
get: (key: string, fallback: unknown) => (storage.has(key) ? storage.get(key) : fallback),
set: (key: string, value: unknown) => storage.set(key, value)
}
})
}))
// './group-chat' is deliberately NOT mocked: filing must go through the real
// room-store path (atom + durable plugin-storage record), with only its
// externals (sdk, data, routing, shared) faked above.
import { $botMeta } from './data'
import { $groupChats } from './group-chat'
import type { RosterRow } from './types'
import {
$botSections,
createBotSection,
groupChatSectionId,
groupRowsBySection,
moveGroupChatsToSection,
UNASSIGNED_SECTION_KEY
} from './user-sections'
const row = (name: string) => ({ bot: { name } as RosterRow, kind: 'bot' as const })
const groupRow = (name: string) => ({ kind: 'group' as const, name })
beforeEach(() => {
storage.clear()
$botMeta.set({})
$botSections.set([])
$groupChats.set({})
saveBotMeta.mockClear()
})
describe('user sections — group chats', () => {
it('filing a group writes sectionId on its room record and rides the durable group-chats persistence; clearing returns it to the bucket', () => {
const section = createBotSection('XYZ')!
moveGroupChatsToSection(['Team Chat'], section.id)
// Membership lives on the room, not on any bot's profile: no bot-meta
// write happens for a group filing.
expect($groupChats.get()['Team Chat']?.sectionId).toBe(section.id)
expect(saveBotMeta).not.toHaveBeenCalled()
// The durable record in plugin storage carries it — the same record a
// reload hydrates rooms from, so the filing survives a restart.
const durable = storage.get('group-chats') as Record<string, { sectionId?: null | string }>
expect(durable['Team Chat']?.sectionId).toBe(section.id)
// Unfiling clears the assignment on the room and persists the clear.
moveGroupChatsToSection(['Team Chat'], null)
expect(groupChatSectionId('Team Chat', $groupChats.get())).toBeNull()
expect((storage.get('group-chats') as Record<string, { sectionId?: null | string }>)['Team Chat']?.sectionId).toBeNull()
})
it('grouping seats group rows per their room record section; unfiled or dangling groups fall to Unassigned', () => {
const section = createBotSection('XYZ')!
moveGroupChatsToSection(['Team Chat'], section.id)
// A room whose section was deleted keeps a dangling id — it must land in
// Unassigned, not vanish (same safety bots get).
$groupChats.set({ ...$groupChats.get(), Ghosted: { sectionId: 'sec-deleted' } as never })
$botMeta.set({ nanox: { sectionId: section.id } })
const rows = [row('nanox'), groupRow('Team Chat'), groupRow('Ghosted'), groupRow('Room')]
const blocks = groupRowsBySection(rows, $botSections.get(), $botMeta.get(), $groupChats.get())
expect(blocks.map(block => [block.key, block.rows.length])).toEqual([
[`section:${section.id}`, 2],
[UNASSIGNED_SECTION_KEY, 2]
])
// Every row lands exactly once, groups included.
expect(blocks.flatMap(block => block.rows)).toHaveLength(rows.length)
})
})

View File

@@ -24,9 +24,17 @@
import { atom } from 'nanostores'
import { $botMeta, saveBotMeta } from './data'
import { $groupChats, updateGroupChat } from './group-chat'
import { botRosterMeta } from './routing'
import { getPluginCtx } from './shared'
import type { BotMeta, RosterRow } from './types'
import type { BotMeta, GroupChat, RosterRow } from './types'
/** The one section-name dialog's state: New section (optionally filing the
* bot or group whose menu opened it) or Rename. */
export type SectionDialogState =
| null
| { bot?: RosterRow; group?: string; mode: 'create' }
| { id: string; mode: 'rename'; name: string }
export const UNASSIGNED_SECTION_KEY = 'section:unassigned'
export const BOT_SECTIONS_KEY = 'bot-sections-v1'
@@ -185,6 +193,52 @@ export function botSectionId(bot: RosterRow, metaByName: Record<string, BotMeta>
return id ? String(id) : null
}
// ── group chats ──────────────────────────────────────────────────────────────
//
// A group chat files into a section by the same membership-on-the-item rule as
// a bot, but a group has no profile meta to carry the field — its room record
// is its only durable identity. So the assignment is a field on the room and
// rides the room's own persistence (plugin storage), which is also why it is
// deliberately NOT part of the bounded gateway sync projection: that mirror
// carries conversations to other clients, not this machine's sidebar layout —
// the same local scope the section list itself has.
/** The drag payload prefix that marks an in-flight GROUP row (vs a bot's
* roster key). */
export const GROUP_DRAG_PREFIX = 'group:'
export function groupDragKey(name: string): string {
return `${GROUP_DRAG_PREFIX}${name}`
}
/** A group's section, off the live room record. */
export function groupChatSectionId(name: string, rooms: Record<string, GroupChat>): null | string {
const id = rooms?.[name]?.sectionId
return id ? String(id) : null
}
/** File `groups` into a section (`null` clears, back to the group-chat
* bucket). One room write per group whose assignment actually changes,
* through `updateGroupChat` so the durable record and the atom move together. */
export function moveGroupChatsToSection(groups: string[], sectionId: null | string): void {
for (const name of groups || []) {
if (!name || groupChatSectionId(name, $groupChats.get()) === (sectionId || null)) {
continue
}
updateGroupChat(
name,
(room: GroupChat) => ({
...room,
sectionId: sectionId || null
}),
// Layout-only: no reason to publish the conversation projection.
{ sync: false }
)
}
}
export interface SectionBlock<TRow> {
id: null | string
key: string
@@ -196,12 +250,15 @@ export interface SectionBlock<TRow> {
* Split roster rows into section blocks, in section order, with Unassigned
* last. Pure, and returns EVERY row exactly once: a row whose `sectionId`
* names a section that no longer exists lands in Unassigned rather than
* vanishing, which is what makes deleting a section safe.
* vanishing, which is what makes deleting a section safe. Group rows seat per
* their room record's `sectionId` (`rooms`); a group with no room yet is
* unassigned.
*/
export function groupRowsBySection<TRow extends { bot?: RosterRow } | RosterRow>(
rows: TRow[],
sections: unknown,
metaByName: Record<string, BotMeta>
metaByName: Record<string, BotMeta>,
groupRooms: Record<string, GroupChat> = {}
): SectionBlock<TRow>[] {
const list = normalizeBotSections(sections)
const known = new Set(list.map(s => s.id))
@@ -209,8 +266,10 @@ export function groupRowsBySection<TRow extends { bot?: RosterRow } | RosterRow>
const loose: TRow[] = []
for (const row of rows || []) {
const bot = ((row as { bot?: RosterRow })?.bot || row) as RosterRow
const id = bot ? botSectionId(bot, metaByName) : null
const group = (row as { kind?: string; name?: string })?.kind === 'group' ? row : null
const id = group
? groupChatSectionId(String((group as { name?: string }).name || ''), groupRooms)
: botSectionId((((row as { bot?: RosterRow })?.bot || row) as RosterRow), metaByName)
if (id && known.has(id)) {
byId.get(id)!.push(row)