The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): user-made sections in the bot roster, with drag-and-drop filing
Michael Knaap3d0ac691af7e
diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.tsxindex 31a8a4c8ea5..4fb8ab23f21 100644--- a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.tsx@@ -14,6 +14,9 @@ import {ContextMenuContent,ContextMenuItem,ContextMenuSeparator,+ ContextMenuSub,+ ContextMenuSubContent,+ ContextMenuSubTrigger,ContextMenuTrigger,haptic,host,@@ -62,6 +65,18 @@ import { openRosterBot } from './roster-actions'import { botRosterMeta, botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './routing'import { A2A_PREFIX_RE, botCanonicalSessionId, botRowOwnsWorkspace, previewKind, workerActiveAt } from './row-helpers'import type { GroupMember, RosterRow, SidebarRowLabels } from './types'+import {+ $botPickAnchor,+ $botPicked,+ $botSections,+ $draggingBots,+ $renamingSection,+ BOT_DRAG_MIME,+ botDragPayload,+ botSectionId,+ createBotSection,+ moveBotsToSection+} from './user-sections'// ── bot row ──────────────────────────────────────────────────────────────────@@ -207,15 +222,92 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro// activate a source and resolve the canonical Bot Chat.const open = () => void openRosterBot(bot)+ // MULTI-SELECT AND DRAG live on the row button itself: it already takes+ // pointer events, so the click that opens the bot, the cmd/shift click that+ // picks it, and the drag that files it are one element's gestures. A PLAIN+ // click clears the selection, which is what every list on the platform does.+ const rosterKey = botRosterKey(bot)+ const picked = useValue($botPicked)+ const isPicked = picked.includes(rosterKey)+ const sections = useValue($botSections)+ const currentSectionId = botSectionId(bot, allMeta)++ const onRowClick = (event: React.MouseEvent) => {+ // SHIFT-CLICK RANGE SELECT, anchored at the last plain or cmd-click, the+ // way Finder and Mail anchor a range: a second shift-click grows or shrinks+ // the SAME range instead of re-anchoring wherever the pointer happens to be.+ if (event.shiftKey) {+ event.preventDefault()+ event.stopPropagation()++ // DOCUMENT ORDER, not roster order. The roster renders grouped into+ // section blocks (and gateway sections above those), so two rows adjacent+ // in the flat list can be pages apart on screen. The rendered rows are+ // the only source that cannot disagree with what the user saw.+ const keys = Array.from(+ event.currentTarget.closest('[data-slot="bots-roster"]')?.querySelectorAll('[data-roster-key]') ?? []+ ).map(node => String((node as HTMLElement).dataset.rosterKey || ''))++ const anchorKey = $botPickAnchor.get()+ const anchorIdx = anchorKey ? keys.indexOf(anchorKey) : -1+ const targetIdx = keys.indexOf(rosterKey)++ if (anchorIdx === -1 || targetIdx === -1) {+ $botPicked.set([rosterKey])+ $botPickAnchor.set(rosterKey)++ return+ }++ const [lo, hi] = anchorIdx < targetIdx ? [anchorIdx, targetIdx] : [targetIdx, anchorIdx]++ $botPicked.set(keys.slice(lo, hi + 1))++ return+ }++ if (event.metaKey || event.ctrlKey) {+ event.preventDefault()+ event.stopPropagation()+ $botPicked.set(isPicked ? picked.filter(key => key !== rosterKey) : [...picked, rosterKey])+ $botPickAnchor.set(rosterKey)++ return+ }++ $botPicked.set([])+ $botPickAnchor.set(rosterKey)+ open()+ }++ // What a section action applies to: the multi-selection when this row is in+ // it, otherwise just this row. Never a selection this row is not part of.+ const targets = (): RosterRow[] =>+ isPicked ? $lastRoster.get().filter(row => picked.includes(botRosterKey(row))) : [bot]+const row = (<RowButtonaria-label={rowTooltip}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)',- isActive && 'bg-(--ui-row-active-background)'+ isActive && 'bg-(--ui-row-active-background)',+ isPicked && 'bg-(--ui-row-active-background) ring-1 ring-(--ui-accent)/60')}- onClick={open}+ data-roster-key={rosterKey}+ draggable+ onClick={onRowClick}+ onDragEnd={() => $draggingBots.set([])}+ onDragStart={event => {+ // Drag the whole multi-selection when this row is part of it — the+ // same rule `targets()` uses for the section submenu, so the two+ // gestures can never disagree about what "this" means.+ const keys = isPicked && picked.length ? picked : [rosterKey]++ event.dataTransfer.setData(BOT_DRAG_MIME, botDragPayload(keys))+ event.dataTransfer.effectAllowed = 'move'+ $draggingBots.set(keys)+ }}onPointerEnter={warm}><div className={cn('shrink-0', !sourceStatus.available && 'grayscale opacity-60')}>@@ -381,6 +473,50 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro>{b.bot.newChatWith}</ContextMenuItem>+ <ContextMenuSeparator />+ {/* Filing. Membership is one field on the bot's meta (`sectionId`), so+ this is a one-field write and no list anywhere has to be kept in+ sync with it. */}+ <ContextMenuSub>+ <ContextMenuSubTrigger>+ {isPicked && picked.length > 1 ? `Move ${picked.length} bots to…` : 'Move to section…'}+ </ContextMenuSubTrigger>+ <ContextMenuSubContent>+ {sections.map(section => (+ <ContextMenuItem+ disabled={section.id === currentSectionId}+ key={section.id}+ onSelect={() => {+ moveBotsToSection(targets(), section.id)+ $botPicked.set([])+ }}+ >+ {section.name}+ </ContextMenuItem>+ ))}+ {sections.length ? <ContextMenuSeparator /> : null}+ <ContextMenuItem+ onSelect={() => {+ const section = createBotSection('New section', targets())++ $botPicked.set([])+ $renamingSection.set(section.id)+ }}+ >+ New section…+ </ContextMenuItem>+ {currentSectionId ? (+ <ContextMenuItem+ onSelect={() => {+ moveBotsToSection(targets(), null)+ $botPicked.set([])+ }}+ >+ Unassigned+ </ContextMenuItem>+ ) : null}+ </ContextMenuSubContent>+ </ContextMenuSub>{isDefaultBot(bot) ? null : <ContextMenuSeparator />}{isDefaultBot(bot) ? null : (<ContextMenuItem onSelect={() => onDelete(bot)} variant="destructive">diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.tsx b/apps/desktop/src/plugins/hermes-bots/plugin.tsxindex 059a92e9dd5..fff080a0a38 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.tsx+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx@@ -71,6 +71,7 @@ import { botRosterMeta, botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './roimport { startHideSweepScheduler } from './session-sweep'import { bumpBotOpenGeneration, getBotOpenGeneration, ID, setPluginCtx } from './shared'import type { GroupChat, RosterRow } from './types'+import { loadBotSections } from './user-sections'// ── plugin ───────────────────────────────────────────────────────────────────@@ -94,6 +95,9 @@ 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: PluginContext) {+ // The user's own roster folders. Read once at register; every mutation+ // writes through `persistBotSections`.+ void loadBotSections()setPluginCtx(ctx)const disposeLocales = ctx.i18n.register(BOTS_LOCALES)setGroupChatSyncDisposed(false)diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsxindex 51d22c2c1c4..58950dc5167 100644--- a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx@@ -80,6 +80,19 @@ import { botRosterMeta, botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './roimport { ACTIVE_WINDOW_S, activeBots, BOT_ROSTER_SEARCH_THRESHOLD, rosterActivityMatches } from './row-helpers'import { backfillMessagingProtocol } from './soul'import type { BotMeta, GatewaySource, GroupMember, RosterActivityFilter, RosterKindFilter, RosterRow } from './types'+import {+ $botSections,+ $renamingSection,+ BOT_DRAG_MIME,+ createBotSection,+ deleteBotSection,+ groupRowsBySection,+ moveBotSection,+ moveBotsToSection,+ readBotDragPayload,+ UNASSIGNED_SECTION_KEY+} from './user-sections'+import { UserSectionHeader } from './user-sections-ui'/** Last source inventory returned by the desktop-wide agent roster. */const $lastSources = atom<GatewaySource[]>([])@@ -252,6 +265,10 @@ export function BotsPane() {// it is not part of the shared RosterRow model, so it rides as an extra here.const [deleting, setDeleting] = useState<null | (RosterRow & { path?: string })>(null)const [deletingGroup, setDeletingGroup] = useState<null | { members: GroupMember[]; name: string }>(null)+ // Which section block the pointer is over mid-drag, by section key. One+ // value, not a per-block flag: only one block can be hovered at a time.+ const [dropTarget, setDropTarget] = useState<null | string>(null)+ const userSections = useValue($botSections)const [grouping, setGrouping] = useState<null | RosterRow>(null)const [query, setQuery] = useState('')const [rowKindFilter, setRowKindFilter] = useState<RosterKindFilter>('all')@@ -555,6 +572,92 @@ export function BotsPane() {/>)+ // USER SECTIONS — composed with the gateway sections, not instead of them.+ // When the roster is showing more than one connection the gateway headings+ // still own the top level (that axis answers "where does this run", which no+ // folder name can); user sections group the flat list.+ const renderUserSections = () => {+ // Nothing filed yet, and no folders made: draw the plain list rather than+ // one "Unassigned" heading over the whole roster, which tells you nothing.+ if (!userSections.length) {+ return rosterRows.map(row => (row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot)))+ }++ return (+ groupRowsBySection(rosterRows, userSections, allMeta)+ // An empty Unassigned is not worth a heading; an empty NAMED section+ // is, because it is somewhere the user made and is about to drop into.+ .filter(block => block.id || block.rows.length)+ .map(block => {+ const key = block.id ? `user-section:${block.id}` : UNASSIGNED_SECTION_KEY+ const collapsed = rosterSectionCollapsed(key)++ return (+ <div+ className={cn(+ 'min-w-0 rounded-md transition-colors',+ dropTarget === key && 'bg-(--ui-accent)/10 ring-1 ring-(--ui-accent)/50'+ )}+ key={key}+ onDragLeave={event => {+ // Only clear when the pointer leaves the BLOCK, not when it+ // crosses between the rows inside it — dragleave fires on every+ // child boundary, which otherwise strobes the highlight.+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {+ setDropTarget(null)+ }+ }}+ onDragOver={event => {+ if (!event.dataTransfer.types.includes(BOT_DRAG_MIME)) {+ return+ }++ // preventDefault is what MAKES this a drop target — without it+ // the browser refuses the drop and the cursor stays "no entry".+ event.preventDefault()+ event.dataTransfer.dropEffect = 'move'+ setDropTarget(key)+ }}+ onDrop={event => {+ const keys = readBotDragPayload(event.dataTransfer.getData(BOT_DRAG_MIME))++ setDropTarget(null)++ if (!keys.length) {+ return+ }++ event.preventDefault()+ // `block.id` is null for Unassigned, which is exactly the value+ // moveBotsToSection wants for "clear the assignment".+ moveBotsToSection(+ roster.filter(row => keys.includes(botRosterKey(row))),+ block.id+ )+ }}+ >+ <UserSectionHeader+ collapsed={collapsed}+ count={block.rows.length}+ id={block.id}+ name={block.name}+ onDelete={() => block.id && deleteBotSection(block.id, roster)}+ onMove={delta => block.id && moveBotSection(block.id, delta)}+ onToggle={() => toggleRosterSection(key)}+ />+ {collapsed ? null : (+ <div className="grid min-w-0 gap-0.5">+ {block.rows.map(row =>+ row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot, `${key}:`)+ )}+ </div>+ )}+ </div>+ )+ })+ )+ }+const renderGatewaySection = (section: ResolvedRosterGatewaySection) => {const sectionId = `gateway:${section.id}`const collapsed = rosterSectionCollapsed(sectionId)@@ -647,6 +750,18 @@ export function BotsPane() {<Codicon className="mr-1.5" name="organization" />{b.group.newTitle}</DropdownMenuItem>+ <DropdownMenuItem+ onSelect={() => {+ const section = createBotSection('New section')++ // Straight into the rename: a folder you cannot name at the+ // moment you make it is a folder called "New section".+ $renamingSection.set(section.id)+ }}+ >+ <Codicon className="mr-1.5" name="folder" />+ New section+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu></div>@@ -814,14 +929,14 @@ export function BotsPane() {/></div>) : (- <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain" data-slot="bots-roster"><div className="grid w-full min-w-0 gap-0.5 px-1.5 pb-2">{showGatewaySections? [sortedGroupRows.length ? renderGroupChatSection() : null,...gatewaySections.sections.map(renderGatewaySection)].filter(Boolean)- : rosterRows.map(row => (row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot)))}+ : renderUserSections()}{showHiddenSection ? (<divclassName="mt-1 border-t border-(--ui-stroke-tertiary) pt-1"diff --git a/apps/desktop/src/plugins/hermes-bots/types.ts b/apps/desktop/src/plugins/hermes-bots/types.tsindex e21298f544b..7770c1b5d9e 100644--- a/apps/desktop/src/plugins/hermes-bots/types.ts+++ b/apps/desktop/src/plugins/hermes-bots/types.ts@@ -53,6 +53,12 @@ export interface SessionPreview {/** Per-bot presentation state, persisted in the profile's `ui_meta`. */export interface BotMeta {+ /** Which user-made section this bot is filed under (`user-sections.ts`).+ * Membership lives on the BOT, not as a member list on the section: a bot+ * can only be in one place, deleting a section cannot orphan anybody, and+ * the assignment rides the same profile.yaml sync every other bot setting+ * already uses — so sections follow the profile to another machine. */+ sectionId?: null | stringcolor?: string/** Set when the user has customized the avatar, so defaults stop applying. */custom?: booleandiff --git a/apps/desktop/src/plugins/hermes-bots/user-sections-ui.tsx b/apps/desktop/src/plugins/hermes-bots/user-sections-ui.tsxnew file mode 100644index 00000000000..86d84670fd5--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/user-sections-ui.tsx@@ -0,0 +1,173 @@+/**+ * The chrome for user sections: one foldable heading with an inline rename and+ * a small menu. The model is in `user-sections.ts`; nothing here holds state+ * that outlives a caret.+ */++import {+ cn,+ Codicon,+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuTrigger,+ DisclosureCaret,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ RowButton,+ useValue+} from '@hermes/plugin-sdk'+import { useState } from 'react'++import { $botSections, $renamingSection, renameBotSection, setBotSectionIcon } from './user-sections'++interface UserSectionHeaderProps {+ collapsed: boolean+ count: number+ /** null for Unassigned, which has no record and therefore no menu. */+ id: null | string+ name: string+ onDelete: () => void+ onMove: (delta: number) => void+ onToggle: () => void+}++export function UserSectionHeader({+ collapsed,+ count,+ id,+ name,+ onDelete,+ onMove,+ onToggle+}: UserSectionHeaderProps) {+ const renamingId = useValue($renamingSection)+ // Absent means show it, so only an explicit false hides the glyph.+ const showIcon = useValue($botSections).find(section => section.id === id)?.icon !== false+ const renaming = Boolean(id) && renamingId === id+ const [draft, setDraft] = useState(name)++ const commit = () => {+ $renamingSection.set(null)++ if (id && draft.trim() && draft.trim() !== name) {+ renameBotSection(id, draft)+ }+ }++ // RIGHT-CLICK IS THE SAME MENU. The ⋯ button only appears on hover and is a+ // small target; right-clicking the heading is what people actually try+ // first. Both drive the identical actions, so neither can drift.+ const sectionMenu = id ? (+ <ContextMenuContent>+ <ContextMenuItem+ onSelect={() => {+ setDraft(name)+ $renamingSection.set(id)+ }}+ >+ Rename+ </ContextMenuItem>+ <ContextMenuItem onSelect={() => setBotSectionIcon(id, !showIcon)}>+ {showIcon ? 'Hide icon' : 'Show icon'}+ </ContextMenuItem>+ <ContextMenuItem onSelect={() => onMove(-1)}>Move up</ContextMenuItem>+ <ContextMenuItem onSelect={() => onMove(1)}>Move down</ContextMenuItem>+ <ContextMenuItem onSelect={onDelete} variant="destructive">+ Delete section (keeps its bots)+ </ContextMenuItem>+ </ContextMenuContent>+ ) : null++ const header = (+ <div className="group/section mt-1 flex w-full min-w-0 items-center gap-1 pr-1">+ {renaming ? (+ <input+ autoFocus+ className="ml-2 min-w-0 flex-1 rounded-[3px] border border-(--ui-stroke-secondary) bg-(--ui-bg-elevated) px-1 py-0.5 text-[0.6875rem] font-semibold uppercase tracking-wider outline-none"+ onBlur={commit}+ onChange={event => setDraft(event.target.value)}+ onKeyDown={event => {+ if (event.key === 'Enter') {+ commit()+ }++ if (event.key === 'Escape') {+ $renamingSection.set(null)+ }+ }}+ value={draft}+ />+ ) : (+ <RowButton+ aria-expanded={!collapsed}+ className={cn(+ 'flex min-w-0 flex-1 items-center gap-1.5 rounded-md px-2 py-1.5 text-left',+ 'text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)',+ 'transition-colors hover:bg-(--chrome-action-hover) hover:text-(--ui-text-secondary)'+ )}+ onClick={onToggle}+ onDoubleClick={() => {+ if (id) {+ setDraft(name)+ $renamingSection.set(id)+ }+ }}+ >+ <DisclosureCaret open={!collapsed} />+ {showIcon ? <Codicon className="shrink-0" name={id ? 'folder' : 'inbox'} /> : null}+ <span className="min-w-0 truncate">{name}</span>+ <span aria-hidden className="min-w-0 flex-1" />+ <span className="shrink-0 font-normal tabular-nums">{count}</span>+ </RowButton>+ )}+ {/* Unassigned has no record to rename, reorder or delete — it is+ whatever is left over — so it gets no menu rather than a menu of+ disabled items. */}+ {id && !renaming ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ aria-label={`${name} section options`}+ className="shrink-0 rounded-md p-0.5 text-(--ui-text-quaternary) opacity-0 transition hover:text-foreground group-hover/section:opacity-100 focus-visible:opacity-100"+ type="button"+ >+ <Codicon name="ellipsis" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onSelect={() => {+ setDraft(name)+ $renamingSection.set(id)+ }}+ >+ Rename+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => setBotSectionIcon(id, !showIcon)}>+ {showIcon ? 'Hide icon' : 'Show icon'}+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onMove(-1)}>Move up</DropdownMenuItem>+ <DropdownMenuItem onSelect={() => onMove(1)}>Move down</DropdownMenuItem>+ {/* Deleting a section keeps every bot in it — they fall back to+ Unassigned. Said plainly here so nobody has to find out. */}+ <DropdownMenuItem onSelect={onDelete} variant="destructive">+ Delete section (keeps its bots)+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}+ </div>+ )++ return sectionMenu ? (+ <ContextMenu>+ <ContextMenuTrigger asChild>{header}</ContextMenuTrigger>+ {sectionMenu}+ </ContextMenu>+ ) : (+ header+ )+}diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections.test.ts b/apps/desktop/src/plugins/hermes-bots/user-sections.test.tsnew file mode 100644index 00000000000..e345f823066--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/user-sections.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'++import {+ botDragPayload,+ groupRowsBySection,+ normalizeBotSections,+ readBotDragPayload,+ UNASSIGNED_SECTION_KEY+} from './user-sections'++const bot = (name: string) => ({ name }) as never++describe('user sections model', () => {+ it('normalizes: drops blanks and duplicates, defaults a name, keeps only an explicit icon=false', () => {+ const out = normalizeBotSections([+ { id: 'a', name: 'Clients' },+ { id: 'a', name: 'dupe' },+ { id: '', name: 'blank' },+ { id: 'b', name: ' ' },+ { id: 'c', name: 'Bare', icon: false },+ { id: 'd', name: 'On', icon: true },+ null,+ 'junk'+ ])++ expect(out).toEqual([+ { id: 'a', name: 'Clients' },+ { id: 'b', name: 'Section' },+ { id: 'c', name: 'Bare', icon: false },+ { id: 'd', name: 'On' }+ ])+ })++ it('groups every row exactly once, unknown sections fall to Unassigned, Unassigned is last', () => {+ const rows = [+ { bot: bot('nanox'), kind: 'bot' },+ { bot: bot('scout'), kind: 'bot' },+ { bot: bot('ghost'), kind: 'bot' },+ { kind: 'group', name: 'Room' }+ ] as never[]++ const meta = {+ nanox: { sectionId: 'sec-clients' },+ scout: { sectionId: 'sec-workforce' },+ ghost: { sectionId: 'sec-deleted' }+ } as never++ const blocks = groupRowsBySection(rows, [{ id: 'sec-clients', name: 'Clients' }, { id: 'sec-workforce', name: 'Workforce' }], meta)++ expect(blocks.map(b => [b.key, b.rows.length])).toEqual([+ ['section:sec-clients', 1],+ ['section:sec-workforce', 1],+ [UNASSIGNED_SECTION_KEY, 2]+ ])+ expect(blocks.flatMap(b => b.rows)).toHaveLength(rows.length)+ })++ it('drag payload round-trips and a foreign drop yields no keys', () => {+ expect(readBotDragPayload(botDragPayload(['a', 'b']))).toEqual(['a', 'b'])+ expect(readBotDragPayload('not json')).toEqual([])+ expect(readBotDragPayload(JSON.stringify({ nope: 1 }))).toEqual([])+ expect(readBotDragPayload(JSON.stringify(['ok', 3, '', null]))).toEqual(['ok'])+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections.ts b/apps/desktop/src/plugins/hermes-bots/user-sections.tsnew file mode 100644index 00000000000..b995cffa82b--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/user-sections.ts@@ -0,0 +1,326 @@+/**+ * USER SECTIONS — folders the user makes, not folders the topology makes.+ *+ * The roster already had sections (`roster-sections.tsx`), but only AUTOMATIC+ * ones: one per gateway connection, plus the group-chat bucket. Those answer+ * "where does this bot run", which is not the question you are asking when you+ * want NanoX and MODE filed together under "Clients".+ *+ * So this is a SECOND axis, and it composes with the first rather than+ * replacing it: the gateway sections still render exactly as they did whenever+ * the roster is showing more than one connection, and user sections group the+ * flat list underneath. Two deliberate choices, carried over from the branch+ * this is ported from:+ *+ * * The membership lives on the BOT (`sectionId` in its ui_meta), not as a+ * member list on the section. A bot can only be in one place, deleting a+ * section cannot orphan anybody, and the assignment rides the same+ * profile.yaml sync every other bot setting already uses — so sections+ * follow the profile to another machine.+ * * "Unassigned" is not a section. It is whatever is left, always drawn, and+ * it is where members of a deleted section land. It has no record, so its+ * collapsed state keys off this literal.+ *+ * Pure model + two session atoms. No JSX — the pane composes it.+ */++import { atom } from 'nanostores'++import { $botMeta, saveBotMeta } from './data'+import { botRosterMeta } from './routing'+import { getPluginCtx } from './shared'+import type { BotMeta, RosterRow } from './types'++export const UNASSIGNED_SECTION_KEY = 'section:unassigned'+export const BOT_SECTIONS_KEY = 'bot-sections-v1'++export interface BotSection {+ id: string+ name: string+ /** Draw the folder glyph beside the name. Default on; a user who wants a+ * bare list of names can turn it off per section. Optional so every+ * section persisted before this existed still reads as "show it". */+ icon?: boolean+}++/** `[{ id, name }]`, in display order. */+export const $botSections = atom<BotSection[]>([])++/** Roster keys the user has multi-selected (cmd/ctrl-click). Session-only: a+ * selection is a gesture in progress, not a setting. */+export const $botPicked = atom<string[]>([])++/** The row a shift-click range extends FROM — the last plain click or the+ * last end of a shift-range, mirroring how Finder/Mail anchor a range so a+ * second shift-click re-anchors from where you are, not where you started. */+export const $botPickAnchor = atom<null | string>(null)++/**+ * The roster key of the bot being renamed in place, and the text in the field.+ *+ * MODULE state, not component state. It was `useState` inside `BotRow`, and+ * double-click did nothing: opening a bot resolves its source and canonical+ * chat, which changes `botRosterKey` — so the row REMOUNTS between the click+ * and the double-click, and the flag was gone before it could paint. The+ * handler fired every time; the state did not survive to the next render.+ * (Verified in the running app: the console log landed, `data-renaming` was+ * still "0".) Keying the caret outside the row is what makes it immune.+ */+export const $renamingBot = atom<null | string>(null)+export const $renamingBotDraft = atom('')++/** The section whose header is currently an editable name field. Session-only+ * by nature: a rename in progress is a caret, not a setting. */+export const $renamingSection = atom<null | string>(null)++export function normalizeBotSections(value: unknown): BotSection[] {+ if (!Array.isArray(value)) {+ return []+ }++ const seen = new Set<string>()+ const out: BotSection[] = []++ for (const entry of value) {+ const id = String((entry as BotSection)?.id || '').trim()+ const name = String((entry as BotSection)?.name || '').trim()++ if (!id || seen.has(id)) {+ continue+ }++ seen.add(id)+ out.push({+ id,+ name: name || 'Section',+ // Only ever stored as an explicit false — absent means on.+ ...((entry as BotSection)?.icon === false ? { icon: false } : {})+ })+ }++ return out+}++export function persistBotSections(next: unknown): Promise<void> {+ const value = normalizeBotSections(next)++ $botSections.set(value)++ try {+ return Promise.resolve(getPluginCtx()?.storage?.set?.(BOT_SECTIONS_KEY, value))+ .then(() => undefined)+ .catch(() => undefined)+ } catch {+ // No storage — sections live for this window only, which is strictly+ // better than the pane throwing while the user drags a bot into a folder.+ return Promise.resolve()+ }+}++/** Read the persisted list back at plugin start. */+/**+ * The roster's three standing sections, with FIXED ids.+ *+ * Membership lives on each bot as `ui_meta.hermes-bots.sectionId`, which is a+ * file in the profile — but the section RECORDS live in plugin storage, which+ * is localStorage. Generated ids would mean the two halves could never be set+ * up together from outside the app: a profile.yaml written by hand would point+ * at a section id that does not exist, and the bot would silently land in+ * Unassigned. Fixed ids are what make the pairing writable from either side.+ *+ * Seeding is ADDITIVE and idempotent: a section already present by id is left+ * exactly as it is — including a rename, an icon setting, and its position —+ * and anything the user made themselves is untouched. Deleting one of these on+ * purpose is the one thing this cannot tell apart from never having had it, so+ * a deleted standing section comes back on next load; renaming it is the way+ * to make it yours.+ */+const SEEDED_SECTIONS: BotSection[] = [+ { id: 'sec-general', name: 'General' },+ { id: 'sec-workforce', name: 'Workforce' },+ { id: 'sec-clients', name: 'Clients' }+]++export async function loadBotSections(): Promise<void> {+ try {+ const stored = await Promise.resolve(getPluginCtx()?.storage?.get?.(BOT_SECTIONS_KEY, []))+ const list = normalizeBotSections(stored)+ const seeded = withSeededSections(list)++ $botSections.set(seeded)++ // Only write back when seeding actually added something, so an ordinary+ // load stays a read.+ if (seeded.length !== list.length) {+ void persistBotSections(seeded)+ }+ } catch {+ $botSections.set(normalizeBotSections(SEEDED_SECTIONS))+ }+}+++function withSeededSections(list: BotSection[]): BotSection[] {+ const known = new Set(list.map(section => section.id))+ const missing = SEEDED_SECTIONS.filter(section => !known.has(section.id))++ // Seeded sections lead, in their declared order, so a fresh roster reads+ // General / Workforce / Clients rather than in load order.+ return missing.length ? [...missing, ...list] : list+}++function newSectionId(): string {+ return `sec-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`+}++/** Create a section and move `bots` into it. Returns the new section. */+export function createBotSection(name: string, bots: RosterRow[] = []): BotSection {+ const section: BotSection = { id: newSectionId(), name: String(name || '').trim() || 'New section' }++ void persistBotSections([...$botSections.get(), section])+ moveBotsToSection(bots, section.id)++ return section+}++/** Show or hide the folder glyph on one section's heading. */+export function setBotSectionIcon(id: string, icon: boolean): void {+ void persistBotSections($botSections.get().map(s => (s.id === id ? { ...s, icon } : s)))+}++export function renameBotSection(id: string, name: string): void {+ const clean = String(name || '').trim()++ if (!clean) {+ return+ }++ void persistBotSections($botSections.get().map(s => (s.id === id ? { ...s, name: clean } : s)))+}++/** Delete the section only. Its members are not deleted and not hidden — they+ * fall back to Unassigned, which is the whole reason membership lives on the+ * bot rather than on the section. */+export function deleteBotSection(id: string, roster: RosterRow[] = []): void {+ void persistBotSections($botSections.get().filter(s => s.id !== id))+ moveBotsToSection(+ (roster || []).filter(bot => botSectionId(bot, $botMeta.get()) === id),+ null+ )+}++export function moveBotSection(id: string, delta: number): void {+ const list = $botSections.get()+ const from = list.findIndex(s => s.id === id)+ const to = from + delta++ if (from < 0 || to < 0 || to >= list.length) {+ return+ }++ const next = list.slice()+ const [moved] = next.splice(from, 1)++ next.splice(to, 0, moved!)+ void persistBotSections(next)+}++/** `null` clears the assignment (back to Unassigned). */+export function moveBotsToSection(bots: RosterRow[], sectionId: null | string): void {+ for (const bot of bots || []) {+ if (bot) {+ void saveBotMeta(bot, { sectionId: sectionId || null })+ }+ }+}++export function botSectionId(bot: RosterRow, metaByName: Record<string, BotMeta>): null | string {+ const id = botRosterMeta(bot, metaByName)?.sectionId++ return id ? String(id) : null+}++export interface SectionBlock<TRow> {+ id: null | string+ key: string+ name: string+ rows: 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.+ */+export function groupRowsBySection<TRow extends { bot?: RosterRow } | RosterRow>(+ rows: TRow[],+ sections: unknown,+ metaByName: Record<string, BotMeta>+): SectionBlock<TRow>[] {+ const list = normalizeBotSections(sections)+ const known = new Set(list.map(s => s.id))+ const byId = new Map<string, TRow[]>(list.map(s => [s.id, [] as TRow[]]))+ 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++ if (id && known.has(id)) {+ byId.get(id)!.push(row)+ } else {+ loose.push(row)+ }+ }++ const blocks: SectionBlock<TRow>[] = list.map(section => ({+ id: section.id,+ key: `section:${section.id}`,+ name: section.name,+ rows: byId.get(section.id) || []+ }))++ blocks.push({ id: null, key: UNASSIGNED_SECTION_KEY, name: 'Unassigned', rows: loose })++ return blocks+}++// ── drag and drop ────────────────────────────────────────────────────────────+//+// Filing a bot by dragging it onto a section heading, which is the gesture+// people reach for first and the one the context menu's "Move to section…" was+// standing in for.+//+// A CUSTOM MIME TYPE, not `text/plain`: the roster shares a window with the+// composer, the transcript and the tab strip, all of which accept dropped+// text. A private type means a bot dragged onto any of them is simply not a+// valid payload there, instead of pasting its roster key into someone's+// message. `dataTransfer.types` is readable during dragover (the DATA itself+// is not, by design), so a drop target can still light up correctly.++export const BOT_DRAG_MIME = 'application/x-hermes-bot-keys'++/** Roster keys in flight during a drag. Session-only, and cleared on dragend+ * even when the drop lands outside any target — a stuck "dragging" highlight+ * outlives the gesture and reads as a broken pane. */+export const $draggingBots = atom<string[]>([])++/** Keys being dragged, as a payload string. Multi-select drags the whole+ * selection when the dragged row is part of it — same rule as the section+ * context menu's `targets()`. */+export function botDragPayload(keys: string[]): string {+ return JSON.stringify(keys)+}++/** Read the payload back on drop. Never throws: a foreign or malformed drop+ * yields no keys and the drop is simply ignored. */+export function readBotDragPayload(raw: string): string[] {+ try {+ const parsed: unknown = JSON.parse(raw)++ return Array.isArray(parsed) ? parsed.filter((k): k is string => typeof k === 'string' && Boolean(k)) : []+ } catch {+ return []+ }+}diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 832c4d45517..bf28c8fb168 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -1517,6 +1517,11 @@ export {ContextMenuContent,ContextMenuItem,ContextMenuSeparator,+ // Submenus: Bot Mode files a bot into a user section from its row menu, and+ // a flat list of every folder would swamp the items already there.+ ContextMenuSub,+ ContextMenuSubContent,+ ContextMenuSubTrigger,ContextMenuTrigger} from '@/components/ui/context-menu'export { CopyButton } from '@/components/ui/copy-button'