Skip to content

The agent that grows with you

chore(desktop): lint the bot-mode modules clean

Brooklyn Nicholson0fececa733b7
diff --git a/apps/desktop/src/plugins/hermes-bots/avatar-image.ts b/apps/desktop/src/plugins/hermes-bots/avatar-image.ts
index 40613c58b7a..3a1f1918124 100644
--- a/apps/desktop/src/plugins/hermes-bots/avatar-image.ts
+++ b/apps/desktop/src/plugins/hermes-bots/avatar-image.ts
@@ -14,6 +14,7 @@ import { getPluginCtx } from './shared'
export function normalizeAvatarImage(dataUrl: string, edge = 256): Promise<string> {
return new Promise(resolve => {
const img = new Image()
+
img.onload = () => {
try {
const canvas = document.createElement('canvas')
@@ -27,32 +28,40 @@ export function normalizeAvatarImage(dataUrl: string, edge = 256): Promise<strin
resolve(dataUrl)
}
}
+
img.onerror = () => resolve(dataUrl)
img.src = dataUrl
})
}
+
export function pickImageFromDevice(): Promise<null | string> {
return new Promise(resolve => {
const input = document.createElement('input')
input.type = 'file'
input.accept = 'image/png,image/jpeg,image/webp,image/gif'
+
input.onchange = () => {
const file = input.files?.[0]
+
if (!file) {
return resolve(null)
}
+
if (file.size > 15_000_000) {
host.notify({
kind: 'error',
message: getPluginCtx()?.i18n.t('avatar.imageTooLarge') ?? 'Image too large (max 15MB).'
})
+
return resolve(null)
}
+
const reader = new FileReader()
reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : null)
reader.onerror = () => resolve(null)
reader.readAsDataURL(file)
}
+
input.click()
})
}
@@ -63,10 +72,12 @@ export function pickImageFromDevice(): Promise<null | string> {
* Only `true` is sticky. */
export const $imagenAvailable = atom<boolean | null>(null)
let imagenProbeInflight: Promise<void> | null = null
+
export function probeImagen() {
if (imagenProbeInflight) {
return imagenProbeInflight
}
+
imagenProbeInflight = host
.request<{ available?: boolean }>('image.generate', {
probe: true
@@ -76,8 +87,10 @@ export function probeImagen() {
.finally(() => {
imagenProbeInflight = null
})
+
return imagenProbeInflight
}
+
/** `image.generate`'s reply. `image_data` is a data URL (works over remote
* gateways); `image` is the raw backend URL fallback. */
export interface GeneratedImage {
@@ -89,12 +102,14 @@ export interface GeneratedImage {
export async function generateAvatarImage(bot: string, title?: string, description?: string): Promise<string | undefined> {
const who = [title || bot, description].filter(Boolean).join(' — ')
+
const res = await host.request<GeneratedImage>('image.generate', {
prompt:
`Cute minimal robot avatar for an AI agent named "${who}". ` +
'Friendly simple mascot face, bold flat vector style, solid color background, centered, no text.',
aspect_ratio: 'square'
})
+
if (!res?.success) {
throw new Error(res?.error || 'generation failed')
}
@@ -110,13 +125,17 @@ export function isBackfilledFacePng(dataUrl: null | string | undefined) {
if (!dataUrl || typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/png;base64,')) {
return false
}
+
try {
const bin = atob(dataUrl.slice('data:image/png;base64,'.length).slice(0, 48))
+
if (bin.length < 24) {
return false
}
+
const w = (bin.charCodeAt(16) << 24) | (bin.charCodeAt(17) << 16) | (bin.charCodeAt(18) << 8) | bin.charCodeAt(19)
const h = (bin.charCodeAt(20) << 24) | (bin.charCodeAt(21) << 16) | (bin.charCodeAt(22) << 8) | bin.charCodeAt(23)
+
return w === 160 && h === 160
} catch {
return false
diff --git a/apps/desktop/src/plugins/hermes-bots/avatar-picker.tsx b/apps/desktop/src/plugins/hermes-bots/avatar-picker.tsx
index c4ae8c13f7d..b3446cc174d 100644
--- a/apps/desktop/src/plugins/hermes-bots/avatar-picker.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/avatar-picker.tsx
@@ -60,6 +60,7 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
const [tab, setTab] = useState('bot')
const [describe, setDescribe] = useState('')
const [genBusy, setGenBusy] = useState(false)
+
if (imagen === null) {
void probeImagen()
}
@@ -68,36 +69,46 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
// tab — the gateway may have restarted with image.generate since.
const goTab = (id: string) => {
setTab(id)
+
if (id === 'generate' && $imagenAvailable.get() === false) {
$imagenAvailable.set(null)
void probeImagen()
}
}
+
const upload = async () => {
const raw = await pickImageFromDevice()
+
if (raw) {
onImage(await normalizeAvatarImage(raw))
}
}
+
const generate = async () => {
if (genBusy) {
return
}
+
setGenBusy(true)
+
try {
const custom = describe.trim()
+
const img = custom
? await (async () => {
const res = await host.request<GeneratedImage>('image.generate', {
prompt: `${custom}. Avatar for an AI agent: centered, bold flat vector style, solid color background, no text.`,
aspect_ratio: 'square'
})
+
if (!res?.success) {
throw new Error(res?.error || 'generation failed')
}
+
return res.image_data || res.image
})()
: await generateAvatarImage(generateSeed?.name || 'agent', generateSeed?.title, generateSeed?.description)
+
if (img) {
onImage(await normalizeAvatarImage(img))
}
@@ -107,10 +118,12 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
setGenBusy(false)
}
}
+
return (
<div className="grid justify-items-center gap-3">
{/* Tab pills: Bot | Generate | Upload | Pet */}
<SegmentedControl
+ onChange={goTab}
options={[
{ id: 'bot', label: 'Bot' },
{ id: 'generate', label: 'Generate' },
@@ -118,10 +131,9 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
{ id: 'pet', label: 'Pet' }
]}
value={tab}
- onChange={goTab}
/>
{image && tab !== 'generate' ? (
- <Button type="button" variant="ghost" size="sm" onClick={() => onImage(null)}>
+ <Button onClick={() => onImage(null)} size="sm" type="button" variant="ghost">
{b.avatar.removeImage}
</Button>
) : null}
@@ -130,29 +142,30 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
(() => {
const { seedPart, kind } = parseBlobShape(shape, pickerName)
const locked = Boolean(seedPart)
+
return (
<div className="grid justify-items-center gap-3">
{/* Silhouette pins: Auto (name decides) + the six blob kinds. */}
<div className="grid grid-cols-4 justify-items-center gap-1.5">
{['', ...BLOB_KINDS].map(k => (
<RowButton
- key={k || 'auto'}
- title={k || 'Auto — the name decides'}
className={cn(
'flex items-center justify-center rounded-md transition-colors hover:bg-(--chrome-action-hover)',
k === kind && !image && 'ring-1 ring-(--ui-accent)'
)}
- style={{
- width: 44,
- height: 44
- }}
+ key={k || 'auto'}
onClick={() => {
onImage(null)
onShape(blobShapeString(seedPart, k))
}}
+ style={{
+ width: 44,
+ height: 44
+ }}
+ title={k || 'Auto — the name decides'}
>
{k ? (
- <BotFace shape={blobShapeString(seedPart, k)} color={avatarColor(color, pickerName)} size={32} name={pickerName} />
+ <BotFace color={avatarColor(color, pickerName)} name={pickerName} shape={blobShapeString(seedPart, k)} size={32} />
) : (
<span className="text-[0.6rem] text-(--ui-text-tertiary)">Auto</span>
)}
@@ -161,27 +174,27 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
</div>
<div className="flex items-center gap-1">
<Button
- type="button"
- variant="ghost"
- size="sm"
onClick={() => {
onImage(null)
onShape(blobShapeString(Math.random().toString(36).slice(2, 10), kind))
}}
+ size="sm"
+ type="button"
+ variant="ghost"
>
- <Codicon name="refresh" className="mr-1 text-[0.8rem]" />
+ <Codicon className="mr-1 text-[0.8rem]" name="refresh" />
{b.avatar.randomize}
</Button>
<Button
- type="button"
- variant="ghost"
+ onClick={() => onShape(blobShapeString(locked ? '' : pickerName, kind))}
size="sm"
title={
locked ? b.avatar.unlockFollowsName : 'Keep this exact face even if the name changes'
}
- onClick={() => onShape(blobShapeString(locked ? '' : pickerName, kind))}
+ type="button"
+ variant="ghost"
>
- <Codicon name={locked ? 'unlock' : 'lock'} className="mr-1 text-[0.8rem]" />
+ <Codicon className="mr-1 text-[0.8rem]" name={locked ? 'unlock' : 'lock'} />
{locked ? 'Unlock' : 'Lock face'}
</Button>
</div>
@@ -189,11 +202,11 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
{locked ? 'Face locked — renaming won\u2019t change it.' : 'Face follows the name.'}
</div>
<Button
- type="button"
- variant="ghost"
- size="sm"
className="text-(--ui-text-tertiary)"
onClick={() => onShape(defaultShapeFor(pickerName))}
+ size="sm"
+ type="button"
+ variant="ghost"
>
{b.avatar.classicShapes}
</Button>
@@ -205,22 +218,22 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
<div className="grid grid-cols-4 justify-items-center gap-1.5">
{(blobatarSvg ? ['blobatar', ...AVATAR_PICKER_SHAPES] : AVATAR_PICKER_SHAPES).map(s => (
<RowButton
- key={s}
- title={s === 'blobatar' ? b.avatar.blobFromName : undefined}
className={cn(
'flex items-center justify-center rounded-md transition-colors hover:bg-(--chrome-action-hover)',
s === shape && !image && 'ring-1 ring-(--ui-accent)'
)}
- style={{
- width: 44,
- height: 44
- }}
+ key={s}
onClick={() => {
onImage(null)
onShape(s)
}}
+ style={{
+ width: 44,
+ height: 44
+ }}
+ title={s === 'blobatar' ? b.avatar.blobFromName : undefined}
>
- <BotFace shape={s} color={avatarColor(color, pickerName)} size={32} name={pickerName} />
+ <BotFace color={avatarColor(color, pickerName)} name={pickerName} shape={s} size={32} />
</RowButton>
))}
</div>
@@ -238,21 +251,21 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
<div className="grid w-full gap-2">
<Textarea
className="min-h-16 text-xs"
+ onChange={event => setDescribe(event.target.value)}
placeholder={b.avatar.describePlaceholder}
value={describe}
- onChange={event => setDescribe(event.target.value)}
/>
<Button
- type="button"
- variant="secondary"
className="w-full justify-center"
disabled={genBusy}
onClick={generate}
+ type="button"
+ variant="secondary"
>
{genBusy ? (
- <GlyphSpinner spinner="breathe" className="mr-1 text-[0.8rem]" />
+ <GlyphSpinner className="mr-1 text-[0.8rem]" spinner="breathe" />
) : (
- <Codicon name="sparkle" className="mr-1 text-[0.8rem]" />
+ <Codicon className="mr-1 text-[0.8rem]" name="sparkle" />
)}
{genBusy ? 'Generating…' : 'Generate'}
</Button>
@@ -271,8 +284,8 @@ export function AvatarPicker({ shape, color, image, onShape, onColor, onImage, g
)
) : null}
{tab === 'upload' ? (
- <Button type="button" variant="secondary" className="w-full justify-center" onClick={upload}>
- <Codicon name="device-camera" className="mr-1 text-[0.8rem]" />
+ <Button className="w-full justify-center" onClick={upload} type="button" variant="secondary">
+ <Codicon className="mr-1 text-[0.8rem]" name="device-camera" />
Choose an image…
</Button>
) : null}
diff --git a/apps/desktop/src/plugins/hermes-bots/avatar.tsx b/apps/desktop/src/plugins/hermes-bots/avatar.tsx
index 5c2e96e0d59..96b95933757 100644
--- a/apps/desktop/src/plugins/hermes-bots/avatar.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/avatar.tsx
@@ -29,16 +29,20 @@ export const AVATAR_PICKER_SHAPES = ['circle', 'blob', 'squircle', 'pill', 'tria
/** xorshift PRNG seeded from a string — stable across sessions/platforms. */
function sigilRng(text: string) {
let h = 2166136261
+
for (const ch of text) {
h ^= ch.charCodeAt(0)
h = Math.imul(h, 16777619)
}
+
let state = h >>> 0 || 88675123
+
return () => {
state ^= state << 13
state ^= state >>> 17
state ^= state << 5
state >>>= 0
+
return state / 4294967296
}
}
@@ -60,6 +64,7 @@ function sigilGeometry(name: string, seed: number): SigilGeometry {
const gy = (j: number) => 8 + j * 6 // 5 rows: 8..32
const strokes: string[] = []
const segments = 4 + Math.floor(rng() * 3)
+
for (let k = 0; k < segments; k++) {
const x1 = Math.floor(rng() * 3) // left half incl. center
const y1 = Math.floor(rng() * 5)
@@ -78,11 +83,13 @@ function sigilGeometry(name: string, seed: number): SigilGeometry {
// spine down the axis grounds every variant
strokes.push(`M20 ${gy(0)} L20 ${gy(4)}`)
const ring = rng() > 0.45 ? 'M20 4 L36 20 L20 36 L4 20 Z' : null
+
return {
strokes: strokes.join(' '),
ring
}
}
+
/** Perceptual luminance — eyes/pupils flip light on dark bodies (ink, oxblood). */
function isDarkColor(hex: string) {
try {
@@ -90,16 +97,20 @@ function isDarkColor(hex: string) {
const r = (n >> 16) & 255
const g = (n >> 8) & 255
const b = n & 255
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b < 110
} catch {
return false
}
}
+
export function defaultShapeFor(name: string): AvatarShape {
let hash = 0
+
for (const ch of name) {
hash = (hash * 31 + ch.charCodeAt(0)) >>> 0
}
+
return AVATAR_SHAPES[hash % AVATAR_SHAPES.length]
}
@@ -133,6 +144,7 @@ const BLOB_KIND_TRAIT: Record<string, number> = {
sun: 0.965,
triangle: 0.99
}
+
export function isBlobShape(shape: null | string | undefined) {
return shape === 'blobatar' || (typeof shape === 'string' && shape.startsWith('blobatar:'))
}
@@ -145,20 +157,24 @@ interface ParsedBlobShape {
/** The pinned seed alone, empty when the face follows the name. */
seedPart: string
}
+
export function parseBlobShape(shape: null | string | undefined, name: string | undefined): ParsedBlobShape {
const parts = typeof shape === 'string' ? shape.split(':') : []
const seedPart = parts[1] || ''
const kind = BLOB_KINDS.includes(parts[2]) ? parts[2] : ''
+
return {
seed: seedPart || name || 'agent',
seedPart,
kind
}
}
+
export function blobShapeString(seedPart: string, kind: string) {
if (kind) {
return `blobatar:${seedPart}:${kind}`
}
+
return seedPart ? `blobatar:${seedPart}` : 'blobatar'
}
@@ -168,15 +184,19 @@ function blobMarkup(shape: null | string | undefined, name: string, size: number
if (!blobatarSvg) {
return null
}
+
const { seed, kind } = parseBlobShape(shape, name)
+
const opts: { size: number; traits?: Record<string, number> } = {
size
}
+
if (kind) {
opts.traits = {
shape: BLOB_KIND_TRAIT[kind]
}
}
+
try {
return blobatarSvg(seed, opts).replace('<svg ', '<svg data-bot-face=' + JSON.stringify(name) + ' ')
} catch {
@@ -201,6 +221,7 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
if (shape.startsWith('sigil-')) {
const seed = Number(shape.slice(6)) || 0
const { strokes, ring } = sigilGeometry(botName, seed)
+
const sw: FacePathProps = {
fill: 'none',
stroke: color,
@@ -208,19 +229,22 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
strokeLinecap: 'round',
strokeLinejoin: 'round'
}
+
return (
<g>
- {ring ? <path d={ring} fill="none" stroke={color} strokeWidth={1.2} opacity={0.5} /> : null}
+ {ring ? <path d={ring} fill="none" opacity={0.5} stroke={color} strokeWidth={1.2} /> : null}
<path d={strokes} {...sw} />
</g>
)
}
+
const stroke: FacePathProps = {
fill: color,
stroke: color,
strokeWidth: 7,
strokeLinejoin: 'round'
}
+
const edge: FacePathProps = {
fill: 'none',
stroke: 'rgba(0,0,0,0.4)',
@@ -228,12 +252,14 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
strokeLinejoin: 'round',
strokeLinecap: 'round'
}
+
const face: FacePathProps = {
fill: color,
stroke: 'rgba(0,0,0,0.4)',
strokeWidth: 1.4,
strokeLinejoin: 'round'
}
+
switch (shape) {
// ── platonic solids ──
case 'tetrahedron':
@@ -243,6 +269,7 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
<path d="M20 5 L20 25 M4 33 L20 25 M36 33 L20 25" {...edge} />
</g>
)
+
case 'cube':
return (
<g>
@@ -250,6 +277,7 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
<path d="M7 11 L20 18 L33 11 M20 18 L20 36" {...edge} />
</g>
)
+
case 'octahedron':
return (
<g>
@@ -257,6 +285,7 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
<path d="M4 20 L36 20 M20 3 L20 37" {...edge} />
</g>
)
+
case 'dodecahedron':
return (
<g>
@@ -273,6 +302,7 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
/>
</g>
)
+
case 'icosahedron':
return (
<g>
@@ -291,21 +321,28 @@ function shapeNode(shape: string, color: string, botName = 'agent') {
// ── legacy flat shapes (stored picks from earlier versions) ──
case 'squircle':
- return <rect x={3} y={3} width={34} height={34} rx={11} fill={color} />
+ return <rect fill={color} height={34} rx={11} width={34} x={3} y={3} />
+
case 'pill':
- return <rect x={2} y={7} width={36} height={26} rx={13} fill={color} />
+ return <rect fill={color} height={26} rx={13} width={36} x={2} y={7} />
+
case 'triangle':
return <path d="M20 5.5 L36 33.5 L4 33.5 Z" {...stroke} />
+
case 'hexagon':
return <path d="M20 3.5 L34.5 11.75 L34.5 28.25 L20 36.5 L5.5 28.25 L5.5 11.75 Z" {...stroke} />
+
case 'cloud':
return <path d="M11 32 a7.5 7.5 0 0 1 -1 -14.9 A9.5 9.5 0 0 1 29 12.5 A7 7 0 0 1 30 32 Z" fill={color} />
+
case 'drop':
return <path d="M20 3 C20 3 6 20 6 27 a14 13.5 0 0 0 28 0 C34 20 20 3 20 3 Z" fill={color} />
+
default:
- return <circle cx={20} cy={20} r={17.5} fill={color} />
+ return <circle cx={20} cy={20} fill={color} r={17.5} />
}
}
+
const EYE_Y = {
// solids: eyes sit on the upper face region, clear of the busiest edges
tetrahedron: 26,
@@ -331,10 +368,13 @@ const EYE_X = {
dodecahedron: [16.5, 23.5],
icosahedron: [16.5, 23.5]
}
+
/** One point in the 40x40 face box. */
type FacePoint = [number, number]
+
function cubicAt(p0: FacePoint, p1: FacePoint, p2: FacePoint, p3: FacePoint, t: number): FacePoint {
const u = 1 - t
+
return [
u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0],
u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]
@@ -345,18 +385,23 @@ function cubicAt(p0: FacePoint, p1: FacePoint, p2: FacePoint, p3: FacePoint, t:
function sampleDropRing(steps: number): FacePoint[] {
const pts: FacePoint[] = []
const n = Math.max(8, Math.floor(steps / 3))
+
for (let i = 0; i < n; i++) {
pts.push(cubicAt([20, 3], [20, 3], [6, 20], [6, 27], i / n))
}
+
for (let i = 0; i <= n; i++) {
const t = (i / n) * Math.PI
pts.push([20 - 14 * Math.cos(t), 27 + 13.5 * Math.sin(t)])
}
+
for (let i = 1; i <= n; i++) {
pts.push(cubicAt([34, 27], [34, 20], [20, 3], [20, 3], i / n))
}
+
return pts
}
+
/** A center-parameterized elliptical arc, as sampleArc walks it. */
interface FaceArc {
cx: number
@@ -366,6 +411,7 @@ interface FaceArc {
ry: number
theta1: number
}
+
function svgArc(
x1: number,
y1: number,
@@ -381,6 +427,7 @@ function svgArc(
let rx2 = rx * rx
let ry2 = ry * ry
const lam = (dx * dx) / rx2 + (dy * dy) / ry2
+
if (lam > 1) {
const s = Math.sqrt(lam)
rx *= s
@@ -388,30 +435,40 @@ function svgArc(
rx2 = rx * rx
ry2 = ry * ry
}
+
const num = rx2 * ry2 - rx2 * dy * dy - ry2 * dx * dx
const den = rx2 * dy * dy + ry2 * dx * dx
let sq = Math.sqrt(Math.max(0, num / den))
+
if (fa === fs) {
sq = -sq
}
+
const cx = sq * ((rx * dy) / ry) + (x1 + x2) / 2
const cy = sq * ((-ry * dx) / rx) + (y1 + y2) / 2
+
const ang = (ux: number, uy: number, vx: number, vy: number) => {
const n = Math.hypot(ux, uy) * Math.hypot(vx, vy) || 1
let a = Math.acos(Math.max(-1, Math.min(1, (ux * vx + uy * vy) / n)))
+
if (ux * vy - uy * vx < 0) {
a = -a
}
+
return a
}
+
const theta1 = ang(1, 0, (x1 - cx) / rx, (y1 - cy) / ry)
let dtheta = ang((x1 - cx) / rx, (y1 - cy) / ry, (x2 - cx) / rx, (y2 - cy) / ry)
+
if (!fs && dtheta > 0) {
dtheta -= Math.PI * 2
}
+
if (fs && dtheta < 0) {
dtheta += Math.PI * 2
}
+
return {
cx,
cy,
@@ -421,12 +478,15 @@ function svgArc(
dtheta
}
}
+
function sampleArc(arc: FaceArc, n: number): FacePoint[] {
const pts: FacePoint[] = []
+
for (let i = 0; i < n; i++) {
const th = arc.theta1 + arc.dtheta * (i / n)
pts.push([arc.cx + arc.rx * Math.cos(th), arc.cy + arc.ry * Math.sin(th)])
}
+
return pts
}
@@ -449,9 +509,11 @@ function sampleCloudRing(steps: number): FacePoint[] {
pts.push(...sampleArc(a1, n1))
pts.push(...sampleArc(a2, n2))
pts.push(...sampleArc(a3, n3))
+
for (let i = 0; i < n4; i++) {
pts.push([30 + (11 - 30) * (i / n4), 32])
}
+
return pts
}
@@ -460,19 +522,24 @@ function sampleCloudRing(steps: number): FacePoint[] {
* a dumped point cloud. */
function sampleFaceRing(shape: null | string | undefined, steps = 52): FacePoint[] {
const kind = (shape || '').startsWith('sigil-') ? 'circle' : shape
+
if (kind === 'drop' || kind === 'teardrop') {
return sampleDropRing(steps)
}
+
if (kind === 'cloud') {
return sampleCloudRing(steps)
}
+
const pts: FacePoint[] = []
+
for (let i = 0; i < steps; i++) {
const a = (i / steps) * Math.PI * 2 - Math.PI / 2
const c = Math.cos(a)
const s = Math.sin(a)
let rx = 16
let ry = 16
+
if (kind === 'circle') {
rx = ry = 16.2
} else if (kind === 'blob') {
@@ -502,10 +569,13 @@ function sampleFaceRing(shape: null | string | undefined, steps = 52): FacePoint
} else {
rx = ry = 16.2
}
+
pts.push([20 + rx * c, 20 + ry * s])
}
+
return pts
}
+
function projectFacePoint(x: number, y: number, turn: number, tilt: number, roll: number): FacePoint {
const dx = x - 20
const dy = y - 20
@@ -514,16 +584,21 @@ function projectFacePoint(x: number, y: number, turn: number, tilt: number, roll
const yr = dx * Math.sin(r) + dy * Math.cos(r)
const sx = 0.74 + 0.26 * Math.abs(Math.cos((turn * Math.PI) / 180))
const sy = 0.8 + 0.2 * Math.abs(Math.cos((tilt * Math.PI) / 180))
+
return [20 + xr * sx, 20 + yr * sy]
}
+
function ringToPath(pts: FacePoint[]) {
if (!pts.length) {
return ''
}
+
let d = `M${pts[0][0].toFixed(2)} ${pts[0][1].toFixed(2)}`
+
for (let i = 1; i < pts.length; i++) {
d += `L${pts[i][0].toFixed(2)} ${pts[i][1].toFixed(2)}`
}
+
return d + 'Z'
}
@@ -556,6 +631,7 @@ function facePose(mood: FaceMood | string, t: number): FacePose {
d2: 0.2 + 0.8 * Math.max(0, Math.sin(t * 2.6 - 1.4))
}
}
+
return {
turn: Math.sin(t * 0.5) * 1.5,
tilt: Math.sin(t * 0.27),
@@ -568,12 +644,14 @@ function facePose(mood: FaceMood | string, t: number): FacePose {
d2: 0
}
}
+
/** The eyes and catchlights are positioned with raw numbers.
* `Element.setAttribute` declares a string value and the DOM coerces —
* stringifying at each call site would be a behavior change. */
interface NumericAttrNode {
setAttribute(name: string, value: number | string): void
}
+
function paintMathFace(svg: SVGSVGElement, t: number) {
const mood = svg.getAttribute('data-hb-mood') || 'idle'
const shape = svg.getAttribute('data-hb-shape') || 'circle'
@@ -584,6 +662,7 @@ function paintMathFace(svg: SVGSVGElement, t: number) {
const el: NumericAttrNode | null = svg.querySelector('[data-hb-el]')
const er: NumericAttrNode | null = svg.querySelector('[data-hb-er]')
const dots = svg.querySelectorAll('[data-hb-dot]')
+
if (body) {
if (shape === 'cloud') {
body.setAttribute('d', 'M11 32 a7.5 7.5 0 0 1 -1 -14.9 A9.5 9.5 0 0 1 29 12.5 A7 7 0 0 1 30 32 Z')
@@ -592,13 +671,16 @@ function paintMathFace(svg: SVGSVGElement, t: number) {
body.setAttribute('d', ringToPath(ring))
}
}
+
const eyeY = (shape === 'cloud' ? 22 : 17.2) + pose.gazeY
const eyeL = 15.4 + pose.gazeX
const eyeR = 24.6 + pose.gazeX
+
if (el) {
el.setAttribute('cx', eyeL)
el.setAttribute('cy', eyeY)
}
+
if (er) {
er.setAttribute('cx', eyeR)
er.setAttribute('cy', eyeY)
@@ -609,17 +691,21 @@ function paintMathFace(svg: SVGSVGElement, t: number) {
// lower-set eyes.
const hl: NumericAttrNode | null = svg.querySelector('[data-hb-hl-l]')
const hr: NumericAttrNode | null = svg.querySelector('[data-hb-hl-r]')
+
if (hl) {
hl.setAttribute('cx', eyeL - 0.6)
hl.setAttribute('cy', eyeY - 0.7)
}
+
if (hr) {
hr.setAttribute('cx', eyeR - 0.6)
hr.setAttribute('cy', eyeY - 0.7)
}
+
if (open) {
open.setAttribute('opacity', pose.blink ? '0' : '1')
}
+
if (shut) {
shut.setAttribute(
'd',
@@ -627,6 +713,7 @@ function paintMathFace(svg: SVGSVGElement, t: number) {
)
shut.setAttribute('opacity', pose.blink ? '1' : '0')
}
+
dots.forEach((dot, i) => {
const o = i === 0 ? pose.d0 : i === 1 ? pose.d1 : pose.d2
dot.setAttribute('opacity', String(o))
@@ -634,18 +721,22 @@ function paintMathFace(svg: SVGSVGElement, t: number) {
svg.style.transform = `rotate(${pose.tilt}deg)`
svg.style.transformOrigin = '50% 70%'
}
+
function walkMathFaces(root: Document | ShadowRoot | null, acc: SVGSVGElement[]): SVGSVGElement[] {
if (!root || !root.querySelectorAll) {
return acc
}
+
root.querySelectorAll<SVGSVGElement>('svg[data-hb-math]').forEach(node => acc.push(node))
root.querySelectorAll('*').forEach(el => {
if (el.shadowRoot) {
walkMathFaces(el.shadowRoot, acc)
}
})
+
return acc
}
+
/** The single shared face clock, parked on `window` so a second plugin load
* adopts the running one instead of starting a rival rAF loop. */
interface FaceClock {
@@ -658,16 +749,20 @@ declare global {
__hbFaceClock?: FaceClock
}
}
+
export function startFaceClock() {
if (typeof window === 'undefined') {
return
}
+
if (window.__hbFaceClock) {
// Already initialized (possibly parked) — make sure it's awake. BotFace
// renders route here, so a face mounting is what wakes a dormant clock.
window.__hbFaceClock.wake()
+
return
}
+
const t0 = performance.now()
// A large roster can mount hundreds of faces. Observe the cached nodes so
// off-screen cards do not consume a full animation frame by themselves.
@@ -676,10 +771,12 @@ export function startFaceClock() {
// Fed from IntersectionObserver entries, whose `target` is a plain Element.
const visibleFaces = new Set<Element>()
const observedFaces = new Set<SVGSVGElement>()
+
const observer =
typeof IntersectionObserver === 'function'
? new IntersectionObserver(entries => {
let becameVisible = false
+
for (const entry of entries) {
if (entry.isIntersecting) {
visibleFaces.add(entry.target)
@@ -695,12 +792,16 @@ export function startFaceClock() {
}
})
: null
+
const scanFaces = () => {
faces = walkMathFaces(document, [])
+
if (!observer) {
return
}
+
const currentFaces = new Set(faces)
+
for (const svg of observedFaces) {
if (!currentFaces.has(svg)) {
observer.unobserve(svg)
@@ -708,6 +809,7 @@ export function startFaceClock() {
visibleFaces.delete(svg)
}
}
+
for (const svg of faces) {
if (!observedFaces.has(svg)) {
observedFaces.add(svg)
@@ -723,8 +825,10 @@ export function startFaceClock() {
scanFaces()
lastScan = now
}
+
const t = (now - t0) / 1000
const facesToPaint = observer ? visibleFaces : faces
+
for (const svg of facesToPaint) {
if (svg.isConnected) {
// Both caches only ever hold nodes matched by `svg[data-hb-math]`.
@@ -741,10 +845,12 @@ export function startFaceClock() {
// idleWhen as `() => boolean`; null is falsy so the loop keeps running as
// intended today. Hence the assertion at the idleWhen call below.
const idle = () => faces.length === 0 || (observer && visibleFaces.size === 0)
+
const teardownCaches = () => {
if (observer) {
observer.disconnect()
}
+
visibleFaces.clear()
observedFaces.clear()
faces = []
@@ -759,6 +865,7 @@ export function startFaceClock() {
fps: 15,
idleWhen: idle as () => boolean
})
+
window.__hbFaceClock = {
stop: () => {
loop.dispose()
@@ -770,6 +877,7 @@ export function startFaceClock() {
loop.wake()
}
}
+
return
}
@@ -778,11 +886,14 @@ export function startFaceClock() {
let rafId = 0
let dormant = false
let stopped = false
+
const tick = (now: number) => {
if (stopped) {
return
}
+
rafId = 0
+
// 15fps is smooth at avatar scale and bounds SVG/DOM churn. The clock
// still uses rAF so Chromium can pause it when the window is occluded.
if (!document.hidden && now - lastPaint >= 1000 / 15) {
@@ -793,27 +904,35 @@ export function startFaceClock() {
// Park instead of burning frames + 1Hz whole-document shadow walks.
if (idle()) {
dormant = true
+
return
}
+
rafId = window.requestAnimationFrame(tick)
}
+
const wake = () => {
if (stopped || !dormant) {
return
}
+
dormant = false
// Faces may have mounted/unmounted while parked — rescan on first tick.
lastScan = -Infinity
rafId = window.requestAnimationFrame(tick)
}
+
const stop = () => {
stopped = true
+
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
+
teardownCaches()
}
+
window.__hbFaceClock = {
stop,
wake
@@ -846,12 +965,13 @@ interface BotFaceProps {
*/
export function BotFace({ shape, color, image, size = 36, name = 'agent', mood = 'idle' }: BotFaceProps) {
startFaceClock()
+
if (image) {
return (
<img
- src={image}
alt=""
aria-hidden
+ src={image}
style={{
width: size,
height: size,
@@ -870,19 +990,20 @@ export function BotFace({ shape, color, image, size = 36, name = 'agent', mood =
// SDK predates the export.
if (isBlobShape(shape)) {
const markup = blobMarkup(shape, name, size)
+
if (markup) {
return (
<span
aria-hidden
+ dangerouslySetInnerHTML={{
+ __html: markup
+ }}
style={{
width: size,
height: size,
display: 'block',
lineHeight: 0
}}
- dangerouslySetInnerHTML={{
- __html: markup
- }}
/>
)
}
@@ -897,17 +1018,19 @@ export function BotFace({ shape, color, image, size = 36, name = 'agent', mood =
if (shape.startsWith('sigil-')) {
const eyes = (
<g>
- <circle cx={16} cy={14} r={2.4} fill={color} />
- <circle cx={24} cy={14} r={2.4} fill={color} />
+ <circle cx={16} cy={14} fill={color} r={2.4} />
+ <circle cx={24} cy={14} fill={color} r={2.4} />
</g>
)
+
return (
- <svg data-bot-face={name} viewBox="0 0 40 40" width={size} height={size} aria-hidden>
+ <svg aria-hidden data-bot-face={name} height={size} viewBox="0 0 40 40" width={size}>
{shapeNode(shape, color, name)}
{eyes}
</svg>
)
}
+
const working = mood === 'work'
const eyeFill = isDarkColor(color) ? 'rgba(232,220,195,0.95)' : 'rgba(0,0,0,0.85)'
// Catchlight contrast follows the pupil, not the body: dark pupils get the
@@ -921,50 +1044,51 @@ export function BotFace({ shape, color, image, size = 36, name = 'agent', mood =
// (and their catchlights) start at the cloud position instead of jumping
// there on the first clock paint.
const eyeY0 = shape === 'cloud' ? 22 : 17.2
+
return (
<svg
+ aria-hidden
data-bot-face={name}
data-hb-math="1"
data-hb-mood={working ? 'work' : 'idle'}
data-hb-shape={shape || 'circle'}
- viewBox="0 0 40 44"
- width={size}
height={size}
- aria-hidden
style={{
overflow: 'visible',
display: 'block'
}}
+ viewBox="0 0 40 44"
+ width={size}
>
<path
- data-hb-body="1"
d={
shape === 'cloud'
? 'M11 32 a7.5 7.5 0 0 1 -1 -14.9 A9.5 9.5 0 0 1 29 12.5 A7 7 0 0 1 30 32 Z'
: ringToPath(ring)
}
+ data-hb-body="1"
fill={color}
/>
<g data-hb-open="1">
- <ellipse data-hb-el="1" cx={15.4} cy={eyeY0} rx={2.2} ry={working ? 2.6 : 2.3} fill={eyeFill} />
- <ellipse data-hb-er="1" cx={24.6} cy={eyeY0} rx={2.2} ry={working ? 2.6 : 2.3} fill={eyeFill} />
- <circle data-hb-hl-l="1" cx={14.8} cy={eyeY0 - 0.7} r={0.65} fill={hlFill} />
- <circle data-hb-hl-r="1" cx={24} cy={eyeY0 - 0.7} r={0.65} fill={hlFill} />
+ <ellipse cx={15.4} cy={eyeY0} data-hb-el="1" fill={eyeFill} rx={2.2} ry={working ? 2.6 : 2.3} />
+ <ellipse cx={24.6} cy={eyeY0} data-hb-er="1" fill={eyeFill} rx={2.2} ry={working ? 2.6 : 2.3} />
+ <circle cx={14.8} cy={eyeY0 - 0.7} data-hb-hl-l="1" fill={hlFill} r={0.65} />
+ <circle cx={24} cy={eyeY0 - 0.7} data-hb-hl-r="1" fill={hlFill} r={0.65} />
</g>
<path
- data-hb-shut="1"
d={`M12.8 ${eyeY0} L18 ${eyeY0} M22 ${eyeY0} L27.2 ${eyeY0}`}
- stroke={eyeFill}
- strokeWidth={2}
- strokeLinecap="round"
+ data-hb-shut="1"
fill="none"
opacity={0}
+ stroke={eyeFill}
+ strokeLinecap="round"
+ strokeWidth={2}
/>
{working ? (
<g>
- <circle data-hb-dot="1" cx={16.4} cy={41.2} r={1.15} fill={color} opacity={rest.d0} />
- <circle data-hb-dot="1" cx={20} cy={41.2} r={1.15} fill={color} opacity={rest.d1} />
- <circle data-hb-dot="1" cx={23.6} cy={41.2} r={1.15} fill={color} opacity={rest.d2} />
+ <circle cx={16.4} cy={41.2} data-hb-dot="1" fill={color} opacity={rest.d0} r={1.15} />
+ <circle cx={20} cy={41.2} data-hb-dot="1" fill={color} opacity={rest.d1} r={1.15} />
+ <circle cx={23.6} cy={41.2} data-hb-dot="1" fill={color} opacity={rest.d2} r={1.15} />
</g>
) : null}
</svg>
@@ -991,6 +1115,7 @@ export function botAppearance(name: string, meta: BotMeta | null | undefined): A
// shape/color they set via the editor (tracked by meta.custom === true).
const isPrimary = (name || '').trim().toLowerCase() === 'default'
const userCustomized = Boolean(meta?.custom)
+
if (isPrimary && !userCustomized) {
return {
shape: 'squircle',
@@ -998,6 +1123,7 @@ export function botAppearance(name: string, meta: BotMeta | null | undefined): A
image: meta?.image || null
}
}
+
return {
shape: meta?.shape || defaultShapeFor(name),
color: meta?.color || profileColor(name),
diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.tsx
index 53ed6ac985e..3977f350f91 100644
--- a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.tsx
@@ -82,6 +82,7 @@ interface BotRowProps {
onGroup: (bot: RosterRow) => void
showHandle?: boolean
}
+
export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowProps) {
const { t } = useI18n()
const b = useBots()
@@ -109,6 +110,7 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
// source-qualified selection is the owner — and it is the only rule that
// can highlight a remote row, which has no focusable local chat.
const isActive = botRowOwnsWorkspace(bot, activeGroup, botChatFocused, focusedOwner, selectedRosterKey)
+
// Turn-busy is a SOCKET fact: only the gateway-home profile can be mid-turn.
const isGatewayHome =
!bot.remoteSource &&
@@ -117,6 +119,7 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
name: activeProfile,
connectionId: activeConnectionId
})
+
const { shape, color, image } = botAppearance(bot.name, meta)
// Keep user photos/pets. Drop the 160px SVG backfill so the math face can move.
const photo = Boolean(image && !isBackfilledFacePng(image))
@@ -132,9 +135,11 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
// A live kanban/tool worker counts as activity (#90268): fresh age while it
// runs, falling back to chat activity when it ends.
const workerActive = workerActiveAt(bot)
+
const rowAgeTs = workerActive
? Math.max(activitySession?.last_active || 0, bot.worker_session?.last_active || 0)
: activitySession?.last_active || 0
+
const botMood = workerActive || (isGatewayHome && gatewayState === 'busy') ? 'work' : 'idle'
// Status keys off the canonical Bot Chat — the very session this row opens,
// so the dot and the click can never describe different conversations.
@@ -146,11 +151,13 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
// too or active-gateway bots never badge. Hidden bots keep their entry;
// hiding is display-only.
const attentionByKey = useValue($botAttention)
+
const attention =
attentionByKey[botSelectionKey(bot)] ||
attentionByKey[botRosterKey(bot)] ||
attentionByKey[`${bot?.connectionId || activeConnectionId}::${bot?.name || 'default'}`] ||
null
+
// WHO sent the last message (bot-to-bot DM vs human) — the full stored
// history lives in the canonical chat, not inline.
// Preview identity must match click identity (#88200): when the backend
@@ -158,16 +165,20 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
// profile's most recent (but unrelated) activity. Liveness checks above
// keep last_session semantics: any recent activity means the bot is alive.
const { fromBot } = previewKind(previewSession?.preview)
+
// DM previews read like DMs: strip the delivery prefix, keep the message.
const displayPreview = stripPreviewMarkdown(
fromBot ? (previewSession?.preview || '').replace(A2A_PREFIX_RE, '').trim() || '…' : previewSession?.preview || ''
)
+
const handle = botHandle(bot.name, bot)
const gatewayLabel = bot.connectionLabel || (bot.connectionId === 'local' ? 'This device' : '')
const showDetailsRow = Boolean(showHandle || displayPreview || fromBot)
+
const rowTooltip = [displayName(bot, meta), `@${handle}`, gatewayLabel, sourceStatus.label]
.filter(Boolean)
.join(' · ')
+
const warm = () => {
// Multi-source row: pre-dial the agent's OWN source (feature-detected).
if (bot.sourceScoped && typeof host.warmAgent === 'function') {
@@ -176,11 +187,14 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
} catch {
/* warm is best-effort */
}
+
return
}
+
if (typeof host.warmProfile !== 'function') {
return
}
+
try {
host.warmProfile(bot.name)
} catch {
@@ -191,19 +205,20 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
// Rows and Active Now share the exact-owner open path; only that path may
// activate a source and resolve the canonical Bot Chat.
const open = () => void openRosterBot(bot)
+
const row = (
<RowButton
- onPointerEnter={warm}
- onClick={open}
+ aria-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)'
)}
- aria-label={rowTooltip}
+ onClick={open}
+ onPointerEnter={warm}
>
<div className={cn('shrink-0', !sourceStatus.available && 'grayscale opacity-60')}>
- <BotFace shape={shape} color={avatarColor(color, bot.name)} image={photo ? image : null} size={34} name={bot.name} mood={botMood} />
+ <BotFace color={avatarColor(color, bot.name)} image={photo ? image : null} mood={botMood} name={bot.name} shape={shape} size={34} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-baseline justify-between gap-2">
@@ -215,12 +230,12 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
</span>
{pinned ? (
<Tip label={b.roster.pinned}>
- <Codicon name="pinned" className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" />
+ <Codicon className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" name="pinned" />
</Tip>
) : null}
{hidden ? (
<Tip label={b.roster.hiddenFromRoster}>
- <Codicon name="eye-closed" className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" />
+ <Codicon className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" name="eye-closed" />
</Tip>
) : null}
<Tip label={rowTooltip}>
@@ -230,9 +245,9 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
{attention ? (
<Tip label={BOT_ATTENTION_HINTS[attention.reason] || 'Needs attention'}>
<Codicon
- name="warning"
- className="shrink-0 text-[0.6875rem] text-amber-600 dark:text-amber-300"
aria-label={b.roster.needsAttention}
+ className="shrink-0 text-[0.6875rem] text-amber-600 dark:text-amber-300"
+ name="warning"
/>
</Tip>
) : null}
@@ -256,6 +271,7 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
</div>
</RowButton>
)
+
return (
<ContextMenu>
<ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
@@ -286,9 +302,11 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }: BotRowPro
void saveBotMeta(bot, {
hidden: !hidden
})
+
if (!hidden) {
fallbackSelectionAfterHide(botSelectionKey(bot))
}
+
host.notify({
kind: 'info',
message: hidden
@@ -373,50 +391,57 @@ interface GroupRowProps {
onDisband: (room: { members: GroupMember[]; name: string }) => void
onOpen: (group: string) => void
}
+
export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }: GroupRowProps) {
const { t } = useI18n()
const b = useBots()
const rooms = useValue($groupChats)
+
const room = rooms[group] || {
log: []
}
+
const log = Array.isArray(room.log) ? room.log : []
const last = log.length ? log[log.length - 1] : null
const lastAt = groupLastActivity(room)
// Room previews speak the same handle vocabulary as the roster, mentions
// and the group prompt: the primary profile is @hermes, not @default.
const lastFrom = last?.from?.name || ''
+
const lastHandle = botHandle(
lastFrom || 'bot',
members.find(member => member?.name === lastFrom)
)
+
const preview = last
? `${last.from?.kind === 'user' ? 'You' : `@${lastHandle}`}: ${stripPreviewMarkdown(last.text) || '…'}`
: `${members.length} bots`
+
const availableMembers = members.filter(member => botSourceStatus(member).available).length
const availabilityLabel = `${availableMembers} of ${members.length} available`
+
const row = (
<RowButton
- onClick={() => {
- haptic('tap')
- onOpen(group)
- }}
+ 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)'
)}
- aria-label={`${group}, ${members.length} bots, ${availabilityLabel}`}
+ onClick={() => {
+ haptic('tap')
+ onOpen(group)
+ }}
>
<div className="relative flex w-[34px] shrink-0 items-center justify-center">
{room.image ? (
<img
- src={room.image}
alt=""
className={cn(
'size-8 rounded-md object-cover ring-1 ring-(--ui-stroke-tertiary)',
availableMembers === 0 && 'grayscale opacity-60'
)}
+ src={room.image}
/>
) : (
<span
@@ -431,8 +456,8 @@ export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }
{members.length > 0 && availableMembers < members.length ? (
<Tip label={availabilityLabel}>
<span
- className="absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full bg-(--ui-bg-primary) text-[0.625rem] text-amber-600 ring-1 ring-(--ui-stroke-tertiary) dark:text-amber-300"
aria-label={availabilityLabel}
+ className="absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full bg-(--ui-bg-primary) text-[0.625rem] text-amber-600 ring-1 ring-(--ui-stroke-tertiary) dark:text-amber-300"
>
<Codicon name="debug-disconnect" />
</span>
@@ -444,7 +469,7 @@ export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-medium">{group}</span>
{needsYou ? (
<Tip label={b.group.needsYourInput}>
- <Codicon name="question" className="shrink-0 text-(--ui-accent)" aria-label={b.roster.needsInput} />
+ <Codicon aria-label={b.roster.needsInput} className="shrink-0 text-(--ui-accent)" name="question" />
</Tip>
) : null}
{lastAt ? (
@@ -457,6 +482,7 @@ export function GroupRow({ active, group, members, needsYou, onOpen, onDisband }
</div>
</RowButton>
)
+
return (
<ContextMenu>
<ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
diff --git a/apps/desktop/src/plugins/hermes-bots/bot-state.ts b/apps/desktop/src/plugins/hermes-bots/bot-state.ts
index 80a0d94a2cf..d458ad508c2 100644
--- a/apps/desktop/src/plugins/hermes-bots/bot-state.ts
+++ b/apps/desktop/src/plugins/hermes-bots/bot-state.ts
@@ -47,16 +47,19 @@ export const $openBotChat = atom<{ key: string; openedRegistryId: string; opened
* lifecycle both key off this rather than reading host.state conditionally
* from render. */
export const $botChatFocused = atom(false)
+
export function saveSelectedRosterBot(bot: RosterRow) {
const key = botRosterKey(bot)
$selectedBot.set(botSelectionKey(bot))
$selectedRosterKey.set(key)
+
try {
Promise.resolve(getPluginCtx()?.storage?.set?.('selected-roster-bot-v1', key)).catch(() => undefined)
} catch {
/* storage unavailable — selection lasts for this window */
}
}
+
export function clearSelectedRosterBot(bot: RosterRow) {
clearSelectedRosterKey(botRosterKey(bot))
}
@@ -68,7 +71,9 @@ export function clearSelectedRosterKey(key: string) {
if ($selectedRosterKey.get() !== key) {
return
}
+
$selectedRosterKey.set('')
+
try {
Promise.resolve(getPluginCtx()?.storage?.set?.('selected-roster-bot-v1', '')).catch(() => undefined)
} catch {
@@ -81,17 +86,20 @@ export function clearSelectedRosterKey(key: string) {
export function parseRosterKey(key: null | string | undefined) {
const raw = String(key || '')
const at = raw.indexOf('::')
+
if (at < 0) {
return {
connectionId: '',
name: ''
}
}
+
return {
connectionId: raw.slice(0, at),
name: raw.slice(at + 2)
}
}
+
const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profile
/** Profile that owns the chat currently on screen. Bot Mode opens another
@@ -100,6 +108,7 @@ const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profil
export function focusedMentionProfile() {
return String($focusedBotProfile.get?.() || '').trim() || 'default'
}
+
function fallbackFocusedBotOwner(profile: string = $focusedBotProfile.get?.()) {
const focusedProfile = String(profile || 'default').trim() || 'default'
const activeProfile = String(host.state.profile?.get?.() || 'default').trim() || 'default'
@@ -111,29 +120,34 @@ function fallbackFocusedBotOwner(profile: string = $focusedBotProfile.get?.()) {
if (host.state.focusedSessionProfile && focusedProfile !== activeProfile) {
return null
}
+
const connectionId = String(
host.state.connectionId?.get?.() ||
(typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||
''
).trim()
+
return {
authoritative: false,
connectionId,
profile: focusedProfile
}
}
+
export const $focusedBotOwner = host.state.focusedSessionOwner || {
get: () => fallbackFocusedBotOwner(),
listen: (listener: (value: ReturnType<typeof fallbackFocusedBotOwner>) => void) => {
const emit = (profile: string) => listener(fallbackFocusedBotOwner(profile))
const unbindProfile = $focusedBotProfile.listen(emit)
const unbindConnection = host.state.connectionId?.listen?.(() => emit($focusedBotProfile.get?.()))
+
return () => {
unbindProfile?.()
unbindConnection?.()
}
}
}
+
export function focusedRosterOwner(
owner: {
authoritative?: boolean
@@ -147,9 +161,11 @@ export function focusedRosterOwner(
// fallbackFocusedBotOwner) both key the profile as `profile`, so the
// `owner?.name` arm is unreachable and a name-only owner would be dropped.
const name = String(owner?.profile || owner?.name || '').trim()
+
if (!owner || !name) {
return null
}
+
return {
authoritative: owner.authoritative !== false,
connectionId: String(owner.connectionId || '').trim(),
diff --git a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
index bebb5c2a2d5..f9cdaef2366 100644
--- a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
@@ -76,22 +76,26 @@ const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/
/** Share one in-flight async operation across concurrent callers. Failures
* clear the slot so a later attempt can retry. */
-function singleFlight<T>(ref: { current: null | Promise<T> }, start: () => Promise<T> | T): Promise<T> {
+export function singleFlight<T>(ref: { current: null | Promise<T> }, start: () => Promise<T> | T): Promise<T> {
if (ref.current) {
return ref.current
}
+
let flight: Promise<T>
+
try {
flight = Promise.resolve(start())
} catch (err) {
flight = Promise.reject(err)
}
+
ref.current = flight
flight.catch(() => {
if (ref.current === flight) {
ref.current = null
}
})
+
return flight
}
@@ -109,6 +113,7 @@ interface CreateAgentDialogProps {
open: boolean
roster: RosterRow[]
}
+
export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogProps) {
const { t } = useI18n()
const b = useBots()
@@ -152,6 +157,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
) {
return
}
+
host
.connections()
// host.connections() returns the registry ROWS on current SDKs, but the
@@ -166,6 +172,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
// Remote target = an explicitly picked registry connection that is not the
// one this window is already on.
const remoteTarget = Boolean(targetConnection) && targetConnection !== (activeConnectionId || 'local')
+
const targetLabel = remoteTarget
? (connections || []).find(c => c.id === targetConnection)?.label || targetConnection
: ''
@@ -192,16 +199,19 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
const [createdForCaps, setCreatedForCaps] = useState<null | string>(null)
const [caps, setCaps] = useState<CapabilityCatalog | null>(null)
const [capsFailed, setCapsFailed] = useState(false)
+
const [dirtyCaps, setDirtyCaps] = useState({
skills: false,
toolsets: false,
mcp: false
})
+
const [capFilter, setCapFilter] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<null | string>(null)
const slug = slugify(name)
const valid = slug.length > 0 && NAME_RE.test(slug)
+
// Once the draft profile is materialized (Capabilities tab / MCP setup) it
// shows up in the roster — its OWN slug must not read as "taken".
// A remote-target create is gated by the TARGET machine's roster: a local
@@ -221,11 +231,14 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
// fire-and-forget: a failed cleanup surfaces a toast, never blocks close.
const discardDraft = () => {
const draft = createdRef.current
+
if (!draft) {
return
}
+
createdRef.current = null
flightRef.current = null
+
const discard = remoteTarget
? requestForTarget('cli.exec', {
argv: ['profile', 'delete', draft, '--yes']
@@ -233,6 +246,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
: deleteBot({
name: draft
})
+
void Promise.resolve(discard)
.then(() =>
host.notify({
@@ -242,6 +256,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
)
.catch(err => host.notifyError(err, `Could not clean up draft profile "${draft}"`))
}
+
const reset = () => {
setName('')
setTitle('')
@@ -279,10 +294,12 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
// Capability catalog for the tabs: the profile doesn't exist yet, so show
// what it WILL have — the clone source's catalog, else the main profile's.
const capSource = cloneFrom === '__none__' ? 'default' : cloneFrom
+
const ensureCaps = () => {
if ((caps && caps.source === capSource) || capsFailed) {
return
}
+
Promise.all([
requestForTarget<ProfileDescribeResponse>('profiles.describe', {
name: remoteTarget ? 'default' : capSource
@@ -315,6 +332,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
})
.catch(() => setCapsFailed(true))
}
+
const toggleCap = (kind: 'mcp' | 'skills' | 'toolsets', name: string, enabled: boolean) => {
setDirtyCaps(prev => ({
...prev,
@@ -350,13 +368,16 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
discardDraft()
setCreatedForCaps(null)
}
+
if (createdRef.current) {
return Promise.resolve(createdRef.current)
}
+
const flight = singleFlight(flightRef, async () => {
if (!valid || taken) {
return null
}
+
const descriptionText = [title, description].filter(Boolean).join(' — ')
await requestForTarget('profiles.create', {
name: slug,
@@ -394,16 +415,20 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
ProfileConfigurePayload,
'disabled_skills' | 'enabled_mcp_servers' | 'enabled_toolsets'
> = {}
+
if (dirtyCaps.skills && caps) {
capPayload.disabled_skills = caps.skills.filter(s => !s.enabled).map(s => s.name)
}
+
if (dirtyCaps.toolsets && caps) {
const en = caps.toolsets.filter(t => t.enabled)
capPayload.enabled_toolsets = en.length === caps.toolsets.length || en.length === 0 ? [] : en.map(t => t.name)
}
+
if (dirtyCaps.mcp && caps) {
capPayload.enabled_mcp_servers = caps.mcp.filter(m => m.enabled).map(m => m.name)
}
+
if (Object.keys(capPayload).length) {
await requestForTarget('profiles.configure', {
name: slug,
@@ -413,6 +438,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
} catch {
/* capability application is best-effort */
}
+
if (remoteTarget) {
// The bot lives on ANOTHER machine — local bot-meta is scoped to the
// active gateway, so write appearance/title into the remote
@@ -426,6 +452,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
title: title.trim(),
created: Date.now()
}
+
try {
void requestForTarget('profiles.configure', {
name: slug,
@@ -433,6 +460,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
'hermes-bots': look
}
}).catch(() => undefined)
+
if (avatarImage) {
void requestForTarget('profiles.set_asset', {
name: slug,
@@ -453,26 +481,35 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
created: Date.now()
})
}
+
queryClient.invalidateQueries({
queryKey: ROSTER_KEY
})
+
return slug
})
+
return flight
}
+
const submit = async () => {
if (!valid || taken || busy) {
return
}
+
setBusy(true)
setError(null)
+
try {
const slugCreated = await ensureAgentCreated()
+
if (!slugCreated) {
setBusy(false)
setError('Could not create the bot.')
+
return
}
+
host.notify({
kind: 'success',
message: remoteTarget
@@ -488,6 +525,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
const wasRemote = remoteTarget
reset()
onClose()
+
if (wasRemote) {
// The bot lives on another machine: it appears in the roster via the
// union enumeration; chat routes through its own source. No local
@@ -495,8 +533,10 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
queryClient.invalidateQueries({
queryKey: ROSTER_KEY
})
+
return
}
+
$selectedBot.set(slug)
// Birth the bot's forever chat right away: it introduces itself as
@@ -509,6 +549,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
const sid = await createCanonicalChat(slug, {
kickoff: true
})
+
if (!sid && typeof host.newChat === 'function') {
host.newChat(slug)
}
@@ -522,9 +563,9 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
setError(err instanceof Error ? err.message : String(err))
}
}
+
return (
<Dialog
- open={open}
onOpenChange={value => {
if (!value && !busy) {
// Cancel path (esc / overlay click): a materialized draft profile is
@@ -534,6 +575,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
onClose()
}
}}
+ open={open}
>
<DialogContent
className={advanced ? 'max-w-3xl' : 'max-w-md'} // Native resize handle (bottom-right corner): the dialog becomes a
@@ -560,24 +602,24 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
</DialogHeader>
<div className="grid gap-3.5">
<div className="flex justify-center py-1">
- <BotFace shape={shape} color={avatarColor(color, slug || 'agent')} image={image} size={56} name={slug || 'agent'} />
+ <BotFace color={avatarColor(color, slug || 'agent')} image={image} name={slug || 'agent'} shape={shape} size={56} />
</div>
<AvatarPicker
- shape={shape}
color={color}
- image={image}
- onShape={setShape}
- onColor={setColor}
- onImage={setImage}
generateSeed={{
name: slug || 'agent',
title,
description
}}
+ image={image}
+ onColor={setColor}
+ onImage={setImage}
+ onShape={setShape}
+ shape={shape}
/>
{labeled(
'Name',
- <Input autoFocus placeholder="inbox-triage" value={name} onChange={event => setName(event.target.value)} />
+ <Input autoFocus onChange={event => setName(event.target.value)} placeholder="inbox-triage" value={name} />
)}
{taken ? (
<div className="text-xs text-(--ui-accent)">
@@ -593,7 +635,6 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
? labeled(
'Create on',
<Select
- value={targetConnection || activeConnectionId || 'local'}
onValueChange={value => {
setTargetConnection(value === (activeConnectionId || 'local') ? '' : value)
// The capability catalog and clone list belong to the
@@ -604,6 +645,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
setCapsFailed(false)
setAdvTab('general')
}}
+ value={targetConnection || activeConnectionId || 'local'}
>
<SelectTrigger className="h-8 rounded-md">
<SelectValue />
@@ -625,15 +667,15 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
) : null}
{labeled(
'Title',
- <Input placeholder="Inbox Triage" value={title} onChange={event => setTitle(event.target.value)} />
+ <Input onChange={event => setTitle(event.target.value)} placeholder="Inbox Triage" value={title} />
)}
{labeled(
'Description',
<Textarea
className="min-h-16"
+ onChange={event => setDescription(event.target.value)}
placeholder={b.bot.helpPromptPlaceholder}
value={description}
- onChange={event => setDescription(event.target.value)}
/>
)}
<Button
@@ -643,6 +685,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
if (!v) {
ensureCaps()
}
+
return !v
})
}}
@@ -655,23 +698,10 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
{advanced ? (
<div className="grid gap-3 rounded-md border border-(--ui-stroke-secondary) p-3">
<SegmentedControl
- options={
- SkillsView && (!remoteTarget || skillsViewRoutesConnections)
- ? [
- { id: 'general', label: 'General' },
- { id: 'capabilities', label: 'Capabilities' }
- ]
- : [
- { id: 'general', label: 'General' },
- { id: 'skills', label: 'Skills' },
- { id: 'toolsets', label: 'Tools' },
- { id: 'mcp', label: 'MCP' }
- ]
- }
- value={advTab}
onChange={id => {
setAdvTab(id)
setCapFilter('')
+
if (id === 'capabilities') {
// The live surface needs a real profile —
// materialize it now (same lazy-create door
@@ -683,6 +713,20 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
ensureCaps()
}
}}
+ options={
+ SkillsView && (!remoteTarget || skillsViewRoutesConnections)
+ ? [
+ { id: 'general', label: 'General' },
+ { id: 'capabilities', label: 'Capabilities' }
+ ]
+ : [
+ { id: 'general', label: 'General' },
+ { id: 'skills', label: 'Skills' },
+ { id: 'toolsets', label: 'Tools' },
+ { id: 'mcp', label: 'MCP' }
+ ]
+ }
+ value={advTab}
/>
{advTab === 'general' ? (
<div className="grid gap-3.5">
@@ -690,12 +734,12 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
remoteTarget ? `Clone from profile (on ${targetLabel})` : 'Clone from profile',
<Select
disabled={remoteTarget}
- value={remoteTarget ? 'default' : cloneFrom}
onValueChange={value => {
setCloneFrom(value)
setCaps(null)
setCapsFailed(false)
}}
+ value={remoteTarget ? 'default' : cloneFrom}
>
<SelectTrigger className="h-8 rounded-md">
<SelectValue />
@@ -711,27 +755,28 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
</Select>
)}
<ModelPicker
- value={{
- provider,
- model
- }}
onChange={patch => {
if ('provider' in patch) {
setProvider(patch.provider)
}
+
if ('model' in patch) {
setModel(patch.model)
}
}}
placeholderModel="inherited from launch profile"
+ value={{
+ provider,
+ model
+ }}
/>
{labeled(
'SOUL.md (optional — replaces the generated persona)',
<Textarea
className="min-h-24 font-mono text-xs leading-5"
+ onChange={event => setSoul(event.target.value)}
placeholder={b.avatar.describeHint}
value={soul}
- onChange={event => setSoul(event.target.value)}
/>
)}
<label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)">
@@ -756,7 +801,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
</div>
) : !createdForCaps ? (
<div className="flex justify-center py-4">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
) : SkillsView ? (
<div
@@ -793,7 +838,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
</div>
) : !caps ? (
<div className="flex justify-center py-4">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
) : advTab === 'skills' ? (
noSkills ? (
@@ -804,9 +849,9 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
<div className="grid gap-1.5">
<Input
className="h-7 text-xs"
+ onChange={event => setCapFilter(event.target.value)}
placeholder={b.tools.filterSkills}
value={capFilter}
- onChange={event => setCapFilter(event.target.value)}
/>
<div
className="overflow-y-auto overscroll-contain"
@@ -815,13 +860,13 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
}}
>
<CheckList
+ columns={2}
items={
capFilter.trim()
? caps.skills.filter(s => s.name.toLowerCase().includes(capFilter.trim().toLowerCase()))
: caps.skills
}
onToggle={(name, enabled) => toggleCap('skills', name, enabled)}
- columns={2}
/>
</div>
<div className="text-[0.65rem] leading-4 text-(--ui-text-quaternary)">{`Catalog from ${caps.source} — unchecked skills are disabled after creation.`}</div>
@@ -855,9 +900,9 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
}}
>
<CheckList
+ columns={2}
items={caps.toolsets}
onToggle={(name, enabled) => toggleCap('toolsets', name, enabled)}
- columns={2}
/>
</div>
<div className="text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
@@ -880,8 +925,9 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
m.fromCatalog &&
!m.installed &&
((m.requires || []).length > 0 || (m.auth || '').toLowerCase() === 'oauth')
+
return (
- <label key={m.name} className="flex items-start gap-2 text-xs text-(--ui-text-secondary)">
+ <label className="flex items-start gap-2 text-xs text-(--ui-text-secondary)" key={m.name}>
<Checkbox
checked={!!m.enabled}
disabled={needsSetup}
@@ -896,9 +942,8 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
) : null}
{needsSetup ? (
<McpSetupButton
- profile={createdRef.current}
- entry={m}
ensureProfile={ensureAgentCreated}
+ entry={m}
onDone={() => {
// Setup done: mark installed so the row's
// checkbox un-disables, and enable it.
@@ -923,6 +968,7 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
mcp: true
}))
}}
+ profile={createdRef.current}
/>
) : null}
{m.description ? (
@@ -952,13 +998,13 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPr
</div>
<DialogFooter>
<Button
- variant="ghost"
disabled={busy}
onClick={() => {
discardDraft()
reset()
onClose()
}}
+ variant="ghost"
>
{t.common.cancel}
</Button>
@@ -985,6 +1031,7 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
const [name, setName] = useState('')
const current = botGroups(botRosterMeta(bot, meta))
const groups = knownGroups(meta)
+
const setMembership = (group: string, enabled: boolean) => {
void saveBotMeta(bot, groupMembershipPatch(botRosterMeta(bot, meta), group, enabled))
host.notify({
@@ -994,14 +1041,15 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
: `${displayName(bot, botRosterMeta(bot, meta))} removed from “${group}”`
})
}
+
return (
<Dialog
- open={Boolean(bot)}
onOpenChange={value => {
if (!value) {
onClose()
}
}}
+ open={Boolean(bot)}
>
<DialogContent className="max-w-sm">
<DialogHeader>
@@ -1012,10 +1060,11 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
<div className="grid gap-1.5">
{groups.map(group => {
const enabled = current.includes(group)
+
return (
<label
- key={group}
className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-(--chrome-action-hover)"
+ key={group}
>
<Checkbox checked={enabled} onCheckedChange={checked => setMembership(group, checked === true)} />
<span>{group}</span>
@@ -1029,6 +1078,7 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
onSubmit={event => {
event.preventDefault()
const trimmed = name.trim()
+
if (trimmed) {
setMembership(trimmed, true)
setName('')
@@ -1037,18 +1087,16 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
>
<Input
autoFocus
+ onChange={event => setName(event.target.value)}
placeholder={groups.length ? 'New group…' : 'Group name (e.g. Research)'}
value={name}
- onChange={event => setName(event.target.value)}
/>
- <Button type="submit" size="sm" disabled={!name.trim()}>
+ <Button disabled={!name.trim()} size="sm" type="submit">
Create & join
</Button>
</form>
{current.length ? (
<Button
- variant="ghost"
- size="sm"
className="justify-self-start"
onClick={() =>
void saveBotMeta(bot, {
@@ -1056,6 +1104,8 @@ export function GroupDialog({ bot, onClose }: GroupDialogProps) {
group: null
})
}
+ size="sm"
+ variant="ghost"
>
{b.bot.removeFromAllGroups}
</Button>
@@ -1101,12 +1151,16 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
const selected = selectableRoster.filter(bot => checked[botRosterKey(bot)])
const visible: RosterRow[] = filterBots(selectableRoster, allMeta, query)
const atCap = selected.length >= GROUP_CHAT_MAX_MEMBERS
+
const placeholder = selected.length
? selected.map(bot => displayName(bot, botRosterMeta(bot, allMeta))).join(', ')
: b.group.nameLabel
+
const canCreate = selected.length >= 2 && Boolean(name.trim() || selected.length)
+
const create = () => {
const base = (name.trim() || placeholder).slice(0, 64)
+
if (selected.length < 2 || !base) {
return
}
@@ -1120,13 +1174,16 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
// disbanded-and-recreated group with the SAME display name still gets
// new sessions instead of resuming the old room's by title.
const taken = new Set(liveGroupChatNames())
+
for (const meta of Object.values($botMeta.get() || {})) {
for (const existing of botGroups(meta)) {
taken.add(existing)
}
}
+
const groupName = uniqueGroupChatName(base, taken)
const roomId = mintGroupRoomId()
+
for (const bot of selected) {
void saveBotMeta(bot, groupMembershipPatch(botRosterMeta(bot, allMeta), groupName, true))
}
@@ -1138,9 +1195,11 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
updateGroupChat(groupName, (room: GroupChatRoom) => {
room.members = roomMembers
room.roomId = roomId
+
if (image) {
room.image = image
}
+
return room
})
host.notify({
@@ -1150,14 +1209,15 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
onClose()
onCreated?.(groupName)
}
+
return (
<Dialog
- open={open}
onOpenChange={value => {
if (!value) {
onClose()
}
}}
+ open={open}
>
<DialogContent className="max-w-md">
<DialogHeader>
@@ -1171,30 +1231,30 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
aria-label={b.group.searchToAdd}
containerClassName="w-full"
inputClassName="w-full"
+ onChange={setQuery}
placeholder={b.group.searchToAddPlaceholder}
value={query}
- onChange={setQuery}
/>
{selected.length ? (
<div className="flex flex-wrap gap-1">
{selected.map(bot => (
<Badge
- key={botRosterKey(bot)}
asChild
className="rounded-full bg-(--chrome-action-hover) pl-2 pr-1.5 text-[0.6875rem] text-(--ui-text-secondary) transition-colors hover:text-foreground"
+ key={botRosterKey(bot)}
variant="muted"
>
<RowButton
- title={b.group.removeFromSelection}
onClick={() =>
setChecked(prev => ({
...prev,
[botRosterKey(bot)]: false
}))
}
+ title={b.group.removeFromSelection}
>
{displayName(bot, botRosterMeta(bot, allMeta))}
- <Codicon name="close" className="text-[0.6rem]" />
+ <Codicon className="text-[0.6rem]" name="close" />
</RowButton>
</Badge>
))}
@@ -1209,20 +1269,21 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
const isChecked = Boolean(checked[botRosterKey(bot)])
const disabled = !isChecked && atCap
const currentGroups = botGroups(meta)
+
return (
<label
- key={botRosterKey(bot)}
className={cn(
'flex cursor-pointer items-center gap-2 rounded-md px-1.5 py-1 transition-colors hover:bg-(--chrome-action-hover)',
disabled && 'cursor-not-allowed opacity-50'
)}
+ key={botRosterKey(bot)}
>
<BotFace
- shape={shape}
color={avatarColor(color, bot.name)}
image={image && !isBackfilledFacePng(image) ? image : null}
- size={24}
name={bot.name}
+ shape={shape}
+ size={24}
/>
<div className="min-w-0 flex-1">
<div className="truncate text-xs text-foreground">{displayName(bot, meta)}</div>
@@ -1259,8 +1320,8 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
<GroupImageControls
image={image}
onImage={setImage}
- seedName={name.trim() || (selected.length ? placeholder : '')}
seedMembers={selected.map(bot => displayName(bot, botRosterMeta(bot, allMeta)))}
+ seedName={name.trim() || (selected.length ? placeholder : '')}
/>
<form
onSubmit={event => {
@@ -1271,20 +1332,20 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
<Input
aria-label={b.group.nameLabel}
maxLength={64}
+ onChange={event => setName(event.target.value)}
placeholder={placeholder}
value={name}
- onChange={event => setName(event.target.value)}
/>
</form>
</div>
<DialogFooter>
- <Button variant="secondary" onClick={onClose}>
+ <Button onClick={onClose} variant="secondary">
{t.common.cancel}
</Button>
<Button
disabled={!canCreate}
- title={selected.length < 2 ? 'Pick at least 2 bots' : undefined}
onClick={create}
+ title={selected.length < 2 ? 'Pick at least 2 bots' : undefined}
>{`Create Group${selected.length ? ` (${selected.length})` : ''}`}</Button>
</DialogFooter>
</DialogContent>
diff --git a/apps/desktop/src/plugins/hermes-bots/cron.tsx b/apps/desktop/src/plugins/hermes-bots/cron.tsx
index 0a3fc65679b..0802c99bc26 100644
--- a/apps/desktop/src/plugins/hermes-bots/cron.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/cron.tsx
@@ -57,6 +57,7 @@ function showsHandle(name: string, meta: BotMeta | null | undefined, bot?: Roste
},
meta
)
+
return Boolean(name && display.toLowerCase() !== botHandle(name, bot).toLowerCase())
}
@@ -79,25 +80,33 @@ interface RoutineListResult {
jobs?: RoutineJob[]
scoped?: string
}
+
function routineBot(job: RoutineJob | null | undefined): null | string {
const match = BOT_TAG_RE.exec(job?.name || '')
+
return match ? match[1].toLowerCase() : null
}
+
function routineTitle(job: RoutineJob | null | undefined): string {
return (job?.name || '').replace(BOT_TAG_RE, '') || 'Untitled job'
}
-function isLegacyDelegatedRoutine(job: RoutineJob | null | undefined): boolean {
+
+export function isLegacyDelegatedRoutine(job: RoutineJob | null | undefined): boolean {
const preview = typeof job?.prompt_preview === 'string' ? job.prompt_preview : job?.prompt
+
return Boolean(routineBot(job) && typeof preview === 'string' && preview.startsWith(LEGACY_DELEGATED_ROUTINE_PREFIX))
}
-async function loadRoutines(owner: RoutineOwner): Promise<RoutineListResult> {
+
+export async function loadRoutines(owner: RoutineOwner): Promise<RoutineListResult> {
const bot =
typeof owner === 'string'
? {
name: owner
}
: owner
+
const profile = String(bot?.name || '').trim()
+
// profile scopes cron.manage to that bot's own cron store (core RPC gained an
// optional `profile` param). Older gateways ignore the unknown param and
// return the launch-profile store — the [bot:] tag filter in selectRoutineJobs
@@ -107,12 +116,15 @@ async function loadRoutines(owner: RoutineOwner): Promise<RoutineListResult> {
profile
}
: {}
+
const data = (await requestForBot(bot, 'cron.manage', {
action: 'list',
include_disabled: true,
...scope
})) as RoutineListResult
+
const jobs = Array.isArray(data?.jobs) ? data.jobs : []
+
const activeLegacyJobs = jobs.filter(
job => isLegacyDelegatedRoutine(job) && job.enabled !== false && job.state !== 'paused'
)
@@ -133,10 +145,13 @@ async function loadRoutines(owner: RoutineOwner): Promise<RoutineListResult> {
.catch(() => false)
)
)
+
if (!activeLegacyJobs.length) {
return data
}
+
const pausedIds = new Set(activeLegacyJobs.filter((job, index) => pauses[index]).map(job => job.job_id))
+
return {
...data,
jobs: jobs.map(job =>
@@ -150,6 +165,7 @@ async function loadRoutines(owner: RoutineOwner): Promise<RoutineListResult> {
)
}
}
+
function useRoutines(owner: RoutineOwner) {
const bot =
typeof owner === 'string'
@@ -157,8 +173,10 @@ function useRoutines(owner: RoutineOwner) {
name: owner
}
: owner
+
const route = botConnectionRoute(bot)
const key = route ? botRosterKey(bot) : bot?.name || ''
+
return useQuery({
queryKey: [...ROUTINES_KEY, key],
queryFn: () => loadRoutines(bot),
@@ -167,18 +185,21 @@ function useRoutines(owner: RoutineOwner) {
staleTime: 8000
})
}
+
/** `activeBot` is always a non-empty profile name, so the result is never
* nullish even when no create-owner has been captured yet. */
-function routineCreateTarget(owner: RoutineOwner, activeBot: string): RosterRow | string {
+export function routineCreateTarget(owner: RoutineOwner, activeBot: string): RosterRow | string {
return owner || activeBot
}
-async function invalidateRoutineOwner(owner: RoutineOwner) {
+
+export async function invalidateRoutineOwner(owner: RoutineOwner) {
const bot =
typeof owner === 'string'
? {
name: owner
}
: owner
+
const route = botConnectionRoute(bot)
const key = route ? botRosterKey(bot) : bot?.name || ''
await queryClient.invalidateQueries({
@@ -188,10 +209,16 @@ async function invalidateRoutineOwner(owner: RoutineOwner) {
}
/** Pick which cron jobs to show. A failed refresh keeps the last good list. */
-function selectRoutineJobs(data: RoutineListResult | undefined, error: unknown, lastJobs: RoutineJob[], bot: string) {
+export function selectRoutineJobs(
+ data: RoutineListResult | undefined,
+ error: unknown,
+ lastJobs: RoutineJob[],
+ bot: string
+) {
const live = Array.isArray(data?.jobs) ? data.jobs : null
const all = live ?? (error ? lastJobs : [])
const scopedToBot = normalizedProfileName(data?.scoped) === normalizedProfileName(bot)
+
return {
live,
all,
@@ -209,34 +236,47 @@ function selectRoutineJobs(data: RoutineListResult | undefined, error: unknown,
* Return a short explanation string in that case, or null when the store is
* genuinely empty (or the active bot's jobs are already shown).
*/
-function routineFilterHint(all: RoutineJob[], jobs: RoutineJob[]): null | string {
+export function routineFilterHint(all: RoutineJob[], jobs: RoutineJob[]): null | string {
if (jobs.length !== 0 || !Array.isArray(all) || all.length === 0) {
return null
}
+
return (
'Scheduled jobs exist in this profile but none are tagged for this bot. ' +
'Name a job "[bot:<name>] …" to show it here, or see them in Cron below.'
)
}
-function normalizedProfileName(profile: unknown): string {
+
+export function normalizedProfileName(profile: unknown): string {
return typeof profile === 'string' ? profile.trim().toLowerCase() : ''
}
+
function shellQuote(value: unknown): string {
return `'${String(value).replaceAll("'", "'\"'\"'")}'`
}
-function routineInputError(title: string, instruction: string): null | string {
+
+export function routineInputError(title: string, instruction: string): null | string {
if (String(title).includes('\0')) {
return 'Job name cannot contain NUL (U+0000).'
}
+
if (String(instruction).includes('\0')) {
return 'Job instruction cannot contain NUL (U+0000).'
}
+
return null
}
-function routinePrompt(bot: string | undefined, title: string, instruction: string, activeProfile: string): string {
+
+export function routinePrompt(
+ bot: string | undefined,
+ title: string,
+ instruction: string,
+ activeProfile: string
+): string {
if (normalizedProfileName(bot) && normalizedProfileName(bot) === normalizedProfileName(activeProfile)) {
return instruction
}
+
return (
`${SAFE_ROUTINE_MARKER}You are running the scheduled routine "${title}" for agent '${bot}'. ` +
`Execute it AS that agent so the run lands in its own history: run this in the terminal and relay the output:\n\n` +
@@ -244,28 +284,40 @@ function routinePrompt(bot: string | undefined, title: string, instruction: stri
`If the command fails, report the error instead.`
)
}
+
function scheduleLabel(schedule: string | undefined): string {
const once = /^once in (.+)$/.exec(schedule || '')
+
if (once) {
return `Once (${once[1]})`
}
+
const bare = /^(\d+)([mhd])$/.exec(schedule || '')
+
if (bare) {
return `Once (${bare[1]}${bare[2]})`
}
+
const match = /^every (\d+)m$/.exec(schedule || '')
+
if (match) {
const minutes = Number(match[1])
+
if (minutes % 1440 === 0) {
const d = minutes / 1440
+
return d === 1 ? 'Daily' : `Every ${d} days`
}
+
if (minutes % 60 === 0) {
const h = minutes / 60
+
return h === 1 ? 'Hourly' : `Every ${h}h`
}
+
return `Every ${minutes}m`
}
+
return schedule || ''
}
@@ -273,6 +325,7 @@ function scheduleLabel(schedule: string | undefined): string {
* has never carried one (a job that has not run yet has no `last_run_at`). */
function routineTimestamp(value: string | undefined): null | string {
const ms = value ? new Date(value).getTime() : Number.NaN
+
return Number.isFinite(ms) ? `${relativeTime(ms)} · ${new Date(ms).toLocaleString()}` : null
}
@@ -280,10 +333,11 @@ function routineTimestamp(value: string | undefined): null | string {
* rows. Pure so the detail contract is testable without a renderer, and so
* the dialog cannot invent a field the gateway never sent: an absent value
* drops its row instead of rendering "undefined". */
-function routineDetailRows(job: RoutineJob | null | undefined): Array<{ label: string; value: string }> {
+export function routineDetailRows(job: RoutineJob | null | undefined): Array<{ label: string; value: string }> {
const paused = job?.enabled === false || job?.state === 'paused'
const label = scheduleLabel(job?.schedule)
const raw = String(job?.schedule || '').trim()
+
// Cells are `number | string | null | undefined` until the filter below
// drops the non-strings; a destructured, non-predicate callback can't carry
// that narrowing into the map, so the rows are typed as filtered.
@@ -313,9 +367,10 @@ function routineDetailRows(job: RoutineJob | null | undefined): Array<{ label: s
/** Why a job is not doing what the user expects. The row only ever showed
* "paused"; the scheduler's own reason and the last fire/delivery failures
* had no surface in Bot Mode at all. */
-function routineDetailIssue(job: RoutineJob | null | undefined): null | string {
+export function routineDetailIssue(job: RoutineJob | null | undefined): null | string {
const reasons = [job?.last_fire_error, job?.last_delivery_error, job?.paused_reason]
const first = reasons.find(value => typeof value === 'string' && value.trim())
+
return first ? first.trim() : null
}
@@ -328,19 +383,20 @@ interface RoutineDetailDialogProps {
/** Read-only inspector for one cronjob, rendered from the list payload the
* pane already holds — no extra RPC, and no second mutation path beside the
* row's own switch and delete. */
-function RoutineDetailDialog({ job, onClose, open }: RoutineDetailDialogProps) {
+export function RoutineDetailDialog({ job, onClose, open }: RoutineDetailDialogProps) {
const { t } = useI18n()
const rows = job ? routineDetailRows(job) : []
const issue = job ? routineDetailIssue(job) : null
const instruction = String(job?.prompt_preview || '').trim()
+
return (
<Dialog
- open={Boolean(open && job)}
onOpenChange={value => {
if (!value) {
onClose()
}
}}
+ open={Boolean(open && job)}
>
<DialogContent className="max-w-md">
<DialogHeader>
@@ -355,7 +411,7 @@ function RoutineDetailDialog({ job, onClose, open }: RoutineDetailDialogProps) {
) : null}
<div className="grid gap-1.5">
{rows.map(row => (
- <div key={row.label} className="flex items-baseline justify-between gap-3 text-xs">
+ <div className="flex items-baseline justify-between gap-3 text-xs" key={row.label}>
<span className="shrink-0 text-(--ui-text-tertiary)">{row.label}</span>
<span className="min-w-0 truncate text-right">{row.value}</span>
</div>
@@ -371,7 +427,7 @@ function RoutineDetailDialog({ job, onClose, open }: RoutineDetailDialogProps) {
: null}
</div>
<DialogFooter>
- <Button variant="secondary" onClick={onClose}>
+ <Button onClick={onClose} variant="secondary">
{t.common.close}
</Button>
</DialogFooter>
@@ -379,6 +435,7 @@ function RoutineDetailDialog({ job, onClose, open }: RoutineDetailDialogProps) {
</Dialog>
)
}
+
interface RoutineRowProps {
job: RoutineJob
onOpen?: (job: RoutineJob) => void
@@ -386,7 +443,8 @@ interface RoutineRowProps {
* this never sees the bare-name arm of RoutineOwner. */
owner: RosterRow
}
-function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
+
+export function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
const { t } = useI18n()
const c = t.cron
const profile = typeof owner === 'string' ? owner : owner?.name
@@ -397,17 +455,22 @@ function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
const legacyUnsafe = isLegacyDelegatedRoutine(job)
const serverActive = !legacyUnsafe && job.enabled !== false && job.state !== 'paused'
const active = pendingActive === null ? serverActive : pendingActive
+
if (pendingActive !== null && pendingActive === serverActive) {
setPendingActive(null) // server caught up
}
+
const act = async (action: 'pause' | 'remove' | 'resume') => {
if (busy) {
return
}
+
setBusy(true)
+
if (action === 'pause' || action === 'resume') {
setPendingActive(action === 'resume')
}
+
try {
await requestForBot(owner, 'cron.manage', {
action,
@@ -426,6 +489,7 @@ function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
setBusy(false)
}
}
+
return (
<div
className={cn(
@@ -438,9 +502,9 @@ function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
/* and delete control are siblings, so opening the details can never */
/* swallow a toggle (and a nested button would be invalid markup). */}
<RowButton
- title={c.manage}
className="flex min-w-0 flex-1 items-center gap-2 text-left transition-colors hover:text-foreground"
onClick={() => onOpen?.(job)}
+ title={c.manage}
>
{/* `--ui-success` rather than a literal emerald: the token is rotated
toward the accent, so a column of active dots can't fight the
@@ -473,7 +537,7 @@ function RoutineRow({ job, onOpen, owner }: RoutineRowProps) {
</div>
<div className="flex items-center justify-between gap-2 pl-3.5">
<span className="inline-flex items-center gap-1 rounded-full border border-(--ui-stroke-secondary) px-1.5 py-0.5 text-[0.65rem] text-(--ui-text-tertiary)">
- <Codicon name="calendar" className="text-[0.7rem]" />
+ <Codicon className="text-[0.7rem]" name="calendar" />
{scheduleLabel(job.schedule)}
</span>
<span className="truncate text-[0.65rem] text-(--ui-text-quaternary)">
@@ -510,6 +574,7 @@ interface ScheduleState {
time: string
weekday: string
}
+
const FREQUENCIES: Array<{ id: ScheduleFreq; label: string }> = [
{
id: 'once',
@@ -544,6 +609,7 @@ const FREQUENCIES: Array<{ id: ScheduleFreq; label: string }> = [
label: 'Advanced\u2026'
}
]
+
const WEEKDAYS = [
{
id: '1',
@@ -574,8 +640,10 @@ const WEEKDAYS = [
label: 'Sunday'
}
]
+
const TIMES = (() => {
const out = []
+
for (let h = 0; h < 24; h++) {
for (const m of [0, 30]) {
const ampm = h < 12 ? 'AM' : 'PM'
@@ -588,69 +656,90 @@ const TIMES = (() => {
})
}
}
+
return out
})()
/** Compose the Hermes schedule string from picker state. */
function composeSchedule(state: ScheduleState): string {
const [h, m] = (state.time || '9:0').split(':').map(Number)
+
switch (state.freq) {
case 'once': {
const n = Math.max(1, parseInt(state.onceN, 10) || 1)
+
return `${n}${state.onceUnit || 'h'}`
}
+
case 'hourly':
return 'every 1h'
+
case 'daily':
return `${m} ${h} * * *`
+
case 'weekdays':
return `${m} ${h} * * 1-5`
+
case 'weekly':
return `${m} ${h} * * ${state.weekday || '1'}`
+
case 'monthly':
return `${m} ${h} ${state.monthday || '1'} * *`
case 'interval': {
const n = Math.max(1, parseInt(state.intervalN, 10) || 1)
+
return `every ${n}${state.intervalUnit || 'h'}`
}
+
default:
return state.raw || ''
}
}
+
function scheduleSummary(state: ScheduleState): string {
const t = TIMES.find(x => x.id === state.time)
const tl = t ? t.label : '9:00 AM'
const unitWord = (u: string) => (u === 'm' ? 'minute(s)' : u === 'd' ? 'day(s)' : 'hour(s)')
+
const cap =
state.freq !== 'once' && String(state.repeatN || '').trim()
? `, ${Math.max(1, parseInt(state.repeatN, 10) || 1)} time(s) total`
: ''
+
switch (state.freq) {
case 'once':
return `Runs once, ${Math.max(1, parseInt(state.onceN, 10) || 1)} ${unitWord(state.onceUnit)} from now`
+
case 'hourly':
return 'Runs at the top of every hour' + cap
+
case 'daily':
return `Runs every day at ${tl}` + cap
+
case 'weekdays':
return `Runs Monday\u2013Friday at ${tl}` + cap
+
case 'weekly':
return `Runs every ${(WEEKDAYS.find(w => w.id === state.weekday) || WEEKDAYS[0]).label} at ${tl}` + cap
+
case 'monthly':
return `Runs on day ${state.monthday || '1'} of each month at ${tl}` + cap
+
case 'interval':
return `Runs every ${Math.max(1, parseInt(state.intervalN, 10) || 1)} ${unitWord(state.intervalUnit)}` + cap
+
default:
return 'Raw schedule \u2014 every Nm/Nh/Nd or 5-field cron'
}
}
+
function pickerSelect<T extends string>(
value: T,
onChange: (value: T) => void,
options: Array<{ id: T; label: string }>
) {
return (
- <Select value={value} onValueChange={onChange}>
+ <Select onValueChange={onChange} value={value}>
<SelectTrigger className="h-8 rounded-md">
<SelectValue />
</SelectTrigger>
@@ -664,17 +753,21 @@ function pickerSelect<T extends string>(
</Select>
)
}
+
interface SchedulePickerProps {
setState: React.Dispatch<React.SetStateAction<ScheduleState>>
state: ScheduleState
}
+
function SchedulePicker({ state, setState }: SchedulePickerProps) {
const upd = (patch: Partial<ScheduleState>) =>
setState(prev => ({
...prev,
...patch
}))
+
const needsTime = ['daily', 'weekdays', 'weekly', 'monthly'].includes(state.freq)
+
return (
<div className="grid gap-2">
<div className={cn('grid gap-2', needsTime ? 'grid-cols-2' : 'grid-cols-1')}>
@@ -701,13 +794,13 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
<div className="grid grid-cols-2 gap-2">
<Input
className="h-8"
- placeholder="30"
- value={state.onceN}
onChange={event =>
upd({
onceN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4)
})
}
+ placeholder="30"
+ value={state.onceN}
/>
{pickerSelect(
state.onceUnit,
@@ -747,13 +840,13 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
'Day of month',
<Input
className="h-8"
- placeholder="1"
- value={state.monthday}
onChange={event =>
upd({
monthday: event.target.value.replace(/[^0-9]/g, '').slice(0, 2)
})
}
+ placeholder="1"
+ value={state.monthday}
/>
)
: null}
@@ -761,13 +854,13 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
<div className="grid grid-cols-2 gap-2">
<Input
className="h-8"
- placeholder="2"
- value={state.intervalN}
onChange={event =>
upd({
intervalN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4)
})
}
+ placeholder="2"
+ value={state.intervalN}
/>
{pickerSelect(
state.intervalUnit,
@@ -795,13 +888,13 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
{state.freq === 'advanced' ? (
<Input
className="h-8 font-mono text-xs"
- placeholder="every 1d · every 2h · 0 9 * * * (cron)"
- value={state.raw}
onChange={event =>
upd({
raw: event.target.value
})
}
+ placeholder="every 1d · every 2h · 0 9 * * * (cron)"
+ value={state.raw}
/>
) : null}
{state.freq !== 'once' && state.freq !== 'advanced' ? (
@@ -809,13 +902,13 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
<span className="text-xs text-(--ui-text-tertiary)">Stop after</span>
<Input
className="h-7 w-16 text-xs"
- placeholder="∞"
- value={state.repeatN}
onChange={event =>
upd({
repeatN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4)
})
}
+ placeholder="∞"
+ value={state.repeatN}
/>
<span className="text-xs text-(--ui-text-tertiary)">runs (blank = forever)</span>
</div>
@@ -824,6 +917,7 @@ function SchedulePicker({ state, setState }: SchedulePickerProps) {
</div>
)
}
+
function defaultScheduleState(): ScheduleState {
return {
freq: 'daily',
@@ -838,6 +932,7 @@ function defaultScheduleState(): ScheduleState {
raw: ''
}
}
+
interface CreateRoutineDialogProps {
/** Never nullish: the pane early-returns its empty state before it renders
* this dialog, so `createTarget` has already fallen back to the active
@@ -846,7 +941,8 @@ interface CreateRoutineDialogProps {
onClose: () => void
open: boolean
}
-function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
+
+export function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
const { t } = useI18n()
const c = t.cron
const [name, setName] = useState('')
@@ -868,6 +964,7 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
const owner: RosterRow = typeof bot === 'string' ? { name: bot } : bot
const profile = owner.name
const schedule = composeSchedule(sched)
+
const reset = () => {
setName('')
setInstruction('')
@@ -877,24 +974,31 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
setBusy(false)
setError(null)
}
+
const submit = async () => {
const title = name.trim()
const task = instruction.trim()
const inputError = routineInputError(title, task)
+
if (inputError) {
setError(inputError)
+
return
}
+
if (!title || !task || !schedule.trim() || busy) {
return
}
+
setBusy(true)
setError(null)
+
try {
const repeatN =
sched.freq !== 'once' && sched.freq !== 'advanced' && String(sched.repeatN || '').trim()
? Math.max(1, parseInt(sched.repeatN, 10) || 1)
: null
+
await requestForBot(owner, 'cron.manage', {
action: 'add',
name: `[bot:${profile}] ${title}`,
@@ -936,17 +1040,18 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
setError(err instanceof Error ? err.message : String(err))
}
}
+
const ownerLabel = displayName(owner, botRosterMeta(owner, $botMeta.get()))
return (
<Dialog
- open={open}
onOpenChange={value => {
if (!value && !busy) {
reset()
onClose()
}
}}
+ open={open}
>
<DialogContent className="max-w-md">
<DialogHeader>
@@ -958,21 +1063,21 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
c.nameLabel,
<Input
autoFocus
+ onChange={event => setName(event.target.value)}
placeholder={c.namePlaceholder}
value={name}
- onChange={event => setName(event.target.value)}
/>
)}
{labeled(
c.promptLabel,
<Textarea
className="min-h-20"
+ onChange={event => setInstruction(event.target.value)}
placeholder={c.promptPlaceholder}
value={instruction}
- onChange={event => setInstruction(event.target.value)}
/>
)}
- {labeled('When to run', <SchedulePicker state={sched} setState={setSched} />)}
+ {labeled('When to run', <SchedulePicker setState={setSched} state={sched} />)}
{labeled(
'Send results to',
pickerSelect(target, setTarget, [
@@ -988,10 +1093,10 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
)}
<label className="flex items-center gap-2 text-xs text-(--ui-text-tertiary) cursor-pointer select-none">
<input
- type="checkbox"
- className="accent-(--ui-accent)"
checked={continuity}
+ className="accent-(--ui-accent)"
onChange={event => setContinuity(event.target.checked)}
+ type="checkbox"
/>
Continuity: each run sees the previous run’s output (dedupe, continue where it left off)
</label>
@@ -1003,12 +1108,12 @@ function CreateRoutineDialog({ bot, open, onClose }: CreateRoutineDialogProps) {
</div>
<DialogFooter>
<Button
- variant="ghost"
disabled={busy}
onClick={() => {
reset()
onClose()
}}
+ variant="ghost"
>
{t.common.cancel}
</Button>
@@ -1043,16 +1148,21 @@ interface ProfileSyncStore {
export function bindProfileSync(ownerStore: ProfileSyncStore) {
const sync = (owner: ProfileSyncOwnerRow | null | string | undefined) => {
const profile = typeof owner === 'string' ? owner : owner?.profile
+
if (!profile || typeof profile !== 'string') {
return
}
+
const connectionId = String(typeof owner === 'object' ? owner?.connectionId || '' : '').trim()
$selectedBot.set(connectionId ? `${connectionId}::${profile}` : profile)
}
+
sync(ownerStore.get?.())
+
return ownerStore.listen(sync)
}
-function resolveRoutineOwner(
+
+export function resolveRoutineOwner(
roster: RosterRow[],
focusedOwner: { authoritative?: boolean; connectionId?: string; name: string } | null,
selected: string
@@ -1065,12 +1175,14 @@ function resolveRoutineOwner(
// placeholder for every agent (#94516).
const selectedBot = roster.find(bot => botSelectionKey(bot) === selected)
const focusedBot = focusedOwner ? roster.find(bot => isActiveRosterBot(bot, focusedOwner)) : null
+
if (focusedOwner?.authoritative) {
// An authoritative focused owner wins, but only through its exact roster
// row. If that row is absent, fail closed instead of routing cron
// reads/mutations through a stale selection or an unscoped profile name.
return focusedBot || null
}
+
return (
focusedBot ||
selectedBot ||
@@ -1081,6 +1193,7 @@ function resolveRoutineOwner(
: null)
)
}
+
export function RoutinesPane() {
const selected = useValue($selectedBot)
const focusedOwner = focusedRosterOwner(useValue($focusedBotOwner))
@@ -1106,29 +1219,38 @@ export function RoutinesPane() {
// instead of freezing the snapshot that was on screen when it opened.
const [detailJobId, setDetailJobId] = useState<null | string>(null)
const createTarget = owner ? routineCreateTarget(createOwner, bot) : null
+
const openCreate = () => {
if (!owner) {
return
}
+
setCreateOwner(owner)
setCreateOpen(true)
}
+
if (!owner) {
return <PanelEmpty description="This agent has to appear in the roster first." icon="hubot" title={c.title} />
}
+
const view = selectRoutineJobs(data, error, $lastJobs.get(), bot)
+
if (view.live) {
$lastJobs.set(view.live)
}
+
const jobs = view.jobs
const detailJob = detailJobId ? jobs.find(job => job.job_id === detailJobId) || null : null
+
const staleNotice =
error && !view.live && view.all.length ? 'Could not refresh scheduled jobs. Showing the last list we had.' : null
+
const filterHint = routineFilterHint(view.all, jobs)
+
return (
<div className="flex h-full flex-col">
<div className="flex items-center gap-2 px-3 pt-3 pb-2">
- <BotFace shape={shape} color={avatarColor(color, bot)} image={image} size={22} name={bot} />
+ <BotFace color={avatarColor(color, bot)} image={image} name={bot} shape={shape} size={22} />
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-baseline gap-1.5 truncate">
<div className="truncate text-xs font-semibold">
@@ -1159,7 +1281,7 @@ export function RoutinesPane() {
) : null}
{isLoading && !view.all.length ? (
<div className="flex flex-1 items-center justify-center">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
) : error && !view.all.length ? (
<PanelEmpty
@@ -1189,25 +1311,25 @@ export function RoutinesPane() {
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
<div className="grid gap-1.5 px-2.5 py-2">
{jobs.map(job => (
- <RoutineRow key={job.job_id} job={job} onOpen={opened => setDetailJobId(opened.job_id)} owner={owner} />
+ <RoutineRow job={job} key={job.job_id} onOpen={opened => setDetailJobId(opened.job_id)} owner={owner} />
))}
</div>
</div>
)}
- <RoutineDetailDialog job={detailJob} open={Boolean(detailJob)} onClose={() => setDetailJobId(null)} />
+ <RoutineDetailDialog job={detailJob} onClose={() => setDetailJobId(null)} open={Boolean(detailJob)} />
<CreateRoutineDialog
+ // Non-null past the `!owner` early return above: `routineCreateTarget`
+ // falls back to the active profile name.
+ bot={createTarget!}
// TODO(bot-mode-types): `createTarget` is a roster row whenever a create
// owner is set, so this key stringifies to "[object Object]" instead of
// identifying the target bot. Cast to keep the as-written behavior.
key={createTarget as string}
- // Non-null past the `!owner` early return above: `routineCreateTarget`
- // falls back to the active profile name.
- bot={createTarget!}
- open={createOpen}
onClose={() => {
setCreateOpen(false)
setCreateOwner(null)
}}
+ open={createOpen}
/>
</div>
)
diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.ts
index 8c77a38e5ae..0a0c7b82a77 100644
--- a/apps/desktop/src/plugins/hermes-bots/data.ts
+++ b/apps/desktop/src/plugins/hermes-bots/data.ts
@@ -73,12 +73,15 @@ export const BOT_ATTENTION_HINTS: Record<string, string> = {
* timeout) — transient classes must NEVER badge. Pure; tested directly. */
function attentionReasonFromError(errorTextOrReason: unknown) {
const raw = String(errorTextOrReason || '').trim()
+
if (!raw) {
return null
}
+
if (BOT_ATTENTION_CLASSES.has(raw)) {
return raw
}
+
const text = raw.toLowerCase()
// Transient failures first, so a retryable error never sticks a badge.
@@ -87,9 +90,11 @@ function attentionReasonFromError(errorTextOrReason: unknown) {
) {
return null
}
+
if (/no llm provider|no access token|not configured|no api key|missing api key/.test(text)) {
return 'missing_config'
}
+
if (
/\b401\b|\b403\b|unauthorized|forbidden|authentication|invalid.?api.?key|credentials? (are )?(invalid|expired)/.test(
text
@@ -97,12 +102,15 @@ function attentionReasonFromError(errorTextOrReason: unknown) {
) {
return 'provider_auth_or_access'
}
+
if (/quota|out of funds|insufficient (credits?|funds|balance)|payment required|\b402\b|billing/.test(text)) {
return 'provider_quota_limit'
}
+
if (/\bblocked\b/.test(text)) {
return 'agent_blocked'
}
+
return null
}
@@ -116,9 +124,11 @@ export const $botAttention = atom<Record<string, { at: number; message: string;
* classify to null and set nothing. Latest failure wins. */
export function noteBotAttention(key: string, errorTextOrReason: unknown) {
const reason = attentionReasonFromError(errorTextOrReason)
+
if (!key || !reason) {
return
}
+
$botAttention.set({
...$botAttention.get(),
[key]: {
@@ -136,9 +146,11 @@ export function clearBotAttention(key: string) {
if (!key || !$botAttention.get()[key]) {
return
}
+
const next = {
...$botAttention.get()
}
+
delete next[key]
$botAttention.set(next)
}
@@ -168,20 +180,24 @@ interface BotMetaStorage {
/** Per-bot appearance + display meta, persisted via ctx.storage:
* { [botName]: { shape, color, title } } */
export const $botMeta = atom<BotMetaSnapshot>({})
+
export function commitBotMetaV2(storage: BotMetaStorage | undefined, snapshot: BotMetaSnapshot) {
const commit = botMetaV2Commit.then(async () => {
if (typeof storage?.remove !== 'function' || typeof storage?.set !== 'function') {
throw new Error('bot metadata v2 storage is unavailable')
}
+
const [previousSnapshot, previousMarker] =
typeof storage.get === 'function'
? await Promise.all([storage.get(BOT_META_V2_KEY), storage.get(BOT_META_MIGRATION_KEY)])
: [null, null]
+
const hasCommittedPrevious =
previousMarker === true &&
previousSnapshot &&
typeof previousSnapshot === 'object' &&
!Array.isArray(previousSnapshot)
+
try {
await storage.remove(BOT_META_MIGRATION_KEY)
await storage.set(BOT_META_V2_KEY, snapshot)
@@ -197,12 +213,16 @@ export function commitBotMetaV2(storage: BotMetaStorage | undefined, snapshot: B
} else {
await Promise.allSettled([BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key)))
}
+
throw error
}
})
+
botMetaV2Commit = commit.catch(() => undefined)
+
return commit
}
+
/** A save target resolved into the four things every write site needs. */
interface BotOwner {
bot: RosterRow
@@ -210,10 +230,12 @@ interface BotOwner {
name: string
route: null | ProfileRoute
}
+
export function botOwner(owner: RosterRow | string): BotOwner {
if (typeof owner === 'string') {
const name = owner.trim()
const route = migratedLocalRoutes.get(name)
+
return {
bot: route
? {
@@ -229,8 +251,10 @@ export function botOwner(owner: RosterRow | string): BotOwner {
route: route || null
}
}
+
const name = String(owner?.name || '').trim()
const route = botConnectionRoute(owner)
+
return {
bot: owner,
name,
@@ -242,6 +266,7 @@ export function botOwner(owner: RosterRow | string): BotOwner {
/** Freshness fence for the server-meta overlay: a roster snapshot fetched
* before the latest local/server metadata write must not overwrite it. */
export const botMetaWriteAt = new Map<string, number>()
+
export function noteBotMetaWrite(key: string) {
botMetaWriteAt.set(key, Date.now())
}
@@ -260,9 +285,11 @@ interface BotMetaSaveResult {
interface ProfilesConfigureResult {
applied?: { ui_meta?: boolean }
}
+
export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMeta): Promise<BotMetaSaveResult> {
const { bot, key, name, route } = botOwner(owner)
const prevMeta = $botMeta.get()[key] || {}
+
const next = {
...$botMeta.get(),
[key]: {
@@ -270,16 +297,19 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
...patch
}
}
+
noteBotMetaWrite(key)
$botMeta.set(next)
// Local plugin storage: instant, and the fallback for older gateways.
let localPersistence = Promise.resolve()
+
try {
const persisted =
route || botMetaV2Active
? commitBotMetaV2(getPluginCtx()?.storage, next)
: Promise.resolve(getPluginCtx()?.storage?.set?.(BOT_META_V1_KEY, next))
+
localPersistence = persisted.catch(() => undefined)
} catch {
/* storage unavailable — look persists for this window only */
@@ -294,8 +324,10 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
// store instead (profiles.set_asset), which is server-side and uncapped by
// the list call — so pfps follow the profile across machines too.
let serverRequest: null | Promise<ProfilesConfigureResult> = null
+
try {
const { image, pet, ...rest } = next[key] || {}
+
const request = route
? requestForBot(bot, 'profiles.configure', {
name,
@@ -309,6 +341,7 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
'hermes-bots': rest
}
})
+
serverRequest = Promise.resolve(request) as Promise<ProfilesConfigureResult>
} catch {
/* older/unavailable gateway — the local fallback remains saved */
@@ -345,6 +378,7 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
asset: 'avatar',
clear: true
})
+
req.catch(() => undefined)
} catch {
/* older gateway */
@@ -361,9 +395,11 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
// 'failed' — gateway speaks the contract and explicitly reported
// the ui_meta write did NOT apply.
let serverOutcome: BotMetaServerOutcome = 'unsupported'
+
if (serverRequest) {
try {
const result = await serverRequest
+
if (result?.applied?.ui_meta === true) {
serverOutcome = 'persisted'
} else if (result && typeof result === 'object' && result.applied && typeof result.applied === 'object') {
@@ -372,12 +408,15 @@ export async function saveBotMeta(owner: RosterRow | string, patch: StoredBotMet
} catch {
/* older/unavailable gateway — the local fallback remains saved */
}
+
// Re-stamp now that the server write settled: a roster snapshot fetched
// while profiles.configure was still in flight predates the new ui_meta
// just as surely as one fetched before the local write.
noteBotMetaWrite(key)
}
+
await localPersistence
+
return {
serverPersisted: serverOutcome === 'persisted',
serverOutcome
@@ -392,6 +431,7 @@ function hydrateBotMeta(snapshot: BotMetaSnapshot, remap: Map<string, string> |
const next = {
...snapshot
}
+
for (const [key, meta] of Object.entries($botMeta.get())) {
const target = remap?.get(key) || key
next[target] = {
@@ -399,13 +439,17 @@ function hydrateBotMeta(snapshot: BotMetaSnapshot, remap: Map<string, string> |
...meta
}
}
+
$botMeta.set(next)
+
return next
}
+
export async function migrateBotMeta(storage: BotMetaStorage | undefined = getPluginCtx()?.storage) {
let v1: BotMetaSnapshot | null = null
let v2: BotMetaSnapshot | null = null
let v2Committed = false
+
try {
;[v1, v2, v2Committed] = await Promise.all([
storage?.get?.(BOT_META_V1_KEY),
@@ -415,45 +459,59 @@ export async function migrateBotMeta(storage: BotMetaStorage | undefined = getPl
} catch {
return false
}
+
if (v2Committed === true && v2 && typeof v2 === 'object' && !Array.isArray(v2)) {
hydrateBotMeta(v2)
botMetaV2Active = true
+
return true
}
+
if (!v1 || typeof v1 !== 'object' || Array.isArray(v1) || typeof host.agents !== 'function') {
if (v1 && typeof v1 === 'object' && !Array.isArray(v1)) {
hydrateBotMeta(v1)
}
+
return false
}
+
let union
let routes
+
try {
union = await host.agents()
routes = typeof host.profileRoutes === 'function' ? await host.profileRoutes() : []
} catch {
hydrateBotMeta(v1)
+
return false
}
+
const sources = Array.isArray(union?.sources) ? union.sources : []
const localAgents = (union?.agents || []).filter(agent => agent?.connectionKind === 'local')
+
const soleLocal =
sources.length === 1
? sources[0]?.kind === 'local'
: sources.length === 0 &&
localAgents.length > 0 &&
(union?.agents || []).every(agent => agent?.connectionKind === 'local')
+
if (!soleLocal) {
hydrateBotMeta(v1)
+
return false
}
+
const migrated: BotMetaSnapshot = {}
const pendingLocalRoutes = new Map<string, ProfileRoute>()
+
for (const [name, meta] of Object.entries(v1)) {
const route =
(routes || []).find(candidate => candidate?.mode === 'local' && candidate?.profile === name) ||
(() => {
const agent = localAgents.find(candidate => candidate.profile === name)
+
return agent
? {
connectionId: agent.connectionId,
@@ -463,25 +521,32 @@ export async function migrateBotMeta(storage: BotMetaStorage | undefined = getPl
}
: null
})()
+
if (!route?.connectionId) {
// A missing route makes the topology proof unusable for this key. Keep
// the v1 record intact rather than guessing a local/remote projection.
hydrateBotMeta(v1)
+
return false
}
+
const captured: ProfileRoute = {
connectionId: route.connectionId,
mode: 'local',
profile: name,
targetProfile: route.targetProfile || name
}
+
migrated[botRouteKey(captured)] = meta
pendingLocalRoutes.set(name, captured)
}
+
const remap = new Map([...pendingLocalRoutes].map(([name, route]) => [name, botRouteKey(route)]))
+
const hydrated = {
...migrated
}
+
for (const [key, meta] of Object.entries($botMeta.get())) {
const target = remap.get(key) || key
hydrated[target] = {
@@ -489,19 +554,25 @@ export async function migrateBotMeta(storage: BotMetaStorage | undefined = getPl
...meta
}
}
+
try {
await commitBotMetaV2(storage, hydrated)
} catch {
botMetaV2Active = false
hydrateBotMeta(v1)
+
return false
}
+
migratedLocalRoutes.clear()
+
for (const [name, route] of pendingLocalRoutes) {
migratedLocalRoutes.set(name, route)
}
+
hydrateBotMeta(hydrated)
botMetaV2Active = true
+
return true
}
@@ -546,6 +617,7 @@ interface UnionRoster {
export function useRoster() {
const activeConnectionId = useValue(host.state.connectionId)
+
return useQuery({
queryKey: [...ROSTER_KEY, activeConnectionId],
queryFn: async () => {
@@ -554,6 +626,7 @@ export function useRoster() {
// a write can only carry pre-write ui_meta. (Issue time is the
// conservative bound — the server answered no earlier than this.)
const issuedAt = Date.now()
+
// Rich rows (last_session, canonical_session, ui_meta, has_avatar)
// come from the ACTIVE gateway's profiles.list — the canonical Bot
// Chat is resolved server-side by NAME (the "Bot Chat" registry row),
@@ -570,11 +643,13 @@ export function useRoster() {
/* keep the previous alias index */
}
}
+
// Owner routing is ambient in the SDK now (post-#92731): requestForBot
// resolves the active owner itself, no captured route needed here.
const activeBot = {
name: String(host.state.profile?.get?.() || 'default').trim() || 'default'
}
+
const local = await requestForBot<RosterSnapshot>(activeBot, 'profiles.list', {})
// Newer backends inject the teammate-messaging protocol into every
// session's system prompt (agent.bot_mode_protocol) — SOUL.md must not
@@ -592,6 +667,7 @@ export function useRoster() {
const previous: RosterRow[] = $lastRoster.get().filter(row => !row?.ghost)
const merged = mergeMultiSourceRoster(local, union, activeConnectionId, previous)
const sources = Array.isArray(union?.sources) ? union.sources : []
+
return {
...merged,
profiles: (merged?.profiles || []).map(row => annotateBotSource(row, sources)),
@@ -602,6 +678,7 @@ export function useRoster() {
/* older build or roster failure — single-source list stands */
}
}
+
return {
...(local && typeof local === 'object' ? local : {}),
fetchedAt: issuedAt
@@ -626,12 +703,15 @@ export function cachedUnionRoster(): RosterSnapshot | null {
if (typeof queryClient === 'undefined' || !queryClient || typeof queryClient.getQueryData !== 'function') {
return null
}
+
try {
const connectionId = String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
const exact = queryClient.getQueryData<RosterSnapshot>([...ROSTER_KEY, connectionId])
+
if (Array.isArray(exact?.profiles)) {
return exact
}
+
if (typeof queryClient.getQueriesData === 'function') {
let best: RosterSnapshot | null = null
@@ -644,11 +724,13 @@ export function cachedUnionRoster(): RosterSnapshot | null {
best = data
}
}
+
return best
}
} catch {
/* cache hiccup — caller falls back (middleware refetches) */
}
+
return null
}
@@ -689,17 +771,21 @@ function mergeMultiSourceRoster(
if (!activeId && liveProvided) {
const primaryId = String(union?.primaryConnectionId || '').trim()
const richNames = new Set(localProfiles.map(profile => String(profile?.name || '').trim()).filter(Boolean))
+
const localMatches = agents.some(
agent => agent?.connectionKind === 'local' && richNames.has(String(agent?.profile || '').trim())
)
+
const primaryMatches = agents.some(
agent =>
String(agent?.connectionId || '').trim() === primaryId && richNames.has(String(agent?.profile || '').trim())
)
+
if (!localMatches && primaryId && primaryMatches) {
activeId = primaryId
}
}
+
const activeByName = new Map<string, RosterRow>()
// Treat the rich list as one row per active-source profile. Clone every
@@ -708,12 +794,15 @@ function mergeMultiSourceRoster(
// next merge, growing duplicate source rows indefinitely.
for (const profile of localProfiles) {
const name = String(profile?.name || '').trim()
+
if (!name || profile?.remoteSource) {
continue
}
+
if (profile?.sourceScoped && activeId && profile.connectionId !== activeId) {
continue
}
+
if (!activeByName.has(name)) {
activeByName.set(name, {
...profile,
@@ -721,19 +810,23 @@ function mergeMultiSourceRoster(
})
}
}
+
const profiles = [...activeByName.values()]
// host.agents is an Electron/main-process capability. Defend the plugin
// boundary too: older shells or reconnect races can still hand us repeated
// identities even after the core roster deduplicates them.
const seenSources = new Set<string>()
+
for (const agent of agents) {
const profile = String(agent?.profile || '').trim()
const connectionId = String(agent?.connectionId || '').trim()
const sourceKey = `${connectionId}::${profile || 'default'}`
+
if (!profile || seenSources.has(sourceKey)) {
continue
}
+
seenSources.add(sourceKey)
// The union enumerates EVERY registered connection, including the active
@@ -744,6 +837,7 @@ function mergeMultiSourceRoster(
// the legacy local-source rule so single-source behavior stays intact.
const isActiveSource = activeId ? connectionId === activeId : agent.connectionKind === 'local'
const row = isActiveSource ? activeByName.get(profile) : null
+
if (row) {
// Annotate in place: the @name-device handle only differs from the
// bare name when the profile exists on several sources.
@@ -759,13 +853,16 @@ function mergeMultiSourceRoster(
targetProfile: agent.targetProfile || profile
}
row.sourceScoped = true
+
continue
}
+
if (isActiveSource) {
// Union saw an active-source profile profiles.list didn't return (older
// backend mid-refresh) — skip rather than invent a thin row.
continue
}
+
profiles.push({
name: profile,
handle: agent.handle,
@@ -790,27 +887,33 @@ function mergeMultiSourceRoster(
if (Array.isArray(previous) && previous.length > 0) {
const present = new Set(profiles.map(row => `${row.connectionId || ''}::${row.name}`))
const unionSourceIds = new Set(agents.map(agent => String(agent?.connectionId || '').trim()).filter(Boolean))
+
const omitted = new Set(
(Array.isArray(union?.sources) ? union.sources : [])
.filter(source => source?.error === 'connect-on-demand' || source?.reachable === false)
.map(source => String(source.connectionId || '').trim())
.filter(Boolean)
)
+
const registered = new Set(
(Array.isArray(union?.sources) ? union.sources : [])
.map(source => String(source?.connectionId || '').trim())
.filter(Boolean)
)
+
for (const row of previous) {
const connectionId = String(row?.connectionId || '').trim()
const name = String(row?.name || '').trim()
const key = `${connectionId}::${name || 'default'}`
+
if (!row?.remoteSource || !connectionId || !name || present.has(key)) {
continue
}
+
if (registered.size > 0 && !registered.has(connectionId)) {
continue
}
+
if (omitted.has(connectionId) || !unionSourceIds.has(connectionId)) {
profiles.push({
...row,
@@ -821,6 +924,7 @@ function mergeMultiSourceRoster(
}
}
}
+
return {
...local,
profiles
@@ -836,6 +940,7 @@ export function botHandle(name: string, bot?: Partial<RosterRow> | null): string
if (bot?.handle && bot.handle !== name) {
return bot.handle
}
+
return (name || '').trim().toLowerCase() === 'default' ? 'hermes' : name
}
@@ -849,11 +954,14 @@ export function mentionNameForms(value: null | string | undefined): string[] {
const name = String(value || '')
.trim()
.toLowerCase()
+
if (!name) {
return []
}
+
const slug = name.replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '')
const collapsed = name.replace(/[^a-z0-9_-]+/g, '')
+
return [...new Set([slug, collapsed])].filter(
form => /^[a-z0-9][a-z0-9_-]*$/.test(form) && !['all', 'everyone', 'user', 'default', 'hermes'].includes(form)
)
@@ -870,10 +978,12 @@ export function botFriendlyNames(bot: Partial<RosterRow> | null | undefined): Ar
const metaByName: Record<string, BotMeta | undefined> | null = typeof $botMeta !== 'undefined' ? $botMeta.get() : null
const localTitle = !bot?.remoteSource ? metaByName?.[bot?.name!]?.title : null
const alias = aliasIdentityFor(bot)
+
const aliasTitle = alias
? alias.metaKeys.map(key => metaByName?.[key]?.title).find(title => typeof title === 'string' && title.trim()) ||
alias.name
: null
+
return [bot?.ui_meta?.['hermes-bots']?.title, localTitle, aliasTitle, bot?.title, bot?.display_name]
}
@@ -883,10 +993,12 @@ export function botFriendlyNames(bot: Partial<RosterRow> | null | undefined): Ar
export function botMentionTag(bot: GroupMember | RosterRow): string {
for (const friendly of botFriendlyNames(bot)) {
const forms = mentionNameForms(friendly)
+
if (forms.length) {
return forms[0]
}
}
+
return botHandle(bot?.name, bot)
}
@@ -902,51 +1014,65 @@ export function isActiveRosterBot(bot: Partial<RosterRow> | null | undefined, ac
if (!active) {
return false
}
+
const activeName = String(active.name || 'default').trim() || 'default'
const activeId = String(active?.connectionId || '').trim()
const botId = String(bot?.connectionId || '').trim()
const botName = String(bot?.name || '').trim() || 'default'
+
if (bot?.remoteSource) {
return Boolean(activeId) && activeId === botId && botName === activeName
}
+
if (activeId && activeId !== 'local' && botId && activeId !== botId) {
return false
}
+
return botName === activeName
}
+
/** The key a bot is selected/badged/watermarked under. `undefined` is
* load-bearing on the nullable overload — callers use it to CLEAR a
* selection, so it must never be coerced to a 'default' fallback the way
* botRosterKey does. A real row always yields a key (`name` is required). */
export function botSelectionKey(bot: RosterRow): string
export function botSelectionKey(bot: Partial<RosterRow> | null | undefined): string | undefined
+
export function botSelectionKey(bot: Partial<RosterRow> | null | undefined): string | undefined {
return bot?.sourceScoped || bot?.remoteSource ? botRosterKey(bot) : bot?.name
}
+
export function isDefaultBot(bot: Partial<RosterRow> | null | undefined): boolean {
const route = botConnectionRoute(bot)
+
return (
String(route?.profile || bot?.name || '')
.trim()
.toLowerCase() === 'default'
)
}
+
export function newBotChat(bot: RosterRow) {
if (typeof host.newChat !== 'function') {
host.notify?.({
kind: 'error',
message: getPluginCtx()?.i18n.t('bot.openAnotherChatUnsupported') ?? 'Update Hermes Desktop to open another Bot chat.'
})
+
return
}
+
const route = botConnectionRoute(bot)
+
if (!route) {
host.notify?.({
kind: 'error',
message: getPluginCtx()?.i18n.t('bot.openAnotherChatUnsupported') ?? 'Update Hermes Desktop to open another Bot chat.'
})
+
return
}
+
const ownerKey = botWorkspaceOwnerKey(bot)
setBotsWorkspaceOwner(ownerKey, bot)
host.newChat(route, {
@@ -964,17 +1090,22 @@ export function resolveRosterMentions(
active: RosterOwnerRef = {}
): RosterRow[] {
const members = Array.isArray(roster) ? roster : []
+
const prose = String(text || '')
.replace(/```[\s\S]*?```/g, ' ')
.replace(/`[^`\n]*`/g, ' ')
+
const byForm = new Map<string, RosterRow | null>()
+
for (const bot of members) {
if (!bot?.name || isActiveRosterBot(bot, active)) {
continue
}
+
const handle = String(botHandle(bot.name, bot) || '').toLowerCase()
const name = String(bot.name || '').toLowerCase()
const forms = new Set([handle, name])
+
if (bot.handle) {
forms.add(String(bot.handle).toLowerCase())
}
@@ -987,38 +1118,52 @@ export function resolveRosterMentions(
forms.add(form)
}
}
+
for (const form of forms) {
if (!form) {
continue
}
+
const existing = byForm.get(form)
+
if (existing && existing !== bot) {
byForm.set(form, null)
+
continue
}
+
if (!existing) {
byForm.set(form, bot)
}
}
}
+
const mentioned: RosterRow[] = []
const seen = new Set<string>()
+
for (const match of prose.matchAll(/(^|\s)@([a-z0-9][a-z0-9_-]*)/gi)) {
let token = match[2].toLowerCase()
+
if (token === 'hermes') {
token = byForm.has('hermes') ? 'hermes' : token
}
+
const bot = byForm.get(token)
+
if (!bot) {
continue
}
+
const key = botRosterKey(bot)
+
if (seen.has(key)) {
continue
}
+
seen.add(key)
mentioned.push(bot)
}
+
return mentioned
}
@@ -1030,25 +1175,31 @@ export function resolveRosterMentions(
export function botRosterKey(bot: Partial<RosterRow> | null | undefined): string {
return `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`
}
+
/** The key a bot's persisted appearance/meta lives under. Same nullable
* contract as botSelectionKey: a real row always resolves to a key, a
* partial/absent one may not. */
export function botMetaKey(bot: RosterRow): string
export function botMetaKey(bot: Partial<RosterRow> | null | undefined): string | undefined
+
export function botMetaKey(bot: Partial<RosterRow> | null | undefined): string | undefined {
const route = botConnectionRoute(bot)
+
return route ? botRouteKey(route) : bot?.name
}
+
export function persistBotMetaSnapshot(value: Record<string, BotMeta>, scoped = false): Promise<void> {
try {
const persisted = scoped
? commitBotMetaV2(getPluginCtx()?.storage, value)
: Promise.resolve(getPluginCtx()?.storage?.set?.(BOT_META_V1_KEY, value))
+
return persisted.catch(() => undefined)
} catch {
return Promise.resolve()
}
}
+
export function sourceByConnection(sources: GatewaySource[] | null | undefined): Map<string, GatewaySource> {
return new Map(
(Array.isArray(sources) ? sources : [])
@@ -1060,11 +1211,14 @@ export function sourceByConnection(sources: GatewaySource[] | null | undefined):
/** Copy current source health onto a row without changing its owner. */
export function annotateBotSource(bot: RosterRow, sources: GatewaySource[] | null | undefined): RosterRow {
const id = String(bot?.connectionId || '').trim()
+
if (!id) {
return bot
}
+
const list = Array.isArray(sources) ? sources : []
const source = sourceByConnection(list).get(id)
+
if (!source) {
return list.length && bot?.sourceScoped
? {
@@ -1074,6 +1228,7 @@ export function annotateBotSource(bot: RosterRow, sources: GatewaySource[] | nul
}
: bot
}
+
return {
...bot,
connectionKind: bot.connectionKind || source.kind,
@@ -1105,6 +1260,7 @@ interface BotSourceStatus {
export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSourceStatus {
const error = String(bot?.sourceError || '').trim()
+
if (bot?.sourceMissing) {
return {
available: false,
@@ -1113,6 +1269,7 @@ export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSou
tone: 'bad'
}
}
+
if (error === 'connect-on-demand') {
return {
available: true,
@@ -1121,6 +1278,7 @@ export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSou
tone: 'muted'
}
}
+
if (error || bot?.sourceReachable === false) {
return {
available: false,
@@ -1129,6 +1287,7 @@ export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSou
tone: 'warn'
}
}
+
if (bot?.sourceReachable === true) {
return {
available: true,
@@ -1137,6 +1296,7 @@ export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSou
tone: 'good'
}
}
+
return {
available: true,
key: 'unknown',
@@ -1160,11 +1320,13 @@ export function botSourceStatus(bot: BotSourceFields | null | undefined): BotSou
export function preferReachableSameNameRows(bots: RosterRow[] | null | undefined): RosterRow[] {
const rows = Array.isArray(bots) ? bots : []
const reachableNames = new Set<string>()
+
for (const bot of rows) {
if (botSourceStatus(bot).available) {
reachableNames.add(bot?.name)
}
}
+
return rows.filter(bot => botSourceStatus(bot).available || bot?.ghost || !reachableNames.has(bot?.name))
}
@@ -1173,9 +1335,11 @@ export function preferReachableSameNameRows(bots: RosterRow[] | null | undefined
* activity order — search narrows the roster, it never re-ranks it. */
export function filterBots(roster: RosterRow[], metaByName: Record<string, BotMeta>, query: string) {
const needle = query.trim().toLowerCase().replace(/^@/, '')
+
if (!needle) {
return roster
}
+
return roster.filter(bot => {
const meta = botRosterMeta(bot, metaByName)
const display = displayName(bot, meta).toLowerCase()
@@ -1186,6 +1350,7 @@ export function filterBots(roster: RosterRow[], metaByName: Record<string, BotMe
const sourceLabel = (bot.connectionLabel || '').toLowerCase()
const role = `${meta?.description || ''} ${bot.description || ''}`.toLowerCase()
const preview = String(botActivitySession(bot)?.preview || '').toLowerCase()
+
return (
display.includes(needle) ||
profile.includes(needle) ||
@@ -1211,8 +1376,10 @@ export function filterBots(roster: RosterRow[], metaByName: Record<string, BotMe
export function botActivitySession(bot: null | RosterRow | undefined): CanonicalSession | SessionPreview | null {
const preferred = bot?.canonical_session
const last = bot?.last_session
+
if (!preferred || !last) {
return preferred || last || null
}
+
return (preferred.last_active || 0) >= (last.last_active || 0) ? preferred : last
}
diff --git a/apps/desktop/src/plugins/hermes-bots/edit-profile-dialog.tsx b/apps/desktop/src/plugins/hermes-bots/edit-profile-dialog.tsx
index f61c24b852f..65cd02af875 100644
--- a/apps/desktop/src/plugins/hermes-bots/edit-profile-dialog.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/edit-profile-dialog.tsx
@@ -43,11 +43,13 @@ interface EditProfileDialogProps {
onClose: () => void
open: boolean
}
+
export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps) {
const { t } = useI18n()
const b = useBots()
const metaAll = useValue($botMeta)
const meta = bot ? botRosterMeta(bot, metaAll) : null
+
// TODO(bot-mode-types): the no-bot fallback omits `image`, which the state
// seeding below reads — `appearance.image` is undefined on that branch, so
// this is NOT an AvatarAppearance. Harmless today only because the component
@@ -59,6 +61,7 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
shape: 'circle',
color: null
}
+
const [shape, setShape] = useState(appearance.shape)
const [color, setColor] = useState<null | string>(appearance.color)
const [image, setImage] = useState<null | string>(appearance.image ?? null)
@@ -71,8 +74,10 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
// Re-seed local state each time a different bot opens the dialog.
const [seedKey, setSeedKey] = useState<null | string>(null)
const currentKey = bot ? `${botSelectionKey(bot)}:${open}` : null
+
if (currentKey !== seedKey) {
setSeedKey(currentKey)
+
if (bot && open) {
setShape(appearance.shape)
setColor(appearance.color)
@@ -84,15 +89,19 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
setAdv(emptyAdvancedState())
}
}
+
if (!bot) {
return null
}
+
const submit = async () => {
if (busy) {
return
}
+
setBusy(true)
let advancedFailed = false
+
const persistence = await saveBotMeta(bot, {
shape,
color: color ?? undefined,
@@ -101,22 +110,27 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
title: title.trim(),
custom: true
})
+
// Only an explicit remote failure is an error — 'unsupported' is the
// documented older-gateway fallback (local wins, silently), and toasting
// it would flag every save on every legacy setup forever.
const lookFailed = persistence.serverOutcome === 'failed'
+
if (lookFailed) {
host.notify({
kind: 'error',
message: b.avatar.savedLocally
})
}
+
if (persistence.serverOutcome === 'persisted') {
queryClient.invalidateQueries({
queryKey: ROSTER_KEY
})
}
+
const desc = description.trim()
+
if (desc !== (bot.description || '').trim()) {
try {
await requestForBot(bot, 'cli.exec', {
@@ -129,10 +143,12 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
host.notifyError(err, b.avatar.savedLocallyDescriptionFailed)
}
}
+
if (adv.loaded && (adv.dirtyModel || adv.dirtySoul || adv.dirtySkills || adv.dirtyToolsets || adv.dirtyMcp)) {
try {
const res = await applyAdvancedConfig(bot, adv)
const failed = Object.entries(res?.applied || {}).filter(([, ok]) => !ok)
+
if (failed.length) {
advancedFailed = true
host.notify({
@@ -145,6 +161,7 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
host.notifyError(err, b.bot.advancedFailed)
}
}
+
if (!advancedFailed && !lookFailed) {
host.notify({
kind: 'success',
@@ -153,11 +170,13 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
})} updated`
})
}
+
setBusy(false)
onClose()
}
+
return (
- <Dialog open={open} onOpenChange={value => !value && !busy && onClose()}>
+ <Dialog onOpenChange={value => !value && !busy && onClose()} open={open}>
<DialogContent
className={advanced ? 'max-w-3xl' : 'max-w-sm'} // Same resizable-window treatment as the create dialog.
style={
@@ -179,36 +198,36 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
</DialogHeader>
<div className="grid gap-4">
<div className="flex justify-center py-1">
- <BotFace shape={shape} color={avatarColor(color, bot.name)} image={image} size={64} name={bot.name} />
+ <BotFace color={avatarColor(color, bot.name)} image={image} name={bot.name} shape={shape} size={64} />
</div>
<AvatarPicker
- shape={shape}
color={color}
- image={image}
- onShape={setShape}
- onColor={setColor}
- onImage={setImage}
generateSeed={{
name: bot.name,
title,
description
}}
+ image={image}
+ onColor={setColor}
+ onImage={setImage}
+ onShape={setShape}
+ shape={shape}
/>
{labeled(
'Title',
<Input
+ onChange={event => setTitle(event.target.value)}
placeholder={displayName(bot, null)}
value={title}
- onChange={event => setTitle(event.target.value)}
/>
)}
{labeled(
'Description',
<Textarea
className="min-h-16"
+ onChange={event => setDescription(event.target.value)}
placeholder={b.bot.helpPromptPlaceholder}
value={description}
- onChange={event => setDescription(event.target.value)}
/>
)}
<Button
@@ -222,12 +241,12 @@ export function EditProfileDialog({ bot, open, onClose }: EditProfileDialogProps
</Button>
{advanced ? (
<div className="rounded-md border border-(--ui-stroke-secondary) p-3">
- <AdvancedProfileConfig bot={bot} state={adv} setState={setAdv} />
+ <AdvancedProfileConfig bot={bot} setState={setAdv} state={adv} />
</div>
) : null}
</div>
<DialogFooter>
- <Button variant="ghost" disabled={busy} onClick={onClose}>
+ <Button disabled={busy} onClick={onClose} variant="ghost">
{t.common.cancel}
</Button>
<Button disabled={busy} onClick={submit}>
diff --git a/apps/desktop/src/plugins/hermes-bots/group-activity.ts b/apps/desktop/src/plugins/hermes-bots/group-activity.ts
index 51cf2162871..fb5be2f09cf 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-activity.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-activity.ts
@@ -31,19 +31,24 @@ export interface GroupActivityEntry extends Omit<GroupActivityEvent, 'group' | '
thread?: null | string
}
export const $groupActivity = atom<Record<string, { events: GroupActivityEntry[] }>>({})
+
export function recordGroupActivity(group: string, event: Omit<GroupActivityEntry, 'at' | 'epoch'>) {
const room = $groupChats.get()[group]
+
if (!room) {
return null
}
+
const current = $groupActivity.get()[group] || {
events: []
}
+
const entry = {
at: Date.now(),
epoch: room.epoch || 0,
...event
}
+
const events = [...current.events, entry].slice(-GROUP_ACTIVITY_LIMIT)
$groupActivity.set({
...$groupActivity.get(),
@@ -52,6 +57,7 @@ export function recordGroupActivity(group: string, event: Omit<GroupActivityEntr
events
}
})
+
return entry
}
@@ -59,6 +65,7 @@ export function recordGroupActivity(group: string, event: Omit<GroupActivityEntr
* are dropped from view instead of describing work that already ended. */
export function currentGroupActivity(group: string) {
const epoch = ($groupChats.get()[group] || {}).epoch || 0
+
return ($groupActivity.get()[group] || {}).events?.filter(event => (event.epoch || 0) === epoch) || []
}
@@ -67,12 +74,16 @@ export function currentGroupActivity(group: string) {
export function groupActivityLabel(event: GroupActivityEntry) {
const kind = event?.kind
const base = GROUP_ACTIVITY_LABELS[kind] || kind || 'did something'
+
if (kind === 'cancelled' || kind === 'settled' || kind === 'capped') {
return base
}
+
const who = event?.member === 'You' ? 'You' : groupSpeakerLabel(event?.member || 'A bot')
+
return `${who} ${base}`
}
+
const GROUP_ACTIVITY_LABELS: Record<GroupActivityKind, string> = {
queued: 'sent a message',
working: 'is working…',
@@ -87,6 +98,7 @@ const GROUP_ACTIVITY_LABELS: Record<GroupActivityKind, string> = {
held: 'is held (stopped by you) — @mention it or say resume to release',
stopped: 'stopped the room — remaining turns are held until resumed'
}
+
export const GROUP_ACTIVITY_GLYPHS: Record<GroupActivityKind, string> = {
queued: 'comment',
working: 'sync',
@@ -108,8 +120,10 @@ export function groupActivityTone(kind: GroupActivityKind) {
if (kind === 'failed' || kind === 'timed-out') {
return 'text-destructive'
}
+
if (kind === 'working' || kind === 'replied' || kind === 'delivered') {
return 'text-(--ui-accent)'
}
+
return 'text-(--ui-text-tertiary)'
}
diff --git a/apps/desktop/src/plugins/hermes-bots/group-attachments.ts b/apps/desktop/src/plugins/hermes-bots/group-attachments.ts
index c7087e91c2d..0c83fbcf536 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-attachments.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-attachments.ts
@@ -17,9 +17,11 @@ function groupAttachmentKind(file: File): AttachmentKind {
if (/^image\//.test(file.type || '')) {
return 'image'
}
+
if (file.type === 'application/pdf' || /\.pdf$/i.test(file.name || '')) {
return 'pdf'
}
+
return 'file'
}
@@ -29,26 +31,32 @@ function groupAttachmentKind(file: File): AttachmentKind {
* picker button, the composer paste handler, and room drag & drop. */
export async function filesToGroupAttachments(files: File[] | FileList | null | undefined): Promise<Attachment[]> {
const picked: Attachment[] = []
+
for (const file of [...(files || [])]) {
if (!file) {
continue
}
+
if (file.size > 15_000_000) {
host.notify({
kind: 'error',
message: `${file.name || 'attachment'}: too large (max 15MB).`
})
+
continue
}
+
const data = await new Promise<null | string>(done => {
const reader = new FileReader()
reader.onload = () => done(typeof reader.result === 'string' ? reader.result : null)
reader.onerror = () => done(null)
reader.readAsDataURL(file)
})
+
if (!data) {
continue
}
+
const kind = groupAttachmentKind(file)
picked.push({
name: file.name || (kind === 'image' ? 'pasted image' : 'attachment'),
@@ -56,6 +64,7 @@ export async function filesToGroupAttachments(files: File[] | FileList | null |
kind
})
}
+
return picked
}
@@ -78,12 +87,15 @@ export function pickGroupAttachments(): Promise<Attachment[]> {
function normalizeGroupAttachment(dataUrl: string, maxEdge = 1568): Promise<string> {
return new Promise(resolve => {
const img = new Image()
+
img.onload = () => {
try {
const long = Math.max(img.width, img.height)
+
if (!long || long <= maxEdge) {
return resolve(dataUrl)
}
+
const scale = maxEdge / long
const canvas = document.createElement('canvas')
canvas.width = Math.max(1, Math.round(img.width * scale))
@@ -94,6 +106,7 @@ function normalizeGroupAttachment(dataUrl: string, maxEdge = 1568): Promise<stri
resolve(dataUrl)
}
}
+
img.onerror = () => resolve(dataUrl)
img.src = dataUrl
})
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
index 307f5bf409f..acd4e9c3337 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-parts.tsx
@@ -46,34 +46,44 @@ export function GroupImageControls({ image, onImage, seedName, seedMembers }: Gr
const b = useBots()
const imagen = useValue($imagenAvailable)
const [busy, setBusy] = useState(false)
+
if (imagen === null) {
void probeImagen()
}
+
const upload = async () => {
const raw = await pickImageFromDevice()
+
if (raw) {
onImage(await normalizeAvatarImage(raw))
}
}
+
const generate = async () => {
if (busy) {
return
}
+
setBusy(true)
+
try {
const who = [seedName, seedMembers?.length ? `a team of ${seedMembers.join(', ')}` : '']
.filter(Boolean)
.join(' — ')
+
const res = await host.request<ImageGenerateResponse>('image.generate', {
prompt:
`Group chat icon for an AI agent team called "${who || 'a bot team'}". ` +
'Friendly minimal emblem, bold flat vector style, solid color background, centered, no text.',
aspect_ratio: 'square'
})
+
if (!res?.success) {
throw new Error(res?.error || 'generation failed')
}
+
const img = res.image_data || res.image
+
if (img) {
onImage(await normalizeAvatarImage(img))
}
@@ -83,31 +93,33 @@ export function GroupImageControls({ image, onImage, seedName, seedMembers }: Gr
setBusy(false)
}
}
+
return (
<div className="flex items-center gap-2">
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-(--chrome-action-hover)">
{image ? (
- <img src={image} alt="" className="size-full object-cover" />
+ <img alt="" className="size-full object-cover" src={image} />
) : (
- <Codicon name="organization" className="text-(--ui-text-tertiary)" />
+ <Codicon className="text-(--ui-text-tertiary)" name="organization" />
)}
</div>
- <Button type="button" variant="secondary" size="sm" onClick={upload}>
+ <Button onClick={upload} size="sm" type="button" variant="secondary">
{b.avatar.upload}
</Button>
{imagen ? (
- <Button type="button" variant="secondary" size="sm" disabled={busy} onClick={generate}>
+ <Button disabled={busy} onClick={generate} size="sm" type="button" variant="secondary">
{busy ? 'Generating…' : 'Generate'}
</Button>
) : null}
{image ? (
- <Button type="button" variant="ghost" size="sm" onClick={() => onImage(null)}>
+ <Button onClick={() => onImage(null)} size="sm" type="button" variant="ghost">
Remove
</Button>
) : null}
</div>
)
}
+
interface MentionToken {
query: string
/** Index of the '@' the token starts at. */
@@ -125,9 +137,11 @@ interface MentionToken {
function mentionTokenAt(text: string, caret: number): MentionToken | null {
const upto = String(text || '').slice(0, caret)
const match = /(^|\s)@([a-z0-9._-]*)$/i.exec(upto)
+
if (!match) {
return null
}
+
return {
query: match[2].toLowerCase(),
start: caret - match[2].length - 1
@@ -165,6 +179,7 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
const [token, setToken] = useState<MentionToken | null>(null)
const [selected, setSelected] = useState(0)
const options: MentionOption[] = []
+
if (token) {
for (const pick of ['everyone', 'all']) {
if (pick.startsWith(token.query)) {
@@ -174,14 +189,17 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
})
}
}
+
for (const member of members) {
const handle = String(member.handle || botHandle(member.name, member) || '').trim()
const display = displayName(member, botRosterMeta(member, allMeta))
// Renamed members complete on their friendly tag; parser resolves both.
const tag = String(botMentionTag(member) || handle).trim()
+
if (!tag) {
continue
}
+
if (
token.query &&
!tag.toLowerCase().startsWith(token.query) &&
@@ -190,24 +208,29 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
) {
continue
}
+
options.push({
handle: tag,
meta: display
})
}
}
+
const open = Boolean(token) && options.length > 0
const active = open ? Math.min(selected, options.length - 1) : 0
+
// The onClick below passes `event.target`, which React types as a bare
// EventTarget even though a click on this textarea always targets it.
const refreshToken = (target: HTMLTextAreaElement) => {
setToken(mentionTokenAt(target.value, target.selectionStart ?? target.value.length))
setSelected(0)
}
+
const insert = (handle: string) => {
if (!token) {
return
}
+
const caret = inputRef.current?.selectionStart ?? value.length
const next = `${value.slice(0, token.start)}@${handle} ${value.slice(caret)}`
onChange(next)
@@ -217,8 +240,10 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
const pos = token.start + handle.length + 2
requestAnimationFrame(() => {
const el = inputRef.current
+
if (el) {
el.focus()
+
try {
el.setSelectionRange(pos, pos)
} catch {
@@ -227,17 +252,18 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
}
})
}
+
return (
<div className="relative min-w-0 flex-1">
{open ? (
<div className="absolute bottom-full left-0 z-50 mb-1 max-h-48 w-64 overflow-y-auto rounded-md border border-(--ui-stroke-secondary) bg-(--ui-bg-primary) py-1 shadow-lg">
{options.map((option, index) => (
<RowButton
- key={option.handle}
className={cn(
'flex w-full items-baseline gap-2 px-2 py-1 text-left text-xs',
index === active ? 'bg-(--ui-control-hover-background) text-foreground' : 'text-(--ui-text-secondary)'
)} // preventDefault on mousedown so the input keeps focus.
+ key={option.handle}
onMouseDown={event => {
event.preventDefault()
insert(option.handle)
@@ -252,13 +278,11 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
) : null}
<Textarea
{...inputProps}
- ref={inputRef}
- value={value}
- rows={1} // Multi-line room prompts (#89884): the composer was a single-line
// Input whose form submitted on every Enter — newlines were
// impossible. Enter (no Shift) still submits via onSubmitDraft;
// Shift+Enter falls through to the textarea's native newline.
className={cn('max-h-40 min-h-9 resize-none', inputProps.className)}
+ onBlur={() => setToken(null)}
onChange={event => {
onChange(event.target.value)
refreshToken(event.target)
@@ -273,34 +297,45 @@ export function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...
if (event.nativeEvent?.isComposing || event.keyCode === 229) {
return
}
+
if (open) {
if (event.key === 'ArrowDown') {
event.preventDefault()
setSelected((active + 1) % options.length)
+
return
}
+
if (event.key === 'ArrowUp') {
event.preventDefault()
setSelected((active - 1 + options.length) % options.length)
+
return
}
+
if (event.key === 'Enter' || event.key === 'Tab') {
event.preventDefault()
insert(options[active].handle)
+
return
}
+
if (event.key === 'Escape') {
event.preventDefault()
setToken(null)
+
return
}
}
+
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
onSubmitDraft?.()
}
}}
- onBlur={() => setToken(null)}
+ ref={inputRef}
+ rows={1} // Multi-line room prompts (#89884): the composer was a single-line
+ value={value}
/>
</div>
)
@@ -342,6 +377,7 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
const [drafts, setDrafts] = useState<Record<string, string>>({})
const [picked, setPicked] = useState<Record<string, string[]>>({})
const [sending, setSending] = useState(false)
+
const questions: GroupClarifyQuestion[] =
entry.questions && entry.questions.length
? entry.questions.map((q, i) => ({
@@ -358,27 +394,36 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
multiSelect: entry.multiSelect
}
]
+
const answerFor = (q: GroupClarifyQuestion) => {
const chosen = picked[q.qid] || []
+
if (chosen.length) {
return q.multiSelect ? JSON.stringify(chosen) : chosen[0]
}
+
return isApproval ? '' : (drafts[q.qid] || '').trim()
}
+
const allAnswered = questions.every(q => answerFor(q))
+
const submit = async () => {
if (!member || sending || !allAnswered) {
return
}
+
setSending(true)
+
try {
if (isApproval || !(entry.questions && entry.questions.length)) {
await answerGroupClarify(entry, member, answerFor(questions[0]))
} else {
const answers: Record<string, string> = {}
+
for (const q of questions) {
answers[q.qid] = answerFor(q)
}
+
await answerGroupClarify(entry, member, answers)
}
@@ -386,6 +431,7 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
const summary = isApproval
? `${answerFor(questions[0])} — ${entry.command || entry.question || 'command approval'}`
: questions.map(q => (questions.length > 1 ? `${q.question}: ${answerFor(q)}` : answerFor(q))).join('\n')
+
appendGroupChatEntry(
group,
{
@@ -404,10 +450,11 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
setSending(false)
}
}
+
return (
<div className="grid gap-1.5 rounded-md border border-(--ui-accent)/50 bg-(--ui-accent)/5 px-2.5 py-2">
<div className="flex items-center gap-1.5 text-xs font-medium">
- <Codicon name={isApproval ? 'shield' : 'question'} className="shrink-0 text-(--ui-accent)" />
+ <Codicon className="shrink-0 text-(--ui-accent)" name={isApproval ? 'shield' : 'question'} />
{isApproval
? `@${botHandle(entry.member, member)} wants to run a command:`
: `@${botHandle(entry.member, member)} asks:`}
@@ -418,21 +465,20 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
</code>
) : null}
{questions.map(q => (
- <div key={`q:${q.qid}`} className="grid gap-1">
+ <div className="grid gap-1" key={`q:${q.qid}`}>
{q.question ? <div className="text-xs whitespace-pre-wrap">{q.question}</div> : null}
{q.choices.length ? (
<div className="flex flex-wrap gap-1">
{q.choices.map(choice => {
const chosen = (picked[q.qid] || []).includes(choice)
+
return (
<Button
- key={`choice:${q.qid}:${choice}`}
- size="sm"
- variant={chosen ? 'default' : 'secondary'}
className={cn(
'h-6 px-2 text-[0.7rem]',
isApproval && choice === 'deny' && !chosen && 'text-destructive'
)}
+ key={`choice:${q.qid}:${choice}`}
onClick={() => {
setDrafts(prev => ({
...prev,
@@ -440,6 +486,7 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
}))
setPicked(prev => {
const current = prev[q.qid] || []
+
const next = q.multiSelect
? chosen
? current.filter(c => c !== choice)
@@ -447,12 +494,15 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
: chosen
? []
: [choice]
+
return {
...prev,
[q.qid]: next
}
})
}}
+ size="sm"
+ variant={chosen ? 'default' : 'secondary'}
>
{choice}
</Button>
@@ -463,10 +513,9 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
{/* Approvals are a closed choice set — no free-text input. */}
{isApproval ? null : (
<Input
- key={`input:${q.qid}`}
aria-label={`Answer @${entry.member}`}
- placeholder={q.choices.length ? 'Or type your own answer…' : 'Type your answer…'}
- value={drafts[q.qid] || ''}
+ className="h-7 text-xs"
+ key={`input:${q.qid}`}
onChange={event => {
const value = event.target.value
setPicked(prev => ({
@@ -483,18 +532,20 @@ export function GroupClarifyCard({ entry, members }: GroupClarifyCardProps) {
if (event.nativeEvent?.isComposing || event.keyCode === 229) {
return
}
+
if (event.key === 'Enter' && questions.length === 1) {
event.preventDefault()
void submit()
}
}}
- className="h-7 text-xs"
+ placeholder={q.choices.length ? 'Or type your own answer…' : 'Type your answer…'}
+ value={drafts[q.qid] || ''}
/>
)}
</div>
))}
<div className="flex justify-end">
- <Button size="sm" disabled={sending || !allAnswered || !member} onClick={() => void submit()}>
+ <Button disabled={sending || !allAnswered || !member} onClick={() => void submit()} size="sm">
{sending ? 'Sending…' : isApproval ? 'Respond' : 'Answer'}
</Button>
</div>
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
index 07830aabb60..67758f027cb 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -114,14 +114,17 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
const all = {
...$groupChats.get()
}
+
const prior = all[group] || {}
const metaBefore = $botMeta.get()
const cleanup = groupDisbandMetadataPlan(group, members, prior, $lastRoster.get(), metaBefore)
let metadataPersistence: Promise<unknown> = Promise.resolve()
+
if (cleanup.patches.size) {
const nextMeta = {
...metaBefore
}
+
for (const [key, patch] of cleanup.patches) {
nextMeta[key] = {
...(nextMeta[key] || {}),
@@ -138,7 +141,9 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
botMetaV2Active || Object.keys(nextMeta).some(key => key.includes('::'))
)
}
+
delete all[group]
+
// Keep a runtime-only tombstone while a drive may still be mid-turn; it
// carries no log and is flagged so persistence and name-dedup skip it —
// updateGroupChat writes the WHOLE atom map, so an unflagged tombstone
@@ -154,16 +159,20 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
tombstone: true
}
}
+
$groupChats.set(all)
+
if ($groupChatWorkspace.get() === group) {
$groupChatWorkspace.set(null)
}
// Retire the room's MAIN-window tab too (host.openWorkspace path).
closeGroupChatMainTab(group)
+
const needs = {
...$groupNeedsYou.get()
}
+
delete needs[group]
$groupNeedsYou.set(needs)
clearGroupClarify(group)
@@ -172,6 +181,7 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
// 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] = {
@@ -186,10 +196,12 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
}
}
}
+
await Promise.resolve(getPluginCtx()?.storage?.set?.('group-chats', durable))
} catch {
/* storage unavailable — the atom reset above still empties the room */
}
+
scheduleGroupChatServerSync($groupChats.get(), {
allowEmpty: true,
deletedRooms: [group]
@@ -201,6 +213,7 @@ export async function disbandGroupChat(group: string, members: RosterRow[]) {
// flaky gateway cannot strand the local disband halfway.
for (const [key, owner] of cleanup.owners) {
const patch = cleanup.patches.get(key)
+
if (patch) {
await saveBotMeta(owner, patch)
}
@@ -228,6 +241,7 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
const next = String(newName || '')
.trim()
.slice(0, 64)
+
if (!next || next === oldName) {
return oldName
}
@@ -236,17 +250,21 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
// silently suffixing like creation does. Disband tombstones don't hold
// their name — the room is gone, only its epoch survives briefly.
const taken = new Set(liveGroupChatNames())
+
for (const meta of Object.values($botMeta.get() || {})) {
for (const existing of botGroups(meta)) {
taken.add(existing)
}
}
+
taken.delete(oldName)
+
if (taken.has(next)) {
host.notify({
kind: 'error',
message: `A group named “${next}” already exists.`
})
+
return null
}
@@ -255,18 +273,25 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
const all: Record<string, GroupChat> = {
...$groupChats.get()
}
+
const room = all[oldName]
+
if (room) {
migrateGroupComposerDraft(groupComposerDraftKey(oldName, room), groupComposerDraftKey(next, room))
}
+
delete all[oldName]
+
if (room) {
all[next] = room
}
+
$groupChats.set(all)
+
const needs: Record<string, boolean> = {
...$groupNeedsYou.get()
}
+
if (oldName in needs) {
needs[next] = needs[oldName]
delete needs[oldName]
@@ -284,6 +309,7 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
if (!member?.name) {
continue
}
+
const meta = botRosterMeta(member, $botMeta.get()) || {}
const groups = [...new Set(botGroups(meta).map(g => (g === oldName ? next : g)))]
await saveBotMeta(member, {
@@ -308,6 +334,7 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
if ($groupChatWorkspace.get() === oldName) {
$groupChatWorkspace.set(next)
}
+
if (groupChatMainTabs.has(oldName)) {
closeGroupChatMainTab(oldName)
openGroupChat(next)
@@ -320,6 +347,7 @@ async function renameGroupChat(oldName: string, newName: string, members: GroupM
queryKey: ROSTER_KEY
})
}
+
return next
}
@@ -348,27 +376,33 @@ function GroupChatSettingsDialog({ group, members, open, onClose, onRenamed }: G
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, group])
+
const save = async () => {
const finalName = await renameGroupChat(group, name, members)
+
if (finalName === null) {
return // collision — dialog stays open for a different name
}
+
if (image !== current) {
setGroupChatImage(finalName, image)
}
+
onClose()
+
if (finalName !== group) {
onRenamed?.(finalName)
}
}
+
return (
<Dialog
- open={open}
onOpenChange={value => {
if (!value) {
onClose()
}
}}
+ open={open}
>
<DialogContent className="max-w-sm">
<DialogHeader>
@@ -378,8 +412,8 @@ function GroupChatSettingsDialog({ group, members, open, onClose, onRenamed }: G
<GroupImageControls
image={image}
onImage={setImage}
- seedName={name.trim() || group}
seedMembers={(members || []).map(member => member.name)}
+ seedName={name.trim() || group}
/>
<form
onSubmit={event => {
@@ -391,12 +425,12 @@ function GroupChatSettingsDialog({ group, members, open, onClose, onRenamed }: G
aria-label={b.group.nameLabel}
autoFocus
maxLength={64}
- value={name}
onChange={event => setName(event.target.value)}
+ value={name}
/>
</form>
<DialogFooter>
- <Button variant="secondary" onClick={onClose}>
+ <Button onClick={onClose} variant="secondary">
{t.common.cancel}
</Button>
<Button disabled={!name.trim()} onClick={() => void save()}>
@@ -432,46 +466,57 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
const b = useBots()
const rooms: Record<string, GroupChatRoom> = useValue($groupChats)
const allMeta: Record<string, BotMeta> = useValue($botMeta)
+
const room: GroupChatRoom = rooms[group] || {
log: [],
running: false
}
+
const composerKey = groupComposerDraftKey(group, room)
const composerKeyRef = useRef(composerKey)
const [composerDraft, setComposerDraft] = useState(() => groupComposerDraftSnapshot(composerKey))
+
if (composerKeyRef.current !== composerKey) {
migrateGroupComposerDraft(composerKeyRef.current, composerKey)
composerKeyRef.current = composerKey
}
+
const updateComposerDraft = (mutate: (draft: GroupComposerDraft) => GroupComposerDraft) => {
const next = updateGroupComposerDraft(composerKeyRef.current, mutate)
setComposerDraft(next)
+
return next
}
+
const draft = composerDraft.main || ''
const replyDrafts = composerDraft.replies || {}
const replyThread = composerDraft.activeReplyThread || null
const pendingImages = composerDraft.pendingAttachments || {}
+
const setDraft = (value: GroupDraftSetter<string>) =>
updateComposerDraft(current => ({
...current,
main: typeof value === 'function' ? value(current.main || '') : value
}))
+
const setReplyDrafts = (value: GroupDraftSetter<Record<string, string>>) =>
updateComposerDraft(current => ({
...current,
replies: typeof value === 'function' ? value(current.replies || {}) : value
}))
+
const setReplyThread = (value: GroupDraftSetter<null | string>) =>
updateComposerDraft(current => ({
...current,
activeReplyThread: typeof value === 'function' ? value(current.activeReplyThread || null) : value
}))
+
const setPendingImages = (value: GroupDraftSetter<Record<string, Attachment[]>>) =>
updateComposerDraft(current => ({
...current,
pendingAttachments: typeof value === 'function' ? value(current.pendingAttachments || {}) : value
}))
+
const [confirmDisband, setConfirmDisband] = useState(false)
const [settingsOpen, setSettingsOpen] = useState(false)
// Click-to-disambiguate: which log entry is showing its speaker's full
@@ -494,19 +539,25 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// already near the bottom, so reading history is never yanked away.
const bottomSentinelRef = useRef<HTMLDivElement | null>(null)
const stickToBottomRef = useRef(true)
+ // eslint-disable-next-line no-restricted-syntax -- tracks live scroll position from a DOM listener, not an atom
useEffect(() => {
const sentinel = bottomSentinelRef.current
+
if (!sentinel) {
return
}
+
const viewport = sentinel.closest('[data-slot="scroll-area-viewport"]')
+
if (viewport) {
const onScroll = () => {
stickToBottomRef.current = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight < 80
}
+
viewport.addEventListener('scroll', onScroll, {
passive: true
})
+
return () => viewport.removeEventListener('scroll', onScroll)
}
}, [])
@@ -524,6 +575,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// hidden → visible edge — an explicit reopen, so it overrides a stale
// read-position and mirrors what a fresh open does.
const wasVisibleRef = useRef(visible)
+ // eslint-disable-next-line no-restricted-syntax -- previous-value tracker for the hidden → visible edge; lagging a render IS the contract
useEffect(() => {
if (visible && !wasVisibleRef.current) {
stickToBottomRef.current = true
@@ -531,19 +583,23 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
block: 'end'
})
}
+
wasVisibleRef.current = visible
}, [visible])
const imagesFor = (thread: null | string) => pendingImages[thread ?? 'main'] || []
+
const addImages = (thread: null | string, picked: Attachment[]) => {
if (!picked.length) {
return
}
+
const key = thread ?? 'main'
setPendingImages(prev => ({
...prev,
[key]: [...(prev[key] || []), ...picked]
}))
}
+
const removeImage = (thread: null | string, index: number) => {
const key = thread ?? 'main'
setPendingImages(prev => ({
@@ -555,9 +611,11 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// Ctrl/⌘-V a screenshot (or any file) into any composer in this room.
const pasteImages = (thread: null | string, event: ClipboardEvent<HTMLTextAreaElement>) => {
const files = [...(event.clipboardData?.files || [])]
+
if (!files.length) {
return
}
+
event.preventDefault()
void filesToGroupAttachments(files).then(picked => addImages(thread, picked))
}
@@ -566,12 +624,15 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// open reply box when one owns the composer, else the main (new-thread)
// composer. Matches the 1:1 chat's drop affordance.
const [dragOver, setDragOver] = useState(false)
+
const dropFiles = (event: DragEvent<HTMLDivElement>) => {
const files = [...(event.dataTransfer?.files || [])]
setDragOver(false)
+
if (!files.length) {
return
}
+
event.preventDefault()
void filesToGroupAttachments(files).then(picked => addImages(replyThread, picked))
}
@@ -583,24 +644,28 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
useValue($groupActivity)
// Pending member questions for THIS room (#90694), oldest first.
const clarifyAll: Record<string, GroupRoomPrompt> = useValue($groupClarify)
+
const roomClarifies = Object.values(clarifyAll || {})
.filter(entry => entry?.group === group)
.sort((a, b) => (a.at || 0) - (b.at || 0))
+
const availableMembers = members.filter(member => botSourceStatus(member).available).length
const availabilityLabel = `${availableMembers} of ${members.length} available`
+
const memberNames =
members.map(b => displayName(b, botRosterMeta(b, allMeta))).join(', ') || 'No bots in this group chat'
+
const header = (
<div className="flex items-center gap-2 px-2.5 pt-2.5 pb-2">
- <Button variant="ghost" size="sm" onClick={() => (onBack ? onBack() : $groupChatWorkspace.set(null))}>
+ <Button onClick={() => (onBack ? onBack() : $groupChatWorkspace.set(null))} size="sm" variant="ghost">
Back
</Button>
{/* Room picture (set via Group settings) leads the title when present. */}
{room.image ? (
<img
- src={room.image}
alt=""
className="size-6 shrink-0 rounded-md object-cover ring-1 ring-(--ui-stroke-secondary)"
+ src={room.image}
/>
) : (
<span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-(--chrome-action-hover) text-(--ui-text-tertiary)">
@@ -610,39 +675,40 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
<div className="min-w-0 flex-1 truncate text-sm font-semibold">{group}</div>
<Tip label={memberNames}>
<span
+ aria-label={availabilityLabel}
className={cn(
'shrink-0 text-[0.65rem] text-(--ui-text-quaternary)',
members.length > 0 && availableMembers < members.length && 'text-amber-600 dark:text-amber-300'
)}
- aria-label={availabilityLabel}
>
{members.length > 0 && availableMembers < members.length ? availabilityLabel : `${members.length} bots`}
</span>
</Tip>
<Tip label={`Group settings — rename ${group} or set a room picture`}>
<Button
- variant="ghost"
- size="sm"
- className="shrink-0 text-(--ui-text-tertiary) hover:text-foreground"
aria-label={`Group settings for ${group}`}
+ className="shrink-0 text-(--ui-text-tertiary) hover:text-foreground"
onClick={() => setSettingsOpen(true)}
+ size="sm"
+ variant="ghost"
>
<Codicon name="gear" />
</Button>
</Tip>
<Tip label={`Disband the ${group} group chat`}>
<Button
- variant="ghost"
- size="sm"
- className="shrink-0 text-(--ui-text-tertiary) hover:text-destructive"
aria-label={`Disband ${group}`}
+ className="shrink-0 text-(--ui-text-tertiary) hover:text-destructive"
onClick={() => setConfirmDisband(true)}
+ size="sm"
+ variant="ghost"
>
<Codicon name="trash" />
</Button>
</Tip>
</div>
)
+
const memberDescriptors = () =>
members.map(b => ({
...b,
@@ -654,6 +720,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// Events are epoch-tagged, so a superseded run's history drops out of view.
const activityEvents: GroupActivityEntry[] = currentGroupActivity(group)
const latestActivity = activityEvents.length ? activityEvents[activityEvents.length - 1] : null
+
// #94570 shell rewired onto the real primitive (#91868/#94569): the button
// must stop the ROUND, not just spray per-member interrupts — without the
// epoch bump + holds the loop marched on to the next member. Thread scope:
@@ -665,17 +732,18 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
message: `Stopped ${group} — remaining turns are held until you resume`
})
}
+
const activityPanel = (
<div className="border-b border-(--ui-stroke-secondary)">
<div className="flex items-center gap-1">
<RowButton
- aria-expanded={activityOpen}
aria-controls={`group-activity:${group}`}
- title={activityOpen ? b.group.hideActivity : b.group.showActivity}
+ aria-expanded={activityOpen}
className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1 text-left text-[0.7rem] text-(--ui-text-quaternary) transition-colors hover:text-foreground"
onClick={() => setActivityOpen(prev => !prev)}
+ title={activityOpen ? b.group.hideActivity : b.group.showActivity}
>
- <Codicon name={activityOpen ? 'chevron-down' : 'chevron-right'} className="shrink-0 text-[0.65rem]" />
+ <Codicon className="shrink-0 text-[0.65rem]" name={activityOpen ? 'chevron-down' : 'chevron-right'} />
<span className="shrink-0 font-medium">{b.group.activity}</span>
{latestActivity ? (
<span className="min-w-0 flex-1 truncate">{`${groupActivityLabel(latestActivity)} · ${relativeTime(latestActivity.at)}`}</span>
@@ -696,13 +764,13 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
) : null}
</div>
{activityOpen ? (
- <div id={`group-activity:${group}`} className="grid gap-0.5 px-2.5 pb-1.5">
+ <div className="grid gap-0.5 px-2.5 pb-1.5" id={`group-activity:${group}`}>
{activityEvents.length ? (
[...activityEvents].reverse().map((event, i) => (
- <div key={`${event.at}:${i}`} className="flex items-center gap-1.5 text-[0.7rem]">
+ <div className="flex items-center gap-1.5 text-[0.7rem]" key={`${event.at}:${i}`}>
<Codicon
- name={GROUP_ACTIVITY_GLYPHS[event.kind] || 'circle-outline'}
className={cn('shrink-0 text-[0.65rem]', groupActivityTone(event.kind))}
+ name={GROUP_ACTIVITY_GLYPHS[event.kind] || 'circle-outline'}
/>
<span className={cn('min-w-0 flex-1 truncate', groupActivityTone(event.kind))}>
{groupActivityLabel(event)}
@@ -730,13 +798,17 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
) : null}
</div>
)
+
const submit = () => {
const text = draft.trim()
const images = imagesFor(null)
+
if (!text && !images.length) {
return
}
+
const before = groupComposerDraftSnapshot(composerKeyRef.current)
+
const cleared = updateComposerDraft(current => ({
...current,
main: '',
@@ -745,10 +817,12 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
main: []
}
}))
+
// Main composer = START A NEW THREAD with the whole group (Slack shape).
// Full descriptors ride into the turn loop: remote members keep their
// connection fields so their turns route to their own machines.
const minted = sendToGroupChat(group, memberDescriptors(), text, null, images)
+
if (minted) {
setOpenThreads(prev => ({
...prev,
@@ -756,18 +830,23 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
}))
} else {
const restored = restoreGroupComposerDraft(composerKeyRef.current, cleared.revision, before)
+
if (restored) {
setComposerDraft(restored)
}
}
}
+
const submitReply = (thread: string) => {
const text = (replyDrafts[thread] || '').trim()
const images = imagesFor(thread)
+
if (!text && !images.length) {
return
}
+
const before = groupComposerDraftSnapshot(composerKeyRef.current)
+
const cleared = updateComposerDraft(current => ({
...current,
pendingAttachments: {
@@ -779,9 +858,11 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
[thread]: ''
}
}))
+
// Reply box = CONTINUE this thread; the member turns it triggers are
// scoped to it.
const sent = sendToGroupChat(group, memberDescriptors(), text, thread, images)
+
if (sent) {
setOpenThreads(prev => ({
...prev,
@@ -789,6 +870,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
}))
} else {
const restored = restoreGroupComposerDraft(composerKeyRef.current, cleared.revision, before)
+
if (restored) {
setComposerDraft(restored)
}
@@ -800,23 +882,25 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
* X removes it. */
const attachmentRow = (thread: null | string) => {
const images = imagesFor(thread)
+
if (!images.length) {
return null
}
+
return (
<div className="flex flex-wrap items-center gap-1.5 px-1 pb-1">
{images.map((img, index) => (
<div
- key={`${img.name || 'img'}:${index}`}
className="flex items-center gap-1 rounded-md border border-(--ui-stroke-secondary) bg-(--ui-bg-secondary) px-1 py-0.5"
+ key={`${img.name || 'img'}:${index}`}
>
{img.kind === 'pdf' || img.kind === 'file' ? (
<Codicon
- name={img.kind === 'pdf' ? 'file-pdf' : 'file'}
className="text-[0.9rem] text-(--ui-text-tertiary)"
+ name={img.kind === 'pdf' ? 'file-pdf' : 'file'}
/>
) : (
- <img src={img.data} alt="" className="size-6 rounded object-cover" />
+ <img alt="" className="size-6 rounded object-cover" src={img.data} />
)}
<span className="max-w-32 truncate text-[0.65rem] text-(--ui-text-tertiary)">{img.name || 'image'}</span>
<Tip label="Remove attachment">
@@ -834,14 +918,15 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
</div>
)
}
+
const attachButton = (thread: null | string) => (
<Button
- type="button"
- variant="ghost"
- size="sm"
className="shrink-0 text-(--ui-text-tertiary) hover:text-foreground"
- title={b.group.attachHint}
onClick={() => void pickGroupAttachments().then(picked => addImages(thread, picked))}
+ size="sm"
+ title={b.group.attachHint}
+ type="button"
+ variant="ghost"
>
<Codicon name="attach" />
</Button>
@@ -851,6 +936,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
const renderEntry = (entry: GroupMessage, index: number) => {
const isUser = entry.from.kind === 'user'
const meta = isUser || entry.from.source ? null : allMeta[entry.from.name]
+
// Match this speaker back to its member descriptor so display
// names and disambiguating handles come from the roster (the
// primary "default" profile renders as Hermes, remote dupes
@@ -862,6 +948,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
b.name === entry.from.name &&
(entry.from.source ? (b.connectionLabel || b.connectionId) === entry.from.source : !b.remoteSource)
) || null
+
const display = isUser
? 'You'
: displayName(
@@ -870,8 +957,10 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
},
meta
)
+
const entryKey = `${entry.at}:${index}`
const revealed = !isUser && revealedSpeaker === entryKey
+
// Clicked: append the gateway name so same-named agents on
// two connections are tellable apart on demand.
const label = isUser
@@ -879,6 +968,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
: revealed
? `${display}${entry.from.source ? `-${entry.from.source}` : ''} (@${botHandle(entry.from.name, member || undefined)})`
: display
+
// Speaker avatar: same appearance pipeline as the roster
// (custom image/pet, else deterministic shape+color face).
// Remote speakers have no local meta and get the
@@ -887,22 +977,23 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
const appearance = isUser ? null : botAppearance(entry.from.name, meta)
const image = appearance?.image ?? null
const photo = Boolean(image && !isBackfilledFacePng(image))
+
return (
<div
- key={entryKey}
className={cn(
'group flex items-start gap-2',
isUser ? 'rounded-md bg-(--chrome-action-hover) px-2 py-1.5' : 'px-2 py-1'
)}
+ key={entryKey}
>
{appearance ? (
<div className="mt-0.5 shrink-0">
<BotFace
- shape={appearance.shape}
color={avatarColor(appearance.color, entry.from.name)}
image={photo ? image : null}
- size={24}
name={entry.from.name}
+ shape={appearance.shape}
+ size={24}
/>
</div>
) : null}
@@ -913,9 +1004,9 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
) : (
<Button
className="text-left text-[0.7rem] font-semibold text-(--ui-accent)"
- title={revealed ? 'Hide full handle' : 'Show full handle'}
onClick={() => setRevealedSpeaker(revealed ? null : entryKey)}
size="inline"
+ title={revealed ? 'Hide full handle' : 'Show full handle'}
variant="text"
>
{label}
@@ -943,20 +1034,20 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
{entry.images.map((img, imgIndex) =>
img.kind === 'pdf' || img.kind === 'file' ? (
<div
- key={`${entryKey}:img:${imgIndex}`}
className="flex items-center gap-1 rounded-md border border-(--ui-stroke-secondary) px-1.5 py-1 text-[0.65rem] text-(--ui-text-tertiary)"
+ key={`${entryKey}:img:${imgIndex}`}
title={img.name || 'attached file'}
>
- <Codicon name={img.kind === 'pdf' ? 'file-pdf' : 'file'} className="text-[0.8rem]" />
+ <Codicon className="text-[0.8rem]" name={img.kind === 'pdf' ? 'file-pdf' : 'file'} />
<span className="max-w-48 truncate">{img.name || 'attached file'}</span>
</div>
) : (
<img
+ alt={img.name || 'attached image'}
+ className="max-h-40 max-w-60 rounded-md border border-(--ui-stroke-secondary) object-contain"
key={`${entryKey}:img:${imgIndex}`}
src={img.data}
- alt={img.name || 'attached image'}
title={img.name || 'attached image'}
- className="max-h-40 max-w-60 rounded-md border border-(--ui-stroke-secondary) object-contain"
/>
)
)}
@@ -974,10 +1065,12 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
// Slack-style summary row unless explicitly opened. Every open thread gets
// its own reply box, which continues THAT thread.
const threadsById = new Map<string, GroupThreadBucket>()
+
for (let i = 0; i < room.log.length; i++) {
const entry = room.log[i]
const id = groupThreadOf(entry)
let bucket = threadsById.get(id)
+
if (!bucket) {
bucket = {
entries: [],
@@ -986,14 +1079,17 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
}
threadsById.set(id, bucket)
}
+
bucket.entries.push({
entry,
index: i
})
}
+
const threads = [...threadsById.values()].sort(
(a, b) => (a.entries[a.entries.length - 1].entry.at || 0) - (b.entries[b.entries.length - 1].entry.at || 0)
)
+
const newestThread = threads.length ? threads[threads.length - 1].id : null
const logChildren: ReactNode[] = []
threads.forEach(threadBucket => {
@@ -1001,50 +1097,54 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
const head = entries.find(({ entry }) => entry.from.kind === 'user')?.entry || entries[0].entry
const isNewest = id === newestThread
const expanded = openThreads[id] ?? isNewest
+
if (!expanded) {
const replies = entries.length - 1
const headText = stripPreviewMarkdown(head?.text || '').slice(0, 80)
logChildren.push(
<RowButton
- key={`fold:${id}`}
className="flex w-full items-center gap-2 rounded-md border border-(--ui-stroke-secondary) px-2 py-1.5 text-left text-xs text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover)"
- title={b.group.openThread}
+ key={`fold:${id}`}
onClick={() =>
setOpenThreads(prev => ({
...prev,
[id]: true
}))
}
+ title={b.group.openThread}
>
- <Codicon name="chevron-right" className="shrink-0 text-[0.65rem]" />
+ <Codicon className="shrink-0 text-[0.65rem]" name="chevron-right" />
<span className="min-w-0 flex-1 truncate">{headText || 'Thread'}</span>
<span className="shrink-0 text-[0.625rem] text-(--ui-text-quaternary)">{`${replies} ${replies === 1 ? 'reply' : 'replies'} · ${relativeTime(entries[entries.length - 1].entry.at)}`}</span>
</RowButton>
)
+
return
}
// Open thread: a rail-indented block — collapse affordance, its entries,
// and its own reply box (Slack's "reply in thread").
const threadRows: ReactNode[] = []
+
if (!isNewest || openThreads[id] !== undefined) {
threadRows.push(
<RowButton
- key={`unfold:${id}`}
className="flex w-full items-center gap-1.5 px-2 pt-1 text-left text-[0.65rem] text-(--ui-text-quaternary) transition-colors hover:text-foreground"
- title={b.group.collapseThreadLabel}
+ key={`unfold:${id}`}
onClick={() =>
setOpenThreads(prev => ({
...prev,
[id]: false
}))
}
+ title={b.group.collapseThreadLabel}
>
- <Codicon name="chevron-down" className="text-[0.6rem]" />
+ <Codicon className="text-[0.6rem]" name="chevron-down" />
{b.group.collapseThread}
</RowButton>
)
}
+
for (const { entry, index } of entries) {
threadRows.push(renderEntry(entry, index))
}
@@ -1054,8 +1154,8 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
threadRows.push(
replyThread === id ? (
<form
- key={`replybox:${id}`}
className="grid gap-0 px-2 pb-1"
+ key={`replybox:${id}`}
onSubmit={event => {
event.preventDefault()
submitReply(id)
@@ -1066,28 +1166,28 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
<GroupMentionInput
aria-label={b.group.replyInThread}
autoFocus
- placeholder={b.group.replyInThreadPlaceholder}
members={members}
- value={replyDrafts[id] || ''}
onChange={text =>
setReplyDrafts(prev => ({
...prev,
[id]: text
}))
}
- onSubmitDraft={() => submitReply(id)}
onPaste={event => pasteImages(id, event)}
+ onSubmitDraft={() => submitReply(id)}
+ placeholder={b.group.replyInThreadPlaceholder}
+ value={replyDrafts[id] || ''}
/>
{attachButton(id)}
- <Button type="submit" size="sm" disabled={!(replyDrafts[id] || '').trim() && !imagesFor(id).length}>
+ <Button disabled={!(replyDrafts[id] || '').trim() && !imagesFor(id).length} size="sm" type="submit">
{b.group.reply}
</Button>
</div>
</form>
) : (
<Button
- key={`replylink:${id}`}
className="w-fit px-2 pb-1 text-left text-[0.65rem] text-(--ui-accent) transition-colors"
+ key={`replylink:${id}`}
onClick={() => setReplyThread(id)}
size="inline"
variant="link"
@@ -1097,20 +1197,15 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
)
)
logChildren.push(
- <div key={`thread:${id}`} className="grid gap-1.5 border-l-2 border-(--ui-stroke-secondary) pl-1.5">
+ <div className="grid gap-1.5 border-l-2 border-(--ui-stroke-secondary) pl-1.5" key={`thread:${id}`}>
{threadRows}
</div>
)
})
+
return (
<div
className="relative flex h-full flex-col"
- onDragOver={event => {
- if ([...(event.dataTransfer?.types || [])].includes('Files')) {
- event.preventDefault()
- setDragOver(true)
- }
- }}
onDragLeave={event => {
// Only clear when leaving the room container itself, not when the
// cursor moves between its children. React types relatedTarget as a
@@ -1119,12 +1214,18 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
setDragOver(false)
}
}}
+ onDragOver={event => {
+ if ([...(event.dataTransfer?.types || [])].includes('Files')) {
+ event.preventDefault()
+ setDragOver(true)
+ }
+ }}
onDrop={dropFiles}
>
{dragOver ? (
<div
- key={'dropzone'}
className="pointer-events-none absolute inset-0 z-40 flex items-center justify-center border-2 border-dashed border-(--ui-accent) text-sm font-medium text-(--ui-accent)"
+ key={'dropzone'}
>
{replyThread ? 'Drop to attach to this thread reply' : 'Drop to attach — every responding bot sees it'}
</div>
@@ -1136,15 +1237,15 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
{room.log.length
? logChildren
: [
- <div key={'empty'} className="px-2 py-4 text-center text-xs text-(--ui-text-tertiary)">
+ <div className="px-2 py-4 text-center text-xs text-(--ui-text-tertiary)" key={'empty'}>
{b.group.composerPlaceholder}
</div>
]}
{roomClarifies.map(entry => (
- <GroupClarifyCard key={`clarify:${entry.memberKey}:${entry.requestId}`} entry={entry} members={members} />
+ <GroupClarifyCard entry={entry} key={`clarify:${entry.memberKey}:${entry.requestId}`} members={members} />
))}
{room.running ? (
- <div key={'working'} className="px-2 py-1 text-[0.7rem] italic text-(--ui-text-quaternary)">
+ <div className="px-2 py-1 text-[0.7rem] italic text-(--ui-text-quaternary)" key={'working'}>
{roomClarifies.length
? 'Waiting for your answer…'
: room.turn
@@ -1155,7 +1256,7 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
{/* Scroll anchor (#89835): rooms opened at scroll position 0, mid- */
/* history. The effect below scrolls this sentinel into view on */
/* mount and on log growth — unless the user has scrolled up. */}
- <div key={'bottom-sentinel'} ref={bottomSentinelRef} aria-hidden />
+ <div aria-hidden key={'bottom-sentinel'} ref={bottomSentinelRef} />
</div>
</div>
<div className="border-t border-(--ui-stroke-secondary) p-2">
@@ -1170,15 +1271,15 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
<div className="flex items-center gap-1.5">
<GroupMentionInput
aria-label={`Message ${group}`}
- placeholder={`New thread in ${group}… (@name to direct, @everyone for all)`}
members={members}
- value={draft}
onChange={setDraft}
- onSubmitDraft={submit}
onPaste={event => pasteImages(null, event)}
+ onSubmitDraft={submit}
+ placeholder={`New thread in ${group}… (@name to direct, @everyone for all)`}
+ value={draft}
/>
{attachButton(null)}
- <Button type="submit" size="sm" disabled={!draft.trim() && !imagesFor(null).length}>
+ <Button disabled={!draft.trim() && !imagesFor(null).length} size="sm" type="submit">
{b.group.newThread}
</Button>
</div>
@@ -1187,12 +1288,12 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
<GroupChatSettingsDialog
group={group}
members={members}
- open={settingsOpen}
onClose={() => setSettingsOpen(false)}
+ open={settingsOpen}
/>
<ConfirmDialog
- open={confirmDisband}
- title={b.group.disbandTitle}
+ busyLabel="Disbanding…"
+ confirmLabel="Disband"
description={
<span>
{'This removes the '}
@@ -1205,8 +1306,6 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
</span>
}
destructive
- confirmLabel="Disband"
- busyLabel="Disbanding…"
doneLabel="Disbanded"
onClose={() => setConfirmDisband(false)}
onConfirm={async () => {
@@ -1217,6 +1316,8 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
message: `Disbanded “${group}”`
})
}}
+ open={confirmDisband}
+ title={b.group.disbandTitle}
/>
</div>
)
@@ -1231,12 +1332,14 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G
interface GroupChatMainViewProps {
group: string
}
+
function GroupChatMainView({ group }: GroupChatMainViewProps) {
const allMeta = useValue($botMeta)
// Subscribe: membership changes ride bot meta AND the room record.
useValue($groupChats)
const roster = useValue($lastRoster)
const members = groupChatMemberBots(group, roster, allMeta)
+
// Older SDKs have no paneVisibility: fall back to an always-visible atom so
// the hook order stays stable and behavior matches the previous build.
const $visible = useMemo(
@@ -1246,9 +1349,11 @@ function GroupChatMainView({ group }: GroupChatMainViewProps) {
: atom(true),
[group]
)
+
const visible = useValue($visible)
+
return (
- <GroupChatWorkspace group={group} members={members} visible={visible} onBack={() => closeGroupChatMainTab(group)} />
+ <GroupChatWorkspace group={group} members={members} onBack={() => closeGroupChatMainTab(group)} visible={visible} />
)
}
@@ -1273,6 +1378,7 @@ export function openGroupChat(group: string): void {
})
const ownerKey = groupWorkspaceOwnerKey(group)
setBotsWorkspaceOwner(ownerKey, null, 'New group conversations start in the group composer.')
+
if (typeof host.openWorkspace === 'function') {
try {
const close = host.openWorkspace(`${ID}:group:${slugify(group)}`, {
@@ -1281,15 +1387,18 @@ export function openGroupChat(group: string): void {
render: () => <GroupChatMainView group={group} />,
onClose: () => {
dropGroupMainTab(group)
+
if ($groupChatWorkspace.get() === group) {
$groupChatWorkspace.set(null)
}
}
})
+
recordGroupMainTab(group, close)
// Tab ownership is on record — the atom now only drives the roster
// highlight; shouldRenderGroupChatInPane stays false throughout.
$groupChatWorkspace.set(group)
+
return
} catch {
// Fall through to the in-panel room below.
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.ts
index 47c5bdc7e28..c3eae7a1397 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.ts
@@ -92,14 +92,17 @@ export 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: unknown) {
+export function groupChatGatewayJsonSize(value: unknown) {
const json = JSON.stringify(value)
let bytes = 0
+
for (const character of json) {
// Non-null: string iteration yields whole code points, never an empty string.
const codePoint = character.codePointAt(0)!
+
if (codePoint <= 0x7f) {
bytes += 1
+
if (character === ',' || character === ':') {
bytes += 1
}
@@ -107,6 +110,7 @@ function groupChatGatewayJsonSize(value: unknown) {
bytes += codePoint <= 0xffff ? 6 : 12
}
}
+
return bytes
}
@@ -130,6 +134,7 @@ function normalizeGroupChatSyncSnapshot(snapshot: GroupChatSyncSnapshot | null |
deleted: {}
}
}
+
if (Number(snapshot.version || 0) >= 3) {
return {
version: 3,
@@ -138,23 +143,29 @@ function normalizeGroupChatSyncSnapshot(snapshot: GroupChatSyncSnapshot | null |
deleted: snapshot.deleted && typeof snapshot.deleted === 'object' ? snapshot.deleted : {}
}
}
+
const rooms: Record<string, GroupChatSyncRoom> = {}
+
for (const [name, room] of Object.entries(snapshot.rooms || {})) {
if (!room || !Array.isArray(room.log)) {
continue
}
+
rooms[`name:${name}`] = {
...room,
name
}
}
+
const deleted: Record<string, number> = {}
+
for (const [name, at] of Object.entries(snapshot.deleted || {})) {
// v1 tombstones carried wall-clock ms, not gateway revisions — they must
// not outrank real revisions (same rule groupChatSyncDeletedRevision
// applied before v3).
deleted[`name:${name}`] = Number(snapshot.version || 0) >= 2 ? Math.max(0, Number(at || 0)) : 0
}
+
return {
version: 3,
updatedAt: Number(snapshot.updatedAt || 0),
@@ -167,7 +178,7 @@ function normalizeGroupChatSyncSnapshot(snapshot: GroupChatSyncSnapshot | null |
* 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(
+export function groupChatSyncSnapshot(
// `revision` is the pre-`syncRevision` field name, still read below as a
// fallback for rooms hydrated from an older plugin-storage record.
all: Record<string, GroupChat & { revision?: number }> = $groupChats.get(),
@@ -180,14 +191,18 @@ function groupChatSyncSnapshot(
.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: Record<string, GroupChatSyncRoom> = {}
+
const boundedDeleted = Object.fromEntries(
Object.entries(deleted)
.sort(([, left], [, right]) => Number(right || 0) - Number(left || 0))
.slice(0, 64)
)
+
const envelope: GroupChatSyncSnapshot = {
version: 3,
updatedAt: Date.now(),
@@ -198,6 +213,7 @@ function groupChatSyncSnapshot(
}
: {})
}
+
for (const [name, room] of ranked) {
const log: GroupMessage[] = room.log.slice(-GROUP_CHAT_SYNC_MESSAGES).map(entry => ({
...(entry?.id
@@ -222,6 +238,7 @@ function groupChatSyncSnapshot(
}
: {})
}))
+
const compact: GroupChatSyncRoom = {
name: String(name).slice(0, 64),
...(typeof room?.roomId === 'string' && room.roomId
@@ -265,24 +282,31 @@ function groupChatSyncSnapshot(
}
: {})
}
+
const key = groupChatRoomKey(name, room)
rooms[key] = compact
+
while (compact.log.length > 1 && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
compact.log.shift()
}
+
if (compact.image && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
delete compact.image
}
+
if (groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
delete rooms[key]
}
}
+
return envelope
}
+
function groupChatSyncEntryKey(entry: GroupMessage) {
if (entry?.id) {
return `id:${String(entry.id)}`
}
+
return JSON.stringify([
Number(entry?.at || 0),
String(entry?.from?.kind || ''),
@@ -299,6 +323,7 @@ function groupChatSyncEntryKey(entry: GroupMessage) {
String(entry?.text || '')
])
}
+
function groupChatSyncMemberKey(member: GroupMember & { source?: string }) {
// TODO(bot-mode-types): `member.source` cannot exist. Member descriptors are
// roster-derived (name/handle/connectionId/connectionLabel); only message
@@ -312,6 +337,7 @@ function groupChatSyncMemberKey(member: GroupMember & { source?: string }) {
String(member?.name || '')
])
}
+
function groupChatSyncDeletedRevision(source: GroupChatSyncSnapshot | null | undefined, value: unknown) {
return Number(source?.version || 0) >= 2 ? Math.max(0, Number(value || 0)) : 0
}
@@ -323,7 +349,7 @@ function groupChatSyncDeletedRevision(source: GroupChatSyncSnapshot | null | und
* itself. Gateway revisions order identity/membership/picture and
* tombstones; stable message ids make concurrent log union idempotent.
* `changedRooms`/`deletedRooms` accept display names or room keys. */
-function mergeGroupChatSyncSnapshots(
+export function mergeGroupChatSyncSnapshots(
remote: GroupChatSyncSnapshot | null | undefined,
local: GroupChatSyncSnapshot | null | undefined,
{
@@ -334,32 +360,41 @@ function mergeGroupChatSyncSnapshots(
) {
const remoteNorm = normalizeGroupChatSyncSnapshot(remote)
const localNorm = normalizeGroupChatSyncSnapshot(local)
+
const keysFor = (label: string, norm: GroupChatSyncSnapshot) => {
const keys = new Set<string>()
+
for (const [key, room] of Object.entries(norm.rooms || {})) {
if (key === label || String(room?.name || '') === label || key === `name:${label}`) {
keys.add(key)
}
}
+
if (String(label).startsWith('id:') || String(label).startsWith('name:')) {
keys.add(label)
} else if (!keys.size) {
keys.add(`name:${label}`)
}
+
return keys
}
+
const changed = new Set<string>()
+
for (const label of changedRooms) {
for (const key of keysFor(label, localNorm)) {
changed.add(key)
}
}
+
const deleted: Record<string, number> = {}
+
for (const source of [remoteNorm, localNorm]) {
for (const [key, at] of Object.entries(source.deleted || {})) {
deleted[key] = Math.max(Number(deleted[key] || 0), Math.max(0, Number(at || 0)))
}
}
+
for (const label of deletedRooms) {
for (const key of new Set([...keysFor(label, remoteNorm), ...keysFor(label, localNorm)])) {
// Rename passes changedRooms:[newName] + deletedRooms:[oldName]. For an
@@ -370,22 +405,30 @@ function mergeGroupChatSyncSnapshots(
if (changed.has(key)) {
continue
}
+
deleted[key] = Math.max(Number(deleted[key] || 0), Number(writeRevision || 0))
}
}
+
const rooms: Record<string, GroupChatSyncRoom> = {}
const roomKeys = new Set([...Object.keys(remoteNorm.rooms || {}), ...Object.keys(localNorm.rooms || {})])
+
for (const key of roomKeys) {
const remoteRoom = remoteNorm.rooms?.[key]
const localRoom = localNorm.rooms?.[key]
+
if ((!remoteRoom || !Array.isArray(remoteRoom.log)) && (!localRoom || !Array.isArray(localRoom.log))) {
continue
}
+
const remoteRevision = Math.max(0, Number(remoteRoom?.revision || 0))
+
const localRevision = changed.has(key)
? Math.max(0, Number(writeRevision || 0))
: Math.max(0, Number(localRoom?.revision || 0))
+
const entries = new Map<string, GroupMessage>()
+
for (const entry of [...(remoteRoom?.log || []), ...(localRoom?.log || [])]) {
entries.set(groupChatSyncEntryKey(entry), entry)
}
@@ -395,6 +438,7 @@ function mergeGroupChatSyncSnapshots(
let identity: GroupChatSyncRoom | undefined
let members: GroupMember[]
let image: null | string | undefined
+
if (localRevision > remoteRevision) {
identity = localRoom
members = [...(localRoom?.members || [])]
@@ -406,12 +450,15 @@ function mergeGroupChatSyncSnapshots(
} else {
identity = localRoom || remoteRoom
const byId = new Map<string, GroupMember>()
+
for (const member of [...(remoteRoom?.members || []), ...(localRoom?.members || [])]) {
byId.set(groupChatSyncMemberKey(member), member)
}
+
members = [...byId.values()]
image = Object.prototype.hasOwnProperty.call(localRoom || {}, 'image') ? localRoom.image : remoteRoom?.image
}
+
rooms[key] = {
...(identity?.name
? {
@@ -425,6 +472,7 @@ function mergeGroupChatSyncSnapshots(
: {}),
log: [...entries.values()].sort((left, right) => {
const byTime = Number(left?.at || 0) - Number(right?.at || 0)
+
return byTime || groupChatSyncEntryKey(left).localeCompare(groupChatSyncEntryKey(right))
}),
members,
@@ -436,6 +484,7 @@ function mergeGroupChatSyncSnapshots(
: {})
}
}
+
for (const [key, deletedRevision] of Object.entries(deleted)) {
if (key.startsWith('id:')) {
// Tombstones for id-keyed rooms are FINAL: the roomId is minted once
@@ -450,6 +499,7 @@ function mergeGroupChatSyncSnapshots(
delete deleted[key]
}
}
+
return groupChatSyncEnvelope(rooms, deleted)
}
@@ -463,6 +513,7 @@ function groupChatSyncEnvelope(
.sort(([, left], [, right]) => Number(right || 0) - Number(left || 0))
.slice(0, 64)
)
+
const envelope: GroupChatSyncSnapshot = {
version: 3,
updatedAt: Date.now(),
@@ -473,22 +524,28 @@ function groupChatSyncEnvelope(
}
: {})
}
+
const ranked = Object.entries(rooms).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 leftAt - rightAt
})
+
for (const [key, room] of ranked) {
while ((room.log?.length || 0) > 1 && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
room.log.shift()
}
+
if (room.image && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
delete room.image
}
+
if (groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
delete rooms[key]
}
}
+
return envelope
}
@@ -496,38 +553,46 @@ function groupChatSyncEnvelope(
* state without discarding local session/watermark/runtime fields. Missing
* remote rooms/messages are not deletions; only explicit tombstones remove a
* room, and a genuinely newer local message wins over a stale tombstone. */
-function mergeRemoteGroupChatSnapshotIntoRooms(
+export function mergeRemoteGroupChatSnapshotIntoRooms(
remote: GroupChatSyncSnapshot | null | undefined,
current: Record<string, GroupChat> = $groupChats.get(),
{ preserveRooms = [], deletedRooms = [] }: { deletedRooms?: string[]; preserveRooms?: string[] } = {}
) {
const remoteNorm = normalizeGroupChatSyncSnapshot(remote)
+
const rooms: Record<string, GroupChat> = {
...(current || {})
}
+
const preserved = new Set(preserveRooms)
const locallyDeleted = new Set(deletedRooms)
// Local rooms indexed by durable identity so an id-keyed projection room
// finds its local twin even when the display name changed remotely.
const localByRoomId = new Map<string, string>()
+
for (const [name, room] of Object.entries(rooms)) {
if (typeof room?.roomId === 'string' && room.roomId) {
localByRoomId.set(room.roomId, name)
}
}
+
for (const [key, projected] of Object.entries(remoteNorm.rooms || {})) {
if (!projected || !Array.isArray(projected.log)) {
continue
}
+
const projectedRoomId = projected.roomId || (key.startsWith('id:') ? key.slice(3) : null)
+
const localName =
projectedRoomId && localByRoomId.has(projectedRoomId)
? localByRoomId.get(projectedRoomId)
: projected.name && rooms[projected.name]
? projected.name
: null
+
const displayName = String(projected.name || localName || (key.startsWith('name:') ? key.slice(5) : key))
+
if (locallyDeleted.has(displayName) || (localName && locallyDeleted.has(localName))) {
// Mid-rename guard: the remote copy may still be under the OLD display
// name while the local record was already re-keyed (same roomId, new
@@ -536,23 +601,31 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
if (localName && localName !== displayName && !locallyDeleted.has(localName)) {
continue
}
+
delete rooms[displayName]
+
if (localName) {
delete rooms[localName]
}
+
continue
}
+
const existing = (localName ? rooms[localName] : rooms[displayName]) || {}
const remoteRevision = Math.max(0, Number(projected.revision || 0))
const localRevision = Math.max(0, Number(existing.syncRevision || 0))
+
const entries = new Map<string, GroupMessage>(
(Array.isArray(existing.log) ? existing.log : []).map(entry => [groupChatSyncEntryKey(entry), entry])
)
+
const members = new Map<string, GroupMember>(
(Array.isArray(existing.members) ? existing.members : []).map(member => [groupChatSyncMemberKey(member), member])
)
+
for (const entry of projected.log) {
const entryKey = groupChatSyncEntryKey(entry)
+
// The projection is COMPACT (truncated text, no images). When the same
// entry exists locally, the local rich copy is authoritative — merging
// the compact twin over it would strip attachments and retrigger
@@ -561,11 +634,14 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
entries.set(entryKey, entry)
}
}
+
const isPreserved = preserved.has(displayName) || (localName && preserved.has(localName))
+
if (!isPreserved) {
if (remoteRevision > localRevision) {
members.clear()
}
+
for (const member of Array.isArray(projected.members) ? projected.members : []) {
members.set(groupChatSyncMemberKey(member), {
...member,
@@ -573,21 +649,26 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
})
}
}
+
const log = assignLegacyThreads(
[...entries.values()].sort((left, right) => {
const byTime = Number(left?.at || 0) - Number(right?.at || 0)
+
return byTime || groupChatSyncEntryKey(left).localeCompare(groupChatSyncEntryKey(right))
})
)
+
const bounded = trimGroupChatLog(log, existing.watermarks || {})
// A remote rename with a higher revision moves the local record to the
// new display name; local views keyed by the old name follow on the
// next repaint (roster derives from $groupChats keys).
const targetName = !isPreserved && remoteRevision > localRevision ? displayName : localName || displayName
+
if (localName && targetName !== localName) {
delete rooms[localName]
}
+
rooms[targetName] = {
...existing,
log: bounded.log,
@@ -610,39 +691,49 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
running: Boolean(existing.running)
}
}
+
for (const [key, deletedAt] of Object.entries(remoteNorm.deleted || {})) {
const deletedRoomId = key.startsWith('id:') ? key.slice(3) : null
+
const targetName =
deletedRoomId && localByRoomId.has(deletedRoomId)
? localByRoomId.get(deletedRoomId)
: key.startsWith('name:')
? key.slice(5)
: null
+
if (!targetName || preserved.has(targetName)) {
continue
}
+
if (deletedRoomId) {
// Id tombstones are final — the id is never reused, so there is no
// legitimate higher-revision recreation to protect.
delete rooms[targetName]
} else {
const deletedRevision = Math.max(0, Number(deletedAt || 0))
+
if (deletedRevision >= Number(rooms[targetName]?.syncRevision || 0)) {
delete rooms[targetName]
}
}
}
+
for (const name of locallyDeleted) {
delete rooms[name]
}
+
return rooms
}
-function durableGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get()) {
+
+export function durableGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get()) {
const durable: Record<string, GroupChat> = {}
+
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
@@ -650,6 +741,7 @@ function durableGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get(
if (room.tombstone) {
continue
}
+
durable[name] = {
log: room.log,
watermarks: room.watermarks || {},
@@ -666,9 +758,11 @@ function durableGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get(
syncRevision: Math.max(0, Number(room.syncRevision || 0))
}
}
+
return durable
}
-function persistGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get()) {
+
+export function persistGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get()) {
try {
return Promise.resolve(getPluginCtx()?.storage?.set?.('group-chats', durableGroupChatRooms(all))).catch(() => undefined)
} catch {
@@ -683,15 +777,20 @@ function persistGroupChatRooms(all: Record<string, GroupChat> = $groupChats.get(
* Returns whether anything changed. */
export function sweepGroupChatMembersForRemovedConnection(connectionId: string) {
const id = String(connectionId || '').trim()
+
if (!id) {
return false
}
+
let changed = false
+
for (const [name, room] of Object.entries($groupChats.get())) {
const members = Array.isArray(room?.members) ? room.members : []
+
if (!members.some(member => groupMemberReferencesConnection(member, id) && !member?.sourceMissing)) {
continue
}
+
changed = true
updateGroupChat(name, (current: GroupChat) => ({
...current,
@@ -700,6 +799,7 @@ export function sweepGroupChatMembersForRemovedConnection(connectionId: string)
)
}))
}
+
return changed
}
@@ -717,27 +817,36 @@ async function groupChatSyncRequest<T>(
): Promise<T> {
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: GroupChatSyncJob) {
const result = await groupChatSyncRequest<{ profiles?: RosterRow[] }>(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] as GroupChatSyncSnapshot | undefined
const supportsCas = Boolean(profile && Object.prototype.hasOwnProperty.call(profile, 'ui_meta_revisions'))
+
return {
snapshot: snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) ? snapshot : null,
revision: Math.max(0, Number(profile?.ui_meta_revisions?.[GROUP_CHAT_SYNC_META_KEY] || 0)),
@@ -751,26 +860,35 @@ export async function pullGroupChatServerState(connectionId: string = groupChatS
const { snapshot: remote } = await groupChatRemoteSnapshot({
connectionId
})
+
if (!remote) {
return false
}
+
const pending = groupChatSyncPendingByConnection.get(String(connectionId || ''))
+
const merged = mergeRemoteGroupChatSnapshotIntoRooms(remote, $groupChats.get(), {
preserveRooms: pending?.changedRooms || [],
deletedRooms: pending?.deletedRooms || []
})
+
$groupChats.set(merged)
await persistGroupChatRooms(merged)
+
return true
}
+
function groupChatSyncBackoff(connectionId: string) {
const count = Number(groupChatSyncRetryCounts.get(connectionId) || 0)
+
return Math.min(30000, 1000 * 2 ** Math.min(count, 5))
}
+
function mergeGroupChatSyncJobs(existing: GroupChatSyncJob | undefined, incoming: GroupChatSyncJob): GroupChatSyncJob {
if (!existing || existing.connectionId !== incoming.connectionId) {
return incoming
}
+
return {
connectionId: incoming.connectionId,
allowEmpty: Boolean(existing.allowEmpty || incoming.allowEmpty),
@@ -778,6 +896,7 @@ function mergeGroupChatSyncJobs(existing: GroupChatSyncJob | undefined, incoming
deletedRooms: [...new Set([...(existing.deletedRooms || []), ...(incoming.deletedRooms || [])])]
}
}
+
function groupChatSyncPayloadEqual(
left: GroupChatSyncSnapshot | null | undefined,
right: GroupChatSyncSnapshot | null | undefined
@@ -797,12 +916,15 @@ async function groupChatSyncTargetConnections() {
const targets = new Set<string>()
const active = groupChatSyncConnectionId()
targets.add(String(active || ''))
+
if (typeof host.profileRoutes === 'function' && typeof host.requestProfile === 'function') {
try {
const routes = await host.profileRoutes()
+
for (const route of Array.isArray(routes) ? routes : []) {
const profile = String(route?.targetProfile || route?.profile || '')
const connectionId = String(route?.connectionId || '')
+
if (profile === 'default' && connectionId) {
targets.add(connectionId)
}
@@ -811,28 +933,36 @@ async function groupChatSyncTargetConnections() {
// Route inventory unavailable — the active gateway alone still syncs.
}
}
+
return [...targets]
}
+
async function flushGroupChatServerSync(connectionId?: string) {
if (connectionId === undefined) {
// Drain every connection with pending work.
for (const pendingId of [...groupChatSyncPendingByConnection.keys()]) {
void flushGroupChatServerSync(pendingId)
}
+
return
}
+
const id = String(connectionId || '')
+
if (groupChatSyncDisposed || groupChatSyncInFlightConnections.has(id) || !groupChatSyncPendingByConnection.has(id)) {
return
}
+
// Non-null: the `has(id)` guard directly above is the entry condition.
const job = groupChatSyncPendingByConnection.get(id)!
groupChatSyncPendingByConnection.delete(id)
groupChatSyncInFlightConnections.add(id)
+
try {
const remoteState = await groupChatRemoteSnapshot(job)
const local = groupChatSyncSnapshot($groupChats.get())
const writeRevision = remoteState.revision + 1
+
const snapshot = mergeGroupChatSyncSnapshots(remoteState.snapshot, local, {
changedRooms: job.changedRooms,
deletedRooms: job.deletedRooms,
@@ -849,16 +979,21 @@ async function flushGroupChatServerSync(connectionId?: string) {
) {
if (remoteState.snapshot) {
const pending = groupChatSyncPendingByConnection.get(id)
+
const mergedRooms = mergeRemoteGroupChatSnapshotIntoRooms(remoteState.snapshot, $groupChats.get(), {
preserveRooms: pending?.changedRooms || [],
deletedRooms: pending?.deletedRooms || []
})
+
$groupChats.set(mergedRooms)
await persistGroupChatRooms(mergedRooms)
}
+
groupChatSyncRetryCounts.delete(id)
+
return
}
+
const configureParams: {
name: string
ui_meta: Record<string, GroupChatSyncSnapshot>
@@ -869,50 +1004,64 @@ async function flushGroupChatServerSync(connectionId?: string) {
[GROUP_CHAT_SYNC_META_KEY]: snapshot
}
}
+
if (remoteState.supportsCas) {
configureParams.ui_meta_expected_revisions = {
[GROUP_CHAT_SYNC_META_KEY]: remoteState.revision
}
}
+
const result = await groupChatSyncRequest<{
applied?: { ui_meta?: boolean; ui_meta_revisions?: Record<string, number> }
}>(job, 'profiles.configure', configureParams)
+
if (result?.applied?.ui_meta !== true) {
throw new Error('Gateway rejected group chat ui_meta')
}
+
if (
remoteState.supportsCas &&
Number(result?.applied?.ui_meta_revisions?.[GROUP_CHAT_SYNC_META_KEY] || 0) !== writeRevision
) {
throw new Error('Gateway did not advance group chat ui_meta revision')
}
+
const confirmedState = await groupChatRemoteSnapshot(job)
+
if (remoteState.supportsCas && confirmedState.revision < writeRevision) {
throw new Error('Group chat ui_meta revision missing after read-back')
}
+
if (confirmedState.snapshot) {
const pending = groupChatSyncPendingByConnection.get(id)
+
const mergedRooms = mergeRemoteGroupChatSnapshotIntoRooms(confirmedState.snapshot, $groupChats.get(), {
preserveRooms: pending?.changedRooms || [],
deletedRooms: pending?.deletedRooms || []
})
+
$groupChats.set(mergedRooms)
await persistGroupChatRooms(mergedRooms)
}
+
groupChatSyncRetryCounts.delete(id)
} catch {
if (!groupChatSyncDisposed) {
const retries = Number(groupChatSyncRetryCounts.get(id) || 0) + 1
+
// A gateway that was REMOVED (not just flaky) has no route anymore and
// would otherwise retry forever. Give up after the backoff ladder tops
// out; local storage remains authoritative and a future reconnect of
// that gateway re-seeds it via the gateway-transition pull/publish.
if (retries > 8) {
groupChatSyncRetryCounts.delete(id)
+
return
}
+
groupChatSyncPendingByConnection.set(id, mergeGroupChatSyncJobs(groupChatSyncPendingByConnection.get(id), job))
groupChatSyncRetryCounts.set(id, retries)
+
if (typeof setTimeout === 'function' && !groupChatSyncRetryTimers.has(id)) {
groupChatSyncRetryTimers.set(
id,
@@ -925,21 +1074,26 @@ async function flushGroupChatServerSync(connectionId?: string) {
}
} finally {
groupChatSyncInFlightConnections.delete(id)
+
if (groupChatSyncPendingByConnection.has(id) && !groupChatSyncRetryTimers.has(id) && !groupChatSyncDisposed) {
void flushGroupChatServerSync(id)
}
}
}
+
export function stopGroupChatServerSync() {
groupChatSyncDisposed = true
groupChatSyncPendingByConnection.clear()
+
if (groupChatSyncTimer !== null) {
clearTimeout(groupChatSyncTimer)
groupChatSyncTimer = null
}
+
for (const timer of groupChatSyncRetryTimers.values()) {
clearTimeout(timer)
}
+
groupChatSyncRetryTimers.clear()
groupChatSyncRetryCounts.clear()
}
@@ -962,27 +1116,34 @@ export function scheduleGroupChatServerSync(
if (typeof setTimeout !== 'function') {
return
}
+
const snapshot = groupChatSyncSnapshot(all)
+
// 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)
}
+
// Queue on the ACTIVE gateway synchronously (tests and older hosts have no
// async route inventory), then widen to every reachable gateway before the
// debounce fires.
const activeId = String(groupChatSyncConnectionId() || '')
+
const queueFor = (connectionId: string) => {
const id = String(connectionId || '')
const retryTimer = groupChatSyncRetryTimers.get(id)
+
if (retryTimer !== undefined) {
clearTimeout(retryTimer)
groupChatSyncRetryTimers.delete(id)
}
+
groupChatSyncPendingByConnection.set(
id,
mergeGroupChatSyncJobs(groupChatSyncPendingByConnection.get(id), {
@@ -993,6 +1154,7 @@ export function scheduleGroupChatServerSync(
})
)
}
+
queueFor(activeId)
groupChatSyncTimer = setTimeout(() => {
groupChatSyncTimer = null
@@ -1008,12 +1170,14 @@ export function scheduleGroupChatServerSync(
.then(() => flushGroupChatServerSync())
}, 350)
}
+
export 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.
const rooms = {
...$groupChats.get()
}
+
for (const name of Object.keys(rooms)) {
rooms[name] = {
...rooms[name],
@@ -1021,6 +1185,7 @@ export function handleSessionsGatewayTransition() {
running: false
}
}
+
$groupChats.set(rooms)
// Pull before re-publishing so a reconnect or source swap never lets this
// client's stale cache hide a room written by another Desktop/mobile client.
@@ -1055,12 +1220,14 @@ export const GROUP_CHAT_MAX_MEMBERS = 6
* @hermes handle) so the main agent never loses its name in rooms. */
export function groupSpeakerLabel(name?: null | string) {
const trimmed = (name || '').trim()
+
if (!trimmed) {
return trimmed
}
// Bot Mode title (edit dialog) — same first rung as displayName().
const title = String($botMeta.get()?.[trimmed]?.title || '').trim()
+
if (title) {
return title
}
@@ -1069,19 +1236,23 @@ export function groupSpeakerLabel(name?: null | string) {
// the ACTIVE gateway's roster row. Source-scoped remote speakers carry
// their device suffix separately and keep their raw name here.
const roster = $lastRoster.get()
+
const row = Array.isArray(roster)
? roster.find(bot => bot?.name === trimmed && !bot?.remoteSource && !bot?.sourceScoped)
: null
+
const renamed = typeof row?.display_name === 'string' ? row.display_name.trim() : ''
+
if (renamed) {
return renamed
}
+
return trimmed.toLowerCase() === 'default' ? 'Hermes' : trimmed
}
/** Trim a room log + its watermarks to the retained window, keeping
* watermark indices consistent with the trimmed array. */
-function trimGroupChatLog(
+export function trimGroupChatLog(
log: GroupMessage[],
watermarks: Record<string, number>,
limit = GROUP_CHAT_HISTORY_LIMIT * 4
@@ -1092,11 +1263,14 @@ function trimGroupChatLog(
watermarks
}
}
+
const drop = log.length - limit
const trimmed: Record<string, number> = {}
+
for (const [name, index] of Object.entries(watermarks || {})) {
trimmed[name] = Math.max(0, index - drop)
}
+
return {
log: log.slice(drop),
watermarks: trimmed
@@ -1116,12 +1290,14 @@ export function updateGroupChat(
const all = {
...$groupChats.get()
}
+
const current = all[group] || {
log: [],
watermarks: {},
epoch: 0,
running: false
}
+
const next = mutate({
...current,
log: [...current.log],
@@ -1129,13 +1305,16 @@ export function updateGroupChat(
...current.watermarks
}
})
+
const bounded = trimGroupChatLog(next.log, next.watermarks)
next.log = bounded.log
next.watermarks = bounded.watermarks
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
@@ -1144,6 +1323,7 @@ export function updateGroupChat(
if (room.tombstone) {
continue
}
+
durable[name] = {
log: room.log,
watermarks: room.watermarks,
@@ -1167,15 +1347,18 @@ export function updateGroupChat(
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 */
}
+
if (sync) {
scheduleGroupChatServerSync(all, {
changedRooms: [group]
})
}
+
return next
}
@@ -1201,6 +1384,7 @@ export interface GroupChatRoom extends GroupChat {
export function setGroupChatImage(group: string, image: null | string | undefined) {
updateGroupChat(group, (room: GroupChatRoom) => {
room.image = image || null
+
return room
})
}
@@ -1209,6 +1393,7 @@ function groupChatEntryId(): string {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
return globalThis.crypto.randomUUID()
}
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
}
@@ -1216,13 +1401,17 @@ function groupChatEntryId(): string {
* a FAILURE marker, never bot text. Mirror gateway/run.py's user-friendly
* substitution so the room log never shows the raw sentinel. */
const GROUP_EMPTY_SENTINEL = '(empty)'
+
const GROUP_EMPTY_FRIENDLY =
'⚠️ The model returned no response after processing tool results. ' +
'This can happen with some models — try again or rephrase your question.'
+
function normalizeGroupChatText(text: string): string {
const trimmed = String(text || '').trim()
+
return trimmed === GROUP_EMPTY_SENTINEL ? GROUP_EMPTY_FRIENDLY : trimmed
}
+
export function appendGroupChatEntry(
group: string,
from: GroupMessageAuthor,
@@ -1237,6 +1426,7 @@ export function appendGroupChatEntry(
text: normalizeGroupChatText(text),
thread: thread || 'legacy'
}
+
if (Array.isArray(images) && images.length) {
// [{ name, data }] — data URLs. Persisted with the room log so reloads
// keep showing what the members were shown.
@@ -1249,11 +1439,14 @@ export function appendGroupChatEntry(
// entries and non-adjacent repeats are never touched.
const priorLog = ($groupChats.get()[group] || {}).log || []
const lastEntry = priorLog[priorLog.length - 1]
+
if (isDuplicateGroupAppend(lastEntry, from, entry.text, entry.thread)) {
return lastEntry
}
+
updateGroupChat(group, (room: GroupChatRoom) => {
room.log.push(entry)
+
return room
})
@@ -1264,6 +1457,7 @@ export function appendGroupChatEntry(
[group]: true
})
}
+
return entry
}
@@ -1281,17 +1475,20 @@ export function uniqueGroupChatName(base: string, taken: Set<string>): string {
if (!taken.has(base)) {
return base
}
+
for (let n = 2; n < 100; n++) {
const suffix = ` ${n}`
const candidate = base.slice(0, 64 - suffix.length) + suffix
+
if (!taken.has(candidate)) {
return candidate
}
}
+
throw new Error('No free name for the group.')
}
-// --- room-turn decision helpers (#93127) — pure, vm-sliced by tests ---
+// --- room-turn decision helpers (#93127) — pure, unit-tested ---
/** #93127: whether a finished member turn may still commit (append its reply
* and advance its watermark). A turn dispatched under an older epoch was
@@ -1308,6 +1505,7 @@ export function shouldCommitMemberTurn(epochAtDispatch: number, currentEpoch: nu
if (epochAtDispatch === currentEpoch) {
return true
}
+
return !newerUserEntryInThread
}
@@ -1317,6 +1515,7 @@ export function shouldCommitMemberTurn(epochAtDispatch: number, currentEpoch: nu
* a residual double-append fires back-to-back; two legitimately identical
* replies hours apart (or with anything in between) are never dropped. */
const GROUP_DUPLICATE_APPEND_WINDOW_MS = 10 * 60 * 1000
+
function isDuplicateGroupAppend(
lastEntry: GroupMessage | undefined,
from: GroupMessageAuthor,
@@ -1327,18 +1526,23 @@ function isDuplicateGroupAppend(
if (!lastEntry || !from || from.kind !== 'member' || lastEntry.from?.kind !== 'member') {
return false
}
+
if (String(lastEntry.from?.name || '') !== String(from.name || '')) {
return false
}
+
if (String(lastEntry.from?.source || '') !== String(from.source || '')) {
return false
}
+
if (String(lastEntry.thread || 'legacy') !== String(thread || 'legacy')) {
return false
}
+
if (now - (lastEntry.at || 0) > GROUP_DUPLICATE_APPEND_WINDOW_MS) {
return false
}
+
return String(lastEntry.text || '') === String(text || '').trim()
}
@@ -1347,6 +1551,7 @@ function isDuplicateGroupAppend(
export function groupThreadOf(entry: GroupMessage): string {
return entry?.thread || 'legacy'
}
+
export function mintGroupThreadId(): string {
return `t${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`
}
@@ -1355,19 +1560,25 @@ export function mintGroupThreadId(): string {
// entry after a real lull starts one, so multi-turn tasks stay whole instead
// of splitting on every follow-up.
const GROUP_THREAD_GAP_MS = 15 * 60000
+
export function assignLegacyThreads(log: GroupMessage[]): GroupMessage[] {
let current: null | string = null
let n = 0
+
return (log || []).map((entry, i) => {
if (entry?.thread) {
current = null
+
return entry
}
+
const prev = log[i - 1]
const lull = !prev || (entry.at || 0) - (prev.at || 0) > GROUP_THREAD_GAP_MS
+
if (!current || (entry.from?.kind === 'user' && lull)) {
current = `legacy-${n++}`
}
+
return {
...entry,
thread: current
diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
index 31468c17db8..c6ba3a9baee 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-membership.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.ts
@@ -25,11 +25,13 @@ export function groupMemberKey(member: GroupMember): string {
export function groupSessionOwner(member: RosterRow) {
const route = botConnectionRoute(member)
const name = String(route?.profile || member?.name || '').trim() || 'default'
+
if (!route) {
return {
name
}
}
+
return {
connectionId: route.connectionId,
name,
@@ -49,18 +51,23 @@ export function botGroups(meta?: BotMeta | null) {
const groups: string[] = []
const seen = new Set<string>()
const values = Array.isArray(meta?.groups) ? meta.groups : [meta?.group]
+
for (const value of values) {
if (typeof value !== 'string') {
continue
}
+
const group = value.trim()
+
if (group && !seen.has(group)) {
seen.add(group)
groups.push(group)
}
}
+
return groups
}
+
interface GroupMembershipPatch {
/** Legacy single-group scalar, kept as a first-membership projection. */
group: null | string
@@ -70,6 +77,7 @@ interface GroupMembershipPatch {
export function groupMembershipPatch(meta: BotMeta | null | undefined, group: string, enabled: boolean): GroupMembershipPatch {
const name = String(group || '').trim()
let groups = botGroups(meta)
+
if (enabled) {
if (name && !groups.includes(name)) {
groups = [...groups, name]
@@ -77,6 +85,7 @@ export function groupMembershipPatch(meta: BotMeta | null | undefined, group: st
} else {
groups = groups.filter(existing => existing !== name)
}
+
return {
groups,
group: groups[0] || null
@@ -98,31 +107,41 @@ export function groupDisbandMetadataPlan(
) {
const owners = new Map<string, RosterRow>()
const patches = new Map<string, GroupMembershipPatch>()
+
const rememberOwner = (owner: RosterRow, required = false) => {
if (!owner?.name) {
return
}
+
let key: string
+
try {
key = botMetaKey(owner)
} catch {
return
}
+
const meta = metaByName?.[key] || botRosterMeta(owner, metaByName) || {}
+
if (!required && !botGroups(meta).includes(group)) {
return
}
+
if (!owners.has(key)) {
owners.set(key, owner)
}
+
patches.set(key, groupMembershipPatch(meta, group, false))
}
+
for (const owner of members || []) {
rememberOwner(owner, true)
}
+
for (const owner of room?.members || []) {
rememberOwner(owner, true)
}
+
for (const owner of roster || []) {
rememberOwner(owner)
}
@@ -136,6 +155,7 @@ export function groupDisbandMetadataPlan(
patches.set(key, groupMembershipPatch(meta, group, false))
}
}
+
return {
owners,
patches
@@ -147,14 +167,17 @@ export function groupDisbandMetadataPlan(
* log — cross-connection rooms whose members can't ride bot-meta. */
export function groupChatNames(metaByName: Record<string, BotMeta>, rooms: Record<string, GroupChat>) {
const names = new Set(knownGroups(metaByName))
+
for (const [name, room] of Object.entries(rooms || {})) {
if (room?.tombstone) {
continue
}
+
if ((Array.isArray(room?.members) && room.members.length) || (Array.isArray(room?.log) && room.log.length)) {
names.add(name)
}
}
+
return [...names]
}
@@ -171,6 +194,7 @@ export function liveGroupChatNames() {
* the group's recency key, competing in the same ordering as bot rows. */
export function groupLastActivity(room?: GroupChat | null) {
const log = Array.isArray(room?.log) ? room.log : []
+
return log.length ? log[log.length - 1].at || 0 : 0
}
@@ -182,6 +206,7 @@ export function groupChatMemberBots(group: string, roster: RosterRow[], metaByNa
const stored = ($groupChats.get()[group] || {}).members || []
const seated = new Set(local.map(botRosterKey))
const remote: RosterRow[] = []
+
for (const descriptor of stored) {
// Legacy descriptors can carry a FRIENDLY name as `name` (older builds
// persisted display names — #92794: `name: '大司命'` for slug `taiyi`).
@@ -194,15 +219,18 @@ export function groupChatMemberBots(group: string, roster: RosterRow[], metaByNa
// the stored descriptor to the slug, so the repair is self-healing.
const resolved = resolveLegacyMemberDescriptor(descriptor, roster)
const key = botRosterKey(resolved)
+
if (seated.has(key)) {
continue
}
+
seated.add(key)
// A selected-but-offline ghost intentionally carries only enough identity
// to paint the roster. Never let it replace the room's durable descriptor,
// which owns the full handle/title used by mentions and remote sync.
remote.push((roster || []).find(bot => !bot?.ghost && botRosterKey(bot) === key) || resolved)
}
+
return [...local, ...remote]
}
@@ -214,12 +242,15 @@ export function groupChatMemberBots(group: string, roster: RosterRow[], metaByNa
* never be used as a `profile:` target. */
function resolveLegacyMemberDescriptor(descriptor: RosterRow, roster: RosterRow[]): RosterRow {
const rows = roster || []
+
if (rows.some(bot => botRosterKey(bot) === botRosterKey(descriptor))) {
return descriptor
}
+
const wanted = String(descriptor?.name || '')
.trim()
.toLowerCase()
+
if (!wanted) {
return descriptor
}
@@ -230,12 +261,15 @@ function resolveLegacyMemberDescriptor(descriptor: RosterRow, roster: RosterRow[
// rooms only ever contained this machine's bots, so local (non-remote)
// rows are the legal candidate set.
const descriptorConnection = String(descriptor?.connectionId || '')
+
const candidates = rows.filter(bot => {
if (bot?.ghost) {
return false
}
+
return descriptorConnection ? String(bot?.connectionId || '') === descriptorConnection : !bot?.remoteSource
})
+
const match = candidates.find(
bot =>
// Case-drifted slug ('Testbot' persisted for profile 'testbot') …
@@ -250,6 +284,7 @@ function resolveLegacyMemberDescriptor(descriptor: RosterRow, roster: RosterRow[
.toLowerCase() === wanted
)
)
+
return match || descriptor
}
@@ -263,12 +298,14 @@ export function durableGroupChatMembers(bots: RosterRow[]): GroupMember[] {
// route — the same degraded shape the hydrate annotate produces. The
// strict throw here would lose the entire room update over one row.
const route = resolveBotConnectionRoute(bot).route
+
// Keep the friendly identity on the stored descriptor: after a
// connection switch the live roster row may be gone, and renamed-tag
// mentions must still resolve against the persisted member.
const title = String(
botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || ''
).trim()
+
return {
name: bot.name,
handle: bot.handle || bot.name,
@@ -308,11 +345,13 @@ export function durableGroupChatMembers(bots: RosterRow[]): GroupMember[] {
/** Existing group names, alphabetical — feeds the Manage-groups dialog. */
export function knownGroups(metaByName: Record<string, BotMeta>) {
const names = new Set<string>()
+
for (const meta of Object.values(metaByName || {})) {
for (const group of botGroups(meta)) {
names.add(group)
}
}
+
return [...names].sort((a, b) =>
a.localeCompare(b, undefined, {
sensitivity: 'base'
diff --git a/apps/desktop/src/plugins/hermes-bots/group-panes.ts b/apps/desktop/src/plugins/hermes-bots/group-panes.ts
index d66a385557a..48ca27a936a 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-panes.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-panes.ts
@@ -27,6 +27,7 @@ export interface GroupComposerDraft {
revision: number
}
const groupComposerDrafts = new Map<string, GroupComposerDraft | undefined>()
+
function emptyGroupComposerDraft(): GroupComposerDraft {
return {
activeReplyThread: null,
@@ -36,14 +37,18 @@ function emptyGroupComposerDraft(): GroupComposerDraft {
revision: 0
}
}
+
export function groupComposerDraftKey(group: string, room: GroupChatRoom): string {
return groupChatRoomKey(group, room)
}
+
export function groupComposerDraftSnapshot(key: string): GroupComposerDraft {
return groupComposerDrafts.get(key) || emptyGroupComposerDraft()
}
+
export function updateGroupComposerDraft(key: string, mutate: (draft: GroupComposerDraft) => GroupComposerDraft) {
const current = groupComposerDraftSnapshot(key)
+
const next = mutate({
...current,
pendingAttachments: Object.fromEntries(
@@ -56,16 +61,21 @@ export function updateGroupComposerDraft(key: string, mutate: (draft: GroupCompo
...(current.replies || {})
}
})
+
next.revision = current.revision + 1
groupComposerDrafts.delete(key)
groupComposerDrafts.set(key, next)
+
return next
}
+
export function restoreGroupComposerDraft(key: string, expectedRevision: number, snapshot: GroupComposerDraft) {
const current = groupComposerDraftSnapshot(key)
+
if (current.revision !== expectedRevision) {
return null
}
+
const restored = {
...snapshot,
pendingAttachments: Object.fromEntries(
@@ -79,21 +89,28 @@ export function restoreGroupComposerDraft(key: string, expectedRevision: number,
},
revision: current.revision + 1
}
+
groupComposerDrafts.set(key, restored)
+
return restored
}
+
export function clearGroupComposerDraft(key: string) {
groupComposerDrafts.delete(key)
}
+
export function migrateGroupComposerDraft(oldKey: string, newKey: string) {
if (oldKey === newKey || !groupComposerDrafts.has(oldKey)) {
return
}
+
if (!groupComposerDrafts.has(newKey)) {
groupComposerDrafts.set(newKey, groupComposerDrafts.get(oldKey))
}
+
groupComposerDrafts.delete(oldKey)
}
+
/** React-style setter argument — the next value, or a function of the current. */
export type GroupDraftSetter<T> = T | ((current: T) => T)
@@ -108,10 +125,12 @@ export const groupChatMainTabs = new Map<string, () => void>()
* nothing). Every map mutation goes through the two helpers below so the
* rev bump re-evaluates the gate. */
export const $groupMainTabsRev = atom(0)
+
export function recordGroupMainTab(group: string, close: () => void) {
groupChatMainTabs.set(group, close)
$groupMainTabsRev.set($groupMainTabsRev.get() + 1)
}
+
export function dropGroupMainTab(group: string) {
if (groupChatMainTabs.delete(group)) {
$groupMainTabsRev.set($groupMainTabsRev.get() + 1)
@@ -128,12 +147,15 @@ export function dropGroupMainTab(group: string) {
export function shouldRenderGroupChatInPane(group: null | string): group is string {
return Boolean(group && !groupChatMainTabs.has(group))
}
+
export function closeGroupChatMainTab(group: string) {
const close = groupChatMainTabs.get(group)
dropGroupMainTab(group)
+
if ($groupChatWorkspace.get() === group) {
$groupChatWorkspace.set(null)
}
+
if (typeof close === 'function') {
try {
close()
diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
index 1638fd27a79..ff65ff2745f 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
@@ -42,17 +42,19 @@ import type { Attachment, GroupMember, GroupMessage } from './types'
/** Deterministic @mention parse. Handles @name, @"two words" via display
* titles, and @everyone/@all. Names match case-insensitively against member
* profile names, display titles, and collapsed no-space forms. */
-function parseGroupChatMentions(text: unknown, members: GroupMember[]) {
+export function parseGroupChatMentions(text: unknown, members: GroupMember[]) {
const source = String(text || '')
const mentioned = new Set<string>()
let everyone = false
const handles = new Map<string, string>()
+
for (const member of members) {
const title = String(member.title || '').trim()
// Cross-connection members are also addressable by their @name-device
// handle (the roster's disambiguated form) — same-named agents on two
// machines resolve to the right one.
const handle = String(member.handle || botHandle(member.name, member) || '').trim()
+
const forms = new Set([
member.name.toLowerCase(),
member.name.toLowerCase().replace(/[\s_-]+/g, ''),
@@ -70,26 +72,34 @@ function parseGroupChatMentions(text: unknown, members: GroupMember[]) {
forms.add(form)
}
}
+
for (const form of forms) {
if (form) {
handles.set(form, groupMemberKey(member))
}
}
}
+
for (const match of source.matchAll(/@([a-z0-9][a-z0-9._-]*)/gi)) {
const handle = match[1].toLowerCase()
+
if (handle === 'everyone' || handle === 'all') {
everyone = true
+
continue
}
+
if (handle === 'user') {
continue
}
+
const resolved = handles.get(handle) || handles.get(handle.replace(/[._-]+/g, ''))
+
if (resolved) {
mentioned.add(resolved)
}
}
+
return {
everyone,
mentioned
@@ -100,43 +110,53 @@ function parseGroupChatMentions(text: unknown, members: GroupMember[]) {
* @-mentioned in messages since the last user entry (or @everyone appears),
* otherwise only the mentioned members. Recomputed every round so a member
* pulled in mid-conversation joins the next round. */
-function resolveGroupResponders(log: GroupMessage[], members: GroupMember[]) {
+export function resolveGroupResponders(log: GroupMessage[], members: GroupMember[]) {
let sinceLastUser: GroupMessage[] = []
+
for (let i = log.length - 1; i >= 0; i--) {
if (log[i].from.kind === 'user') {
sinceLastUser = log.slice(i)
+
break
}
}
+
const mentioned = new Set<string>()
let everyone = false
+
for (const entry of sinceLastUser) {
const parsed = parseGroupChatMentions(entry.text, members)
+
if (parsed.everyone) {
everyone = true
}
+
for (const name of parsed.mentioned) {
mentioned.add(name)
}
}
+
if (everyone || mentioned.size === 0) {
return members
}
+
return members.filter(member => mentioned.has(groupMemberKey(member)))
}
/** Rotate the roster so a different member leads each round. */
-function rotateGroupSpeakers(members: GroupMember[], round: number) {
+export function rotateGroupSpeakers(members: GroupMember[], round: number) {
if (members.length < 2) {
return members
}
+
const shift = round % members.length
+
return [...members.slice(shift), ...members.slice(0, shift)]
}
/** Room-log line as a member sees it: `Name (user): …` / `Name: …` /
* `Name (you): …`. */
-function formatGroupChatLine(entry: GroupMessage, viewerName: string) {
+export function formatGroupChatLine(entry: GroupMessage, viewerName: string) {
// Attachments are staged into each member's session as real payloads; the
// transcript line names them so the delta text and the bytes line up.
const attached =
@@ -144,17 +164,21 @@ function formatGroupChatLine(entry: GroupMessage, viewerName: string) {
? ` ${entry.images
.map(img => {
const label = img.kind === 'pdf' ? 'attached PDF' : img.kind === 'file' ? 'attached file' : 'attached image'
+
return `[${label}: ${img.name || 'image'}]`
})
.join(' ')}`
: ''
+
if (entry.from.kind === 'user') {
return `${entry.from.name || 'User'} (user): ${entry.text}${attached}`
}
+
const suffix = entry.from.name === viewerName ? ' (you)' : ''
// Cross-connection speakers carry their device so same-named agents on
// two machines stay tellable apart in every member's transcript.
const source = entry.from.source ? ` [${entry.from.source}]` : ''
+
return `${groupSpeakerLabel(entry.from.name)}${suffix}${source}: ${entry.text}${attached}`
}
@@ -168,15 +192,18 @@ interface GroupChatTurnPromptInput {
/** The full per-turn payload for one member: participation rules + the room
* delta. Rules travel in the turn payload (not SOUL) so every existing bot
* can join a group chat without a profile migration. */
-function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }: GroupChatTurnPromptInput) {
+export function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }: GroupChatTurnPromptInput) {
const viewerKey = groupMemberKey(viewer)
const peers = members.filter(m => groupMemberKey(m) !== viewerKey)
+
const peerNames = peers
.map(m => {
const handle = m.title ? `${m.title} (@${botHandle(m.name, m)})` : `@${botHandle(m.name, m)}`
+
return m.remoteSource ? `${handle} [on ${m.connectionLabel || m.connectionId}]` : handle
})
.join(', ')
+
return [
`[Group chat: "${groupName}"] You are @${botHandle(viewer.name, viewer)}, one participant in a group chat with ${peerNames || 'no one else yet'} and the user.`,
'',
@@ -191,7 +218,7 @@ function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }: Gr
].join('\n')
}
-// --- member-hold helpers (#93129) — pure, vm-sliced by tests ---
+// --- member-hold helpers (#93129) — pure, unit-tested ---
/** #93129: classify a USER room message's effect on member holds. Only user
* sends ever reach this (bot replies are appended by the round loop, never
@@ -203,7 +230,7 @@ function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }: Gr
* one keeps doing work it was told to stop). A non-stop direct mention
* releases the mentioned members — the user addressing a bot directly
* overrides its hold. */
-function classifyGroupHoldDirective(
+export function classifyGroupHoldDirective(
text: string,
mentionedKeys: Iterable<string> | null | undefined,
everyone: boolean
@@ -212,6 +239,7 @@ function classifyGroupHoldDirective(
const mentioned = [...(mentionedKeys || [])]
const stop = /\b(stop|halt|pause)\b/i.test(value)
const resume = /\b(resume|continue|go|proceed)\b/i.test(value)
+
if (stop) {
// "@all stop" holds every member — symmetric with "@all resume".
return {
@@ -221,6 +249,7 @@ function classifyGroupHoldDirective(
releaseAll: false
}
}
+
if (resume) {
return {
hold: [],
@@ -229,6 +258,7 @@ function classifyGroupHoldDirective(
releaseAll: Boolean(everyone)
}
}
+
return {
hold: [],
holdAll: false,
@@ -248,7 +278,7 @@ interface GroupMentionParse {
* mints a NEW thread, so a thread-scoped hold would never block the next
* send's turns and the stop would not stick. Returns the same object when
* nothing changed. */
-function applyGroupHoldDirective(
+export function applyGroupHoldDirective(
holds: Record<string, GroupHoldStamp> | null | undefined,
mentions: GroupMentionParse | null | undefined,
text: string,
@@ -257,6 +287,7 @@ function applyGroupHoldDirective(
): Record<string, GroupHoldStamp> {
const prior: Record<string, GroupHoldStamp> = holds && typeof holds === 'object' ? holds : {}
const action = classifyGroupHoldDirective(text, mentions?.mentioned || [], Boolean(mentions?.everyone))
+
if (action.releaseAll) {
return Object.keys(prior).length ? {} : prior
}
@@ -264,18 +295,21 @@ function applyGroupHoldDirective(
// "@all stop": expand to every member key the caller knows about.
const toHold = action.holdAll ? [...allMemberKeys] : action.hold
let next = prior
+
for (const key of toHold) {
if (next === prior) {
next = {
...prior
}
}
+
next[key] = {
at: stamp?.at || Date.now(),
byMessageId: stamp?.byMessageId || null,
thread: stamp?.thread || null
}
}
+
for (const key of action.release) {
if (Object.prototype.hasOwnProperty.call(next, key)) {
if (next === prior) {
@@ -283,16 +317,18 @@ function applyGroupHoldDirective(
...prior
}
}
+
delete next[key]
}
}
+
return next
}
/** #93129: a held member's skip must consume its delta exactly once —
* advance the watermark past the current log so the same entries never
* re-trigger the skip. Null = nothing to consume (no write, no spin). */
-function heldMemberWatermarkAdvance(seen: number | undefined, logLength: number): null | number {
+export function heldMemberWatermarkAdvance(seen: number | undefined, logLength: number): null | number {
return logLength > (seen || 0) ? logLength : null
}
@@ -304,10 +340,11 @@ function heldMemberWatermarkAdvance(seen: number | undefined, logLength: number)
* but the round loop exits first when nobody has new delta to read
* (`spokeThisRound === 0`) or a cap lands, so the room settles while a
* called bot never answers. Returns member keys still owed a turn. */
-function unaddressedGroupMentions(group: string, members: GroupMember[], thread: string) {
+export function unaddressedGroupMentions(group: string, members: GroupMember[], thread: string) {
const room = $groupChats.get()[group] || {
log: []
}
+
const log = (room.log || []).filter((e: GroupMessage) => groupThreadOf(e) === thread)
// key → log INDEX of the entry that most recently cited this member.
@@ -315,6 +352,7 @@ function unaddressedGroupMentions(group: string, members: GroupMember[], thread:
// the only guaranteed ordering, and it is what "answered after the citing
// entry" actually means. (#94478 review)
const citedAt = new Map()
+
for (const entry of log) {
const parsed = parseGroupChatMentions(entry.text || '', members)
@@ -323,9 +361,11 @@ function unaddressedGroupMentions(group: string, members: GroupMember[], thread:
if (entry.from.kind !== 'member') {
continue
}
+
for (const key of parsed.mentioned) {
const citingMemberKey = (() => {
const m = members.find((mm: GroupMember) => mm.name === entry.from?.name)
+
return m ? groupMemberKey(m) : null
})()
@@ -339,21 +379,27 @@ function unaddressedGroupMentions(group: string, members: GroupMember[], thread:
// A citation is answered when the cited member posts any entry after the
// citing one (its turn, whatever the content).
const lastPostAt = new Map()
+
for (const entry of log) {
if (entry.from.kind !== 'member') {
continue
}
+
const speakerKey = (() => {
const m = members.find((mm: GroupMember) => mm.name === entry.from?.name)
+
return m ? groupMemberKey(m) : null
})()
+
if (speakerKey) {
lastPostAt.set(speakerKey, log.indexOf(entry))
}
}
+
return [...citedAt.keys()].filter(key => {
const citedIdx = citedAt.get(key)
const answeredIdx = lastPostAt.get(key)
+
return answeredIdx === undefined || answeredIdx <= citedIdx
})
}
@@ -381,11 +427,13 @@ export async function stopGroupThread(group: string, thread: null | string, memb
const room = $groupChats.get()[group] || {}
const roster = Array.isArray(members) && members.length ? members : room.members || []
const turnName = room.turn || null
+
const stamp: GroupHoldStamp = {
at: Date.now(),
byMessageId: null,
thread: thread || null
}
+
updateGroupChat(group, (r: GroupChatRoom) => {
r.epoch = (r.epoch || 0) + 1
r.running = false
@@ -397,15 +445,19 @@ export async function stopGroupThread(group: string, thread: null | string, memb
const holds: Record<string, GroupHoldStamp> = {
...(r.holds || {})
}
+
for (const member of roster) {
const key = groupMemberKey(member)
+
if (key && !holds[key]) {
holds[key] = {
...stamp
}
}
}
+
r.holds = holds
+
return r
})
@@ -422,6 +474,7 @@ export async function stopGroupThread(group: string, thread: null | string, memb
// names exactly one member (the loop is serial); a settled room has none.
const onTurn = turnName ? roster.find((member: GroupMember) => member?.name === turnName) : null
const sessionId = onTurn ? (room.sessions || {})[groupMemberKey(onTurn)] : null
+
if (onTurn && sessionId) {
try {
await requestForBot(onTurn, 'session.interrupt', {
@@ -439,7 +492,7 @@ export async function stopGroupThread(group: string, thread: null | string, memb
* next member boundary, bails, and the newest send's own loop takes over.
* Watermarks are per thread+member (`${thread}::${memberKey}`), so parallel
* topics never eat each other's deltas. */
-async function runGroupChatRounds(group: string, members: GroupMember[], thread: string) {
+export async function runGroupChatRounds(group: string, members: GroupMember[], thread: string) {
const startEpoch = ($groupChats.get()[group] || {}).epoch || 0
const isCurrent = () => (($groupChats.get()[group] || {}).epoch || 0) === startEpoch
let posted = 0
@@ -448,6 +501,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// passed with nothing pending); 'capped' means a round/message/continuation
// cap forced the exit — the activity feed must tell those apart.
let exitKind: 'capped' | 'settled' = 'settled'
+
try {
for (let round = 0; round < GROUP_CHAT_MAX_ROUNDS; round++) {
// Deliver any replies that finished after their turn timed out —
@@ -460,13 +514,17 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
member: null,
thread
})
+
return
}
+
await harvestStrandedGroupReply(group, member)
}
+
const roomLog = (($groupChats.get()[group] || {}).log || []).filter(
(e: GroupMessage) => groupThreadOf(e) === thread
)
+
// Exclude members the harvest pass just above confirmed are STILL
// running (their stranded marker survived harvest because
// state.inflight/running was true). Re-selecting one here would
@@ -480,10 +538,13 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// value shape, since markers are a bare number pre-thread or
// {before, thread} post-thread.
const strandedNow = ($groupChats.get()[group] || {}).stranded || {}
+
const responders = rotateGroupSpeakers(resolveGroupResponders(roomLog, members), round).filter(
(member: GroupMember) => !Object.prototype.hasOwnProperty.call(strandedNow, groupMemberKey(member))
)
+
let spokeThisRound = 0
+
for (const member of responders) {
if (!isCurrent() || posted >= GROUP_CHAT_MAX_MESSAGES) {
if (!isCurrent()) {
@@ -495,18 +556,22 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
} else {
exitKind = 'capped' // message cap, not consensus (#94478)
}
+
return
}
+
const room = $groupChats.get()[group] || {
log: [],
watermarks: {}
}
+
const memberKey = groupMemberKey(member)
const markKey = `${thread}::${memberKey}`
const seen = room.watermarks[markKey] || 0
// Delta: NEW room entries, narrowed to this thread — the member's
// turn sees only the conversation it's part of.
const delta = room.log.slice(seen).filter((e: GroupMessage) => groupThreadOf(e) === thread)
+
if (!delta.length) {
continue
}
@@ -517,12 +582,14 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// current log) so the same entries never re-trigger this skip, and
// surface WHY the bot is silent in the activity feed the first time.
const heldEntry = (room.holds || {})[memberKey]
+
if (heldEntry) {
const advance = heldMemberWatermarkAdvance(seen, room.log.length)
updateGroupChat(group, (r: GroupChatRoom) => {
if (advance !== null) {
r.watermarks[markKey] = advance
}
+
if (r.holds?.[memberKey] && !r.holds[memberKey].noted) {
r.holds = {
...r.holds,
@@ -532,8 +599,10 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
}
}
}
+
return r
})
+
if (!heldEntry.noted) {
recordGroupActivity(group, {
kind: 'held',
@@ -541,8 +610,10 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
thread
})
}
+
continue
}
+
const prompt = buildGroupChatTurnPrompt({
groupName: group,
members,
@@ -563,9 +634,11 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// long model turns otherwise read as the room being stuck.
updateGroupChat(group, (r: GroupChatRoom) => {
r.turn = member.name
+
return r
})
let reply: null | string = null
+
try {
reply = await runGroupChatMemberTurn(group, member, prompt, thread, deltaImages)
@@ -606,29 +679,35 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
const roomNow = $groupChats.get()[group] || {
log: []
}
+
const epochNow = roomNow.epoch || 0
const anchorId = room.log.length ? room.log[room.log.length - 1].id : null
const anchorIdx = anchorId === null ? -1 : roomNow.log.findIndex((e: GroupMessage) => e.id === anchorId)
// Anchor trimmed away ⇒ every pre-turn entry was dropped, so every
// surviving entry is newer — scanning the whole log stays exact.
const turnTail = anchorIdx >= 0 ? roomNow.log.slice(anchorIdx + 1) : roomNow.log
+
const newerUserEntryInThread = turnTail.some(
(e: GroupMessage) => e.from?.kind === 'user' && groupThreadOf(e) === thread
)
+
if (!shouldCommitMemberTurn(startEpoch, epochNow, newerUserEntryInThread)) {
recordGroupActivity(group, {
kind: 'cancelled',
member: member.name,
thread
})
+
return
}
// The member has now seen everything up to the pre-reply log length.
updateGroupChat(group, (r: GroupChatRoom) => {
r.watermarks[markKey] = r.log.length
+
return r
})
+
if (reply !== null && !isGroupPassText(reply)) {
appendGroupChatEntry(
group,
@@ -647,12 +726,14 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// Its own message counts as seen too.
updateGroupChat(group, (r: GroupChatRoom) => {
r.watermarks[markKey] = r.log.length
+
return r
})
posted += 1
spokeThisRound += 1
}
}
+
if (spokeThisRound === 0) {
// #94478: "everyone passed" is NOT the only way a round can go quiet —
// responders can be narrowed to members with no new delta while the
@@ -667,21 +748,27 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// message cap so a pathological mention chain can't consume the
// room's entire budget on back-and-forth handoffs.
continuations += 1
+
if (pendingKeys.length && continuations <= GROUP_CHAT_MAX_CONTINUATIONS) {
const citedMembers = members.filter((member: GroupMember) => pendingKeys.includes(groupMemberKey(member)))
+
if (citedMembers.length && posted < GROUP_CHAT_MAX_MESSAGES) {
const strandedNow = ($groupChats.get()[group] || {}).stranded || {}
+
const continuationResponders = citedMembers.filter(
(member: GroupMember) => !Object.prototype.hasOwnProperty.call(strandedNow, groupMemberKey(member))
)
+
for (const member of continuationResponders) {
if (!isCurrent() || posted >= GROUP_CHAT_MAX_MESSAGES || continuations > GROUP_CHAT_MAX_CONTINUATIONS) {
break
}
+
const room = $groupChats.get()[group] || {
log: [],
watermarks: {}
}
+
const memberKey = groupMemberKey(member)
const markKey = `${thread}::${memberKey}`
const seen = room.watermarks[markKey] || 0
@@ -693,10 +780,13 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
if (!delta.length) {
continue
}
+
const heldEntry = (room.holds || {})[memberKey]
+
if (heldEntry) {
continue // holds still apply to continuation turns (#93129)
}
+
const prompt = buildGroupChatTurnPrompt({
groupName: group,
members,
@@ -708,13 +798,17 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
.slice(-GROUP_CHAT_HISTORY_LIMIT)
.map((e: GroupMessage) => formatGroupChatLine(e, member.name))
})
+
updateGroupChat(group, (r: GroupChatRoom) => {
r.turn = member.name
+
return r
})
let continuationReply: null | string = null
+
try {
continuationReply = await runGroupChatMemberTurn(group, member, prompt, thread)
+
if (continuationReply !== null) {
clearBotAttention(memberKey)
}
@@ -727,13 +821,17 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
noteBotAttention(memberKey, error?.message || error)
continuationReply = null
}
+
if (!isCurrent()) {
return
}
+
updateGroupChat(group, (r: GroupChatRoom) => {
r.watermarks[markKey] = r.log.length
+
return r
})
+
if (continuationReply !== null && !isGroupPassText(continuationReply)) {
appendGroupChatEntry(
group,
@@ -751,6 +849,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
)
updateGroupChat(group, (r: GroupChatRoom) => {
r.watermarks[markKey] = r.log.length
+
return r
})
posted += 1
@@ -765,6 +864,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
}
}
}
+
if (spokeThisRound === 0) {
// Genuinely nothing left to say — including after the continuation
// attempt above produced no spoken turns. Settle honestly, but if
@@ -777,6 +877,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
) {
exitKind = 'capped'
}
+
return
}
}
@@ -795,6 +896,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
updateGroupChat(group, (r: GroupChatRoom) => {
r.running = false
r.turn = null
+
return r
})
@@ -804,6 +906,7 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
// in the background (bounded) so long work is late, never lost.
// (window feature-detect: the engine also runs under node in tests.)
const strandedLeft = Object.keys(($groupChats.get()[group] || {}).stranded || {})
+
if (strandedLeft.length && typeof window !== 'undefined') {
void harvestStrandedUntilSettled(group, members, thread)
}
@@ -818,16 +921,21 @@ async function runGroupChatRounds(group: string, members: GroupMember[], thread:
async function harvestStrandedUntilSettled(group: string, members: GroupMember[], thread: string) {
const HARVEST_INTERVAL_MS = 5000
const HARVEST_MAX_TRIES = 60
+
for (let attempt = 0; attempt < HARVEST_MAX_TRIES; attempt++) {
await new Promise(resolve => window.setTimeout(resolve, HARVEST_INTERVAL_MS))
const room = $groupChats.get()[group]
+
if (!room || room.running) {
return
}
+
const stranded = room.stranded || {}
+
if (!Object.keys(stranded).length) {
return
}
+
for (const member of members) {
if (Object.prototype.hasOwnProperty.call(stranded, groupMemberKey(member))) {
try {
@@ -838,6 +946,7 @@ async function harvestStrandedUntilSettled(group: string, members: GroupMember[]
}
}
}
+
recordGroupActivity(group, {
kind: 'failed',
member: null,
@@ -859,9 +968,11 @@ export function sendToGroupChat(
): null | string {
const trimmed = String(text || '').trim()
const attached = Array.isArray(images) ? images.filter((img: Attachment) => img && img.data) : []
+
if ((!trimmed && !attached.length) || !members.length) {
return null
}
+
const target = thread || mintGroupThreadId()
$groupNeedsYou.set({
...$groupNeedsYou.get(),
@@ -872,8 +983,10 @@ export function sendToGroupChat(
// members overlap across multiple groups.
updateGroupChat(group, (room: GroupChatRoom) => {
room.members = durableGroupChatMembers(members)
+
return room
})
+
const sent = appendGroupChatEntry(
group,
{
@@ -884,6 +997,7 @@ export function sendToGroupChat(
target,
attached
)
+
const wasRunning = ($groupChats.get()[group] || {}).running === true
updateGroupChat(group, (room: GroupChatRoom) => {
room.epoch = (room.epoch || 0) + 1
@@ -903,6 +1017,7 @@ export function sendToGroupChat(
},
members.map((member: GroupMember) => groupMemberKey(member))
)
+
return room
})
recordGroupActivity(group, {
@@ -910,10 +1025,12 @@ export function sendToGroupChat(
member: 'You',
thread: target
})
+
if (!wasRunning) {
void runGroupChatRounds(group, members, target).catch(() => {
updateGroupChat(group, (r: GroupChatRoom) => {
r.running = false
+
return r
})
})
@@ -924,10 +1041,12 @@ export function sendToGroupChat(
void runGroupChatRounds(group, members, target).catch(() => {
updateGroupChat(group, (r: GroupChatRoom) => {
r.running = false
+
return r
})
})
}, 250)
}
+
return target
}
diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
index bba9826ff1c..b648885799f 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts
@@ -18,9 +18,11 @@ import type { Attachment, GroupMember, GroupPrompt, GroupPromptQuestion, Profile
/** "(pass)" (loosely: pass / (pass) / pass.) or empty = the member stayed silent. */
export function isGroupPassText(text: unknown) {
const trimmed = String(text || '').trim()
+
if (!trimmed) {
return true
}
+
return /^\(?\s*pass\s*\)?\.?$/i.test(trimmed)
}
@@ -43,26 +45,34 @@ interface GroupTurnTranscriptMessage {
* assistant message appears in that range. */
function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: number): null | string {
let passText: null | string = null
+
for (let i = messages.length - 1; i >= before; i--) {
const msg = messages[i]
+
if (msg?.role !== 'assistant') {
continue
}
+
const text =
typeof msg.content === 'string'
? msg.content
: Array.isArray(msg.content)
? msg.content.map(p => (typeof p === 'string' ? p : p?.text || '')).join('')
: msg?.text || ''
+
const replyText = String(text).trim()
+
if (isGroupPassText(replyText)) {
if (passText === null) {
passText = replyText
}
+
continue
}
+
return replyText
}
+
return passText
}
@@ -112,7 +122,7 @@ interface GroupMemberSessionHandle {
* title, which also covers rehydrated rooms whose sid was lost — reopens
* it after restarts. Cross-connection members route to their OWN source
* via requestForBot; the window's gateway never switches. */
-async function ensureGroupChatSession(group: string, member: GroupMember): Promise<GroupMemberSessionHandle> {
+export async function ensureGroupChatSession(group: string, member: GroupMember): Promise<GroupMemberSessionHandle> {
const room = $groupChats.get()[group] || {}
// New rooms title member sessions by their immutable roomId so a
// same-name recreate never resumes the old room's sessions by title;
@@ -137,12 +147,14 @@ async function ensureGroupChatSession(group: string, member: GroupMember): Promi
if (!target || target === true) {
continue
}
+
try {
const res = (await requestForBot(member, 'session.resume', {
session_id: target,
profile: member.name,
omit_messages: true
})) as GroupSessionSnapshot
+
if (res?.session_id) {
// TODO(bot-mode-types): `known` is `room.sessions[key]`, which the
// domain model types `string | true` — and the `target === true` skip
@@ -152,6 +164,7 @@ async function ensureGroupChatSession(group: string, member: GroupMember): Promi
// durable id, which later rides into `session_id` on the recovery
// resume and on session.interrupt. Typed as-written.
const stored = res.session_key || known
+
if (stored) {
updateGroupChat(group, (current: GroupChatRoom) => {
current.sessions = {
@@ -162,9 +175,11 @@ async function ensureGroupChatSession(group: string, member: GroupMember): Promi
...(current.sessionOwners || {}),
[key]: groupSessionOwner(member)
}
+
return current
})
}
+
return {
runtime: res.session_id,
stored
@@ -178,13 +193,16 @@ async function ensureGroupChatSession(group: string, member: GroupMember): Promi
/* genuinely doesn't exist (4007) — try the next target / fall through to create */
}
}
+
const created = (await requestForBot(member, 'session.create', {
profile: member.name,
title,
// Room member sessions are plumbing — always hidden from the sidebar.
hidden: true
})) as { session_id?: string; stored_session_id?: string }
+
const stored = created?.stored_session_id || null
+
if (stored) {
updateGroupChat(group, (r: GroupChatRoom) => {
r.sessions = {
@@ -195,14 +213,17 @@ async function ensureGroupChatSession(group: string, member: GroupMember): Promi
...(r.sessionOwners || {}),
[key]: groupSessionOwner(member)
}
+
return r
})
}
+
return {
runtime: created?.session_id || null,
stored
}
}
+
const GROUP_TURN_TIMEOUT_MS = 180000
const GROUP_TURN_POLL_MS = 2000
@@ -225,16 +246,18 @@ interface GatewayErrorLike {
/** 4001-class "the runtime session was reaped" failure. Distinct from 4007
* ("genuinely never existed"), which must keep flowing to session.create. */
-function isSessionGoneError(error: GatewayErrorLike | null | undefined): boolean {
+export function isSessionGoneError(error: GatewayErrorLike | null | undefined): boolean {
if (!error || error.code === 4007) {
return false
}
+
if (error.code === 4001) {
return true
}
// Duck-typed (not instanceof): gateway errors can cross realm boundaries.
const message = typeof error?.message === 'string' ? error.message : typeof error === 'string' ? error : ''
+
return message.includes('not in memory') || /session not found/i.test(message)
}
// --- end group-turn session-lease helpers ---
@@ -246,16 +269,20 @@ function isSessionGoneError(error: GatewayErrorLike | null | undefined): boolean
async function retainGroupTurnRoute(member: GroupMember): Promise<() => void> {
const noop = () => undefined
let route: ProfileRoute | null = null
+
try {
route = botConnectionRoute(member)
} catch {
return noop
}
+
if (!route || typeof host.retainProfile !== 'function') {
return noop
}
+
try {
const release = await host.retainProfile(route)
+
return typeof release === 'function' ? release : noop
} catch {
return noop
@@ -278,24 +305,30 @@ async function submitGroupTurnPrompt(
session_id: runtime,
text
})
+
return runtime
} catch (error: any) {
if (!isSessionGoneError(error) || !stored) {
throw error
}
+
const res = (await requestForBot(member, 'session.resume', {
session_id: stored,
profile: member.name,
omit_messages: true
})) as GroupSessionSnapshot
+
const fresh = res?.session_id
+
if (!fresh) {
throw error
}
+
await requestForBot(member, 'prompt.submit', {
session_id: fresh,
text
})
+
return fresh
}
}
@@ -316,27 +349,32 @@ const GROUP_TURN_HARD_CAP_MS = 20 * 60000
* payload always sync to "no prompt". Clarify wins when both are somehow
* present (approvals resolve inside tool batches; clarify is the outer
* blocker). */
-function syncGroupClarify(group: string, member: GroupMember, state: GroupSessionSnapshot | null): boolean {
+export function syncGroupClarify(group: string, member: GroupMember, state: GroupSessionSnapshot | null): boolean {
const key = `${group}::${groupMemberKey(member)}`
const clarify = state && typeof state.pending_clarify === 'object' ? state.pending_clarify : null
+
// The `!requestId` bail below is what makes the approval branch reachable,
// so an approval read there is never the null arm of this ternary — a fact
// control-flow analysis can't carry across the two separate locals.
const approval = (
state && typeof state.pending_approval === 'object' ? state.pending_approval : null
) as GroupPendingApproval
+
const pending = clarify || approval
const requestId = pending?.request_id || null
const all = $groupClarify.get()
const current = all[key]
+
if (!requestId) {
if (current) {
const next = {
...all
}
+
delete next[key]
$groupClarify.set(next)
}
+
return false
}
@@ -345,6 +383,7 @@ function syncGroupClarify(group: string, member: GroupMember, state: GroupSessio
if (current?.requestId === requestId) {
return true
}
+
const base = {
requestId,
group,
@@ -355,6 +394,7 @@ function syncGroupClarify(group: string, member: GroupMember, state: GroupSessio
sessionId: state?.session_id || null,
at: Date.now()
}
+
$groupClarify.set({
...all,
[key]: clarify
@@ -388,6 +428,7 @@ function syncGroupClarify(group: string, member: GroupMember, state: GroupSessio
...$groupNeedsYou.get(),
[group]: true
})
+
return true
}
@@ -396,6 +437,7 @@ export function clearGroupClarify(group: string) {
const all = $groupClarify.get()
const next: Record<string, GroupPrompt> = {}
let changed = false
+
for (const [key, value] of Object.entries<GroupPrompt>(all)) {
if (value?.group === group) {
changed = true
@@ -403,6 +445,7 @@ export function clearGroupClarify(group: string) {
next[key] = value
}
}
+
if (changed) {
$groupClarify.set(next)
}
@@ -445,12 +488,15 @@ export async function answerGroupClarify(
answer: typeof answers === 'string' ? answers : ''
})
}
+
const all = $groupClarify.get()
const key = `${entry.group}::${entry.memberKey}`
+
if (all[key]?.requestId === entry.requestId) {
const next = {
...all
}
+
delete next[key]
$groupClarify.set(next)
}
@@ -475,12 +521,14 @@ export async function runGroupChatMemberTurn(
// socket that minted `runtime` can close between RPCs, the gateway reaps
// the runtime session, and prompt.submit dies 4001 — the bot goes silent.
const releaseTurnLease = await retainGroupTurnRoute(member)
+
try {
return await runGroupChatMemberTurnLeased(group, member, prompt, thread, images)
} finally {
releaseTurnLease()
}
}
+
async function runGroupChatMemberTurnLeased(
group: string,
member: GroupMember,
@@ -489,6 +537,7 @@ async function runGroupChatMemberTurnLeased(
images?: Attachment[]
): Promise<null | string> {
const { runtime, stored } = await ensureGroupChatSession(group, member)
+
if (!runtime) {
return null
}
@@ -505,11 +554,13 @@ async function runGroupChatMemberTurnLeased(
// Baseline: how many messages exist before our submit.
let before = 0
+
try {
const pre = (await requestForBot(member, 'session.resume', {
session_id: stored || runtime,
profile: member.name
})) as GroupSessionSnapshot
+
before = Array.isArray(pre?.messages) ? pre.messages.length : pre?.message_count || 0
} catch {
/* lazy session — zero messages */
@@ -525,10 +576,12 @@ async function runGroupChatMemberTurnLeased(
// member to text-only; the transcript line still names the attachment so
// the member knows something was shared.
const fileRefs: string[] = []
+
for (const img of Array.isArray(images) ? images : []) {
if (!img || typeof img.data !== 'string' || !img.data) {
continue
}
+
try {
if (img.kind === 'pdf') {
await requestForBot(member, 'pdf.attach', {
@@ -542,6 +595,7 @@ async function runGroupChatMemberTurnLeased(
data_url: img.data,
name: img.name || 'attachment'
})) as { ref_text?: string }
+
if (res?.ref_text) {
fileRefs.push(`${img.name || 'attachment'} → ${res.ref_text}`)
}
@@ -556,6 +610,7 @@ async function runGroupChatMemberTurnLeased(
/* text-only fallback for this member */
}
}
+
const turnText = fileRefs.length
? `${prompt}\n\nAttached files staged in your session workspace:\n${fileRefs.join('\n')}`
: prompt
@@ -566,6 +621,7 @@ async function runGroupChatMemberTurnLeased(
const liveRuntime = await submitGroupTurnPrompt(member, runtime, stored, turnText)
const started = Date.now()
let deadline = started + GROUP_TURN_TIMEOUT_MS
+
while (Date.now() < deadline) {
await new Promise(resolve => setTimeout(resolve, GROUP_TURN_POLL_MS))
@@ -576,10 +632,13 @@ async function runGroupChatMemberTurnLeased(
// a hold, and that turn must keep polling so finished work can still be
// delivered (the #93127 commit check decides its fate, not this loop).
const roomDuringPoll = $groupChats.get()[group] || {}
+
if ((roomDuringPoll.epoch || 0) !== dispatchEpoch && (roomDuringPoll.holds || {})[memberKey]) {
return null
}
+
let state: GroupSessionSnapshot | null = null
+
try {
state = (await requestForBot(member, 'session.resume', {
session_id: stored || liveRuntime,
@@ -588,6 +647,7 @@ async function runGroupChatMemberTurnLeased(
} catch {
continue
}
+
const messages = Array.isArray(state?.messages) ? state.messages : []
const busy = Boolean(state?.inflight || state?.running)
// A clarify blocking inside the member's session is a question for the
@@ -595,21 +655,26 @@ async function runGroupChatMemberTurnLeased(
// hold the turn open: the member isn't stalling, it's waiting on us.
const awaitingUser = syncGroupClarify(group, member, state)
const done = !busy && !awaitingUser
+
if (messages.length > before && done) {
const replyText = pickGroupTurnReply(messages, before)
+
if (replyText !== null) {
recordGroupActivity(group, {
kind: isGroupPassText(replyText) ? 'passed' : 'replied',
member: member.name,
thread
})
+
return replyText
}
+
recordGroupActivity(group, {
kind: 'passed',
member: member.name,
thread
})
+
return null
}
@@ -639,8 +704,10 @@ async function runGroupChatMemberTurnLeased(
thread
}
}
+
return r
})
+
return null
}
@@ -654,10 +721,13 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
// Markers were a bare number before threads; normalize both shapes.
const strandedBefore = typeof marker === 'number' ? marker : marker?.before
const strandedThread = (typeof marker === 'object' && marker?.thread) || 'legacy'
+
if (typeof strandedBefore !== 'number') {
return
}
+
let state: GroupSessionSnapshot | null = null
+
try {
const stored = room.sessions?.[memberKey]
state = (await requestForBot(member, 'session.resume', {
@@ -667,6 +737,7 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
} catch {
return // source unreachable — leave the marker for the next boundary
}
+
if (state?.inflight || state?.running) {
return // still grinding — keep waiting
}
@@ -682,15 +753,20 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
const next = {
...(r.stranded || {})
}
+
delete next[memberKey]
r.stranded = next
+
return r
})
const messages = Array.isArray(state?.messages) ? state.messages : []
+
if (messages.length <= strandedBefore) {
return
}
+
const reply = pickGroupTurnReply(messages, strandedBefore)
+
if (reply && !isGroupPassText(reply)) {
recordGroupActivity(group, {
kind: 'delivered',
@@ -713,6 +789,7 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMemb
)
updateGroupChat(group, (r: GroupChatRoom) => {
r.watermarks[`${strandedThread}::${memberKey}`] = r.log.length
+
return r
})
}
diff --git a/apps/desktop/src/plugins/hermes-bots/hidden-bots.ts b/apps/desktop/src/plugins/hermes-bots/hidden-bots.ts
index cbdfb3ea21b..a3f8c406a93 100644
--- a/apps/desktop/src/plugins/hermes-bots/hidden-bots.ts
+++ b/apps/desktop/src/plugins/hermes-bots/hidden-bots.ts
@@ -21,9 +21,11 @@ import type { RosterRow } from './types'
/** Session-only view toggle: reveal hidden bots (dimmed) in the roster. */
export const $showHiddenBots = atom(false)
+
export function isBotHidden(bot: RosterRow, metaByName: BotMetaSnapshot) {
return Boolean(botRosterMeta(bot, metaByName)?.hidden)
}
+
export function isBotPinned(bot: RosterRow, metaByName: BotMetaSnapshot) {
return Boolean(botRosterMeta(bot, metaByName)?.pinned)
}
@@ -33,13 +35,18 @@ export function fallbackSelectionAfterHide(name: string) {
if ($selectedBot.get() !== name) {
return
}
+
const meta = $botMeta.get()
const visible = $lastRoster.get().filter(bot => botSelectionKey(bot) !== name && !botRosterMeta(bot, meta)?.hidden)
+
if (visible.length) {
$selectedBot.set(botSelectionKey(visible[0]))
+
return
}
+
const defaultBot = $lastRoster.get().find(bot => isDefaultBot(bot) && !botRosterMeta(bot, meta)?.hidden)
+
if (defaultBot && botSelectionKey(defaultBot) !== name) {
$selectedBot.set(botSelectionKey(defaultBot))
} else if (!$lastRoster.get().some(isDefaultBot)) {
diff --git a/apps/desktop/src/plugins/hermes-bots/hygiene.ts b/apps/desktop/src/plugins/hermes-bots/hygiene.ts
index 8bff8983c9c..356af0b13ff 100644
--- a/apps/desktop/src/plugins/hermes-bots/hygiene.ts
+++ b/apps/desktop/src/plugins/hermes-bots/hygiene.ts
@@ -28,11 +28,14 @@ export function markOrphanedGroupMemberDescriptor(member: GroupMember): GroupMem
sourceReachable: false
}
}
+
export function groupMemberReferencesConnection(member: GroupMember, connectionId: string) {
const id = String(connectionId || '').trim()
+
if (!id) {
return false
}
+
return String(member?.connectionId || '').trim() === id || String(member?.route?.connectionId || '').trim() === id
}
@@ -54,32 +57,42 @@ export function annotateOrphanedGroupChatMembers(
const live = liveConnectionIds && typeof liveConnectionIds.has === 'function' ? liveConnectionIds : null
const next: Record<string, GroupChat> = {}
let changed = false
+
for (const [name, room] of Object.entries(rooms || {})) {
const members = Array.isArray(room?.members) ? room.members : []
+
const orphaned = (member: GroupMember) => {
if (!member || member.sourceMissing) {
return false
}
+
if (!member.sourceScoped && !member.remoteSource) {
return false
}
+
const id = String(member.route?.connectionId || member.connectionId || '').trim()
+
if (!id) {
// Route unresolvable: this is the row shape that threw on render.
return true
}
+
return live ? !live.has(id) : false
}
+
if (!members.some(orphaned)) {
next[name] = room
+
continue
}
+
changed = true
next[name] = {
...room,
members: members.map(member => (orphaned(member) ? markOrphanedGroupMemberDescriptor(member) : member))
}
}
+
return {
rooms: next,
changed
diff --git a/apps/desktop/src/plugins/hermes-bots/labels.ts b/apps/desktop/src/plugins/hermes-bots/labels.ts
index c69f5471e73..39de2166e5a 100644
--- a/apps/desktop/src/plugins/hermes-bots/labels.ts
+++ b/apps/desktop/src/plugins/hermes-bots/labels.ts
@@ -31,6 +31,7 @@ export function displayName(bot: Partial<RosterRow>, meta?: BotMeta | null): str
) {
return bot.connectionLabel
}
+
if (meta?.title?.trim()) {
return meta.title.trim()
}
@@ -46,6 +47,7 @@ export function displayName(bot: Partial<RosterRow>, meta?: BotMeta | null): str
// never generic "Hermes" or a hostname-derived label.
if (alias) {
const raw = alias.name.replace(/[-_]+/g, ' ').trim()
+
return raw.replace(/\b\w/g, ch => ch.toUpperCase())
}
@@ -55,9 +57,12 @@ export function displayName(bot: Partial<RosterRow>, meta?: BotMeta | null): str
if ((bot.name || '').trim().toLowerCase() === 'default' && !bot.title) {
return 'Hermes'
}
+
const raw = (bot.title || bot.name || '').replace(/[-_]+/g, ' ').trim()
+
return raw.replace(/\b\w/g, ch => ch.toUpperCase())
}
+
export function slugify(value: string) {
return value
.toLowerCase()
diff --git a/apps/desktop/src/plugins/hermes-bots/mcp-setup.tsx b/apps/desktop/src/plugins/hermes-bots/mcp-setup.tsx
index 3424f039eab..50a5ff1c9f0 100644
--- a/apps/desktop/src/plugins/hermes-bots/mcp-setup.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/mcp-setup.tsx
@@ -42,18 +42,21 @@ async function mcpRpc(method: string, params: Record<string, unknown>): Promise<
// doesn't know the method (older backend) vs a real error.
try {
const res = await host.request<McpServerPayload>(method, params)
+
return {
ok: true,
result: res
}
} catch (err: any) {
const msg = String((err && err.message) || err || '')
+
if (/unknown method/i.test(msg)) {
return {
ok: false,
unsupported: true
}
}
+
return {
ok: false,
error: msg
@@ -63,12 +66,15 @@ async function mcpRpc(method: string, params: Record<string, unknown>): Promise<
// Probe whether the new lifecycle RPCs exist on this gateway (cached per session).
let _mcpRpcSupported: boolean | null = null
+
async function mcpSetupSupported(): Promise<boolean> {
if (_mcpRpcSupported !== null) {
return _mcpRpcSupported
}
+
const r = await mcpRpc('mcp.servers.list', {})
_mcpRpcSupported = !(r.ok === false && r.unsupported)
+
return _mcpRpcSupported
}
@@ -110,34 +116,42 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
const [keyValues, setKeyValues] = useState<Record<string, string>>({})
const [message, setMessage] = useState('')
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
- const profileRef = useRef<McpSetupScope>(profile || null)
- useEffect(() => {
- if (profile) {
- profileRef.current = profile
- }
- }, [profile])
+ // Holds ONLY the profile this component created on demand. The live prop
+ // wins wherever both exist, so there is nothing to mirror into the ref and
+ // no render of lag between the parent supplying a profile and us using it.
+ const createdProfileRef = useRef<McpSetupScope>(null)
// Resolve the target profile, creating it on demand for the New Bot flow.
const resolveProfile = async () => {
- if (profileRef.current) {
- return profileRef.current
+ const known = profile || createdProfileRef.current
+
+ if (known) {
+ return known
}
+
if (ensureProfile) {
const created = await ensureProfile()
+
if (created) {
- profileRef.current = created
+ createdProfileRef.current = created
}
+
return created
}
+
return null
}
+
+ // eslint-disable-next-line no-restricted-syntax -- clears a timer handle on unmount, not an atom mirror
useEffect(() => {
let alive = true
mcpSetupSupported().then(ok => {
- if (alive) setSupported(ok)
+ if (alive) {setSupported(ok)}
})
+
return () => {
alive = false
+
if (pollRef.current) {
clearInterval(pollRef.current)
pollRef.current = null
@@ -146,59 +160,76 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
}, [])
const isOAuth = (entry.auth || '').toLowerCase() === 'oauth'
const requires = entry.requires || []
+
const beginKeys = async () => {
// Ensure the server exists in the target profile first (add from catalog).
setPhase('busy')
setMessage('')
const profile = await resolveProfile()
+
if (!profile) {
setPhase('idle')
+
return
}
+
if (entry.fromCatalog && !entry.installed) {
const add = await mcpRpc('mcp.servers.add', {
profile,
name: entry.name,
preset: entry.name
})
+
if (!add.ok) {
setPhase('error')
setMessage(add.error || 'Could not add server')
+
return
}
}
+
setPhase(isOAuth ? 'oauth' : 'keys')
}
+
const submitKeys = async () => {
setPhase('busy')
- const profile = profileRef.current
- if (!profile) {
+ const target = profile || createdProfileRef.current
+
+ if (!target) {
setPhase('error')
setMessage('No target profile')
+
return
}
+
for (const k of requires) {
const val = (keyValues[k] || '').trim()
+
if (!val) {
continue
}
+
const r = await mcpRpc('mcp.servers.set_api_key', {
- profile,
+ profile: target,
name: entry.name,
env_var: k,
value: val
})
+
if (!r.ok) {
setPhase('error')
setMessage(r.error || 'Failed to set ' + k)
+
return
}
}
+
// Verify via test.
const t = await mcpRpc('mcp.servers.test', {
- profile,
+ profile: target,
name: entry.name
})
+
if (t.ok && t.result && (t.result.ok || (t.result.result && t.result.result.ok))) {
setPhase('done')
host.notify({
@@ -213,6 +244,7 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
)
}
}
+
const beginOAuth = async () => {
// A second click (retry, impatient double-click) must not orphan the
// previous poll interval — an overwritten pollRef leaks a 2s poller that
@@ -221,37 +253,48 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
clearInterval(pollRef.current)
pollRef.current = null
}
+
setPhase('busy')
setMessage('')
const profile = await resolveProfile()
+
if (!profile) {
setPhase('idle')
+
return
}
+
if (entry.fromCatalog && !entry.installed) {
const add = await mcpRpc('mcp.servers.add', {
profile,
name: entry.name,
preset: entry.name
})
+
if (!add.ok) {
setPhase('error')
setMessage(add.error || 'Could not add server')
+
return
}
}
+
const start = await mcpRpc('mcp.servers.oauth.start', {
profile,
name: entry.name
})
+
const payload = start.result && (start.result.result || start.result)
const authUrl = payload && (payload.auth_url || payload.verification_url)
const sessionId = payload && payload.session_id
+
if (!start.ok || !authUrl || !sessionId) {
setPhase('error')
setMessage(start.error || 'Could not start OAuth')
+
return
}
+
// Open the auth URL in the native browser, same as provider OAuth.
// TODO(bot-mode-types): the plugin SDK's `host` has no `openExternal`, so this
// branch is dead and the window bridge / window.open fallbacks are the only
@@ -270,6 +313,7 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
} catch {
/* fall through to poll; user can open the URL from the toast */
}
+
setPhase('oauth')
setMessage('Complete sign-in in your browser...')
pollRef.current = setInterval(async () => {
@@ -278,8 +322,10 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
name: entry.name,
session_id: sessionId
})
+
const pd = poll.result && (poll.result.result || poll.result)
const status = pd && pd.status
+
if (status === 'approved') {
clearInterval(pollRef.current!)
pollRef.current = null
@@ -297,6 +343,7 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
}
}, 2000)
}
+
if (supported === false) {
return (
<span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">
@@ -304,44 +351,49 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
</span>
)
}
+
if (phase === 'done') {
return <span className="ml-1.5 text-[0.65rem] text-(--ui-success)">set up ✓</span>
}
+
if (phase === 'keys') {
return (
<div className="mt-1 grid gap-1">
{requires.map(k => (
<Input
- key={k}
- type="password"
className="h-6 text-[0.7rem]"
- placeholder={k}
- value={keyValues[k] || ''}
+ key={k}
onChange={e =>
setKeyValues(prev => ({
...prev,
[k]: e.target.value
}))
}
+ placeholder={k}
+ type="password"
+ value={keyValues[k] || ''}
/>
))}
<div className="flex gap-1">
- <Button size="xs" variant="secondary" onClick={() => void submitKeys()}>
+ <Button onClick={() => void submitKeys()} size="xs" variant="secondary">
Save & test
</Button>
- <Button size="xs" variant="ghost" onClick={() => setPhase('idle')}>
+ <Button onClick={() => setPhase('idle')} size="xs" variant="ghost">
{t.common.cancel}
</Button>
</div>
</div>
)
}
+
if (phase === 'oauth') {
return <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">{message || 'Authorizing\u2026'}</span>
}
+
if (phase === 'busy') {
return <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">Working…</span>
}
+
if (phase === 'error') {
return (
<span className="ml-1.5 text-[0.65rem] text-(--ui-danger,#f87171)">
@@ -352,6 +404,7 @@ export function McpSetupButton({ profile, entry, onDone, ensureProfile }: McpSet
</span>
)
}
+
// idle
return (
<Button
diff --git a/apps/desktop/src/plugins/hermes-bots/model-picker.tsx b/apps/desktop/src/plugins/hermes-bots/model-picker.tsx
index a0484eb7490..5004ecec763 100644
--- a/apps/desktop/src/plugins/hermes-bots/model-picker.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/model-picker.tsx
@@ -33,25 +33,31 @@ import type { RosterRow } from './types'
// attempt: past the budget the query rejects and ModelPicker falls back to its
// free-text inputs instead of an eternal GlyphSpinner.
const MODEL_OPTIONS_SETTLE_MS = 20000
+
function boundedModelOptionsFetch<T>(fetch: Promise<T>, settleMs = MODEL_OPTIONS_SETTLE_MS): Promise<T> {
// window.setTimeout (not bare setTimeout): bare vm test harnesses expose
// timers only through the window shim. With no scheduler at all, degrade to
// the old unbounded behavior rather than not fetching.
const scope = typeof window === 'undefined' ? null : window
+
if (!scope || typeof scope.setTimeout !== 'function') {
return fetch
}
+
// `any`: the timer id is assigned synchronously by the executor below, but
// it is still `null` on the declaration TypeScript sees from the closure,
// and clearTimeout's signature takes `number | undefined`.
let timerId: any = null
+
const deadline = new Promise<never>((_, reject) => {
timerId = scope.setTimeout(() => {
reject(new Error(`model.options did not answer within ${Math.round(settleMs / 1000)}s (#95279 settle guard)`))
}, settleMs)
})
+
return Promise.race([fetch, deadline]).finally(() => scope.clearTimeout(timerId))
}
+
/** One provider row of the gateway's `model.options` inventory. Entries in
* `models` are bare slugs on current gateways and objects on older ones. */
interface ModelProviderOption {
@@ -62,12 +68,14 @@ interface ModelProviderOption {
interface ModelOptionsResponse {
providers?: ModelProviderOption[]
}
+
function useModelOptions(bot: null | RosterRow = null) {
// Hook body runs during render: an orphaned row must paint the picker
// disabled/erroring, not throw into the pane's error boundary.
const resolved = bot ? resolveBotConnectionRoute(bot) : null
const route = resolved?.status === 'resolved' ? resolved.route : null
const orphaned = resolved?.status === 'owner_removed'
+
return useQuery<ModelOptionsResponse>({
queryKey: [ID, 'model-options', route ? botRouteKey(route) : 'active'],
// No forced `refresh`: forcing a network read on EVERY mount bypassed the
@@ -107,6 +115,7 @@ interface ModelPickerProps {
placeholderModel?: string
value: ModelSelection
}
+
export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'gateway default' }: ModelPickerProps) {
const { data, isLoading, error } = useModelOptions(bot)
@@ -117,13 +126,15 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
const providers = (data?.providers || []).filter(p => p && p.slug)
const isKnown = !value.provider || value.provider === NONE || providers.some(p => p.slug === value.provider)
const [useFreeText, setUseFreeText] = useState(!isKnown)
+
if (isLoading) {
return (
<div className="flex justify-center py-2">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
)
}
+
if (error || !providers.length) {
// Fallback: free text (older gateway or empty inventory).
return (
@@ -131,30 +142,31 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
{labeled(
'Provider',
<Input
- placeholder="omnirouter / 9router / nous …"
- value={value.provider}
onChange={event =>
onChange({
provider: event.target.value
})
}
+ placeholder="omnirouter / 9router / nous …"
+ value={value.provider}
/>
)}
{labeled(
'Model',
<Input
- placeholder="antigravity/gemini-3.6-flash-high"
- value={value.model}
onChange={event =>
onChange({
model: event.target.value
})
}
+ placeholder="antigravity/gemini-3.6-flash-high"
+ value={value.model}
/>
)}
</div>
)
}
+
if (useFreeText) {
return (
<div
@@ -168,49 +180,51 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
{labeled(
'Provider (Custom)',
<Input
- placeholder="e.g. omnirouter, inferx, 9router"
- value={value.provider}
onChange={event =>
onChange({
provider: event.target.value
})
}
+ placeholder="e.g. omnirouter, inferx, 9router"
+ value={value.provider}
/>
)}
{labeled(
'Model (Custom)',
<Input
- placeholder="e.g. antigravity/gemini-3.6-flash-high"
- value={value.model}
onChange={event =>
onChange({
model: event.target.value
})
}
+ placeholder="e.g. antigravity/gemini-3.6-flash-high"
+ value={value.model}
/>
)}
</div>
<Button
- variant="ghost"
- size="sm"
className="h-6 self-start text-xs text-(--ui-text-tertiary)"
onClick={() => setUseFreeText(false)}
+ size="sm"
+ variant="ghost"
>
← Back to dropdowns
</Button>
</div>
)
}
+
const activeProvider = providers.find(p => p.slug === value.provider) || null
+
const models = activeProvider
? (activeProvider.models || []).map(m => (typeof m === 'string' ? m : m.id || m.name || ''))
: []
+
return (
<div className="grid grid-cols-[1fr_1.4fr] gap-2.5">
{labeled(
'Provider',
<Select
- value={value.provider || NONE}
onValueChange={v => {
if (v === NONE) {
onChange({
@@ -229,6 +243,7 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
})
}
}}
+ value={value.provider || NONE}
>
<SelectTrigger className="h-8 rounded-md">
<SelectValue />
@@ -248,12 +263,12 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
'Model',
activeProvider && models.length > 0 ? (
<Select
- value={value.model || (models[0] ?? '')}
onValueChange={v =>
onChange({
model: v
})
}
+ value={value.model || (models[0] ?? '')}
>
<SelectTrigger className="h-8 rounded-md">
<SelectValue />
@@ -268,13 +283,13 @@ export function ModelPicker({ bot = null, value, onChange, placeholderModel = 'g
</Select>
) : (
<Input
- placeholder={placeholderModel || 'e.g. model name'}
- value={value.model}
onChange={event =>
onChange({
model: event.target.value
})
}
+ placeholder={placeholderModel || 'e.g. model name'}
+ value={value.model}
/>
)
)}
diff --git a/apps/desktop/src/plugins/hermes-bots/pet.tsx b/apps/desktop/src/plugins/hermes-bots/pet.tsx
index 60c865beadb..a3eb3c4df2e 100644
--- a/apps/desktop/src/plugins/hermes-bots/pet.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/pet.tsx
@@ -21,6 +21,7 @@ const PET_FRAME_H = 208
const petFrameCache = new Map<string, Promise<null | string>>()
let petFetchActive = 0
const petFetchQueue: Array<() => Promise<void>> = []
+
function pumpPetQueue() {
while (petFetchActive < 4 && petFetchQueue.length) {
const job = petFetchQueue.shift()!
@@ -31,10 +32,12 @@ function pumpPetQueue() {
})
}
}
+
function petFrameIcon(spriteUrl: null | string | undefined): Promise<null | string> {
if (!spriteUrl) {
return Promise.resolve(null)
}
+
if (!petFrameCache.has(spriteUrl)) {
petFrameCache.set(
spriteUrl,
@@ -44,6 +47,7 @@ function petFrameIcon(spriteUrl: null | string | undefined): Promise<null | stri
const resp = await fetch(spriteUrl, {
signal: AbortSignal.timeout(15000)
})
+
const blob = await resp.blob()
// Crop frame 0 during decode — never materialize the full sheet.
const bitmap = await createImageBitmap(blob, 0, 0, PET_FRAME_W, PET_FRAME_H)
@@ -62,6 +66,7 @@ function petFrameIcon(spriteUrl: null | string | undefined): Promise<null | stri
})
)
}
+
return petFrameCache.get(spriteUrl)!
}
@@ -80,10 +85,12 @@ function PetThumb({ spriteUrl, size = 40 }: PetThumbProps) {
setIcon(url)
}
})
+
return () => {
alive = false
}
}, [spriteUrl])
+
if (!icon) {
return (
<div
@@ -96,10 +103,11 @@ function PetThumb({ spriteUrl, size = 40 }: PetThumbProps) {
/>
)
}
+
return (
<img
- src={icon}
alt=""
+ src={icon}
style={{
width: size,
height: size,
@@ -132,23 +140,27 @@ export function PetTab({ image, onImage }: PetTabProps) {
// uploaded/generated image (a direct meta write here gets clobbered by
// Save's own image state).
const [selectedSlug, setSelectedSlug] = useState<null | string>(null)
+
const { data, isLoading } = useQuery({
queryKey: [ID, 'pet-gallery'],
queryFn: () => host.request<{ pets?: PetGalleryEntry[] }>('pet.gallery', {}),
staleTime: 300000
})
+
const [query, setQuery] = useState('')
// Windowed rendering: the gallery is 4500+ pets — mounting an <img> per pet
// froze the dialog. Render `limit` at a time and grow on scroll-to-bottom.
const [limit, setLimit] = useState(24)
const pets = data?.pets ?? []
+
if (isLoading) {
return (
<div className="flex justify-center py-4">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
)
}
+
if (!pets.length) {
return (
<div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
@@ -156,22 +168,30 @@ export function PetTab({ image, onImage }: PetTabProps) {
</div>
)
}
+
const q = query.trim().toLowerCase()
+
const filtered = q
? pets.filter(pet => (pet.displayName || '').toLowerCase().includes(q) || (pet.slug || '').includes(q))
: pets
+
// Installed and curated pets surface first — they're the likeliest picks.
const ranked = filtered.slice().sort((a, b) => {
const rank = (pet: PetGalleryEntry) => (pet.installed ? 0 : pet.curated ? 1 : 2)
+
return rank(a) - rank(b)
})
+
const visible = ranked.slice(0, limit)
+
const onScroll = (event: { currentTarget: HTMLDivElement }) => {
const el = event.currentTarget
+
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120 && limit < ranked.length) {
setLimit(prev => Math.min(prev + 24, ranked.length))
}
}
+
return (
<div className="grid w-full gap-2">
<div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">
@@ -179,23 +199,23 @@ export function PetTab({ image, onImage }: PetTabProps) {
</div>
<Input
className="h-7 text-xs"
- placeholder={`Search ${pets.length} pets…`}
- value={query}
onChange={event => {
setQuery(event.target.value)
setLimit(24)
}}
+ placeholder={`Search ${pets.length} pets…`}
+ value={query}
/>
{image && selectedSlug ? (
<Button
- type="button"
- variant="ghost"
- size="sm"
className="justify-center"
onClick={() => {
setSelectedSlug(null)
onImage(null)
}}
+ size="sm"
+ type="button"
+ variant="ghost"
>
{b.avatar.removeBackToShape}
</Button>
@@ -213,11 +233,11 @@ export function PetTab({ image, onImage }: PetTabProps) {
<div className="grid grid-cols-3 gap-1.5">
{visible.map(pet => (
<RowButton
- key={pet.slug}
className={cn(
'grid justify-items-center gap-1 rounded-md p-1.5 transition-colors hover:bg-(--chrome-action-hover)',
selectedSlug === pet.slug && 'ring-1 ring-(--ui-accent)'
)}
+ key={pet.slug}
onClick={() => {
// The pet IS the profile picture: extract frame 0
// and hand it to the dialog as the avatar image.
@@ -236,7 +256,7 @@ export function PetTab({ image, onImage }: PetTabProps) {
})
}}
>
- <PetThumb spriteUrl={pet.spritesheetUrl} size={40} />
+ <PetThumb size={40} spriteUrl={pet.spritesheetUrl} />
<span className="w-full truncate text-center text-[0.6rem] text-(--ui-text-tertiary)">
{pet.displayName}
</span>
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
index 6f9022eba63..a794cc573e8 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/profile-config.tsx
@@ -66,6 +66,7 @@ interface CheckListProps {
items: CapabilityEntry[]
onToggle: (name: string, enabled: boolean) => void
}
+
export function CheckList({ items, onToggle, columns = 2 }: CheckListProps) {
return (
<div
@@ -77,8 +78,8 @@ export function CheckList({ items, onToggle, columns = 2 }: CheckListProps) {
>
{items.map(item => (
<label
- key={item.name}
className="flex min-w-0 cursor-pointer items-center gap-1.5 py-0.5 text-xs text-(--ui-text-secondary)"
+ key={item.name}
title={item.description || item.name}
>
<Checkbox checked={item.enabled} onCheckedChange={value => onToggle(item.name, Boolean(value))} />
@@ -91,6 +92,7 @@ export function CheckList({ items, onToggle, columns = 2 }: CheckListProps) {
</div>
)
}
+
/** `profiles.describe` as the advanced editor reads it. */
export interface ProfileDescribeResponse {
mcp_servers?: CapabilityEntry[]
@@ -124,6 +126,7 @@ interface AdvancedProfileConfigProps {
setState: (update: (prev: AdvancedConfigState) => AdvancedConfigState) => void
state: AdvancedConfigState
}
+
export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileConfigProps) {
const b = useBots()
const [loaded, setLoaded] = useState(false)
@@ -134,6 +137,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
const botRoute = resolveBotConnectionRoute(bot).route
const backendProfile = botRoute?.targetProfile || botRoute?.profile || bot.name
const backendScope = botBackendProfileScope(botRoute, bot.name)
+
if (!loaded) {
setLoaded(true)
Promise.all([
@@ -177,6 +181,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
})
.catch(() => setUnsupported(true))
}
+
if (unsupported) {
return (
<div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
@@ -184,16 +189,19 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
</div>
)
}
+
if (!state.loaded) {
return (
<div className="flex justify-center py-4">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
)
}
+
const visibleSkills = skillFilter.trim()
? state.skills.filter(s => s.name.toLowerCase().includes(skillFilter.trim().toLowerCase()))
: state.skills
+
const toggleSkill = (name: string, enabled: boolean) =>
setState(prev => ({
...prev,
@@ -207,6 +215,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
: s
)
}))
+
const toggleToolset = (name: string, enabled: boolean) =>
setState(prev => ({
...prev,
@@ -220,6 +229,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
: t
)
}))
+
const toggleMcp = (name: string, enabled: boolean) =>
setState(prev => ({
...prev,
@@ -233,6 +243,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
: m
)
}))
+
const enabledSkills = state.skills.filter(s => s.enabled).length
const enabledToolsets = state.toolsets.filter(t => t.enabled).length
const mcpList = state.mcp || []
@@ -250,10 +261,6 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
<div className="grid gap-4">
<ModelPicker
bot={bot}
- value={{
- provider: state.provider,
- model: state.model
- }}
onChange={patch =>
setState(prev => ({
...prev,
@@ -261,6 +268,10 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
...patch
}))
}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
/>
{labeled(
'Capabilities (applies immediately — skills, tools, MCP)',
@@ -288,7 +299,6 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
'SOUL.md (persona + agent-messaging protocol)',
<Textarea
className="min-h-28 font-mono text-xs leading-5"
- value={state.soul}
onChange={event =>
setState(prev => ({
...prev,
@@ -296,20 +306,18 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
soul: event.target.value
}))
}
+ value={state.soul}
/>
)}
</div>
)
}
+
if (bot?.sourceScoped && botRoute?.mode === 'remote' && !skillsViewRoutesConnections) {
return (
<div className="grid gap-4">
<ModelPicker
bot={bot}
- value={{
- provider: state.provider,
- model: state.model
- }}
onChange={patch =>
setState(prev => ({
...prev,
@@ -317,6 +325,10 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
...patch
}))
}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
/>
<div className="rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-text-tertiary)">
Remote capabilities require a newer desktop. Model and SOUL changes remain staged until you save.
@@ -325,7 +337,6 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
'SOUL.md (persona + agent-messaging protocol)',
<Textarea
className="min-h-28 font-mono text-xs leading-5"
- value={state.soul}
onChange={event =>
setState(prev => ({
...prev,
@@ -333,19 +344,17 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
soul: event.target.value
}))
}
+ value={state.soul}
/>
)}
</div>
)
}
+
return (
<div className="grid gap-4">
<ModelPicker
bot={bot}
- value={{
- provider: state.provider,
- model: state.model
- }}
onChange={patch =>
setState(prev => ({
...prev,
@@ -353,15 +362,19 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
...patch
}))
}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
/>
{labeled(
`Skills (${enabledSkills}/${state.skills.length} enabled)`,
<div className="grid gap-1.5 rounded-md border border-(--ui-stroke-secondary) p-2">
<Input
className="h-7 text-xs"
+ onChange={event => setSkillFilter(event.target.value)}
placeholder={b.tools.filterSkills}
value={skillFilter}
- onChange={event => setSkillFilter(event.target.value)}
/>
<div
className="overflow-y-auto overscroll-contain"
@@ -369,7 +382,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
maxHeight: 180
}}
>
- <CheckList items={visibleSkills} onToggle={toggleSkill} columns={2} />
+ <CheckList columns={2} items={visibleSkills} onToggle={toggleSkill} />
</div>
<HubSkillsSection
forProfile={backendScope}
@@ -403,7 +416,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
>
<div className="grid gap-1.5">
{state.toolsets.map(tset => (
- <div key={tset.name} className="rounded-md border border-(--ui-stroke-secondary) p-2">
+ <div className="rounded-md border border-(--ui-stroke-secondary) p-2" key={tset.name}>
<label className="flex items-center gap-2 text-xs font-medium text-(--ui-text-secondary)">
<Checkbox
checked={!!tset.enabled}
@@ -416,7 +429,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
/* the desktop build exposes it. Older builds: just the toggle. */}
{ToolsetConfigPanel ? (
<div className="mt-1.5 border-t border-(--ui-stroke-secondary) pt-1.5">
- <ToolsetConfigPanel toolset={tset.name} profile={backendScope} />
+ <ToolsetConfigPanel profile={backendScope} toolset={tset.name} />
</div>
) : null}
</div>
@@ -452,8 +465,9 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
m.fromCatalog &&
!m.installed &&
((m.requires || []).length > 0 || (m.auth || '').toLowerCase() === 'oauth')
+
return (
- <label key={m.name} className="flex items-start gap-2 text-xs text-(--ui-text-secondary)">
+ <label className="flex items-start gap-2 text-xs text-(--ui-text-secondary)" key={m.name}>
<Checkbox
checked={!!m.enabled}
disabled={needsSetup}
@@ -467,7 +481,7 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
</span>
) : null}
{needsSetup ? (
- <McpSetupButton profile={backendScope} entry={m} onDone={() => toggleMcp(m.name, true)} />
+ <McpSetupButton entry={m} onDone={() => toggleMcp(m.name, true)} profile={backendScope} />
) : null}
{m.description ? (
<div className="truncate text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
@@ -487,7 +501,6 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
'SOUL.md (persona + agent-messaging protocol)',
<Textarea
className="min-h-28 font-mono text-xs leading-5"
- value={state.soul}
onChange={event =>
setState(prev => ({
...prev,
@@ -495,11 +508,13 @@ export function AdvancedProfileConfig({ bot, state, setState }: AdvancedProfileC
soul: event.target.value
}))
}
+ value={state.soul}
/>
)}
</div>
)
}
+
export function emptyAdvancedState(): AdvancedConfigState {
return {
loaded: false,
@@ -543,13 +558,17 @@ export async function applyAdvancedConfig(bot: RosterRow, state: AdvancedConfigS
const payload: ProfileConfigurePayload = {
name: bot.name
}
+
const applied: Record<string, boolean> = {}
+
if (state.dirtySoul) {
payload.soul = ensureMessagingProtocol(state.soul, bot.name, $lastRoster.get())
}
+
if (state.dirtyModel) {
const model = state.model.trim()
const provider = state.provider.trim()
+
if (model && provider) {
payload.model = model
payload.provider = provider
@@ -558,6 +577,7 @@ export async function applyAdvancedConfig(bot: RosterRow, state: AdvancedConfigS
const result = (await requestForBot(bot, 'cli.exec', {
argv: ['--profile', bot.name, 'config', 'unset', 'model']
})) as { blocked?: boolean; code?: number }
+
applied.model = result?.blocked !== true && result?.code === 0
} catch {
applied.model = false
@@ -566,25 +586,31 @@ export async function applyAdvancedConfig(bot: RosterRow, state: AdvancedConfigS
applied.model = false
}
}
+
if (state.dirtySkills) {
payload.disabled_skills = state.skills.filter(s => !s.enabled).map(s => s.name)
}
+
if (state.dirtyToolsets) {
const all = state.toolsets.length
const enabled = state.toolsets.filter(t => t.enabled)
// All enabled (or none) = clear the pin; otherwise pin the checked set.
payload.enabled_toolsets = enabled.length === all || enabled.length === 0 ? [] : enabled.map(t => t.name)
}
+
if (state.dirtyMcp) {
payload.enabled_mcp_servers = (state.mcp || []).filter(m => m.enabled).map(m => m.name)
}
+
if (Object.keys(payload).length === 1) {
return {
ok: Object.values(applied).every(Boolean),
applied
}
}
+
const result = (await requestForBot(bot, 'profiles.configure', payload)) as ProfileConfigureResult
+
const merged = {
...applied,
...(result?.applied || {})
@@ -615,6 +641,7 @@ export async function applyAdvancedConfig(bot: RosterRow, state: AdvancedConfigS
}) as Promise<ProfileConfigureResult>
})
}
+
return {
...result,
ok: Object.values(merged).every(Boolean),
diff --git a/apps/desktop/src/plugins/hermes-bots/profile-ops.ts b/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
index 74f7533e239..f6391ee3110 100644
--- a/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
+++ b/apps/desktop/src/plugins/hermes-bots/profile-ops.ts
@@ -48,12 +48,16 @@ const avatarPushInflight = new Set<string>()
function pushLocalAvatars(roster: RosterRow[]) {
for (const bot of roster) {
const key = botMetaKey(bot)
+
if (bot.has_avatar || avatarPushInflight.has(key)) {
continue
}
+
const image = $botMeta.get()[key]?.image
+
if (image && typeof image === 'string' && image.startsWith('data:')) {
avatarPushInflight.add(key)
+
const request = bot.sourceScoped
? requestForBot(bot, 'profiles.set_asset', {
name: bot.name,
@@ -65,6 +69,7 @@ function pushLocalAvatars(roster: RosterRow[]) {
asset: 'avatar',
data: image
})
+
Promise.resolve(request)
.then(() =>
queryClient.invalidateQueries({
@@ -72,6 +77,7 @@ function pushLocalAvatars(roster: RosterRow[]) {
})
)
.catch(() => avatarPushInflight.delete(key))
+
continue
}
@@ -79,9 +85,11 @@ function pushLocalAvatars(roster: RosterRow[]) {
// live SVG (tagged data-bot-face) to a PNG and push that, so the
// inter-agent notices (core #85855/#85888) can show the real pfp.
const svg = document.querySelector('svg[data-bot-face=' + JSON.stringify(bot.name) + ']')
+
if (!svg) {
continue
}
+
avatarPushInflight.add(key)
rasterizeSvgToPng(svg, 160)
.then(png =>
@@ -121,6 +129,7 @@ function rasterizeSvgToPng(svgEl: Element, size: number): Promise<null | string>
const markup = new XMLSerializer().serializeToString(clone)
const url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(markup)
const img = new Image()
+
img.onload = () => {
try {
const canvas = document.createElement('canvas')
@@ -134,6 +143,7 @@ function rasterizeSvgToPng(svgEl: Element, size: number): Promise<null | string>
resolve(null)
}
}
+
img.onerror = () => resolve(null)
img.src = url
} catch {
@@ -141,23 +151,30 @@ function rasterizeSvgToPng(svgEl: Element, size: number): Promise<null | string>
}
})
}
+
/** `profiles.get_asset` reply for the `avatar` asset. */
interface ProfilesGetAssetResult {
/** Data URL. */
data?: string
found?: boolean
}
+
export function pullServerAvatars(roster: RosterRow[]) {
pushLocalAvatars(roster)
+
for (const bot of roster) {
const key = botMetaKey(bot)
+
if (!bot.has_avatar || avatarFetchInflight.has(key)) {
continue
}
+
if ($botMeta.get()[key]?.image) {
continue
}
+
avatarFetchInflight.add(key)
+
const assetRequest = bot.sourceScoped
? requestForBot(bot, 'profiles.get_asset', {
name: bot.name,
@@ -167,16 +184,19 @@ export function pullServerAvatars(roster: RosterRow[]) {
name: bot.name,
asset: 'avatar'
})
+
Promise.resolve(assetRequest as Promise<ProfilesGetAssetResult>)
.then(res => {
if (res?.found && res.data) {
const current = $botMeta.get()
const mine = current[key] || {}
+
// A 160px raster of the vector face is only for inter-agent
// notices. Do not park it on the roster or the live face dies.
if (isBackfilledFacePng(res.data) && mine.imageKind !== 'photo' && !mine.pet) {
return
}
+
$botMeta.set({
...current,
[key]: {
@@ -209,17 +229,23 @@ export function pullServerAvatars(roster: RosterRow[]) {
export function mergeServerMeta(roster: RosterRow[], fetchedAt = 0) {
const local = $botMeta.get()
let changed = false
+
const next = {
...local
}
+
for (const bot of roster) {
const server = bot.ui_meta?.['hermes-bots']
+
if (server && typeof server === 'object') {
const key = botMetaKey(bot)
+
if (fetchedAt && fetchedAt < (botMetaWriteAt.get(key) || 0)) {
continue
}
+
const mine = next[key] || {}
+
const merged = {
...mine,
...server
@@ -246,12 +272,14 @@ export function mergeServerMeta(roster: RosterRow[], fetchedAt = 0) {
) {
delete merged.group
}
+
if (JSON.stringify(next[key] || null) !== JSON.stringify(merged)) {
next[key] = merged
changed = true
}
}
}
+
if (changed) {
$botMeta.set(next)
@@ -276,12 +304,14 @@ export async function duplicateBot(bot: RosterRow, roster: RosterRow[]) {
const ownerRoute = botConnectionRoute(bot)
const ownerKey = ownerRoute ? botRouteKey(ownerRoute) : null
let name = null
+
for (let n = 2; n < 100; n++) {
// Truncate the BASE, never the suffix — slicing the joined string chops
// the "-2" off a max-length name and the candidate collides with the
// base forever (#19).
const suffix = `-${n}`
const candidate = base.slice(0, 64 - suffix.length) + suffix
+
if (
!roster.some(
// A truthy ownerKey is minted from ownerRoute, so the route is present
@@ -290,12 +320,15 @@ export async function duplicateBot(bot: RosterRow, roster: RosterRow[]) {
)
) {
name = candidate
+
break
}
}
+
if (!name) {
throw new Error('No free name for the duplicate.')
}
+
await requestForBot(bot, 'profiles.create', {
name,
clone_from: base,
@@ -306,6 +339,7 @@ export async function duplicateBot(bot: RosterRow, roster: RosterRow[]) {
// are tellable apart in the roster until the user renames. Do not copy
// chat or created. Those belong to the original bot.
const meta = $botMeta.get()[botMetaKey(bot)]
+
if (meta) {
const { chat, created, ...look } = meta
await saveBotMeta(
@@ -325,6 +359,7 @@ export async function duplicateBot(bot: RosterRow, roster: RosterRow[]) {
}
)
}
+
return name
}
@@ -349,9 +384,11 @@ interface CliExecResult {
* directory (hermes-agent#52279). That is the "can't delete a bot" error. */
export async function deleteBot(bot: RosterRow) {
const route = botConnectionRoute(bot)
+
if (isDefaultBot(bot) || String(route?.targetProfile || '').toLowerCase() === 'default') {
throw new Error('The default profile cannot be deleted.')
}
+
if (typeof host.deleteProfile === 'function') {
if (route) {
await host.deleteProfile(route)
@@ -363,18 +400,23 @@ export async function deleteBot(bot: RosterRow) {
if (route) {
throw new Error('Source-scoped profile deletion requires host.deleteProfile.')
}
+
const result: CliExecResult = await host.request('cli.exec', {
argv: ['profile', 'delete', bot.name, '--yes']
})
+
if (result?.blocked || result?.code !== 0) {
throw new Error(result?.hint || result?.output || `Could not delete profile ${bot.name}.`)
}
}
+
const meta = {
...$botMeta.get()
}
+
delete meta[botMetaKey(bot)]
$botMeta.set(meta)
+
try {
if (route) {
await commitBotMetaV2(getPluginCtx()?.storage, meta)
@@ -384,26 +426,33 @@ export async function deleteBot(bot: RosterRow) {
} catch {
/* profile is deleted; stale local appearance is harmless if storage fails */
}
+
// Both ids: the marker may have been filed under either tip of the chat's
// compression lineage.
forgetSessionUnread([bot.canonical_session?.id, bot.canonical_session?.resolved_id], bot.name)
rosterWatermarks.delete(botSelectionKey(bot))
avatarFetchInflight.delete(botMetaKey(bot))
avatarPushInflight.delete(botMetaKey(bot))
+
if ($selectedBot.get() === botSelectionKey(bot)) {
$selectedBot.set('default')
}
+
clearSelectedRosterBot(bot)
+
if ($openBotChat.get()?.key === botRosterKey(bot)) {
$openBotChat.set(null)
}
+
queryClient.invalidateQueries({
queryKey: ROSTER_KEY
})
const activeOwner = focusedRosterOwner($focusedBotOwner.get?.())
+
const deletedOwnerIsActive = route
? activeOwner?.connectionId === route.connectionId && activeOwner?.name === route.profile
: activeOwner?.name === bot.name
+
if (deletedOwnerIsActive && typeof host.newChat === 'function') {
host.newChat('default')
}
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.ts
index ed86323308c..be097b263d5 100644
--- a/apps/desktop/src/plugins/hermes-bots/relay.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts
@@ -89,10 +89,13 @@ function syncRelayRetention(connections: RelayConnection[]) {
if (typeof host.retainProfileSocket !== 'function') {
return
}
+
const live = new Set(connections.map(connection => connection.id))
+
for (const [id, release] of [...relayRouteRetentions]) {
if (!live.has(id)) {
relayRouteRetentions.delete(id)
+
try {
release()
} catch {
@@ -100,9 +103,11 @@ function syncRelayRetention(connections: RelayConnection[]) {
}
}
}
+
if (relayDisposed) {
return
}
+
for (const connection of connections) {
if (!relayRouteRetentions.has(connection.id)) {
relayRouteRetentions.set(connection.id, host.retainProfileSocket(connection.route))
@@ -119,6 +124,7 @@ function releaseRelayRetention() {
// Disposer from an older shell shape — never break teardown.
}
}
+
relayRouteRetentions.clear()
}
@@ -127,15 +133,19 @@ async function relayConnections(): Promise<RelayConnection[]> {
if (typeof host.profileRoutes !== 'function' || typeof host.requestProfile !== 'function') {
return []
}
+
try {
const routes = await host.profileRoutes()
const byConnection = new Map<string, ProfileRoute>()
+
for (const route of Array.isArray(routes) ? routes : []) {
const id = String(route?.connectionId || '')
+
if (id && !byConnection.has(id)) {
byConnection.set(id, route)
}
}
+
return [...byConnection.entries()].map(([id, route]) => ({
id,
route
@@ -156,12 +166,14 @@ async function relayAgentsOn(connection: RelayConnection): Promise<RelayAgentRow
const res = await host.requestProfile<{ profiles?: RosterRow[] }>(connection.route, 'profiles.list', {
include_sessions: false
})
+
const profiles = Array.isArray(res?.profiles) ? res.profiles : []
// TODO(bot-mode-types): neither `connectionLabel` nor `label` can exist on
// a `host.profileRoutes()` route (connectionId / mode / profile /
// targetProfile only), so this always falls through to the raw connection
// id and peer gateways list agents by id instead of the human label.
const label = String(connection.route?.connectionLabel || connection.route?.label || connection.id)
+
return profiles
.map(profile => ({
profile: String(profile?.name || ''),
@@ -186,16 +198,21 @@ async function syncRelayRosters() {
if (relayDisposed || relayRosterBusy) {
return
}
+
relayRosterBusy = true
+
try {
const connections = await relayConnections()
+
if (connections.length < 2) {
return
}
+
const agentsByConnection = new Map<string, RelayAgentRow[]>()
await Promise.all(
connections.map(async connection => {
const agents = await relayAgentsOn(connection)
+
if (agents === null) {
// Transient fetch failure: reuse the last good rows for this
// connection (or contribute nothing this cycle) so the pushed
@@ -212,19 +229,23 @@ async function syncRelayRosters() {
// Connections gone from profileRoutes are genuinely disconnected — drop
// their cache so a later reconnect starts from live data.
const liveIds = new Set(connections.map(connection => connection.id))
+
for (const id of [...relayAgentsCache.keys()]) {
if (!liveIds.has(id)) {
relayAgentsCache.delete(id)
}
}
+
await Promise.all(
connections.map(async connection => {
const others: RelayAgentRow[] = []
+
for (const [id, agents] of agentsByConnection) {
if (id !== connection.id) {
others.push(...agents)
}
}
+
try {
await host.requestProfile(connection.route, 'bot_relay.roster.sync', {
agents: others
@@ -246,42 +267,54 @@ async function drainRelayOutboxes() {
if (relayDisposed) {
return
}
+
if (relayDrainBusy) {
// A push signal raced an in-flight drain. The gateway never re-sends it
// (monotone signature), so without this flag the envelope would wait out
// the full poll interval — exactly the latency the push path removes.
relayDrainRerun = true
+
return
}
+
relayDrainBusy = true
+
try {
const connections = await relayConnections()
// Retention follows the relay-eligible set: with fewer than two
// connections there is nothing to relay, so nothing stays pinned.
syncRelayRetention(connections.length >= 2 ? connections : [])
+
if (connections.length < 2) {
return
}
+
const byId = new Map(connections.map(connection => [connection.id, connection]))
+
for (const sender of connections) {
let envelopes: RelayEnvelope[] = []
+
try {
const res = await host.requestProfile<{ envelopes?: RelayEnvelope[] }>(
sender.route,
'bot_relay.outbox.drain',
{}
)
+
envelopes = Array.isArray(res?.envelopes) ? res.envelopes : []
} catch {
continue
}
+
for (const envelope of envelopes) {
if (relayDisposed) {
return
}
+
const envelopeId = String(envelope?.id || '')
const target = byId.get(String(envelope?.target_connection || ''))
+
const postReply = async (payload: { error?: string; reason?: string; reply?: string }) => {
try {
await host.requestProfile(sender.route, 'bot_relay.reply', {
@@ -292,24 +325,29 @@ async function drainRelayOutboxes() {
// Sender gateway unreachable — its waiter times out with guidance.
}
}
+
if (!envelopeId) {
continue
}
+
if (!target) {
await postReply({
error: `connection '${envelope?.target_connection}' is not connected to this Desktop right now`
})
+
continue
}
// Needs-attention hook (#93091 item 3): a delivered background DM is
// this bot's "good turn"; a classified delivery failure badges it.
const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`
+
try {
const res = await host.requestProfile<{ reply?: string }>(target.route, 'bot_relay.deliver', {
profile: String(envelope?.target_profile || ''),
message: String(envelope?.message || '')
})
+
clearBotAttention(attentionKey)
await postReply({
reply: String(res?.reply || '')
@@ -335,6 +373,7 @@ async function drainRelayOutboxes() {
}
} finally {
relayDrainBusy = false
+
if (relayDrainRerun && !relayDisposed) {
// Envelopes signaled mid-drain: schedule one follow-up pass (debounced)
// instead of leaving them to the interval poll.
@@ -350,14 +389,17 @@ function scheduleRelayPushDrain() {
if (relayDisposed || typeof setTimeout !== 'function') {
return
}
+
if (relayPushDebounceTimer !== null) {
return
}
+
relayPushDebounceTimer = setTimeout(() => {
relayPushDebounceTimer = null
void drainRelayOutboxes()
}, RELAY_PUSH_DEBOUNCE_MS)
}
+
export function startBotRelay() {
relayDisposed = false
@@ -366,10 +408,12 @@ export function startBotRelay() {
if (typeof setInterval !== 'function' || typeof clearInterval !== 'function') {
return
}
+
if (relayRosterTimer === null) {
relayRosterTimer = setInterval(() => void syncRelayRosters(), RELAY_ROSTER_INTERVAL_MS)
void syncRelayRosters()
}
+
if (relayDrainTimer === null) {
relayDrainTimer = setInterval(() => void drainRelayOutboxes(), RELAY_DRAIN_INTERVAL_MS)
}
@@ -382,6 +426,7 @@ export function startBotRelay() {
relayPushUnsub = host.onEvent('bot_relay.outbox.pending', () => scheduleRelayPushDrain())
}
}
+
export function stopBotRelay() {
relayDisposed = true
// A rerun remembered mid-drain must not leak into the next start —
@@ -390,24 +435,29 @@ export function stopBotRelay() {
// Unpin every relay-retained socket (#93594): with the relay stopped the
// pooled entries return to dispose-at-refcount-0 semantics.
releaseRelayRetention()
+
if (relayRosterTimer !== null) {
clearInterval(relayRosterTimer)
relayRosterTimer = null
}
+
if (relayDrainTimer !== null) {
clearInterval(relayDrainTimer)
relayDrainTimer = null
}
+
if (relayPushDebounceTimer !== null) {
clearTimeout(relayPushDebounceTimer)
relayPushDebounceTimer = null
}
+
if (relayPushUnsub !== null) {
try {
relayPushUnsub()
} catch {
// Disposer from an older shell shape — never break teardown.
}
+
relayPushUnsub = null
}
}
diff --git a/apps/desktop/src/plugins/hermes-bots/roster-actions.ts b/apps/desktop/src/plugins/hermes-bots/roster-actions.ts
index be7e5b79494..3d365e6b804 100644
--- a/apps/desktop/src/plugins/hermes-bots/roster-actions.ts
+++ b/apps/desktop/src/plugins/hermes-bots/roster-actions.ts
@@ -35,6 +35,7 @@ export const $activityToasts = atom(false)
/** Flip the activity-toast pref and persist it. */
export function setActivityToasts(enabled: boolean) {
$activityToasts.set(enabled)
+
try {
Promise.resolve(getPluginCtx()?.storage?.set?.('activity-toasts', enabled)).catch(() => undefined)
} catch {
@@ -55,12 +56,14 @@ export function setActivityToasts(enabled: boolean) {
export function trackInboundActivity(roster: RosterRow[]) {
const seeding = !watermarksSeeded
watermarksSeeded = true
+
for (const bot of roster) {
const key = botSelectionKey(bot)
const activity = botActivitySession(bot)
const ts = activity?.last_active || 0
const prev = rosterWatermarks.get(key) || 0
rosterWatermarks.set(key, Math.max(prev, ts))
+
if (seeding || ts <= prev) {
continue
}
@@ -75,6 +78,7 @@ export function trackInboundActivity(roster: RosterRow[]) {
// row's SessionStatusDot reads — a parallel map here would be a second
// badge that drifts from the dot.
const canonicalSessionId = botCanonicalSessionId(bot)
+
if (canonicalSessionId) {
markSessionUnreadFinished(canonicalSessionId, bot.name)
}
@@ -113,25 +117,31 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
// has actually fronted a new owner; a failed open must not steal the center
// from a group the user was reading.
const previousGroup = $groupChatWorkspace.get()
+
const previousGroupRef = previousGroup
? {
group: previousGroup,
roomId: String($groupChats.get()[previousGroup]?.roomId || '')
}
: null
+
haptic('tap')
saveSelectedRosterBot(bot)
setBotsWorkspaceOwner(botWorkspaceOwnerKey(bot), bot)
const dismissedGroup = bot.remoteSource ? null : dismissGroupChatForLocalBotOpen()
+
if (!dismissedGroup) {
$groupChatWorkspace.set(null)
}
+
const restorePreviousGroup = () => {
if (!previousGroupRef || $groupChatWorkspace.get()) {
return
}
+
const restoreRef = dismissedGroup || previousGroupRef
const rooms = $groupChats.get()
+
const currentGroup = restoreRef.roomId
? Object.keys(rooms).find(
name => !rooms[name]?.tombstone && String(rooms[name]?.roomId || '') === restoreRef.roomId
@@ -139,16 +149,20 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
: liveGroupChatNames().includes(restoreRef.group)
? restoreRef.group
: null
+
if (!currentGroup) {
return
}
+
openGroupChat(currentGroup)
}
+
// The persisted half of clear-on-open. The transient dot is retired by
// core's own selection path once the chat lands; this retires the marker,
// which the selection listener alone would file against the wrong profile —
// a bot open deliberately leaves the gateway on the launch profile.
ackStoredSessionId(botCanonicalSessionId(bot), bot.name)
+
try {
// Activation selects this row's source only. Canonical identity is resolved
// after that by the owner profile's "Bot Chat" title registry.
@@ -159,16 +173,21 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
restorePreviousGroup()
notifyBotOpenFailure(error, bot, `Could not reach ${bot.connectionLabel || 'the gateway'}`)
}
+
return false
}
+
if (generation !== getBotOpenGeneration()) {
return false
}
+
try {
const opened = await openBotCanonicalChat(bot, () => generation === getBotOpenGeneration())
+
if (generation !== getBotOpenGeneration()) {
return false
}
+
if (opened) {
// This is not an identity preference: opening already completed through
// the name registry. Keep only enough ephemeral state to release the
@@ -182,6 +201,7 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
openedRegistryId: opened.registryId,
openedSessionId: opened.openedId
})
+
return true
}
} catch (error) {
@@ -190,6 +210,7 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
restorePreviousGroup()
notifyBotOpenFailure(error, bot, `Could not open ${displayName(bot, meta)}'s chat — try again`)
}
+
return false
}
@@ -198,13 +219,16 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
if (typeof host.newChat !== 'function') {
$openBotChat.set(null)
restorePreviousGroup()
+
return false
}
+
$openBotChat.set({
key,
openedRegistryId: ''
})
newBotChat(bot)
+
return true
}
@@ -213,11 +237,14 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {
* canonical open. */
function dismissGroupChatForLocalBotOpen(): null | { group: string; roomId: string } {
const group = $groupChatWorkspace.get()
+
if (!group) {
return null
}
+
const roomId = String($groupChats.get()[group]?.roomId || '')
closeGroupChatMainTab(group)
+
return {
group,
roomId
diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
index 61aa055c28d..a798be91403 100644
--- a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
@@ -99,14 +99,18 @@ export function selectedRosterBot(roster: RosterRow[], key: string): RosterRow |
* while other sources are live. Unknown (no sources yet) is NOT proof. */
function ghostRosterOwner(key: string, sources: GatewaySource[]): RosterRow | null {
const { connectionId, name } = parseRosterKey(key)
+
if (!name) {
return null
}
+
const list = Array.isArray(sources) ? sources : []
const source = sourceByConnection(list).get(connectionId)
+
if (source ? source.reachable === true : list.length > 0) {
return null
}
+
return {
name,
connectionId,
@@ -127,10 +131,13 @@ function ghostRosterOwner(key: string, sources: GatewaySource[]): RosterRow | nu
* (or reconciliation clears it when the bot was actually removed). */
function rosterWithSelectedOwner(roster: RosterRow[], sources: GatewaySource[], key: string): RosterRow[] {
const rows = Array.isArray(roster) ? roster : []
+
if (!key || selectedRosterBot(rows, key)) {
return rows
}
+
const ghost = ghostRosterOwner(key, sources)
+
return ghost ? [...rows, ghost] : rows
}
@@ -142,29 +149,38 @@ function reconcileRosterSelection(roster: RosterRow[], sources: GatewaySource[],
if (!$rosterHydrated.get() || !$selectedRosterHydrated.get()) {
return
}
+
const key = $selectedRosterKey.get()
+
if (key) {
if (selectedRosterBot(roster, key) || ghostRosterOwner(key, sources)) {
return
}
+
clearSelectedRosterKey(key)
}
+
const first = (Array.isArray(roster) ? roster : []).find(
bot => !isBotHidden(bot, metaByName) && botSourceStatus(annotateBotSource(bot, sources)).available
)
+
if (first) {
saveSelectedRosterBot(first)
}
}
+
/** True when a session owns the main workspace. Prefers the focused STORED
* session (tab focus moves without swapping the gateway socket); bare test
* harnesses with neither atom drive $botChatFocused directly. */
export function sessionOwnsWorkspace(): boolean {
const focused = host.state?.focusedStoredSessionId?.get?.()
+
if (focused !== undefined) {
return Boolean(focused)
}
+
const active = host.state?.activeSessionId?.get?.()
+
return active === undefined ? $botChatFocused.get() : Boolean(active)
}
@@ -186,9 +202,11 @@ export function botChatOwnsWorkspace(): boolean {
* session actually takes focus. */
export function releaseStaleOpenBotChat(focusedStoredId: null | string | undefined): void {
const open = $openBotChat.get()
+
if (!open) {
return
}
+
const focused = focusedStoredId === null || focusedStoredId === undefined ? '' : String(focusedStoredId)
// The focused stored id is the compression-lineage TIP; the claim carries
// both the durable registry id and the tip it actually opened. Either
@@ -196,10 +214,12 @@ export function releaseStaleOpenBotChat(focusedStoredId: null | string | undefin
// the very focus edge the open itself caused.
const owned = [open.openedSessionId, open.openedRegistryId].filter(Boolean)
const stale = owned.length ? !owned.includes(focused) : Boolean(focused)
+
if (stale) {
$openBotChat.set(null)
}
}
+
/** The two row shapes the roster sorts together — `kind` is the discriminant. */
interface RosterBotRow {
active: boolean
@@ -216,6 +236,7 @@ interface RosterGroupRow {
name: string
pinned: boolean
}
+
export function BotsPane() {
const { t } = useI18n()
const b = useBots()
@@ -259,6 +280,7 @@ export function BotsPane() {
}
}, [gatewayUp, refetch])
const allMeta = useValue($botMeta)
+
// Messaging-app order: most recent activity first, where "activity" is
// the newest of (bot created, last message in any of its sessions). A
// freshly created bot tops the list until another bot gets a message.
@@ -266,8 +288,10 @@ export function BotsPane() {
const activityOf = (bot: RosterRow): number => {
const created = botRosterMeta(bot, allMeta)?.created || bot.ui_meta?.['hermes-bots']?.created || 0
const lastMsg = (botActivitySession(bot)?.last_active || 0) * 1000
+
return Math.max(created, lastMsg)
}
+
// Pin is a source-qualified Desktop preference, not gateway profile state.
const isPinned = (bot: RosterRow): boolean => isBotPinned(bot, allMeta)
// Resilience (@wesleysimplicio, #13): a failed refresh must not erase a
@@ -277,16 +301,21 @@ export function BotsPane() {
const live = Array.isArray(data?.profiles) ? data.profiles : null
const source = live ?? (error ? $lastRoster.get() : [])
const sourceSnapshot = Array.isArray(data?.sources) ? data.sources : rememberedSources
+
const sourceWithSelectedOwner =
selectionHydrated && rosterHydrated ? rosterWithSelectedOwner(source, sourceSnapshot, selectedRosterKey) : source
+
const roster = sourceWithSelectedOwner.slice().sort((a, b) => {
const pa = isPinned(a) ? 1 : 0
const pb = isPinned(b) ? 1 : 0
+
if (pa !== pb) {
return pb - pa
}
+
return activityOf(b) - activityOf(a)
})
+
// React Query can briefly report neither loading nor data while the plugin
// and the persisted connection registry hydrate. Keep that transition in a
// neutral loading state instead of flashing the first-run "No bots" copy.
@@ -307,6 +336,7 @@ export function BotsPane() {
const hiddenBots = roster.filter(bot => isBotHidden(bot, allMeta))
const visibleRoster = roster.filter(bot => !isBotHidden(bot, allMeta))
const gatewayRoster = filterBotsByGateway(visibleRoster, gatewayFilter)
+
const filteredRoster = filterBots(gatewayRoster, allMeta, query).filter((bot: RosterRow) =>
rosterActivityMatches(
{
@@ -316,6 +346,7 @@ export function BotsPane() {
activityFilter
)
)
+
const filteredHiddenBots = filterBots(filterBotsByGateway(hiddenBots, gatewayFilter), allMeta, query).filter(
(bot: RosterRow) =>
rosterActivityMatches(
@@ -326,7 +357,9 @@ export function BotsPane() {
activityFilter
)
)
+
const groupNames = groupChatNames(allMeta, groupRooms)
+
const groupRows = groupNames
.map(name => ({
name,
@@ -346,6 +379,7 @@ export function BotsPane() {
) || row.members.some(member => activeRosterKeys.has(botRosterKey(member)))
}))
.filter(row => rowKindFilter !== 'bots' && rosterActivityMatches(row, activityFilter))
+
const botRows =
rowKindFilter === 'groups'
? []
@@ -356,37 +390,48 @@ export function BotsPane() {
activity: activityOf(bot),
active: activeRosterKeys.has(botRosterKey(bot))
}))
+
const sortRosterRows = <T extends { activity: number; pinned: boolean }>(rows: T[]): T[] =>
rows.slice().sort((a, b) => {
const pa = a.pinned ? 1 : 0
const pb = b.pinned ? 1 : 0
+
if (pa !== pb) {
return pb - pa
}
+
return b.activity - a.activity
})
+
const rosterRows = sortRosterRows([...botRows, ...groupRows])
const sortedGroupRows = sortRosterRows(groupRows)
const gatewaySections = rosterGatewaySections(botRows, gatewayOptions, gatewayFilter)
const showGatewaySections = gatewaySections.sectioned && botRows.length > 0
+
const activeFilterCount =
(rowKindFilter === 'all' ? 0 : 1) + (activityFilter === 'all' ? 0 : 1) + (gatewayFilter === 'all' ? 0 : 1)
+
const hasRosterConstraint = Boolean(query.trim()) || activeFilterCount > 0
const matchingHiddenBots = rowKindFilter === 'groups' ? [] : filteredHiddenBots
const showHiddenSection = hiddenBots.length > 0 && (!hasRosterConstraint || matchingHiddenBots.length > 0)
const showHiddenRows = hiddenExpanded || hasRosterConstraint
const rosterItemCount = roster.length + groupNames.length
+
const allBotsHidden =
!hasRosterConstraint && visibleRoster.length === 0 && groupNames.length === 0 && hiddenBots.length > 0
+
const showRosterSearch =
gatewayOptions.length > 1 || rosterItemCount >= BOT_ROSTER_SEARCH_THRESHOLD || Boolean(query.trim())
+
const showRosterFilters =
gatewayOptions.length > 1 ||
groupNames.length > 0 ||
rosterItemCount >= BOT_ROSTER_SEARCH_THRESHOLD ||
activeFilterCount > 0
+
const showRosterTools = showRosterSearch || showRosterFilters
const rosterSectionCollapsed = (id: string): boolean => !hasRosterConstraint && collapsedRosterSections.has(id)
+
const hiddenGatewaySections = rosterGatewaySections(
matchingHiddenBots.map((bot: RosterRow) => ({
kind: 'bot',
@@ -395,26 +440,32 @@ export function BotsPane() {
gatewayOptions,
gatewayFilter
)
+
const toggleRosterSection = (id: string): void => {
setCollapsedRosterSections(previous => {
const next = new Set(previous)
+
if (next.has(id)) {
next.delete(id)
} else {
next.add(id)
}
+
return next
})
}
+
useEffect(() => {
if (!hiddenExpanded || hasRosterConstraint) {
return
}
+
const frame = requestAnimationFrame(() =>
hiddenSectionRef.current?.scrollIntoView({
block: 'nearest'
})
)
+
return () => cancelAnimationFrame(frame)
}, [hiddenExpanded, hasRosterConstraint])
useEffect(() => {
@@ -427,9 +478,11 @@ export function BotsPane() {
// writes must settle after render: other subscribers of the same atoms
// would otherwise be updated while BotsPane was still rendering.
$lastRoster.set(roster.filter(row => !row?.ghost))
+
if (Array.isArray(data?.sources)) {
$lastSources.set(data.sources)
}
+
mergeServerMeta(activeSourceRoster, data?.fetchedAt || 0)
pullServerAvatars(activeSourceRoster)
trackInboundActivity(roster)
@@ -448,50 +501,60 @@ export function BotsPane() {
if (!data && !error) {
return
}
+
$rosterHydrated.set(true)
+
if (selectionHydrated) {
reconcileRosterSelection(roster, sourceSnapshot, allMeta)
const selected = selectedRosterBot(roster, $selectedRosterKey.get())
+
if ($botsPaneVisible.get() && !$groupChatWorkspace.get() && selected) {
setBotsWorkspaceOwner(botWorkspaceOwnerKey(selected), selected)
}
}
}, [data, error, selectionHydrated, roster, sourceSnapshot, allMeta])
+
const staleNotice =
error && !live && roster.length
? 'Roster refresh failed — showing the last good list.' +
(gatewayUp ? '' : ' Waiting for the gateway to reconnect…')
: null
+
const groupChatMembers = groupChatName ? groupChatMemberBots(groupChatName, roster, allMeta) : []
+
if (shouldRenderGroupChatInPane(groupChatName) && groupChatMembers.length) {
return <GroupChatWorkspace group={groupChatName} members={groupChatMembers} />
}
+
const renderBotRow = (bot: RosterRow, keyPrefix = '') => (
<BotRow
- key={`${keyPrefix}${botRosterKey(bot)}`}
bot={bot}
+ key={`${keyPrefix}${botRosterKey(bot)}`}
onDelete={setDeleting}
onEdit={setEditing}
onGroup={setGrouping}
showHandle={botNeedsHandleLabel(bot, roster, allMeta)}
/>
)
+
const renderGroupRow = (row: { members: GroupMember[]; name: string }) => (
<GroupRow
- key={`group:${row.name}`}
active={groupChatName === row.name}
group={row.name}
+ key={`group:${row.name}`}
members={row.members}
needsYou={Boolean(groupNeedsYou[row.name])}
- onOpen={openGroupChat}
onDisband={setDeletingGroup}
+ onOpen={openGroupChat}
/>
)
+
const renderGatewaySection = (section: ResolvedRosterGatewaySection) => {
const sectionId = `gateway:${section.id}`
const collapsed = rosterSectionCollapsed(sectionId)
+
return (
- <div key={sectionId} className="min-w-0">
+ <div className="min-w-0" key={sectionId}>
<GatewaySectionHeading
collapsed={collapsed}
count={section.rows.length}
@@ -504,11 +567,13 @@ export function BotsPane() {
</div>
)
}
+
const renderGroupChatSection = () => {
const sectionId = 'group-chats'
const collapsed = rosterSectionCollapsed(sectionId)
+
return (
- <div key={sectionId} className="min-w-0">
+ <div className="min-w-0" key={sectionId}>
<RosterSectionHeader
collapsed={collapsed}
count={sortedGroupRows.length}
@@ -521,8 +586,9 @@ export function BotsPane() {
</div>
)
}
+
const renderHiddenGatewaySection = (section: ResolvedRosterGatewaySection) => (
- <div key={`hidden-gateway:${section.id}`} className="min-w-0">
+ <div className="min-w-0" key={`hidden-gateway:${section.id}`}>
<div className="flex min-w-0 items-center gap-1.5 px-2 py-1 text-[0.625rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)">
<GatewayKindGlyph kind={section.option?.kind} />
<span className="min-w-0 flex-1 truncate">
@@ -533,6 +599,7 @@ export function BotsPane() {
{section.rows.map(row => renderBotRow(row.bot, `hidden:${section.id}:`))}
</div>
)
+
return (
<div className="flex h-full flex-col">
<div className="flex items-center justify-between gap-2 px-2.5 pt-2.5 pb-1.5">
@@ -567,11 +634,11 @@ export function BotsPane() {
</Tip>
<DropdownMenuContent align="end">
<DropdownMenuItem onSelect={() => setCreateOpen(true)}>
- <Codicon name="hubot" className="mr-1.5" />
+ <Codicon className="mr-1.5" name="hubot" />
{b.bot.newTitle}
</DropdownMenuItem>
<DropdownMenuItem disabled={activeSourceRoster.length < 2} onSelect={() => setGroupCreateOpen(true)}>
- <Codicon name="organization" className="mr-1.5" />
+ <Codicon className="mr-1.5" name="organization" />
{b.group.newTitle}
</DropdownMenuItem>
</DropdownMenuContent>
@@ -582,16 +649,16 @@ export function BotsPane() {
<div className="flex min-w-0 items-center gap-1 px-2.5 pb-1.5">
{showRosterSearch ? (
<SearchField
- key={'roster-search'}
aria-label={b.roster.search}
containerClassName={cn('min-w-0 flex-1', query ? 'opacity-100!' : 'opacity-50 focus-within:opacity-100')}
inputClassName="w-full text-[0.75rem] placeholder:text-(--ui-text-tertiary)"
+ key={'roster-search'}
+ onChange={setQuery}
placeholder={b.roster.searchPlaceholder}
value={query}
- onChange={setQuery}
/>
) : (
- <span key={'roster-search-spacer'} className="min-w-0 flex-1" />
+ <span className="min-w-0 flex-1" key={'roster-search-spacer'} />
)}
{showRosterFilters ? (
<DropdownMenu key={'roster-filters'}>
@@ -640,7 +707,7 @@ export function BotsPane() {
{gatewayOptions.length > 1 ? <DropdownMenuSeparator /> : null}
{gatewayOptions.length > 1 ? (
<DropdownMenuItem onSelect={() => setGatewayFilter('all')}>
- <Codicon name="globe" className="mr-1.5" />
+ <Codicon className="mr-1.5" name="globe" />
<span className="min-w-0 flex-1">All gateways</span>
{gatewayFilter === 'all' ? <Codicon name="check" /> : null}
</DropdownMenuItem>
@@ -651,14 +718,15 @@ export function BotsPane() {
sourceError: option.error,
sourceReachable: option.reachable
})
+
return (
<DropdownMenuItem
key={option.connectionId}
onSelect={() => setGatewayFilter(option.connectionId)}
>
<GatewayKindGlyph
- kind={option.kind}
className={cn('mr-1.5', !status.available && 'text-amber-600 dark:text-amber-300')}
+ kind={option.kind}
/>
<span className="min-w-0 flex-1 truncate">{option.label || option.connectionId}</span>
<span className="text-[0.625rem] tabular-nums text-(--ui-text-quaternary)">
@@ -693,7 +761,7 @@ export function BotsPane() {
) : null}
{(isLoading || initialRosterLoading) && !roster.length ? (
<div className="flex flex-1 items-center justify-center">
- <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ <GlyphSpinner className="text-(--ui-text-tertiary)" spinner="breathe" />
</div>
) : error && !roster.length ? (
<div className="grid gap-2 px-3 py-4 text-xs text-(--ui-text-tertiary)">
@@ -702,7 +770,7 @@ export function BotsPane() {
? b.roster.rosterUnavailable(error instanceof Error ? error.message : 'gateway error')
: b.roster.waitingForGateway}
</div>
- <Button variant="secondary" size="sm" className="justify-self-start" onClick={() => void refetch()}>
+ <Button className="justify-self-start" onClick={() => void refetch()} size="sm" variant="secondary">
{b.roster.retryNow}
</Button>
</div>
@@ -711,15 +779,15 @@ export function BotsPane() {
) : allBotsHidden && !hiddenExpanded ? (
<div className="grid content-start gap-2 px-3 py-4 text-xs text-(--ui-text-tertiary)">
<div className="flex items-center gap-1.5 font-medium text-(--ui-text-secondary)">
- <Codicon name="eye-closed" className="text-(--ui-text-quaternary)" />
+ <Codicon className="text-(--ui-text-quaternary)" name="eye-closed" />
{b.roster.allHidden}
</div>
<p className="leading-relaxed">{b.roster.allHiddenDesc}</p>
<Button
- variant="secondary"
- size="sm"
className="justify-self-start"
onClick={() => $showHiddenBots.set(true)}
+ size="sm"
+ variant="secondary"
>
{b.roster.showHidden}
</Button>
@@ -750,9 +818,9 @@ export function BotsPane() {
: rosterRows.map(row => (row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot)))}
{showHiddenSection ? (
<div
+ className="mt-1 border-t border-(--ui-stroke-tertiary) pt-1"
key={'hidden-section'}
ref={hiddenSectionRef}
- className="mt-1 border-t border-(--ui-stroke-tertiary) pt-1"
>
{hasRosterConstraint ? (
<div className="flex w-full items-center gap-1 px-2 py-1.5 text-[0.6875rem] font-medium text-(--ui-text-tertiary)">
@@ -788,32 +856,32 @@ export function BotsPane() {
</div>
)}
<CreateAgentDialog
- open={createOpen}
onClose={() => {
setCreateOpen(false)
void refetch()
}}
+ open={createOpen}
roster={activeSourceRoster}
/>
<CreateGroupChatDialog
+ onClose={() => setGroupCreateOpen(false)}
+ onCreated={groupName => openGroupChat(groupName)}
open={groupCreateOpen} // Full multi-source roster: group chats can seat bots from other
// registered connections — their turns route to their own machines.
roster={roster}
- onClose={() => setGroupCreateOpen(false)}
- onCreated={groupName => openGroupChat(groupName)}
/>
<EditProfileDialog
bot={editing}
- open={Boolean(editing)}
onClose={() => {
setEditing(null)
void refetch()
}}
+ open={Boolean(editing)}
/>
{grouping ? <GroupDialog bot={grouping} onClose={() => setGrouping(null)} /> : null}
<ConfirmDialog
- open={Boolean(deleting)}
- title={b.bot.deleteTitle}
+ busyLabel="Deleting…"
+ confirmLabel={t.common.delete}
description={
deleting ? (
<span>
@@ -825,14 +893,13 @@ export function BotsPane() {
) : null
}
destructive
- confirmLabel={t.common.delete}
- busyLabel="Deleting…"
doneLabel="Deleted"
onClose={() => setDeleting(null)}
onConfirm={async () => {
if (!deleting) {
return
}
+
const name = deleting.name
await deleteBot(deleting)
await refetch()
@@ -841,28 +908,30 @@ export function BotsPane() {
message: `Deleted profile ${name}`
})
}}
+ open={Boolean(deleting)}
+ title={b.bot.deleteTitle}
/>
<ConfirmDialog
- open={Boolean(deletingGroup)}
- title={b.group.deleteTitle}
+ busyLabel="Deleting…"
+ confirmLabel={b.group.deleteAction}
description={
deletingGroup
? `This removes “${deletingGroup.name}” from its bots and clears the shared room log. The bots and their individual chats are kept.`
: null
}
destructive
- confirmLabel={b.group.deleteAction}
- busyLabel="Deleting…"
doneLabel="Deleted"
onClose={() => setDeletingGroup(null)}
onConfirm={async () => {
- if (!deletingGroup) return
+ if (!deletingGroup) {return}
await disbandGroupChat(deletingGroup.name, deletingGroup.members)
host.notify({
kind: 'success',
message: `Deleted group “${deletingGroup.name}”`
})
}}
+ open={Boolean(deletingGroup)}
+ title={b.group.deleteTitle}
/>
</div>
)
diff --git a/apps/desktop/src/plugins/hermes-bots/roster-sections.tsx b/apps/desktop/src/plugins/hermes-bots/roster-sections.tsx
index cfc4654896d..76d570559dd 100644
--- a/apps/desktop/src/plugins/hermes-bots/roster-sections.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/roster-sections.tsx
@@ -19,11 +19,14 @@ export function filterBotsByGateway(roster: RosterRow[], connectionId: string) {
if (!connectionId || connectionId === 'all') {
return roster
}
+
return (roster || []).filter(bot => String(bot?.connectionId || '') === connectionId)
}
+
export function botNeedsHandleLabel(bot: RosterRow, roster: RosterRow[], metaByName: Record<string, BotMeta>) {
const identity = displayName(bot, botRosterMeta(bot, metaByName)).trim().toLowerCase()
const connectionId = String(bot?.connectionId || '')
+
return (roster || []).some(
candidate =>
botRosterKey(candidate) !== botRosterKey(bot) &&
@@ -32,6 +35,7 @@ export function botNeedsHandleLabel(bot: RosterRow, roster: RosterRow[], metaByN
botHandle(candidate.name, candidate) !== botHandle(bot.name, bot)
)
}
+
export function groupMatchesRosterFilters(
name: string,
members: RosterRow[],
@@ -40,13 +44,16 @@ export function groupMatchesRosterFilters(
connectionId: string
) {
const inGateway = filterBotsByGateway(members, connectionId)
+
if (connectionId && connectionId !== 'all' && inGateway.length === 0) {
return false
}
+
const needle = String(query || '')
.trim()
.toLowerCase()
.replace(/^@/, '')
+
return (
!needle ||
String(name || '')
@@ -78,10 +85,13 @@ interface RosterGatewaySection<TRow extends RosterGatewayRow = RosterGatewayRow>
/** Sections built from rows that always carry their resolved roster row. */
export type ResolvedRosterGatewaySection = RosterGatewaySection<RosterGatewayRow & { bot: RosterRow }>
+
export function rosterGatewayOptions(sources: GatewaySource[], roster: RosterRow[]) {
const byId = new Map<string, RosterGatewayOption & { count: number }>()
+
for (const source of Array.isArray(sources) ? sources : []) {
const id = String(source?.connectionId || '').trim()
+
if (id) {
byId.set(id, {
...source,
@@ -90,11 +100,14 @@ export function rosterGatewayOptions(sources: GatewaySource[], roster: RosterRow
})
}
}
+
for (const bot of roster || []) {
const id = String(bot?.connectionId || '').trim()
+
if (!id) {
continue
}
+
const source = byId.get(id) || {
connectionId: id,
kind: bot.connectionKind,
@@ -103,15 +116,18 @@ export function rosterGatewayOptions(sources: GatewaySource[], roster: RosterRow
error: bot.sourceError,
count: 0
}
+
source.count += 1
byId.set(id, source)
}
+
return [...byId.values()].sort((a, b) =>
String(a.label || a.connectionId).localeCompare(String(b.label || b.connectionId), undefined, {
sensitivity: 'base'
})
)
}
+
export function rosterGatewaySections<TRow extends RosterGatewayRow>(
botRows: TRow[],
gatewayOptions: RosterGatewayOption[],
@@ -119,6 +135,7 @@ export function rosterGatewaySections<TRow extends RosterGatewayRow>(
): { sectioned: boolean; sections: RosterGatewaySection<TRow>[] } {
const rows = Array.isArray(botRows) ? botRows : []
const options = Array.isArray(gatewayOptions) ? gatewayOptions : []
+
if (gatewayFilter !== 'all' || options.length <= 1) {
return {
sectioned: false,
@@ -131,7 +148,9 @@ export function rosterGatewaySections<TRow extends RosterGatewayRow>(
]
}
}
+
const byId = new Map<string, TRow[]>()
+
for (const row of rows) {
const bot = row?.bot || row
const id = String(bot?.connectionId || 'legacy').trim() || 'legacy'
@@ -139,14 +158,18 @@ export function rosterGatewaySections<TRow extends RosterGatewayRow>(
bucket.push(row)
byId.set(id, bucket)
}
+
const known = new Set<string>()
const sections: RosterGatewaySection<TRow>[] = []
+
for (const option of options) {
const id = String(option?.connectionId || '').trim()
const sectionRows = byId.get(id)
+
if (!id || !sectionRows?.length) {
continue
}
+
known.add(id)
sections.push({
id,
@@ -154,10 +177,12 @@ export function rosterGatewaySections<TRow extends RosterGatewayRow>(
rows: sectionRows
})
}
+
for (const [id, sectionRows] of byId) {
if (known.has(id)) {
continue
}
+
const bot = sectionRows[0]?.bot || sectionRows[0]
sections.push({
id,
@@ -171,22 +196,32 @@ export function rosterGatewaySections<TRow extends RosterGatewayRow>(
rows: sectionRows
})
}
+
return {
sectioned: true,
sections
}
}
+
function gatewayKindIcon(kind?: string) {
const icons: Partial<typeof sdk.icons> = (typeof sdk === 'undefined' ? null : sdk.icons) || {}
- if (kind === 'local') return icons.Monitor
- if (kind === 'cloud') return icons.Cloud
- if (kind === 'ssh') return icons.Terminal
+
+ if (kind === 'local') {return icons.Monitor}
+
+ if (kind === 'cloud') {return icons.Cloud}
+
+ if (kind === 'ssh') {return icons.Terminal}
+
return icons.Network
}
+
function gatewayKindCodicon(kind?: string) {
- if (kind === 'local') return 'device-desktop'
- if (kind === 'cloud') return 'cloud'
- if (kind === 'ssh') return 'terminal'
+ if (kind === 'local') {return 'device-desktop'}
+
+ if (kind === 'cloud') {return 'cloud'}
+
+ if (kind === 'ssh') {return 'terminal'}
+
return 'remote-explorer'
}
@@ -199,6 +234,7 @@ interface GatewayKindGlyphProps {
* usable until they expose the shared icon namespace. */
export function GatewayKindGlyph({ className, kind }: GatewayKindGlyphProps) {
const Icon = gatewayKindIcon(kind)
+
return (
<span
aria-hidden
@@ -206,7 +242,7 @@ export function GatewayKindGlyph({ className, kind }: GatewayKindGlyphProps) {
data-connection-kind={kind || 'remote'}
data-slot="connection-glyph"
>
- {Icon ? <Icon className="size-3" /> : <Codicon name={gatewayKindCodicon(kind)} className="text-[0.75rem]" />}
+ {Icon ? <Icon className="size-3" /> : <Codicon className="text-[0.75rem]" name={gatewayKindCodicon(kind)} />}
</span>
)
}
@@ -223,6 +259,7 @@ interface RosterSectionHeaderProps {
status?: { available: boolean; label: string }
tip?: string
}
+
export function RosterSectionHeader({
collapsed,
count,
@@ -246,34 +283,39 @@ export function RosterSectionHeader({
// TODO(bot-mode-types): neither `gatewayKind` nor `icon` is required, so a header
// given neither renders `codicon-undefined`. Both current callers pass exactly one.
// @ts-expect-error `icon` is optional here; Codicon's `name` is required.
- <Codicon name={icon} className="shrink-0" />
+ <Codicon className="shrink-0" name={icon} />
)}
<span className="flex min-w-0 items-center gap-1">
<span className="min-w-0 truncate">{label}</span>
{status && !status.available ? <span className="sr-only">{status.label}</span> : null}
</span>
- <span className="min-w-0 flex-1" aria-hidden />
+ <span aria-hidden className="min-w-0 flex-1" />
<span className="shrink-0 font-normal tabular-nums text-(--ui-text-quaternary)">{count}</span>
{status && !status.available ? (
- <Codicon name="debug-disconnect" className="shrink-0 text-amber-600 dark:text-amber-300" aria-hidden />
+ <Codicon aria-hidden className="shrink-0 text-amber-600 dark:text-amber-300" name="debug-disconnect" />
) : null}
</RowButton>
)
+
return tip ? <Tip label={tip}>{button}</Tip> : button
}
+
interface GatewaySectionHeadingProps {
collapsed: boolean
count: number
onToggle: () => void
option?: RosterGatewayOption | null
}
+
export function GatewaySectionHeading({ collapsed, count, onToggle, option }: GatewaySectionHeadingProps) {
const status = botSourceStatus({
sourceError: option?.error,
sourceReachable: option?.reachable
})
+
const label = option?.label || option?.connectionId || 'Current gateway'
const kind = option?.kind || 'remote'
+
return (
<RosterSectionHeader
collapsed={collapsed}
diff --git a/apps/desktop/src/plugins/hermes-bots/routing.ts b/apps/desktop/src/plugins/hermes-bots/routing.ts
index a3eb6b6fc4e..375915fa590 100644
--- a/apps/desktop/src/plugins/hermes-bots/routing.ts
+++ b/apps/desktop/src/plugins/hermes-bots/routing.ts
@@ -41,15 +41,18 @@ export function resolveBotConnectionRoute(bot: Partial<RosterRow> | null | undef
route: null
}
}
+
const candidate = bot.route || {
connectionId: bot.connectionId,
mode: bot.connectionKind === 'local' ? 'local' : 'remote',
profile: bot.name,
targetProfile: bot.targetProfile || bot.name
}
+
const connectionId = String(candidate?.connectionId || '').trim()
const profile = String(candidate?.profile || bot?.name || '').trim() || 'default'
const targetProfile = String(candidate?.targetProfile || profile).trim() || profile
+
if (!connectionId) {
return {
status: 'owner_removed',
@@ -57,6 +60,7 @@ export function resolveBotConnectionRoute(bot: Partial<RosterRow> | null | undef
profile
}
}
+
return {
status: 'resolved',
route: Object.freeze({
@@ -76,17 +80,22 @@ export function resolveBotConnectionRoute(bot: Partial<RosterRow> | null | undef
* resolveBotConnectionRoute() directly instead of catching this throw. */
export function botConnectionRoute(bot: Partial<RosterRow> | null | undefined): null | ProfileRoute {
const resolved = resolveBotConnectionRoute(bot)
+
if (resolved.status === 'owner_removed') {
throw new Error(`Bot ${resolved.profile} has no connection owner`)
}
+
return resolved.route
}
+
export function botWorkspaceOwnerKey(bot: RosterRow) {
// Render-reachable (sidebar sync, context menus): an orphaned row must
// yield a stable degraded key, never the dispatch throw.
const route = resolveBotConnectionRoute(bot).route
+
return `bot:${route ? botRouteKey(route) : String(bot?.name || 'default')}`
}
+
export function setBotsWorkspaceOwner(
ownerKey: string,
bot: null | RosterRow = null,
@@ -95,6 +104,7 @@ export function setBotsWorkspaceOwner(
// Render-reachable (sidebar listener fires on visibility flips). An
// orphaned row degrades to the blocked target instead of throwing.
const route = bot ? resolveBotConnectionRoute(bot).route : null
+
const target: { kind: 'blocked'; message: string } | { kind: 'route'; route: ProfileRoute } = route
? {
kind: 'route',
@@ -104,16 +114,21 @@ export function setBotsWorkspaceOwner(
kind: 'blocked',
message: blockedMessage
}
+
host.setWorkspaceScope?.('bots', ownerKey, target)
}
+
export function backendTargetProfile(route: null | ProfileRoute | undefined, fallbackProfile = 'default') {
if (!route) {
return fallbackProfile
}
+
return route.targetProfile || route.profile
}
+
function rewriteCliProfileOperands(argv: string[], logical: string, target: string) {
const next = [...argv]
+
for (let index = 0; index < next.length; index += 1) {
if (next[index] === '--profile' && next[index + 1] === logical) {
next[index + 1] = target
@@ -122,47 +137,58 @@ function rewriteCliProfileOperands(argv: string[], logical: string, target: stri
next[index] = `--profile=${target}`
}
}
+
const profileCommand = next.indexOf('profile')
const operand = profileCommand >= 0 ? profileCommand + 2 : -1
+
if (operand < next.length && next[operand] === logical) {
next[operand] = target
}
+
return next
}
+
function scopedBotParams(route: ProfileRoute, method: string, params: Record<string, unknown>) {
const logical = route.profile
const target = backendTargetProfile(route, logical)
let next = params
+
if (Object.prototype.hasOwnProperty.call(params, 'profile')) {
next = {
...next,
profile: target
}
}
+
if (method.startsWith('profiles.') && method !== 'profiles.create' && params.name === logical) {
next = {
...next,
name: target
}
}
+
if (params.clone_from === logical) {
next = {
...next,
clone_from: target
}
}
+
if (method === 'cli.exec' && Array.isArray(params.argv)) {
next = {
...next,
argv: rewriteCliProfileOperands(params.argv, logical, target)
}
}
+
return next
}
+
export function botBackendProfileScope(route: null | ProfileRoute | undefined, fallbackProfile = 'default') {
if (!route) {
return fallbackProfile
}
+
return {
connectionId: route.connectionId,
profile: backendTargetProfile(route, fallbackProfile)
@@ -177,10 +203,12 @@ export async function requestForBot<T = unknown>(
params: Record<string, unknown> = {}
): Promise<T> {
const route = botConnectionRoute(bot)
+
if (route) {
if (typeof host.requestProfile !== 'function') {
throw new Error(`Cannot route ${method} for ${route.connectionId}::${route.profile}`)
}
+
try {
return await host.requestProfile(route, method, scopedBotParams(route, method, params))
} catch (error) {
@@ -190,6 +218,7 @@ export async function requestForBot<T = unknown>(
throw asRpcError(error, `Gateway request ${method} failed`)
}
}
+
try {
return await host.request(method, params)
} catch (error) {
@@ -224,15 +253,19 @@ function asRpcError(value: unknown, fallback: string): unknown {
const hasStringName = typeof name === 'string'
const hasStringMessage = typeof message === 'string'
const hasStack = isObject && typeof (value as RpcErrorLike).stack === 'string'
+
if (isObject && hasStringName && (hasStack || hasStringMessage)) {
return value
}
+
if (isObject) {
const text = hasStringMessage && String(message).trim() ? String(message) : fallback
const error = new Error(text)
error.cause = value
+
return error
}
+
return new Error(value == null || value === '' ? fallback : String(value))
}
@@ -266,13 +299,16 @@ let aliasRouteIndex = new Map<string, AliasIdentity | null>()
* genuine aliases (route.profile !== route.targetProfile) participate. */
export function indexAliasRoutes(routes: ProfileRoute[]) {
const next = new Map<string, AliasIdentity | null>()
+
for (const route of Array.isArray(routes) ? routes : []) {
const connectionId = String(route?.connectionId || '').trim()
const profile = String(route?.profile || '').trim()
const target = String(route?.targetProfile || '').trim()
+
if (!connectionId || !profile || !target || profile === target) {
continue
}
+
const key = `${connectionId}::${target}`
// Two aliases pointing at the same backend row are ambiguous — neither
@@ -289,6 +325,7 @@ export function indexAliasRoutes(routes: ProfileRoute[]) {
}
)
}
+
aliasRouteIndex = next
}
@@ -299,6 +336,7 @@ export function aliasIdentityFor(bot: Partial<RosterRow> | null | undefined): Al
if (!aliasRouteIndex.size) {
return null
}
+
const connectionId = String(
bot?.connectionId ||
bot?.route?.connectionId ||
@@ -306,11 +344,14 @@ export function aliasIdentityFor(bot: Partial<RosterRow> | null | undefined): Al
// the ACTIVE gateway — Cloud-only mode must resolve the alias too.
(!bot?.remoteSource && !bot?.sourceScoped ? host.state.connectionId?.get?.() || '' : '')
).trim()
+
if (!connectionId) {
return null
}
+
const target = String(bot?.targetProfile || bot?.route?.targetProfile || bot?.name || '').trim() || 'default'
const entry = aliasRouteIndex.get(`${connectionId}::${target}`) || null
+
return entry && entry.name !== String(bot?.name || '').trim() ? entry : null
}
@@ -329,10 +370,13 @@ export function botRosterMeta(bot: RosterRow, metaByName: Record<string, BotMeta
const resolved = resolveBotConnectionRoute(bot)
const route = resolved.status === 'resolved' ? resolved.route : null
const direct = route ? metaByName?.[botRouteKey(route)] : null
+
if (direct) {
return direct
}
+
const alias = aliasIdentityFor(bot)
+
if (alias) {
for (const key of alias.metaKeys) {
if (metaByName?.[key]) {
@@ -340,13 +384,18 @@ export function botRosterMeta(bot: RosterRow, metaByName: Record<string, BotMeta
}
}
}
+
return direct
}
+
const own = metaByName?.[bot?.name]
+
if (own) {
return own
}
+
const alias = aliasIdentityFor(bot)
+
if (alias) {
for (const key of alias.metaKeys) {
if (metaByName?.[key]) {
@@ -354,5 +403,6 @@ export function botRosterMeta(bot: RosterRow, metaByName: Record<string, BotMeta
}
}
}
+
return own
}
diff --git a/apps/desktop/src/plugins/hermes-bots/row-helpers.ts b/apps/desktop/src/plugins/hermes-bots/row-helpers.ts
index 0218e10fc84..b85dd59dfc2 100644
--- a/apps/desktop/src/plugins/hermes-bots/row-helpers.ts
+++ b/apps/desktop/src/plugins/hermes-bots/row-helpers.ts
@@ -26,21 +26,26 @@ export const A2A_PREFIX_RE = /^Message from (?:agent '[^']+'|🤖[^:]+):\s*/i
* bot's row should show WHO sent it, not present it as the human's chat. */
export function previewKind(preview: null | string | undefined): { fromBot: null | string } {
const text = (preview || '').trim()
+
if (!text) {
return {
fromBot: null
}
}
+
const match = text.match(A2A_RE)
+
if (match) {
// The captured name is whatever the delivery prefix carried — a raw
// profile name. Map it the way every other surface does so the primary
// profile reads @hermes, never @default (#89484).
const sender = (match[1] || match[2] || '').trim().toLowerCase()
+
return {
fromBot: sender ? botHandle(sender) : null
}
}
+
return {
fromBot: null
}
@@ -48,6 +53,7 @@ export function previewKind(preview: null | string | undefined): { fromBot: null
/** Session titles the gateway auto-assigns that carry no information. */
const GENERIC_TITLES = new Set(['', 'bot chat', 'new chat', 'new conversation', 'conversation', 'chat', 'untitled'])
+
function isGenericTitle(title: null | string | undefined): boolean {
return GENERIC_TITLES.has((title || '').trim().toLowerCase())
}
@@ -58,21 +64,27 @@ function isGenericTitle(title: null | string | undefined): boolean {
* conversation is actually about. */
export function generatedSessionTitle(session: CanonicalSession | null | undefined, preview: null | string | undefined) {
const raw = (session?.title || '').trim()
+
if (raw && !isGenericTitle(raw)) {
return raw
}
+
const cleaned = (preview || '').trim().replace(A2A_PREFIX_RE, '').trim()
+
if (!cleaned) {
return raw || 'Conversation'
}
+
const words = cleaned
.split(/\s+/)
.slice(0, 5)
.join(' ')
.replace(/[,;:.]+$/, '')
+
if (!words) {
return raw || 'Conversation'
}
+
return words.length > 34 ? `${words.slice(0, 33)}…` : words
}
@@ -105,6 +117,7 @@ const WORKER_ACTIVE_WINDOW_S = 150
* (hermes-agent#90268). Older gateways omit worker_session — always false. */
export function workerActiveAt(bot: null | RosterRow | undefined, now = Date.now()): boolean {
const ts = bot?.worker_session?.last_active || 0
+
return Boolean(ts && now / 1000 - ts < WORKER_ACTIVE_WINDOW_S)
}
@@ -123,15 +136,18 @@ export function activeBots(
const busyTurn = !bot.remoteSource && bot.name === activeProfile && gatewayState === 'busy'
const last = botActivitySession(bot)?.last_active || 0
const inWindow = Boolean(last && now / 1000 - last < ACTIVE_WINDOW_S)
+
return busyTurn || inWindow || workerActiveAt(bot, now)
})
}
+
/** What the roster list wraps around a bot or group before filtering:
* `activity` is a millisecond stamp, `active` the live pulse. */
interface RosterActivityRow {
active?: boolean
activity?: number
}
+
export function rosterActivityMatches(
row: null | RosterActivityRow | undefined,
filter: null | RosterActivityFilter | undefined,
@@ -140,13 +156,17 @@ export function rosterActivityMatches(
if (!filter || filter === 'all') {
return true
}
+
if (filter === 'active') {
return Boolean(row?.active)
}
+
const activity = Number(row?.activity || 0)
const recent = Boolean(activity && now - activity <= RECENT_ACTIVITY_WINDOW_S * 1000)
+
return filter === 'recent' ? recent : !recent
}
+
export function botRowOwnsWorkspace(
bot: RosterRow,
activeGroup: null | string,
@@ -157,8 +177,10 @@ export function botRowOwnsWorkspace(
if (activeGroup) {
return false
}
+
if (!botChatFocused) {
return selectedRosterKey === botRosterKey(bot)
}
+
return isActiveRosterBot(bot, focusedOwner)
}
diff --git a/apps/desktop/src/plugins/hermes-bots/session-sweep.ts b/apps/desktop/src/plugins/hermes-bots/session-sweep.ts
index db6cb323cfd..2a5cc0e1c24 100644
--- a/apps/desktop/src/plugins/hermes-bots/session-sweep.ts
+++ b/apps/desktop/src/plugins/hermes-bots/session-sweep.ts
@@ -36,57 +36,72 @@ export function startHideSweepScheduler(ctx: HideSweepContext) {
let inflight: Promise<unknown> | null = null
let pending = false
let disposed = false
+
const run = () => {
timer = null
+
if (disposed) {
return
}
+
if (inflight) {
pending = true
+
return
}
+
inflight = Promise.resolve()
.then(() => hideOwnedBotSessions())
.catch(() => undefined)
.finally(() => {
inflight = null
+
if (pending && !disposed) {
pending = false
schedule()
}
})
}
+
const schedule = () => {
if (disposed) {
return
}
+
try {
if (timer !== null) {
clearTimeout(timer)
}
+
timer = setTimeout(run, 0)
} catch {
run()
}
}
+
const stopGatewayListener = host.state.gateway.listen(state => {
if (state === 'open') {
schedule()
}
})
+
const teardown = () => {
disposed = true
stopGatewayListener()
+
if (timer !== null) {
clearTimeout(timer)
timer = null
}
}
+
if (typeof ctx.onDispose === 'function') {
ctx.onDispose(teardown)
}
+
schedule()
}
+
/** One (owner, session id) pair the sweep will hide, plus the key it dedupes
* on when the same member session is seated in several rooms. */
interface RoomSessionEntry {
@@ -94,6 +109,7 @@ interface RoomSessionEntry {
id: string
owner: RosterRow
}
+
function hideOwnedBotSessions() {
// `.filter(Boolean)` doesn't narrow away the nulls the map returns, so the
// element type is restated here rather than at every read below.
@@ -103,8 +119,10 @@ function hideOwnedBotSessions() {
if (!id || id === true) {
return null
}
+
const persisted = room?.sessionOwners?.[key]
const derived = (room?.members || []).find((member: GroupMember) => groupMemberKey(member) === key)
+
// Bare keys are legacy local rooms. A source-qualified key without its
// immutable owner is unsafe: never let it fall through ambient routing.
const owner =
@@ -115,14 +133,17 @@ function hideOwnedBotSessions() {
name: key
}
: null)
+
if (key.includes('::')) {
const route = owner?.route
const sourceMarked = owner?.sourceScoped || owner?.remoteSource
const routeKey = route?.connectionId && route?.profile ? `${route.connectionId}::${route.profile}` : ''
+
if (!sourceMarked || !route?.targetProfile || routeKey !== key) {
return null
}
}
+
return owner
? {
owner,
@@ -138,6 +159,7 @@ function hideOwnedBotSessions() {
// share ids) — hide each (owner, id) pair exactly once.
const rooms = [...new Map(roomEntries.map(entry => [entry.dedupe, entry])).values()]
const known = Promise.all(rooms.map(({ owner, id }) => hidePersistedBotSession(owner, id).catch(() => undefined)))
+
return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])
}
@@ -148,9 +170,11 @@ function hidePersistedBotSession(bot: RosterRow, sessionId: string, profileOverr
if (typeof host.setPersistedSessionHidden !== 'function') {
return Promise.resolve()
}
+
const route = botConnectionRoute(bot)
const fallback = String(bot?.name || '').trim() || 'default'
const profile = profileOverride || backendTargetProfile(route, fallback)
+
return Promise.resolve(
host.setPersistedSessionHidden(route, {
sessionId,
@@ -169,8 +193,10 @@ function hidePersistedBotSession(bot: RosterRow, sessionId: string, profileOverr
// user gave it and is never touched.
const BOT_MODE_SWEEP_TITLES = new Set(['Bot Chat', 'Agent Inbox'])
const BOT_MODE_SWEEP_MIN_AGE_SECONDS = 5 * 60
+
function isBotModeSweepTitle(title: null | string | undefined) {
const t = String(title || '').trim()
+
return BOT_MODE_SWEEP_TITLES.has(t) || t.startsWith('Group: ')
}
@@ -182,8 +208,10 @@ interface SweepSessionRow {
started_at?: number
title?: null | string
}
+
function isBotModeSweepCandidate(row: SweepSessionRow | null | undefined, nowSeconds = Date.now() / 1000) {
const startedAt = Number(row?.started_at)
+
return (
row &&
row.id &&
@@ -220,8 +248,10 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {
if (typeof host.listPersistedSessions !== 'function' || typeof host.setPersistedSessionHidden !== 'function') {
return
}
+
const cached = $lastRoster.get()
let roster: RosterRow[] | null = Array.isArray(cached) && cached.length ? cached : null
+
if (!roster) {
// Plugin load can run before the Bots pane hydrates $lastRoster — fall
// back to the active gateway's own profile list (local bots; remote
@@ -230,25 +260,31 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {
const activeBot = {
name: String(host.state.profile?.get?.() || 'default').trim() || 'default'
}
+
const res = (await requestForBot(activeBot, 'profiles.list', {})) as ProfilesListResult
roster = Array.isArray(res?.profiles) ? res.profiles : []
} catch {
return
}
}
+
await Promise.all(
roster.map(async (bot: RosterRow) => {
const name = String(bot?.name || '').trim()
+
if (!name) {
return
}
+
try {
const route = botConnectionRoute(bot)
const profile = backendTargetProfile(route, name)
+
const res = await host.listPersistedSessions(route, {
profile,
limit: PROFILE_SESSION_LIST_LIMIT
})
+
const rows = Array.isArray(res?.sessions) ? res.sessions : []
await Promise.all(
rows
diff --git a/apps/desktop/src/plugins/hermes-bots/skills-hub.tsx b/apps/desktop/src/plugins/hermes-bots/skills-hub.tsx
index 452a167d418..5ad8cb1ecd9 100644
--- a/apps/desktop/src/plugins/hermes-bots/skills-hub.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/skills-hub.tsx
@@ -31,6 +31,7 @@ interface HubSkillsSectionProps {
forProfile: null | string | { connectionId?: null | string; profile?: null | string }
onInstalled?: (name: string) => void
}
+
export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionProps) {
const b = useBots()
const [query, setQuery] = useState('')
@@ -50,17 +51,22 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
if (!browseHub) {
return undefined
}
+
const onMessage = (event: MessageEvent) => {
if (event.origin !== HUB_ORIGIN) {
return
}
+
if (!frameRef.current || event.source !== frameRef.current.contentWindow) {
return
}
+
const data = event.data
+
if (!data || data.type !== 'hermes-skill-pick' || !data.name) {
return
}
+
const target = String(data.identifier || data.name)
// Skill identifiers are slugs / owner-name paths — keep anything
@@ -68,25 +74,33 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
if (!/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(target)) {
return
}
+
if (installRef.current) {
void installRef.current(target, String(data.name))
}
}
+
window.addEventListener('message', onMessage)
+
return () => window.removeEventListener('message', onMessage)
}, [browseHub])
+
const search = async () => {
const q = query.trim()
+
if (!q || searching) {
return
}
+
setSearching(true)
setResults(null)
+
try {
const res: { results?: HubSkillResult[] } = await host.request('skills.manage', {
action: 'search',
query: q
})
+
setResults(res.results || [])
} catch {
setResults([])
@@ -94,12 +108,16 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
setSearching(false)
}
}
+
const install = async (name: string, displayName?: string) => {
const label = displayName || name
+
if (installing) {
return
}
+
setInstalling(label)
+
try {
// With forProfile the install lands in that bot's skills dir
// (gateway skills.manage profile scoping); null = launch profile,
@@ -121,6 +139,7 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
kind: 'success',
message: `Skill "${label}" installed`
})
+
if (typeof onInstalled === 'function') {
onInstalled(label)
}
@@ -130,7 +149,9 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
setInstalling(null)
}
}
+
installRef.current = install
+
return (
<div className="grid gap-1.5 border-t border-(--ui-stroke-secondary) pt-2">
<div className="flex items-baseline justify-between gap-2">
@@ -166,9 +187,9 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
}}
>
<iframe
- src={HUB_PICKER_URL}
- title={b.tools.skillsHub}
ref={frameRef}
+ sandbox="allow-scripts allow-same-origin"
+ src={HUB_PICKER_URL}
style={{
width: '133.34%',
height: '133.34%',
@@ -177,7 +198,7 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
transform: 'scale(0.75)',
transformOrigin: 'top left'
}}
- sandbox="allow-scripts allow-same-origin"
+ title={b.tools.skillsHub}
/>
</div>
<div className="px-1 text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
@@ -190,21 +211,22 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
<div className="flex gap-1.5">
<Input
className="h-7 flex-1 text-xs"
- placeholder={b.tools.searchHub}
- value={query}
onChange={event => setQuery(event.target.value)}
onKeyDown={event => {
// IME guard: Enter confirming a composed word must not search.
if (event.nativeEvent?.isComposing || event.keyCode === 229) {
return
}
+
if (event.key === 'Enter') {
event.preventDefault()
void search()
}
}}
+ placeholder={b.tools.searchHub}
+ value={query}
/>
- <Button size="sm" variant="secondary" disabled={searching || !query.trim()} onClick={() => void search()}>
+ <Button disabled={searching || !query.trim()} onClick={() => void search()} size="sm" variant="secondary">
{searching ? 'Searching…' : 'Search'}
</Button>
</div>
@@ -224,7 +246,7 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
>
<div className="grid gap-1">
{results.map(r => (
- <div key={r.name} className="flex items-center gap-2 text-xs">
+ <div className="flex items-center gap-2 text-xs" key={r.name}>
<div className="min-w-0 flex-1">
<div className="truncate font-medium">{r.name}</div>
{r.description ? (
@@ -235,12 +257,12 @@ export function HubSkillsSection({ forProfile, onInstalled }: HubSkillsSectionPr
<span className="shrink-0 text-[0.65rem] text-(--ui-text-tertiary)">✓ added</span>
) : (
<Button
- size="sm"
- variant="ghost"
className="shrink-0 px-2 font-semibold"
disabled={installing !== null}
- title={`Install "${r.name}" and add it to the list above`}
onClick={() => void install(r.name)}
+ size="sm"
+ title={`Install "${r.name}" and add it to the list above`}
+ variant="ghost"
>
{installing === r.name ? '…' : '+'}
</Button>
diff --git a/apps/desktop/src/plugins/hermes-bots/soul.ts b/apps/desktop/src/plugins/hermes-bots/soul.ts
index 78897dcb5ad..171c41b4b02 100644
--- a/apps/desktop/src/plugins/hermes-bots/soul.ts
+++ b/apps/desktop/src/plugins/hermes-bots/soul.ts
@@ -19,6 +19,7 @@ import type { RosterRow } from './types'
function messagingProtocolSection(name: string, roster: RosterRow[] | null | undefined): string {
const teammates = (roster || []).filter(b => b.name !== name)
const handle = botHandle(name)
+
return [
'## Messaging other agents',
'',
@@ -81,10 +82,13 @@ export function ensureMessagingProtocol(
roster: RosterRow[] | null | undefined
) {
const text = (soul || '').trim()
- if (serverInjectsProtocol || hasMessagingProtocol(text)) return text
+
+ if (serverInjectsProtocol || hasMessagingProtocol(text)) {return text}
const section = messagingProtocolSection(name, roster)
+
return text ? text + '\n\n' + section : section
}
+
const soulProtocolChecked = new Set<string>()
const soulProtocolInflight = new Set<string>()
@@ -97,11 +101,14 @@ export function backfillMessagingProtocol(roster: RosterRow[] | null | undefined
if (serverInjectsProtocol) {
return
}
+
for (const bot of roster || []) {
const name = bot && bot.name
+
if (!name || soulProtocolChecked.has(name) || soulProtocolInflight.has(name)) {
continue
}
+
soulProtocolInflight.add(name)
host
.request<{ soul?: string }>('profiles.describe', {
@@ -109,10 +116,13 @@ export function backfillMessagingProtocol(roster: RosterRow[] | null | undefined
})
.then(res => {
const soul = (res && res.soul) || ''
+
if (hasMessagingProtocol(soul)) {
soulProtocolChecked.add(name)
+
return null
}
+
return host
.request('profiles.configure', {
name,
@@ -143,10 +153,12 @@ interface ComposeSoulOptions {
roster?: RosterRow[] | null
title?: null | string
}
+
export function composeSoul({ name, title, description, roster, customSoul }: ComposeSoulOptions): string {
if (customSoul && customSoul.trim()) {
return ensureMessagingProtocol(customSoul, name, roster)
}
+
const lines = [
`# ${displayName({
name,
@@ -162,6 +174,8 @@ export function composeSoul({ name, title, description, roster, customSoul }: Co
})}, a persistent named agent (profile \`${name}\`) on this machine.`,
'You keep your own memory, skills, and conversation history across sessions.'
]
+
const identity = lines.filter(line => line !== null).join('\n')
+
return serverInjectsProtocol ? identity : identity + '\n\n' + messagingProtocolSection(name, roster)
}
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 158c87d1cfe..ae6e5ae4fd8 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1414,15 +1414,15 @@ export { SkillsView } from '@/app/skills'
* renders anywhere (a plugin dialog); pass a live `gateway` (see
* `host.getGateway()`) and an optional `profile` to scope it to one bot. */
export { McpTab } from '@/app/skills/mcp-tab'
+/** The oversized Collapse lettering an empty chat is titled with — core writes
+ * "HERMES AGENT" with it, a `chat.empty` contribution writes its own name. */
+export { Wordmark } from '@/components/chat/wordmark'
/** Pane placement roles. `'floating'` is the one NON-tiling value: the pane is
* excluded from the layout tree and rendered as a fixed, draggable card above
* it — it takes no width from any zone, has no tab, and can't be docked.
* Pair it with `anchor` (spawn corner, default `'top-right'`) plus
* `width`/`height`. */
export type { FloatingAnchor } from '@/components/pane-shell/tree/renderer/floating-rect'
-/** The oversized Collapse lettering an empty chat is titled with — core writes
- * "HERMES AGENT" with it, a `chat.empty` contribution writes its own name. */
-export { Wordmark } from '@/components/chat/wordmark'
export { StatusDot, type StatusTone } from '@/components/status-dot'
export { Badge } from '@/components/ui/badge'
export { Button } from '@/components/ui/button'
@@ -1538,6 +1538,9 @@ export {
* Plugins must route animation clocks through this instead of raw rAF loops
* so a disabled plugin or an empty roster costs zero frames. */
export { type BudgetedLoop, type BudgetedLoopOptions, createBudgetedLoop } from '@/lib/budgeted-loop'
+/** The blank transcript as a contribution area: claim the sessions you own and
+ * render what stands in the gap. Core's own splash keeps a fresh draft. */
+export { CHAT_EMPTY_AREA, type ChatEmptyContribution, type ChatEmptyProps } from '@/lib/chat-empty'
/** THE compact-number formatter — every user-facing count/token figure goes
* through here (1230 → "1.2k", 1_500_000 → "1.5M"). Don't hand-roll `/1000`. */
export { compactNumber } from '@/lib/format'
@@ -1568,6 +1571,8 @@ export { PROFILE_SWATCHES, profileColor, profileColorSoft } from '@/lib/profile-
* `ctx.socket` frame invalidating a query). Inside components keep using
* `useQueryClient`. */
export { queryClient } from '@/lib/query-client'
+
+export const PANES_AREA = 'panes'
/** Hermes' reasoning levels + their compact labels, so a plugin surfacing a
* thinking depth uses the same scale and spelling as the rest of the app. */
export {
@@ -1577,15 +1582,13 @@ export {
type ReasoningEffort,
reasoningEffortLabel
} from '@/lib/reasoning-effort'
+export const STATUSBAR_AREAS = { left: 'statusBar.left', right: 'statusBar.right' } as const
+export const TITLEBAR_AREAS = { center: 'titleBar.center', left: 'titleBar.left', right: 'titleBar.right' } as const
-export const PANES_AREA = 'panes'
/** The app's own gateway-readiness evaluation (setup.status +
* setup.runtime_check, reconciled) — pass `host.request`. Don't hand-roll
* readiness from raw RPC shapes. */
export { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
-export const STATUSBAR_AREAS = { left: 'statusBar.left', right: 'statusBar.right' } as const
-export const TITLEBAR_AREAS = { center: 'titleBar.center', left: 'titleBar.left', right: 'titleBar.right' } as const
-
/** Canonical time formatting — every surface pulls from here so timestamps read
* the same app-wide. For a row's AGE, bucket with `coarseElapsed` and render
* the compact suffixes (`t.sidebar.row.ageMin` → "52m"), which is what the
@@ -1593,9 +1596,6 @@ export const TITLEBAR_AREAS = { center: 'titleBar.center', left: 'titleBar.left'
* suffix. `relativeTime` is the bidirectional Intl form ("in 14 hr") — use it
* for a scheduled next-run, not for an age. */
export { type AgoLabels, coarseElapsed, fmtDateTime, fmtDayTime, formatAgo, relativeTime } from '@/lib/time'
-/** The blank transcript as a contribution area: claim the sessions you own and
- * render what stands in the gap. Core's own splash keeps a fresh draft. */
-export { CHAT_EMPTY_AREA, type ChatEmptyContribution, type ChatEmptyProps } from '@/lib/chat-empty'
/** The transcript as a contribution area: register a named `::directive{...}`
* and the model can render your component inline in assistant messages. */
export {
diff --git a/eslint.config.shared.mjs b/eslint.config.shared.mjs
index 5e0f2c8503a..29955335739 100644
--- a/eslint.config.shared.mjs
+++ b/eslint.config.shared.mjs
@@ -44,9 +44,13 @@ export default [
},
rules: {
'@typescript-eslint/consistent-type-imports': ['error', { prefer: 'type-imports' }],
+ // The base rule counts a TS overload signature as a redeclaration of its
+ // implementation. Swap in the TS-aware version, same as no-undef below.
+ '@typescript-eslint/no-redeclare': 'error',
'@typescript-eslint/no-unused-vars': 'off',
curly: ['error', 'all'],
'no-fallthrough': ['error', { allowEmptyCase: true }],
+ 'no-redeclare': 'off',
'no-undef': 'off',
'no-unused-vars': 'off',
'padding-line-between-statements': [
diff --git a/ui-tui/eslint.config.mjs b/ui-tui/eslint.config.mjs
index c3fed73f26c..db3a3d45c8d 100644
--- a/ui-tui/eslint.config.mjs
+++ b/ui-tui/eslint.config.mjs
@@ -6,6 +6,7 @@ export default [
files: ['packages/hermes-ink/**/*.{ts,tsx}'],
rules: {
'@typescript-eslint/consistent-type-imports': 'off',
+ '@typescript-eslint/no-redeclare': 'off',
'no-constant-condition': 'off',
'no-empty': 'off',
'no-redeclare': 'off',