Skip to content

The agent that grows with you

refactor(desktop): convert Bot Mode from hand-written jsx() calls to TSX

Brooklyn Nicholsonb2e5b1d42007
diff --git a/apps/desktop/scripts/codemod/dejsx.mjs b/apps/desktop/scripts/codemod/dejsx.mjs
new file mode 100644
index 00000000000..cb0b75b2083
--- /dev/null
+++ b/apps/desktop/scripts/codemod/dejsx.mjs
@@ -0,0 +1,251 @@
+/**
+ * Inverse-compile `jsx()` / `jsxs()` runtime calls back into JSX syntax.
+ *
+ * hermes-bots/plugin.js is hand-written JSX compiler output: it imports
+ * { jsx, jsxs } from 'react/jsx-runtime' and calls them directly. That makes
+ * the conversion to real JSX a deterministic AST transform rather than a
+ * rewrite.
+ *
+ * Usage: node dejsx.mjs <in.js> <out.tsx>
+ */
+import { readFileSync, writeFileSync } from 'node:fs'
+
+import generate from '@babel/generator'
+import { parse } from '@babel/parser'
+import traverse from '@babel/traverse'
+import * as t from '@babel/types'
+
+const gen = generate.default ?? generate
+const walk = traverse.default ?? traverse
+
+const [, , inPath, outPath] = process.argv
+
+const source = readFileSync(inPath, 'utf8')
+const ast = parse(source, {
+ sourceType: 'module',
+ plugins: ['jsx'],
+ attachComment: true
+})
+
+const stats = { jsx: 0, jsxs: 0, skipped: [] }
+
+/** `'div'` → intrinsic; `Foo` → component; `Foo.Bar` → member. */
+function toJsxName(node) {
+ if (t.isStringLiteral(node)) {
+ // Only bare tag names are expressible as JSX intrinsics.
+ return /^[a-z][a-z0-9]*$/i.test(node.value) ? t.jsxIdentifier(node.value) : null
+ }
+
+ if (t.isIdentifier(node)) {
+ return t.jsxIdentifier(node.name)
+ }
+
+ if (t.isMemberExpression(node) && !node.computed) {
+ const object = toJsxName(node.object)
+ const property = t.isIdentifier(node.property) ? t.jsxIdentifier(node.property.name) : null
+
+ return object && property ? t.jsxMemberExpression(object, property) : null
+ }
+
+ return null
+}
+
+/** JSX attribute names permit dashes and colons, so most keys pass through. */
+function toAttrName(key, computed) {
+ if (computed) {
+ return null
+ }
+
+ const raw = t.isIdentifier(key) ? key.name : t.isStringLiteral(key) ? key.value : null
+
+ return raw && /^[A-Za-z_$][-:A-Za-z0-9_$]*$/.test(raw) ? t.jsxIdentifier(raw) : null
+}
+
+/**
+ * A string child is safe as bare JSXText only when it survives a round trip:
+ * no JSX metacharacters, and no leading/trailing whitespace (which JSX trims).
+ */
+function textIsSafe(value) {
+ return value.length > 0 && !/[{}<>]/.test(value) && value === value.trim() && !/\n/.test(value)
+}
+
+function toChild(node) {
+ if (t.isJSXElement(node) || t.isJSXFragment(node)) {
+ return node
+ }
+
+ if (t.isStringLiteral(node) && textIsSafe(node.value)) {
+ return t.jsxText(node.value)
+ }
+
+ // `null` / `false` children are pure noise once inlined, but they carry
+ // meaning inside conditionals, so only drop the standalone literals.
+ if (t.isNullLiteral(node) || (t.isBooleanLiteral(node) && node.value === false)) {
+ return null
+ }
+
+ return t.jsxExpressionContainer(node)
+}
+
+/**
+ * Comments between children have to become `{/* … *␟/}` — a bare `//` in JSX
+ * children position is literal text, not a comment. Line comments are
+ * rewritten as block comments so they survive the move.
+ */
+function commentChild(comments) {
+ const empty = t.jsxEmptyExpression()
+
+ empty.innerComments = comments.map(comment => ({
+ type: 'CommentBlock',
+ value: comment.type === 'CommentLine' ? ` ${comment.value.trim()} ` : comment.value
+ }))
+
+ return t.jsxExpressionContainer(empty)
+}
+
+function childrenFrom(node) {
+ const items = t.isArrayExpression(node) ? node.elements : [node]
+ const children = []
+
+ for (const item of items) {
+ if (!item) {
+ continue
+ }
+
+ if (item.leadingComments?.length) {
+ children.push(commentChild(item.leadingComments))
+ item.leadingComments = null
+ }
+
+ const child = t.isSpreadElement(item) ? t.jsxExpressionContainer(item.argument) : toChild(item)
+
+ if (child) {
+ children.push(child)
+ }
+
+ if (item.trailingComments?.length) {
+ children.push(commentChild(item.trailingComments))
+ item.trailingComments = null
+ }
+ }
+
+ return children
+}
+
+function convert(path) {
+ const { node } = path
+ const [type, props, key] = node.arguments
+
+ const name = toJsxName(type)
+
+ if (!name) {
+ stats.skipped.push(`${node.loc?.start.line}: dynamic element type`)
+
+ return
+ }
+
+ if (!t.isObjectExpression(props)) {
+ stats.skipped.push(`${node.loc?.start.line}: non-literal props`)
+
+ return
+ }
+
+ const attributes = []
+ let children = []
+
+ if (key) {
+ attributes.push(t.jsxAttribute(t.jsxIdentifier('key'), t.jsxExpressionContainer(key)))
+ }
+
+ for (const prop of props.properties) {
+ if (t.isSpreadElement(prop)) {
+ attributes.push(t.jsxSpreadAttribute(prop.argument))
+
+ continue
+ }
+
+ if (!t.isObjectProperty(prop)) {
+ stats.skipped.push(`${node.loc?.start.line}: object method in props`)
+
+ return
+ }
+
+ const attrName = toAttrName(prop.key, prop.computed)
+
+ if (!attrName) {
+ stats.skipped.push(`${node.loc?.start.line}: unexpressible prop key`)
+
+ return
+ }
+
+ if (attrName.name === 'children') {
+ children = childrenFrom(prop.value)
+
+ continue
+ }
+
+ // `foo={true}` is idiomatic as a bare `foo`; string values print unquoted.
+ const value =
+ t.isStringLiteral(prop.value) && !/[\n"]/.test(prop.value.value)
+ ? t.stringLiteral(prop.value.value)
+ : t.isBooleanLiteral(prop.value) && prop.value.value === true
+ ? null
+ : t.jsxExpressionContainer(prop.value)
+
+ const attribute = t.jsxAttribute(attrName, value)
+
+ // Carry the explanatory comments that sit above props — this file's
+ // comments are most of its documentation.
+ if (prop.leadingComments?.length) {
+ attribute.leadingComments = prop.leadingComments
+ }
+
+ attributes.push(attribute)
+ }
+
+ const selfClosing = children.length === 0
+ const element = t.jsxElement(
+ t.jsxOpeningElement(name, attributes, selfClosing),
+ selfClosing ? null : t.jsxClosingElement(name),
+ children,
+ selfClosing
+ )
+
+ t.inherits(element, node)
+ path.replaceWith(element)
+
+ stats[node.callee.name] += 1
+}
+
+walk(ast, {
+ CallExpression: {
+ // Post-order: inner calls are already JSXElements by the time we rebuild
+ // the parent, so they slot straight in as children.
+ exit(path) {
+ const callee = path.node.callee
+
+ if (t.isIdentifier(callee) && (callee.name === 'jsx' || callee.name === 'jsxs')) {
+ convert(path)
+ }
+ }
+ }
+})
+
+// The runtime import is what we just eliminated.
+walk(ast, {
+ ImportDeclaration(path) {
+ if (path.node.source.value === 'react/jsx-runtime') {
+ path.remove()
+ }
+ }
+})
+
+const output = gen(ast, { jsescOption: { minimal: true }, retainLines: false, comments: true }, source)
+
+writeFileSync(outPath, output.code)
+
+console.log(`jsx: ${stats.jsx} jsxs: ${stats.jsxs} skipped: ${stats.skipped.length}`)
+
+for (const skip of stats.skipped.slice(0, 40)) {
+ console.log(` skip ${skip}`)
+}
diff --git a/apps/desktop/scripts/codemod/verify.mjs b/apps/desktop/scripts/codemod/verify.mjs
new file mode 100644
index 00000000000..a1c00977763
--- /dev/null
+++ b/apps/desktop/scripts/codemod/verify.mjs
@@ -0,0 +1,267 @@
+/**
+ * Prove the de-JSX codemod was lossless.
+ *
+ * Recompiles the generated .tsx back down to jsx-runtime calls with esbuild,
+ * then compares it against the original hand-written source. Both sides are
+ * normalized through the same printer so the diff reflects semantics, not
+ * formatting.
+ *
+ * jsx/jsxs selection is deliberately collapsed: the pair differ only in React's
+ * dev-mode static-children key warning, and esbuild picks between them on its
+ * own rules rather than the ones the file was hand-written with.
+ */
+import { readFileSync } from 'node:fs'
+
+import generate from '@babel/generator'
+import { parse } from '@babel/parser'
+import traverse from '@babel/traverse'
+import * as t from '@babel/types'
+import { transformSync } from 'esbuild'
+
+const gen = generate.default ?? generate
+const walk = traverse.default ?? traverse
+
+const [, , originalPath, convertedPath] = process.argv
+
+const allowed = { spreadChildren: 0, redundantKeyProp: 0 }
+
+function normalize(code, plugins) {
+ const ast = parse(code, { sourceType: 'module', plugins })
+
+ walk(ast, {
+ /**
+ * JSX has no spread-children syntax: `children: [...items.map(f), x]` can
+ * only be written `{items.map(f)}<X/>`, which compiles to
+ * `children: [items.map(f), x]`. React flattens nested array children and
+ * the mapped elements keep their explicit keys, so the two are equivalent
+ * — this is the idiom the whole ecosystem writes. Fold the spread away on
+ * the original side so the comparison doesn't flag it, and count it.
+ */
+ ObjectProperty(path) {
+ if (!t.isIdentifier(path.node.key, { name: 'children' }) || !t.isArrayExpression(path.node.value)) {
+ return
+ }
+
+ path.node.value.elements = path.node.value.elements.map(element => {
+ if (!t.isSpreadElement(element)) {
+ return element
+ }
+
+ allowed.spreadChildren += 1
+
+ return element.argument
+ })
+ },
+ // Drop captured raw text so both sides re-print literals canonically —
+ // one quote style, and `48000` rather than esbuild's `48e3`.
+ 'StringLiteral|NumericLiteral'(path) {
+ delete path.node.extra
+ },
+ // Template chunks keep their raw text, so an emoji written as a surrogate
+ // pair on one side and a code point on the other reads as a diff.
+ TemplateElement(path) {
+ const { cooked } = path.node.value
+
+ if (typeof cooked === 'string') {
+ path.node.value.raw = cooked.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${')
+ }
+ },
+ /**
+ * Some call sites pass `key` twice — inside props AND as the third
+ * argument. React's jsx runtime takes the key from the third argument and
+ * never copies `key` into props, so the props copy is dead either way.
+ */
+ CallExpression(path) {
+ const callee = path.node.callee
+ const [, props] = path.node.arguments
+
+ if (!t.isIdentifier(callee) || callee.name !== 'jsx' || !t.isObjectExpression(props)) {
+ return
+ }
+
+ props.properties = props.properties.filter(prop => {
+ if (t.isObjectProperty(prop) && !prop.computed && t.isIdentifier(prop.key, { name: 'key' })) {
+ allowed.redundantKeyProp += 1
+
+ return false
+ }
+
+ return true
+ })
+ },
+ // esbuild folds adjacent string/template concatenation into one literal.
+ BinaryExpression: {
+ exit(path) {
+ const { operator, left, right } = path.node
+
+ if (operator !== '+') {
+ return
+ }
+
+ if (t.isStringLiteral(left) && t.isStringLiteral(right)) {
+ path.replaceWith(t.stringLiteral(left.value + right.value))
+
+ return
+ }
+
+ // `` `a${x}b` + 'c' `` → `` `a${x}bc` ``
+ if (t.isTemplateLiteral(left) && t.isStringLiteral(right)) {
+ const quasis = left.quasis.map(quasi => t.cloneNode(quasi))
+ const last = quasis[quasis.length - 1]
+
+ last.value = { raw: last.value.cooked + right.value, cooked: last.value.cooked + right.value }
+ path.replaceWith(t.templateLiteral(quasis, left.expressions))
+
+ return
+ }
+
+ // `'a' + `b${x}` ` → `` `ab${x}` ``
+ if (t.isStringLiteral(left) && t.isTemplateLiteral(right)) {
+ const quasis = right.quasis.map(quasi => t.cloneNode(quasi))
+ const first = quasis[0]
+
+ first.value = { raw: left.value + first.value.cooked, cooked: left.value + first.value.cooked }
+ path.replaceWith(t.templateLiteral(quasis, right.expressions))
+
+ return
+ }
+
+ // `` `a${x}` + `b${y}` `` → `` `a${x}b${y}` `` — the seam quasis merge.
+ if (t.isTemplateLiteral(left) && t.isTemplateLiteral(right)) {
+ const leftQuasis = left.quasis.map(quasi => t.cloneNode(quasi))
+ const rightQuasis = right.quasis.map(quasi => t.cloneNode(quasi))
+ const seam = leftQuasis.pop()
+ const head = rightQuasis.shift()
+ const merged = (seam.value.cooked ?? '') + (head.value.cooked ?? '')
+
+ seam.value = { raw: merged, cooked: merged }
+ path.replaceWith(
+ t.templateLiteral([...leftQuasis, seam, ...rightQuasis], [...left.expressions, ...right.expressions])
+ )
+ }
+ }
+ },
+ // esbuild prefers a template literal when it saves escaping.
+ TemplateLiteral: {
+ exit(path) {
+ if (path.node.expressions.length === 0) {
+ path.replaceWith(t.stringLiteral(path.node.quasis[0].value.cooked ?? ''))
+ }
+ }
+ },
+ // esbuild rewrites `undefined` to `void 0`.
+ UnaryExpression(path) {
+ if (path.node.operator === 'void' && t.isNumericLiteral(path.node.argument, { value: 0 })) {
+ path.replaceWith(t.identifier('undefined'))
+ }
+ },
+ // esbuild emits `import { jsx as _jsx }`; the original imports it bare.
+ Identifier(path) {
+ if (path.node.name === '_jsx' || path.node.name === '_jsxs') {
+ path.node.name = 'jsx'
+ }
+
+ if (path.node.name === 'jsxs') {
+ path.node.name = 'jsx'
+ }
+ },
+ ImportDeclaration(path) {
+ if (path.node.source.value === 'react/jsx-runtime') {
+ path.remove()
+ }
+ },
+ // esbuild hoists the spread helper for `{...props}` on intrinsics.
+ VariableDeclarator(path) {
+ if (t.isIdentifier(path.node.id) && /^__(spread|assign|objRest)/.test(path.node.id.name)) {
+ path.remove()
+ }
+ }
+ })
+
+ // esbuild hoists `export default {…}` into
+ // `var X = {…}; export { X as default }`.
+ const body = ast.program.body
+ const exportIndex = body.findIndex(
+ node =>
+ (t.isExportDefaultDeclaration(node) && t.isIdentifier(node.declaration)) ||
+ (t.isExportNamedDeclaration(node) &&
+ !node.declaration &&
+ node.specifiers.length === 1 &&
+ t.isExportSpecifier(node.specifiers[0]) &&
+ t.isIdentifier(node.specifiers[0].exported, { name: 'default' }))
+ )
+
+ if (exportIndex !== -1) {
+ const exported = body[exportIndex]
+ const name = t.isExportDefaultDeclaration(exported)
+ ? exported.declaration.name
+ : exported.specifiers[0].local.name
+ const declIndex = body.findIndex(
+ node =>
+ t.isVariableDeclaration(node) &&
+ node.declarations.length === 1 &&
+ t.isIdentifier(node.declarations[0].id, { name })
+ )
+
+ if (declIndex !== -1) {
+ body[exportIndex] = t.exportDefaultDeclaration(body[declIndex].declarations[0].init)
+ body.splice(declIndex, 1)
+ }
+ }
+
+ // esbuild renames locals that shadow an outer binding (`displayName` →
+ // `displayName2`). Canonically rename every binding in declaration order on
+ // both sides so the comparison tests alpha-equivalence rather than spelling.
+ // Numbered per scope, not globally: one extra binding on one side then
+ // shifts only its own scope instead of desynchronizing the whole file.
+ let scopeId = 0
+
+ walk(ast, {
+ Scopable(path) {
+ const bindings = Object.values(path.scope.bindings).sort(
+ (a, b) => (a.identifier.start ?? 0) - (b.identifier.start ?? 0)
+ )
+ const scope = (scopeId += 1)
+
+ bindings.forEach((binding, index) => {
+ path.scope.rename(binding.identifier.name, `__s${scope}_${index}`)
+ })
+ }
+ })
+
+ return gen(ast, { comments: false, compact: true, jsescOption: { minimal: true } }).code
+}
+
+const original = normalize(readFileSync(originalPath, 'utf8'), [])
+const recompiled = normalize(
+ transformSync(readFileSync(convertedPath, 'utf8'), {
+ loader: 'tsx',
+ jsx: 'automatic',
+ format: 'esm',
+ target: 'esnext'
+ }).code,
+ []
+)
+
+console.log(
+ `allowed rewrites — spread children folded: ${allowed.spreadChildren}, redundant key props dropped: ${allowed.redundantKeyProp}`
+)
+
+if (original === recompiled) {
+ console.log(`IDENTICAL — ${original.length} chars of normalized output match`)
+ process.exit(0)
+}
+
+console.log(`DIFFER — original ${original.length} chars, recompiled ${recompiled.length} chars`)
+
+// Report the first divergence with surrounding context so it can be chased.
+let i = 0
+while (i < original.length && original[i] === recompiled[i]) {
+ i += 1
+}
+
+const window = 260
+console.log(`\nfirst divergence at char ${i}:`)
+console.log(`\n--- original ---\n${original.slice(Math.max(0, i - window), i + window)}`)
+console.log(`\n--- recompiled ---\n${recompiled.slice(Math.max(0, i - window), i + window)}`)
+process.exit(1)
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.tsx
similarity index 68%
rename from apps/desktop/src/plugins/hermes-bots/plugin.js
rename to apps/desktop/src/plugins/hermes-bots/plugin.tsx
index 0dab6d76b71..5fa61e1b67a 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx
@@ -65,8 +65,6 @@ import {
useValue
} from '@hermes/plugin-sdk'
import { useEffect, useMemo, useRef, useState } from 'react'
-import { jsx, jsxs } from 'react/jsx-runtime'
-
const { McpTab, ToolsetConfigPanel } = sdk
// Keep optional exports feature-detected; test harnesses may strip the SDK namespace.
const SkillsView = typeof sdk === 'undefined' ? undefined : sdk.SkillsView
@@ -83,7 +81,6 @@ const blobatarSvg = typeof sdk === 'undefined' ? undefined : sdk.blobatarSvg
// Budgeted render loop (fps cap + observability pause + dormancy + teardown).
// Feature-detected: older desktops fall back to the hand-rolled clock below.
const createBudgetedLoop = typeof sdk === 'undefined' ? undefined : sdk.createBudgetedLoop
-
const ID = 'hermes-bots'
/** Tree pane id of the Bots home workspace tab (openWorkspace prefixes
* `plugin-workspace:`). Tab visibility — not session focus — is what says
@@ -132,7 +129,6 @@ const $activityToasts = atom(false)
/** Flip the activity-toast pref and persist it. */
function setActivityToasts(enabled) {
$activityToasts.set(enabled)
-
try {
Promise.resolve(pluginCtx?.storage?.set?.('activity-toasts', enabled)).catch(() => undefined)
} catch {
@@ -148,14 +144,12 @@ function setActivityToasts(enabled) {
function trackInboundActivity(roster) {
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
}
@@ -165,8 +159,10 @@ function trackInboundActivity(roster) {
if ($selectedBot.get() === key) {
continue
}
-
- $botUnread.set({ ...$botUnread.get(), [key]: true })
+ $botUnread.set({
+ ...$botUnread.get(),
+ [key]: true
+ })
// Roster-hidden bots stay quiet: the unread flag above accumulates
// silently (unhiding reveals the badge) but a hidden bot never toasts.
@@ -181,7 +177,6 @@ function trackInboundActivity(roster) {
const label = displayName(bot, meta)
const preview = (activity?.preview || '').trim()
const inbound = /^Message from/i.test(preview)
-
host.notify({
kind: 'info',
title: inbound ? `\uD83E\uDD16 New message for ${label}` : `${label} has new activity`,
@@ -216,38 +211,36 @@ const BOT_ATTENTION_HINTS = {
* timeout) — transient classes must NEVER badge. Pure; tested directly. */
function attentionReasonFromError(errorTextOrReason) {
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.
- if (/rate.?limit|too many requests|\b429\b|\b5\d\d\b|server error|overloaded|timed?.?out|timeout|temporar/.test(text)) {
+ if (
+ /rate.?limit|too many requests|\b429\b|\b5\d\d\b|server error|overloaded|timed?.?out|timeout|temporar/.test(text)
+ ) {
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)) {
+ if (
+ /\b401\b|\b403\b|unauthorized|forbidden|authentication|invalid.?api.?key|credentials? (are )?(invalid|expired)/.test(
+ text
+ )
+ ) {
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
}
@@ -261,14 +254,18 @@ const $botAttention = atom({})
* classify to null and set nothing. Latest failure wins. */
function noteBotAttention(key, errorTextOrReason) {
const reason = attentionReasonFromError(errorTextOrReason)
-
if (!key || !reason) {
return
}
-
$botAttention.set({
...$botAttention.get(),
- [key]: { reason, at: Date.now(), message: String(errorTextOrReason || '').trim().slice(0, 200) }
+ [key]: {
+ reason,
+ at: Date.now(),
+ message: String(errorTextOrReason || '')
+ .trim()
+ .slice(0, 200)
+ }
})
}
@@ -277,8 +274,9 @@ function clearBotAttention(key) {
if (!key || !$botAttention.get()[key]) {
return
}
-
- const next = { ...$botAttention.get() }
+ const next = {
+ ...$botAttention.get()
+ }
delete next[key]
$botAttention.set(next)
}
@@ -319,27 +317,22 @@ const $botChatFocused = atom(false)
* chat can remain alive behind it, so session focus alone cannot decide which
* roster row owns the visible workspace. */
const $botsHomeFronted = atom(false)
-
let botsHomeClose = null
let suppressBotsHomeReopen = false
// Latched while a re-front attempt has not yet been answered with visibility.
// Cleared the moment the home is actually fronted, and whenever the tab is
// retired — a fresh open starts the budget over. See openBotsHomeWorkspace.
let botsHomeRefrontTried = false
-
function saveSelectedRosterBot(bot) {
const key = botRosterKey(bot)
-
$selectedBot.set(botSelectionKey(bot))
$selectedRosterKey.set(key)
-
try {
Promise.resolve(pluginCtx?.storage?.set?.('selected-roster-bot-v1', key)).catch(() => undefined)
} catch {
/* storage unavailable — selection lasts for this window */
}
}
-
function clearSelectedRosterBot(bot) {
clearSelectedRosterKey(botRosterKey(bot))
}
@@ -351,9 +344,7 @@ function clearSelectedRosterKey(key) {
if ($selectedRosterKey.get() !== key) {
return
}
-
$selectedRosterKey.set('')
-
try {
Promise.resolve(pluginCtx?.storage?.set?.('selected-roster-bot-v1', '')).catch(() => undefined)
} catch {
@@ -366,14 +357,17 @@ function clearSelectedRosterKey(key) {
function parseRosterKey(key) {
const raw = String(key || '')
const at = raw.indexOf('::')
-
if (at < 0) {
- return { connectionId: '', name: '' }
+ return {
+ connectionId: '',
+ name: ''
+ }
+ }
+ return {
+ connectionId: raw.slice(0, at),
+ name: raw.slice(at + 2)
}
-
- 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
@@ -382,7 +376,6 @@ const $focusedBotProfile = host.state.focusedSessionProfile || host.state.profil
function focusedMentionProfile() {
return String($focusedBotProfile.get?.() || '').trim() || 'default'
}
-
function fallbackFocusedBotOwner(profile = $focusedBotProfile.get?.()) {
const focusedProfile = String(profile || 'default').trim() || 'default'
const activeProfile = String(host.state.profile?.get?.() || 'default').trim() || 'default'
@@ -394,41 +387,34 @@ function fallbackFocusedBotOwner(profile = $focusedBotProfile.get?.()) {
if (host.state.focusedSessionProfile && focusedProfile !== activeProfile) {
return null
}
-
const connectionId = String(
host.state.connectionId?.get?.() ||
- (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||
- ''
+ (typeof host.activeConnectionId === 'function' ? host.activeConnectionId() : '') ||
+ ''
).trim()
-
return {
authoritative: false,
connectionId,
profile: focusedProfile
}
}
-
const $focusedBotOwner = host.state.focusedSessionOwner || {
get: () => fallbackFocusedBotOwner(),
listen: listener => {
const emit = profile => listener(fallbackFocusedBotOwner(profile))
const unbindProfile = $focusedBotProfile.listen(emit)
const unbindConnection = host.state.connectionId?.listen?.(() => emit($focusedBotProfile.get?.()))
-
return () => {
unbindProfile?.()
unbindConnection?.()
}
}
}
-
function focusedRosterOwner(owner) {
const name = String(owner?.profile || owner?.name || '').trim()
-
if (!owner || !name) {
return null
}
-
return {
authoritative: owner.authoritative !== false,
connectionId: String(owner.connectionId || '').trim(),
@@ -465,19 +451,27 @@ const $groupClarify = atom({})
// name — stale events under the old key simply have no room to attach to).
const GROUP_ACTIVITY_LIMIT = 50
const $groupActivity = atom({})
-
function recordGroupActivity(group, event) {
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 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(), [group]: { ...current, events } })
-
+ $groupActivity.set({
+ ...$groupActivity.get(),
+ [group]: {
+ ...current,
+ events
+ }
+ })
return entry
}
@@ -493,16 +487,12 @@ function currentGroupActivity(group) {
function groupActivityLabel(event) {
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 = {
queued: 'sent a message',
working: 'is working…',
@@ -517,7 +507,6 @@ const GROUP_ACTIVITY_LABELS = {
held: 'is held (stopped by you) — @mention it or say resume to release',
stopped: 'stopped the room — remaining turns are held until resumed'
}
-
const GROUP_ACTIVITY_GLYPHS = {
queued: 'comment',
working: 'sync',
@@ -539,14 +528,11 @@ function groupActivityTone(kind) {
if (kind === 'failed' || kind === 'timed-out') {
return 'text-destructive'
}
-
if (kind === 'working' || kind === 'replied' || kind === 'delivered') {
return 'text-(--ui-accent,#4f9cf9)'
}
-
return 'text-(--ui-text-tertiary)'
}
-
const GROUP_CHAT_SYNC_META_KEY = 'hermes-bots-groups'
// Gateway ui_meta is capped after Python JSON serialization. Keep a healthy
// margin below that limit because Python escapes Unicode while JS does not.
@@ -570,10 +556,8 @@ let groupChatSyncDisposed = false
function groupChatGatewayJsonSize(value) {
const json = JSON.stringify(value)
let bytes = 0
-
for (const character of json) {
const codePoint = character.codePointAt(0)
-
if (codePoint <= 0x7f) {
bytes += 1
if (character === ',' || character === ':') {
@@ -583,7 +567,6 @@ function groupChatGatewayJsonSize(value) {
bytes += codePoint <= 0xffff ? 6 : 12
}
}
-
return bytes
}
@@ -594,16 +577,18 @@ function groupChatGatewayJsonSize(value) {
* rooms (no roomId) fall back to `name:<name>` keys with the older
* revision-gated tombstone semantics. */
function groupChatRoomKey(name, room) {
- return typeof room?.roomId === 'string' && room.roomId
- ? `id:${room.roomId}`
- : `name:${String(name)}`
+ return typeof room?.roomId === 'string' && room.roomId ? `id:${room.roomId}` : `name:${String(name)}`
}
/** Lift any historical projection shape (v1 wall-clock, v2 name-keyed) to
* the v3 room-key shape so one merge path serves mixed-version fleets. */
function normalizeGroupChatSyncSnapshot(snapshot) {
if (!snapshot || typeof snapshot !== 'object') {
- return { version: 3, rooms: {}, deleted: {} }
+ return {
+ version: 3,
+ rooms: {},
+ deleted: {}
+ }
}
if (Number(snapshot.version || 0) >= 3) {
return {
@@ -618,7 +603,10 @@ function normalizeGroupChatSyncSnapshot(snapshot) {
if (!room || !Array.isArray(room.log)) {
continue
}
- rooms[`name:${name}`] = { ...room, name }
+ rooms[`name:${name}`] = {
+ ...room,
+ name
+ }
}
const deleted = {}
for (const [name, at] of Object.entries(snapshot.deleted || {})) {
@@ -627,7 +615,12 @@ function normalizeGroupChatSyncSnapshot(snapshot) {
// 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), rooms, deleted }
+ return {
+ version: 3,
+ updatedAt: Number(snapshot.updatedAt || 0),
+ rooms,
+ deleted
+ }
}
/** Compact, display-oriented copy of Desktop's room log for gateway clients.
@@ -654,39 +647,79 @@ function groupChatSyncSnapshot(all = $groupChats.get(), deleted = {}) {
version: 3,
updatedAt: Date.now(),
rooms,
- ...(Object.keys(boundedDeleted).length ? { deleted: boundedDeleted } : {})
+ ...(Object.keys(boundedDeleted).length
+ ? {
+ deleted: boundedDeleted
+ }
+ : {})
}
-
for (const [name, room] of ranked) {
const log = room.log.slice(-GROUP_CHAT_SYNC_MESSAGES).map(entry => ({
- ...(entry?.id ? { id: String(entry.id).slice(0, 160) } : {}),
+ ...(entry?.id
+ ? {
+ id: String(entry.id).slice(0, 160)
+ }
+ : {}),
from: {
kind: entry?.from?.kind === 'member' ? 'member' : 'user',
name: String(entry?.from?.name || (entry?.from?.kind === 'member' ? 'Bot' : 'You')).slice(0, 128),
- ...(entry?.from?.source ? { source: String(entry.from.source).slice(0, 128) } : {})
+ ...(entry?.from?.source
+ ? {
+ source: String(entry.from.source).slice(0, 128)
+ }
+ : {})
},
text: String(entry?.text || '').slice(0, GROUP_CHAT_SYNC_TEXT_CHARS),
at: Number(entry?.at || 0),
- ...(entry?.thread ? { thread: String(entry.thread).slice(0, 128) } : {})
+ ...(entry?.thread
+ ? {
+ thread: String(entry.thread).slice(0, 128)
+ }
+ : {})
}))
const compact = {
name: String(name).slice(0, 64),
- ...(typeof room?.roomId === 'string' && room.roomId ? { roomId: String(room.roomId).slice(0, 128) } : {}),
+ ...(typeof room?.roomId === 'string' && room.roomId
+ ? {
+ roomId: String(room.roomId).slice(0, 128)
+ }
+ : {}),
log,
revision: Math.max(0, Number(room?.syncRevision ?? room?.revision ?? 0)),
members: (Array.isArray(room.members) ? room.members : []).slice(0, GROUP_CHAT_MAX_MEMBERS).map(member => ({
name: String(member?.name || '').slice(0, 128),
- ...(member?.handle ? { handle: String(member.handle).slice(0, 128) } : {}),
- ...(member?.connectionId ? { connectionId: String(member.connectionId).slice(0, 128) } : {}),
- ...(member?.connectionKind ? { connectionKind: String(member.connectionKind).slice(0, 64) } : {}),
- ...(member?.connectionLabel ? { connectionLabel: String(member.connectionLabel).slice(0, 128) } : {}),
- ...(member?.sourceScoped ? { sourceScoped: true } : {})
+ ...(member?.handle
+ ? {
+ handle: String(member.handle).slice(0, 128)
+ }
+ : {}),
+ ...(member?.connectionId
+ ? {
+ connectionId: String(member.connectionId).slice(0, 128)
+ }
+ : {}),
+ ...(member?.connectionKind
+ ? {
+ connectionKind: String(member.connectionKind).slice(0, 64)
+ }
+ : {}),
+ ...(member?.connectionLabel
+ ? {
+ connectionLabel: String(member.connectionLabel).slice(0, 128)
+ }
+ : {}),
+ ...(member?.sourceScoped
+ ? {
+ sourceScoped: true
+ }
+ : {})
})),
...(typeof room?.image === 'string' && room.image.length <= GROUP_CHAT_SYNC_IMAGE_CHARS
- ? { image: room.image }
+ ? {
+ image: room.image
+ }
: {})
}
-
const key = groupChatRoomKey(name, room)
rooms[key] = compact
while (compact.log.length > 1 && groupChatGatewayJsonSize(envelope) > GROUP_CHAT_SYNC_MAX_BYTES) {
@@ -699,10 +732,8 @@ function groupChatSyncSnapshot(all = $groupChats.get(), deleted = {}) {
delete rooms[key]
}
}
-
return envelope
}
-
function groupChatSyncEntryKey(entry) {
if (entry?.id) {
return `id:${String(entry.id)}`
@@ -723,7 +754,6 @@ function groupChatSyncEntryKey(entry) {
String(entry?.text || '')
])
}
-
function groupChatSyncMemberKey(member) {
return JSON.stringify([
String(member?.source || ''),
@@ -733,7 +763,6 @@ function groupChatSyncMemberKey(member) {
String(member?.name || '')
])
}
-
function groupChatSyncDeletedRevision(source, value) {
return Number(source?.version || 0) >= 2 ? Math.max(0, Number(value || 0)) : 0
}
@@ -745,11 +774,7 @@ function groupChatSyncDeletedRevision(source, value) {
* 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(
- remote,
- local,
- { changedRooms = [], deletedRooms = [], writeRevision = 0 } = {}
-) {
+function mergeGroupChatSyncSnapshots(remote, local, { changedRooms = [], deletedRooms = [], writeRevision = 0 } = {}) {
const remoteNorm = normalizeGroupChatSyncSnapshot(remote)
const localNorm = normalizeGroupChatSyncSnapshot(local)
const keysFor = (label, norm) => {
@@ -791,7 +816,6 @@ function mergeGroupChatSyncSnapshots(
deleted[key] = Math.max(Number(deleted[key] || 0), Number(writeRevision || 0))
}
}
-
const rooms = {}
const roomKeys = new Set([...Object.keys(remoteNorm.rooms || {}), ...Object.keys(localNorm.rooms || {})])
for (const key of roomKeys) {
@@ -832,9 +856,15 @@ function mergeGroupChatSyncSnapshots(
image = Object.prototype.hasOwnProperty.call(localRoom || {}, 'image') ? localRoom.image : remoteRoom?.image
}
rooms[key] = {
- ...(identity?.name ? { name: identity.name } : {}),
+ ...(identity?.name
+ ? {
+ name: identity.name
+ }
+ : {}),
...(identity?.roomId || (key.startsWith('id:') ? key.slice(3) : '')
- ? { roomId: identity?.roomId || key.slice(3) }
+ ? {
+ roomId: identity?.roomId || key.slice(3)
+ }
: {}),
log: [...entries.values()].sort((left, right) => {
const byTime = Number(left?.at || 0) - Number(right?.at || 0)
@@ -842,10 +872,13 @@ function mergeGroupChatSyncSnapshots(
}),
members,
revision: Math.max(remoteRevision, localRevision),
- ...(typeof image === 'string' && image ? { image } : {})
+ ...(typeof image === 'string' && image
+ ? {
+ image
+ }
+ : {})
}
}
-
for (const [key, deletedRevision] of Object.entries(deleted)) {
if (key.startsWith('id:')) {
// Tombstones for id-keyed rooms are FINAL: the roomId is minted once
@@ -860,7 +893,6 @@ function mergeGroupChatSyncSnapshots(
delete deleted[key]
}
}
-
return groupChatSyncEnvelope(rooms, deleted)
}
@@ -875,7 +907,11 @@ function groupChatSyncEnvelope(rooms, deleted = {}) {
version: 3,
updatedAt: Date.now(),
rooms,
- ...(Object.keys(boundedDeleted).length ? { deleted: boundedDeleted } : {})
+ ...(Object.keys(boundedDeleted).length
+ ? {
+ deleted: boundedDeleted
+ }
+ : {})
}
const ranked = Object.entries(rooms).sort(([, left], [, right]) => {
const leftAt = Number(left?.log?.[left.log.length - 1]?.at || 0)
@@ -906,7 +942,9 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
{ preserveRooms = [], deletedRooms = [] } = {}
) {
const remoteNorm = normalizeGroupChatSyncSnapshot(remote)
- const rooms = { ...(current || {}) }
+ const rooms = {
+ ...(current || {})
+ }
const preserved = new Set(preserveRooms)
const locallyDeleted = new Set(deletedRooms)
@@ -918,15 +956,17 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
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 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
@@ -951,7 +991,6 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
const members = new Map(
(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
@@ -968,10 +1007,12 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
members.clear()
}
for (const member of Array.isArray(projected.members) ? projected.members : []) {
- members.set(groupChatSyncMemberKey(member), { ...member, remoteSource: true })
+ members.set(groupChatSyncMemberKey(member), {
+ ...member,
+ remoteSource: true
+ })
}
}
-
const log = assignLegacyThreads(
[...entries.values()].sort((left, right) => {
const byTime = Number(left?.at || 0) - Number(right?.at || 0)
@@ -983,11 +1024,10 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
// 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)
+ const targetName = !isPreserved && remoteRevision > localRevision ? displayName : localName || displayName
if (localName && targetName !== localName) {
delete rooms[localName]
}
-
rooms[targetName] = {
...existing,
log: bounded.log,
@@ -995,7 +1035,11 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
sessions: existing.sessions && typeof existing.sessions === 'object' ? existing.sessions : {},
stranded: existing.stranded && typeof existing.stranded === 'object' ? existing.stranded : {},
members: [...members.values()],
- ...(projectedRoomId || existing.roomId ? { roomId: existing.roomId || projectedRoomId } : {}),
+ ...(projectedRoomId || existing.roomId
+ ? {
+ roomId: existing.roomId || projectedRoomId
+ }
+ : {}),
image: isPreserved
? existing.image || null
: remoteRevision >= localRevision && Object.prototype.hasOwnProperty.call(projected, 'image')
@@ -1006,12 +1050,14 @@ 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
+ const targetName =
+ deletedRoomId && localByRoomId.has(deletedRoomId)
+ ? localByRoomId.get(deletedRoomId)
+ : key.startsWith('name:')
+ ? key.slice(5)
+ : null
if (!targetName || preserved.has(targetName)) {
continue
}
@@ -1029,13 +1075,10 @@ function mergeRemoteGroupChatSnapshotIntoRooms(
for (const name of locallyDeleted) {
delete rooms[name]
}
-
return rooms
}
-
function durableGroupChatRooms(all = $groupChats.get()) {
const durable = {}
-
for (const [name, room] of Object.entries(all || {})) {
if (!room || !Array.isArray(room.log)) {
continue
@@ -1063,10 +1106,8 @@ function durableGroupChatRooms(all = $groupChats.get()) {
syncRevision: Math.max(0, Number(room.syncRevision || 0))
}
}
-
return durable
}
-
function persistGroupChatRooms(all = $groupChats.get()) {
try {
return Promise.resolve(pluginCtx?.storage?.set?.('group-chats', durableGroupChatRooms(all))).catch(() => undefined)
@@ -1095,18 +1136,12 @@ function markOrphanedGroupMemberDescriptor(member) {
sourceReachable: false
}
}
-
function groupMemberReferencesConnection(member, connectionId) {
const id = String(connectionId || '').trim()
-
if (!id) {
return false
}
-
- return (
- String(member?.connectionId || '').trim() === id ||
- String(member?.route?.connectionId || '').trim() === id
- )
+ return String(member?.connectionId || '').trim() === id || String(member?.route?.connectionId || '').trim() === id
}
/** Register-removed sweep: annotate (not delete) every persisted group-chat
@@ -1116,20 +1151,15 @@ function groupMemberReferencesConnection(member, connectionId) {
* Returns whether anything changed. */
function sweepGroupChatMembersForRemovedConnection(connectionId) {
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 => ({
...current,
@@ -1138,7 +1168,6 @@ function sweepGroupChatMembersForRemovedConnection(connectionId) {
)
}))
}
-
return changed
}
@@ -1157,43 +1186,37 @@ function annotateOrphanedGroupChatMembers(rooms, liveConnectionIds = null) {
const live = liveConnectionIds && typeof liveConnectionIds.has === 'function' ? liveConnectionIds : null
const next = {}
let changed = false
-
for (const [name, room] of Object.entries(rooms || {})) {
const members = Array.isArray(room?.members) ? room.members : []
const orphaned = member => {
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 }
+ return {
+ rooms: next,
+ changed
+ }
}
-
function groupChatSyncConnectionId() {
return String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || '')
}
@@ -1208,21 +1231,20 @@ async function groupChatSyncRequest(job, method, params) {
const profile = String(candidate?.targetProfile || candidate?.profile || '')
return String(candidate?.connectionId || '') === job.connectionId && profile === 'default'
})
-
if (route) {
return host.requestProfile(route, method, params)
}
}
-
const currentConnectionId = groupChatSyncConnectionId()
if (job.connectionId && currentConnectionId && job.connectionId !== currentConnectionId) {
throw new Error('Group chat gateway changed before sync')
}
return host.request(method, params)
}
-
async function groupChatRemoteSnapshot(job) {
- const result = await groupChatSyncRequest(job, 'profiles.list', { include_sessions: false })
+ const result = await groupChatSyncRequest(job, 'profiles.list', {
+ include_sessions: false
+ })
const profile = (Array.isArray(result?.profiles) ? result.profiles : []).find(row => row?.name === 'default')
const snapshot = profile?.ui_meta?.[GROUP_CHAT_SYNC_META_KEY]
const supportsCas = Boolean(profile && Object.prototype.hasOwnProperty.call(profile, 'ui_meta_revisions'))
@@ -1236,8 +1258,9 @@ async function groupChatRemoteSnapshot(job) {
/** Pull the shared room projection into this Desktop before it publishes any
* local state. This is the receive half of the client-only sync contract. */
async function pullGroupChatServerState(connectionId = groupChatSyncConnectionId()) {
- const { snapshot: remote } = await groupChatRemoteSnapshot({ connectionId })
-
+ const { snapshot: remote } = await groupChatRemoteSnapshot({
+ connectionId
+ })
if (!remote) {
return false
}
@@ -1250,12 +1273,10 @@ async function pullGroupChatServerState(connectionId = groupChatSyncConnectionId
await persistGroupChatRooms(merged)
return true
}
-
function groupChatSyncBackoff(connectionId) {
const count = Number(groupChatSyncRetryCounts.get(connectionId) || 0)
return Math.min(30000, 1000 * 2 ** Math.min(count, 5))
}
-
function mergeGroupChatSyncJobs(existing, incoming) {
if (!existing || existing.connectionId !== incoming.connectionId) {
return incoming
@@ -1267,7 +1288,6 @@ function mergeGroupChatSyncJobs(existing, incoming) {
deletedRooms: [...new Set([...(existing.deletedRooms || []), ...(incoming.deletedRooms || [])])]
}
}
-
function groupChatSyncPayloadEqual(left, right) {
return (
JSON.stringify(left?.rooms || {}) === JSON.stringify(right?.rooms || {}) &&
@@ -1300,7 +1320,6 @@ async function groupChatSyncTargetConnections() {
}
return [...targets]
}
-
async function flushGroupChatServerSync(connectionId) {
if (connectionId === undefined) {
// Drain every connection with pending work.
@@ -1316,7 +1335,6 @@ async function flushGroupChatServerSync(connectionId) {
const job = groupChatSyncPendingByConnection.get(id)
groupChatSyncPendingByConnection.delete(id)
groupChatSyncInFlightConnections.add(id)
-
try {
const remoteState = await groupChatRemoteSnapshot(job)
const local = groupChatSyncSnapshot($groupChats.get())
@@ -1330,7 +1348,11 @@ async function flushGroupChatServerSync(connectionId) {
// Reconnect/startup reconciliation often discovers that the gateway
// already holds the exact merged projection. Avoid advancing a revision
// merely because a view reopened.
- if (!(job.changedRooms || []).length && !(job.deletedRooms || []).length && groupChatSyncPayloadEqual(snapshot, remoteState.snapshot)) {
+ if (
+ !(job.changedRooms || []).length &&
+ !(job.deletedRooms || []).length &&
+ groupChatSyncPayloadEqual(snapshot, remoteState.snapshot)
+ ) {
if (remoteState.snapshot) {
const pending = groupChatSyncPendingByConnection.get(id)
const mergedRooms = mergeRemoteGroupChatSnapshotIntoRooms(remoteState.snapshot, $groupChats.get(), {
@@ -1343,16 +1365,18 @@ async function flushGroupChatServerSync(connectionId) {
groupChatSyncRetryCounts.delete(id)
return
}
-
const configureParams = {
name: 'default',
- ui_meta: { [GROUP_CHAT_SYNC_META_KEY]: snapshot }
+ ui_meta: {
+ [GROUP_CHAT_SYNC_META_KEY]: snapshot
+ }
}
if (remoteState.supportsCas) {
- configureParams.ui_meta_expected_revisions = { [GROUP_CHAT_SYNC_META_KEY]: remoteState.revision }
+ configureParams.ui_meta_expected_revisions = {
+ [GROUP_CHAT_SYNC_META_KEY]: remoteState.revision
+ }
}
const result = await groupChatSyncRequest(job, 'profiles.configure', configureParams)
-
if (result?.applied?.ui_meta !== true) {
throw new Error('Gateway rejected group chat ui_meta')
}
@@ -1362,7 +1386,6 @@ async function flushGroupChatServerSync(connectionId) {
) {
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')
@@ -1391,10 +1414,13 @@ async function flushGroupChatServerSync(connectionId) {
groupChatSyncPendingByConnection.set(id, mergeGroupChatSyncJobs(groupChatSyncPendingByConnection.get(id), job))
groupChatSyncRetryCounts.set(id, retries)
if (typeof setTimeout === 'function' && !groupChatSyncRetryTimers.has(id)) {
- groupChatSyncRetryTimers.set(id, setTimeout(() => {
- groupChatSyncRetryTimers.delete(id)
- void flushGroupChatServerSync(id)
- }, groupChatSyncBackoff(id)))
+ groupChatSyncRetryTimers.set(
+ id,
+ setTimeout(() => {
+ groupChatSyncRetryTimers.delete(id)
+ void flushGroupChatServerSync(id)
+ }, groupChatSyncBackoff(id))
+ )
}
}
} finally {
@@ -1404,7 +1430,6 @@ async function flushGroupChatServerSync(connectionId) {
}
}
}
-
function stopGroupChatServerSync() {
groupChatSyncDisposed = true
groupChatSyncPendingByConnection.clear()
@@ -1454,12 +1479,15 @@ function scheduleGroupChatServerSync(
clearTimeout(retryTimer)
groupChatSyncRetryTimers.delete(id)
}
- groupChatSyncPendingByConnection.set(id, mergeGroupChatSyncJobs(groupChatSyncPendingByConnection.get(id), {
- connectionId: id,
- allowEmpty,
- changedRooms,
- deletedRooms
- }))
+ groupChatSyncPendingByConnection.set(
+ id,
+ mergeGroupChatSyncJobs(groupChatSyncPendingByConnection.get(id), {
+ connectionId: id,
+ allowEmpty,
+ changedRooms,
+ deletedRooms
+ })
+ )
}
queueFor(activeId)
groupChatSyncTimer = setTimeout(() => {
@@ -1476,16 +1504,19 @@ function scheduleGroupChatServerSync(
.then(() => flushGroupChatServerSync())
}, 350)
}
-
function handleSessionsGatewayTransition() {
// A gateway swap invalidates any in-flight room drive: bump every room's
// epoch so running loops bail at their next member boundary.
- const rooms = { ...$groupChats.get() }
-
+ const rooms = {
+ ...$groupChats.get()
+ }
for (const name of Object.keys(rooms)) {
- rooms[name] = { ...rooms[name], epoch: (rooms[name].epoch || 0) + 1, running: false }
+ rooms[name] = {
+ ...rooms[name],
+ epoch: (rooms[name].epoch || 0) + 1,
+ 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.
@@ -1546,9 +1577,7 @@ function syncRelayRetention(connections) {
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)
@@ -1559,11 +1588,9 @@ function syncRelayRetention(connections) {
}
}
}
-
if (relayDisposed) {
return
}
-
for (const connection of connections) {
if (!relayRouteRetentions.has(connection.id)) {
relayRouteRetentions.set(connection.id, host.retainProfileSocket(connection.route))
@@ -1580,7 +1607,6 @@ function releaseRelayRetention() {
// Disposer from an older shell shape — never break teardown.
}
}
-
relayRouteRetentions.clear()
}
@@ -1589,20 +1615,19 @@ async function relayConnections() {
if (typeof host.profileRoutes !== 'function' || typeof host.requestProfile !== 'function') {
return []
}
-
try {
const routes = await host.profileRoutes()
const byConnection = new Map()
-
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 }))
+ return [...byConnection.entries()].map(([id, route]) => ({
+ id,
+ route
+ }))
} catch {
return []
}
@@ -1616,12 +1641,11 @@ async function relayConnections() {
* definitively offline → false runtime_offline refusals (#93091 item 2). */
async function relayAgentsOn(connection) {
try {
- const res = await host.requestProfile(connection.route, 'profiles.list', { include_sessions: false })
+ const res = await host.requestProfile(connection.route, 'profiles.list', {
+ include_sessions: false
+ })
const profiles = Array.isArray(res?.profiles) ? res.profiles : []
- const label = String(
- connection.route?.connectionLabel || connection.route?.label || connection.id
- )
-
+ const label = String(connection.route?.connectionLabel || connection.route?.label || connection.id)
return profiles
.map(profile => ({
profile: String(profile?.name || ''),
@@ -1646,21 +1670,16 @@ async function syncRelayRosters() {
if (relayDisposed || relayRosterBusy) {
return
}
-
relayRosterBusy = true
-
try {
const connections = await relayConnections()
-
if (connections.length < 2) {
return
}
-
const agentsByConnection = new Map()
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
@@ -1682,19 +1701,18 @@ async function syncRelayRosters() {
relayAgentsCache.delete(id)
}
}
-
await Promise.all(
connections.map(async connection => {
const others = []
-
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 })
+ await host.requestProfile(connection.route, 'bot_relay.roster.sync', {
+ agents: others
+ })
} catch {
// Older backend without the relay RPCs — skip this connection.
}
@@ -1712,76 +1730,70 @@ 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 = []
-
try {
const res = await host.requestProfile(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 => {
try {
- await host.requestProfile(sender.route, 'bot_relay.reply', { id: envelopeId, ...payload })
+ await host.requestProfile(sender.route, 'bot_relay.reply', {
+ id: envelopeId,
+ ...payload
+ })
} catch {
// 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` })
+ 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(target.route, 'bot_relay.deliver', {
profile: String(envelope?.target_profile || ''),
message: String(envelope?.message || '')
})
clearBotAttention(attentionKey)
- await postReply({ reply: String(res?.reply || '') })
+ await postReply({
+ reply: String(res?.reply || '')
+ })
} catch (error) {
// #93091: bot_relay.deliver classifies the failed turn and ships the
// typed code in the JSON-RPC error's `data.reason`; forward it into
@@ -1792,14 +1804,17 @@ async function drainRelayOutboxes() {
noteBotAttention(attentionKey, reason || error?.message || error)
await postReply({
error: String(error?.message || error || 'delivery failed'),
- ...(reason ? { reason } : {})
+ ...(reason
+ ? {
+ reason
+ }
+ : {})
})
}
}
}
} finally {
relayDrainBusy = false
-
if (relayDrainRerun && !relayDisposed) {
// Envelopes signaled mid-drain: schedule one follow-up pass (debounced)
// instead of leaving them to the interval poll.
@@ -1815,17 +1830,14 @@ function scheduleRelayPushDrain() {
if (relayDisposed || typeof setTimeout !== 'function') {
return
}
-
if (relayPushDebounceTimer !== null) {
return
}
-
relayPushDebounceTimer = setTimeout(() => {
relayPushDebounceTimer = null
void drainRelayOutboxes()
}, RELAY_PUSH_DEBOUNCE_MS)
}
-
function startBotRelay() {
relayDisposed = false
@@ -1834,12 +1846,10 @@ 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)
}
@@ -1852,7 +1862,6 @@ function startBotRelay() {
relayPushUnsub = host.onEvent('bot_relay.outbox.pending', () => scheduleRelayPushDrain())
}
}
-
function stopBotRelay() {
relayDisposed = true
// A rerun remembered mid-drain must not leak into the next start —
@@ -1861,22 +1870,18 @@ 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()
@@ -1890,24 +1895,20 @@ function stopBotRelay() {
/** Per-bot appearance + display meta, persisted via ctx.storage:
* { [botName]: { shape, color, title } } */
const $botMeta = atom({})
-
function commitBotMetaV2(storage, snapshot) {
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 &&
+ 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)
@@ -1918,65 +1919,72 @@ function commitBotMetaV2(storage, snapshot) {
await storage.set(BOT_META_V2_KEY, previousSnapshot)
await storage.set(BOT_META_MIGRATION_KEY, true)
} catch {
- await Promise.allSettled([
- storage.remove(BOT_META_MIGRATION_KEY),
- storage.remove(BOT_META_V2_KEY)
- ])
+ await Promise.allSettled([storage.remove(BOT_META_MIGRATION_KEY), storage.remove(BOT_META_V2_KEY)])
}
} else {
- await Promise.allSettled(
- [BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key))
- )
+ await Promise.allSettled([BOT_META_MIGRATION_KEY, BOT_META_V2_KEY].map(key => storage.remove(key)))
}
throw error
}
})
-
botMetaV2Commit = commit.catch(() => undefined)
-
return commit
}
-
function botOwner(owner) {
if (typeof owner === 'string') {
const name = owner.trim()
const route = migratedLocalRoutes.get(name)
-
return {
- bot: route ? { name, sourceScoped: true, route } : { name },
+ bot: route
+ ? {
+ name,
+ sourceScoped: true,
+ route
+ }
+ : {
+ name
+ },
name,
key: route ? botRouteKey(route) : name,
route: route || null
}
}
-
const name = String(owner?.name || '').trim()
const route = botConnectionRoute(owner)
-
- return { bot: owner, name, key: route ? botRouteKey(route) : name, route }
+ return {
+ bot: owner,
+ name,
+ key: route ? botRouteKey(route) : name,
+ route
+ }
}
/** Freshness fence for the server-meta overlay: a roster snapshot fetched
* before the latest local/server metadata write must not overwrite it. */
const botMetaWriteAt = new Map()
-
function noteBotMetaWrite(key) {
botMetaWriteAt.set(key, Date.now())
}
-
async function saveBotMeta(owner, patch) {
const { bot, key, name, route } = botOwner(owner)
const prevMeta = $botMeta.get()[key] || {}
- const next = { ...$botMeta.get(), [key]: { ...prevMeta, ...patch } }
+ const next = {
+ ...$botMeta.get(),
+ [key]: {
+ ...prevMeta,
+ ...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(pluginCtx?.storage, next)
- : Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, next))
+ const persisted =
+ route || botMetaV2Active
+ ? commitBotMetaV2(pluginCtx?.storage, next)
+ : Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, next))
localPersistence = persisted.catch(() => undefined)
} catch {
/* storage unavailable — look persists for this window only */
@@ -1993,8 +2001,19 @@ async function saveBotMeta(owner, patch) {
let serverRequest = null
try {
const { image, pet, ...rest } = next[key] || {}
- const request = route ? requestForBot(bot, 'profiles.configure', { name, ui_meta: { 'hermes-bots': rest } }) :
- host.request('profiles.configure', { name, ui_meta: { 'hermes-bots': rest } })
+ const request = route
+ ? requestForBot(bot, 'profiles.configure', {
+ name,
+ ui_meta: {
+ 'hermes-bots': rest
+ }
+ })
+ : host.request('profiles.configure', {
+ name,
+ ui_meta: {
+ 'hermes-bots': rest
+ }
+ })
serverRequest = Promise.resolve(request)
} catch {
/* older/unavailable gateway — the local fallback remains saved */
@@ -2009,12 +2028,28 @@ async function saveBotMeta(owner, patch) {
if ('image' in patch && patch.image !== (prevMeta.image ?? null)) {
try {
const req = patch.image
- ? (route
- ? requestForBot(bot, 'profiles.set_asset', { name, asset: 'avatar', data: patch.image })
- : host.request('profiles.set_asset', { name, asset: 'avatar', data: patch.image }))
- : (route
- ? requestForBot(bot, 'profiles.set_asset', { name, asset: 'avatar', clear: true })
- : host.request('profiles.set_asset', { name, asset: 'avatar', clear: true }))
+ ? route
+ ? requestForBot(bot, 'profiles.set_asset', {
+ name,
+ asset: 'avatar',
+ data: patch.image
+ })
+ : host.request('profiles.set_asset', {
+ name,
+ asset: 'avatar',
+ data: patch.image
+ })
+ : route
+ ? requestForBot(bot, 'profiles.set_asset', {
+ name,
+ asset: 'avatar',
+ clear: true
+ })
+ : host.request('profiles.set_asset', {
+ name,
+ asset: 'avatar',
+ clear: true
+ })
req.catch(() => undefined)
} catch {
/* older gateway */
@@ -2047,10 +2082,11 @@ async function saveBotMeta(owner, patch) {
// just as surely as one fetched before the local write.
noteBotMetaWrite(key)
}
-
await localPersistence
-
- return { serverPersisted: serverOutcome === 'persisted', serverOutcome }
+ return {
+ serverPersisted: serverOutcome === 'persisted',
+ serverOutcome
+ }
}
/** Migrate name-keyed appearance state only when the live registry proves
@@ -2058,23 +2094,23 @@ async function saveBotMeta(owner, patch) {
* multi-source desktop, so the conservative result there is to retain v1 as
* rollback data and leave remote rows unpainted. */
function hydrateBotMeta(snapshot, remap = null) {
- const next = { ...snapshot }
-
+ const next = {
+ ...snapshot
+ }
for (const [key, meta] of Object.entries($botMeta.get())) {
const target = remap?.get(key) || key
- next[target] = { ...(next[target] || {}), ...meta }
+ next[target] = {
+ ...(next[target] || {}),
+ ...meta
+ }
}
-
$botMeta.set(next)
-
return next
}
-
async function migrateBotMeta(storage = pluginCtx?.storage) {
let v1 = null
let v2 = null
let v2Committed = false
-
try {
;[v1, v2, v2Committed] = await Promise.all([
storage?.get?.(BOT_META_V1_KEY),
@@ -2084,54 +2120,45 @@ async function migrateBotMeta(storage = pluginCtx?.storage) {
} 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')
-
+ 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 = {}
const pendingLocalRoutes = new Map()
-
for (const [name, meta] of Object.entries(v1)) {
- const route = (routes || []).find(candidate => candidate?.mode === 'local' && candidate?.profile === name) ||
+ const route =
+ (routes || []).find(candidate => candidate?.mode === 'local' && candidate?.profile === name) ||
(() => {
const agent = localAgents.find(candidate => candidate.profile === name)
-
return agent
? {
connectionId: agent.connectionId,
@@ -2141,15 +2168,12 @@ async function migrateBotMeta(storage = pluginCtx?.storage) {
}
: 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 = {
connectionId: route.connectionId,
mode: 'local',
@@ -2159,33 +2183,30 @@ async function migrateBotMeta(storage = pluginCtx?.storage) {
migrated[botRouteKey(captured)] = meta
pendingLocalRoutes.set(name, captured)
}
-
- const remap = new Map(
- [...pendingLocalRoutes].map(([name, route]) => [name, botRouteKey(route)])
- )
- const hydrated = { ...migrated }
-
+ 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] = { ...(hydrated[target] || {}), ...meta }
+ hydrated[target] = {
+ ...(hydrated[target] || {}),
+ ...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
}
@@ -2195,11 +2216,9 @@ async function migrateBotMeta(storage = pluginCtx?.storage) {
/** Session-only view toggle: reveal hidden bots (dimmed) in the roster. */
const $showHiddenBots = atom(false)
-
function isBotHidden(bot, metaByName) {
return Boolean(botRosterMeta(bot, metaByName)?.hidden)
}
-
function isBotPinned(bot, metaByName) {
return Boolean(botRosterMeta(bot, metaByName)?.pinned)
}
@@ -2209,17 +2228,12 @@ function fallbackSelectionAfterHide(name) {
if ($selectedBot.get() !== name) {
return
}
-
const meta = $botMeta.get()
- const visible = $lastRoster
- .get()
- .filter(bot => botSelectionKey(bot) !== name && !botRosterMeta(bot, meta)?.hidden)
-
+ 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))
@@ -2245,7 +2259,6 @@ function startHideSweepScheduler(ctx) {
let inflight = null
let pending = false
let disposed = false
-
const run = () => {
timer = null
if (disposed) {
@@ -2255,7 +2268,6 @@ function startHideSweepScheduler(ctx) {
pending = true
return
}
-
inflight = Promise.resolve()
.then(() => hideOwnedBotSessions())
.catch(() => undefined)
@@ -2271,7 +2283,6 @@ function startHideSweepScheduler(ctx) {
if (disposed) {
return
}
-
try {
if (timer !== null) {
clearTimeout(timer)
@@ -2286,7 +2297,6 @@ function startHideSweepScheduler(ctx) {
schedule()
}
})
-
const teardown = () => {
disposed = true
stopGatewayListener()
@@ -2300,7 +2310,6 @@ function startHideSweepScheduler(ctx) {
}
schedule()
}
-
function hideOwnedBotSessions() {
const roomEntries = Object.values($groupChats.get()).flatMap(room =>
Object.entries(room?.sessions || {})
@@ -2308,26 +2317,33 @@ function hideOwnedBotSessions() {
if (!id || id === true) {
return null
}
-
const persisted = room?.sessionOwners?.[key]
const derived = (room?.members || []).find(member => 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 = persisted || derived || (!key.includes('::') ? { name: key } : null)
-
+ const owner =
+ persisted ||
+ derived ||
+ (!key.includes('::')
+ ? {
+ 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}`
- : ''
-
+ const routeKey = route?.connectionId && route?.profile ? `${route.connectionId}::${route.profile}` : ''
if (!sourceMarked || !route?.targetProfile || routeKey !== key) {
return null
}
}
-
- return owner ? { owner, id, dedupe: `${key}\u0000${id}` } : null
+ return owner
+ ? {
+ owner,
+ id,
+ dedupe: `${key}\u0000${id}`
+ }
+ : null
})
.filter(Boolean)
)
@@ -2335,13 +2351,7 @@ function hideOwnedBotSessions() {
// The same member session can appear in several rooms (and legacy rooms can
// 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)
- )
- )
-
+ const known = Promise.all(rooms.map(({ owner, id }) => hidePersistedBotSession(owner, id).catch(() => undefined)))
return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])
}
@@ -2352,12 +2362,16 @@ function hidePersistedBotSession(bot, sessionId, profileOverride = '') {
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, profile, hidden: true }))
+ return Promise.resolve(
+ host.setPersistedSessionHidden(route, {
+ sessionId,
+ profile,
+ hidden: true
+ })
+ )
}
// Titles Bot Mode itself mints for its plumbing sessions. Bot-to-bot CLI
@@ -2369,12 +2383,10 @@ function hidePersistedBotSession(bot, sessionId, profileOverride = '') {
// 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) {
const t = String(title || '').trim()
return BOT_MODE_SWEEP_TITLES.has(t) || t.startsWith('Group: ')
}
-
function isBotModeSweepCandidate(row, nowSeconds = Date.now() / 1000) {
const startedAt = Number(row?.started_at)
return (
@@ -2408,45 +2420,40 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {
if (typeof host.listPersistedSessions !== 'function' || typeof host.setPersistedSessionHidden !== 'function') {
return
}
-
const cached = $lastRoster.get()
let roster = 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
// sources get covered by the next sweep once the roster cache exists).
try {
- const activeBot = { name: String(host.state.profile?.get?.() || 'default').trim() || 'default' }
+ const activeBot = {
+ name: String(host.state.profile?.get?.() || 'default').trim() || 'default'
+ }
const res = await requestForBot(activeBot, 'profiles.list', {})
roster = Array.isArray(res?.profiles) ? res.profiles : []
} catch {
return
}
}
-
await Promise.all(
roster.map(async bot => {
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 res = await host.listPersistedSessions(route, {
+ profile,
+ limit: PROFILE_SESSION_LIST_LIMIT
+ })
const rows = Array.isArray(res?.sessions) ? res.sessions : []
-
await Promise.all(
rows
.filter(row => isBotModeSweepCandidate(row, nowSeconds))
- .map(row =>
- Promise.resolve(
- hidePersistedBotSession(bot, row.id, profile)
- ).catch(() => undefined)
- )
+ .map(row => Promise.resolve(hidePersistedBotSession(bot, row.id, profile)).catch(() => undefined))
)
} catch {
/* older gateway / unreachable source — leave this profile alone */
@@ -2458,7 +2465,6 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {
/** Fetch server-side avatars for roster rows flagged has_avatar when the
* local cache doesn't already have an image for them. Fire-and-forget. */
const avatarFetchInflight = new Set()
-
const avatarPushInflight = new Set()
/** Backfill: local meta has art the server lacks -> profiles.set_asset.
@@ -2467,20 +2473,29 @@ const avatarPushInflight = new Set()
function pushLocalAvatars(roster) {
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, asset: 'avatar', data: image })
- : host.request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: image })
+ ? requestForBot(bot, 'profiles.set_asset', {
+ name: bot.name,
+ asset: 'avatar',
+ data: image
+ })
+ : host.request('profiles.set_asset', {
+ name: bot.name,
+ asset: 'avatar',
+ data: image
+ })
Promise.resolve(request)
- .then(() => queryClient.invalidateQueries({ queryKey: ['hermes-bots', 'roster'] }))
+ .then(() =>
+ queryClient.invalidateQueries({
+ queryKey: ['hermes-bots', 'roster']
+ })
+ )
.catch(() => avatarPushInflight.delete(key))
continue
}
@@ -2489,19 +2504,29 @@ function pushLocalAvatars(roster) {
// 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 =>
png
? (bot.sourceScoped
- ? requestForBot(bot, 'profiles.set_asset', { name: bot.name, asset: 'avatar', data: png })
- : host.request('profiles.set_asset', { name: bot.name, asset: 'avatar', data: png }))
- .then(() => queryClient.invalidateQueries({ queryKey: ['hermes-bots', 'roster'] }))
+ ? requestForBot(bot, 'profiles.set_asset', {
+ name: bot.name,
+ asset: 'avatar',
+ data: png
+ })
+ : host.request('profiles.set_asset', {
+ name: bot.name,
+ asset: 'avatar',
+ data: png
+ })
+ ).then(() =>
+ queryClient.invalidateQueries({
+ queryKey: ['hermes-bots', 'roster']
+ })
+ )
: Promise.reject(new Error('rasterize failed'))
)
.catch(() => avatarPushInflight.delete(key))
@@ -2519,7 +2544,6 @@ function rasterizeSvgToPng(svgEl, size) {
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')
@@ -2545,7 +2569,6 @@ function isBackfilledFacePng(dataUrl) {
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) {
@@ -2558,25 +2581,26 @@ function isBackfilledFacePng(dataUrl) {
return false
}
}
-
function pullServerAvatars(roster) {
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, asset: 'avatar' })
- : host.request('profiles.get_asset', { name: bot.name, asset: 'avatar' })
+ ? requestForBot(bot, 'profiles.get_asset', {
+ name: bot.name,
+ asset: 'avatar'
+ })
+ : host.request('profiles.get_asset', {
+ name: bot.name,
+ asset: 'avatar'
+ })
Promise.resolve(assetRequest)
.then(res => {
if (res?.found && res.data) {
@@ -2587,7 +2611,13 @@ function pullServerAvatars(roster) {
if (isBackfilledFacePng(res.data) && mine.imageKind !== 'photo' && !mine.pet) {
return
}
- $botMeta.set({ ...current, [key]: { ...mine, image: res.data } })
+ $botMeta.set({
+ ...current,
+ [key]: {
+ ...mine,
+ image: res.data
+ }
+ })
persistBotMetaSnapshot($botMeta.get(), Boolean(bot.sourceScoped))
}
})
@@ -2613,8 +2643,9 @@ function pullServerAvatars(roster) {
function mergeServerMeta(roster, fetchedAt = 0) {
const local = $botMeta.get()
let changed = false
- const next = { ...local }
-
+ const next = {
+ ...local
+ }
for (const bot of roster) {
const server = bot.ui_meta?.['hermes-bots']
if (server && typeof server === 'object') {
@@ -2623,7 +2654,10 @@ function mergeServerMeta(roster, fetchedAt = 0) {
continue
}
const mine = next[key] || {}
- const merged = { ...mine, ...server }
+ const merged = {
+ ...mine,
+ ...server
+ }
// Local-only fields survive the server overlay.
if (mine.image) {
@@ -2646,21 +2680,22 @@ function mergeServerMeta(roster, fetchedAt = 0) {
) {
delete merged.group
}
-
if (JSON.stringify(next[key] || null) !== JSON.stringify(merged)) {
next[key] = merged
changed = true
}
}
}
-
if (changed) {
$botMeta.set(next)
// Persist server reconciliation so a relaunch cannot rehydrate stale
// local fields that the server intentionally removed.
try {
- persistBotMetaSnapshot(next, roster.some(bot => bot.sourceScoped))
+ persistBotMetaSnapshot(
+ next,
+ roster.some(bot => bot.sourceScoped)
+ )
} catch {
/* storage unavailable — reconciliation lasts for this window only */
}
@@ -2681,16 +2716,18 @@ async function duplicateBot(bot, roster) {
// base forever (#19).
const suffix = `-${n}`
const candidate = base.slice(0, 64 - suffix.length) + suffix
- if (!roster.some(b => b.name === candidate && (!ownerKey || botMetaKey(b)?.startsWith(`${ownerRoute.connectionId}::`)))) {
+ if (
+ !roster.some(
+ b => b.name === candidate && (!ownerKey || botMetaKey(b)?.startsWith(`${ownerRoute.connectionId}::`))
+ )
+ ) {
name = candidate
break
}
}
-
if (!name) {
throw new Error('No free name for the duplicate.')
}
-
await requestForBot(bot, 'profiles.create', {
name,
clone_from: base,
@@ -2703,12 +2740,19 @@ async function duplicateBot(bot, roster) {
const meta = $botMeta.get()[botMetaKey(bot)]
if (meta) {
const { chat, created, ...look } = meta
- await saveBotMeta({ ...bot, name, route: ownerRoute, sourceScoped: Boolean(ownerRoute) }, {
- ...look,
- title: meta.title ? `${meta.title} (copy)` : ''
- })
+ await saveBotMeta(
+ {
+ ...bot,
+ name,
+ route: ownerRoute,
+ sourceScoped: Boolean(ownerRoute)
+ },
+ {
+ ...look,
+ title: meta.title ? `${meta.title} (copy)` : ''
+ }
+ )
}
-
return name
}
@@ -2725,11 +2769,9 @@ async function duplicateBot(bot, roster) {
* directory (hermes-agent#52279). That is the "can't delete a bot" error. */
async function deleteBot(bot) {
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)
@@ -2741,20 +2783,18 @@ async function deleteBot(bot) {
if (route) {
throw new Error('Source-scoped profile deletion requires host.deleteProfile.')
}
-
const result = 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() }
+ const meta = {
+ ...$botMeta.get()
+ }
delete meta[botMetaKey(bot)]
$botMeta.set(meta)
-
try {
if (route) {
await commitBotMetaV2(pluginCtx?.storage, meta)
@@ -2764,31 +2804,29 @@ async function deleteBot(bot) {
} catch {
/* profile is deleted; stale local appearance is harmless if storage fails */
}
-
- const unread = { ...$botUnread.get() }
+ const unread = {
+ ...$botUnread.get()
+ }
delete unread[botSelectionKey(bot)]
$botUnread.set(unread)
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)
syncBotsHomeWorkspace()
}
-
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
-
+ 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')
}
@@ -2820,7 +2858,6 @@ if (typeof document !== 'undefined' && !document.getElementById('hermes-bots-ros
'.hermes-bots-pulse { animation: hermes-bots-pulse 1.2s ease-in-out infinite; }'
document.head.appendChild(style)
}
-
const AVATAR_SHAPES = ['circle', 'squircle', 'pill', 'triangle', 'hexagon', 'cloud', 'drop']
const AVATAR_PICKER_SHAPES = ['circle', 'blob', 'squircle', 'pill', 'triangle', 'hexagon', 'cloud', 'drop']
@@ -2851,13 +2888,11 @@ function sigilGeometry(name, seed) {
const gy = j => 8 + j * 6 // 5 rows: 8..32
const strokes = []
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)
const x2 = Math.min(2, Math.max(0, x1 + (rng() > 0.5 ? 1 : -1)))
const y2 = Math.min(4, Math.max(0, y1 + Math.floor(rng() * 3) - 1))
-
strokes.push(`M${gx(x1)} ${gy(y1)} L${gx(x2)} ${gy(y2)}`)
// mirror (col i → col 4-i)
strokes.push(`M${gx(4 - x1)} ${gy(y1)} L${gx(4 - x2)} ${gy(y2)}`)
@@ -2870,21 +2905,31 @@ function sigilGeometry(name, seed) {
// 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 }
+ return {
+ strokes: strokes.join(' '),
+ ring
+ }
}
-
const AVATAR_COLORS = [
- '#f5f5f4', // white
- '#8d6748', // brown
- '#ef4444', // red
- '#f97316', // orange
- '#14b8a6', // teal
- '#38bdf8', // cyan
- '#3b40c8', // royal blue
- '#8b5cf6', // violet
- '#ec4899', // magenta
+ '#f5f5f4',
+ // white
+ '#8d6748',
+ // brown
+ '#ef4444',
+ // red
+ '#f97316',
+ // orange
+ '#14b8a6',
+ // teal
+ '#38bdf8',
+ // cyan
+ '#3b40c8',
+ // royal blue
+ '#8b5cf6',
+ // violet
+ '#ec4899',
+ // magenta
'#9ca3af' // silver
]
@@ -2900,7 +2945,6 @@ function isDarkColor(hex) {
return false
}
}
-
function defaultShapeFor(name) {
let hash = 0
for (const ch of name) {
@@ -2926,21 +2970,30 @@ const BLOB_KINDS = ['round', 'organic', 'boxy', 'capsule', 'nub', 'cloud', 'drop
// frozen per blobatar major (gen2: 0.22 / 0.48 / 0.60 / 0.70 / 0.79 / 0.86 /
// 0.915 / 0.95 / 0.98).
const BLOB_KIND_TRAIT = {
- round: 0.11, organic: 0.35, boxy: 0.54, capsule: 0.65, nub: 0.745,
- cloud: 0.825, droplet: 0.8875, hexagon: 0.9325, sun: 0.965, triangle: 0.99
+ round: 0.11,
+ organic: 0.35,
+ boxy: 0.54,
+ capsule: 0.65,
+ nub: 0.745,
+ cloud: 0.825,
+ droplet: 0.8875,
+ hexagon: 0.9325,
+ sun: 0.965,
+ triangle: 0.99
}
-
function isBlobShape(shape) {
return shape === 'blobatar' || (typeof shape === 'string' && shape.startsWith('blobatar:'))
}
-
function parseBlobShape(shape, name) {
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 }
+ return {
+ seed: seedPart || name || 'agent',
+ seedPart,
+ kind
+ }
}
-
function blobShapeString(seedPart, kind) {
if (kind) {
return `blobatar:${seedPart}:${kind}`
@@ -2954,14 +3007,15 @@ function blobMarkup(shape, name, size) {
if (!blobatarSvg) {
return null
}
-
const { seed, kind } = parseBlobShape(shape, name)
- const opts = { size }
-
+ const opts = {
+ size
+ }
if (kind) {
- opts.traits = { shape: BLOB_KIND_TRAIT[kind] }
+ opts.traits = {
+ shape: BLOB_KIND_TRAIT[kind]
+ }
}
-
try {
return blobatarSvg(seed, opts).replace('<svg ', '<svg data-bot-face=' + JSON.stringify(name) + ' ')
} catch {
@@ -2976,93 +3030,111 @@ function shapeNode(shape, color, botName = 'agent') {
if (shape.startsWith('sigil-')) {
const seed = Number(shape.slice(6)) || 0
const { strokes, ring } = sigilGeometry(botName, seed)
- const sw = { fill: 'none', stroke: color, strokeWidth: 2.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
- return jsxs('g', {
- children: [
- ring ? jsx('path', { d: ring, fill: 'none', stroke: color, strokeWidth: 1.2, opacity: 0.5 }) : null,
- jsx('path', { d: strokes, ...sw })
- ]
- })
+ const sw = {
+ fill: 'none',
+ stroke: color,
+ strokeWidth: 2.2,
+ strokeLinecap: 'round',
+ strokeLinejoin: 'round'
+ }
+ return (
+ <g>
+ {ring ? <path d={ring} fill="none" stroke={color} strokeWidth={1.2} opacity={0.5} /> : null}
+ <path d={strokes} {...sw} />
+ </g>
+ )
+ }
+ const stroke = {
+ fill: color,
+ stroke: color,
+ strokeWidth: 7,
+ strokeLinejoin: 'round'
+ }
+ const edge = {
+ fill: 'none',
+ stroke: 'rgba(0,0,0,0.4)',
+ strokeWidth: 1.4,
+ strokeLinejoin: 'round',
+ strokeLinecap: 'round'
+ }
+ const face = {
+ fill: color,
+ stroke: 'rgba(0,0,0,0.4)',
+ strokeWidth: 1.4,
+ strokeLinejoin: 'round'
}
-
- const stroke = { fill: color, stroke: color, strokeWidth: 7, strokeLinejoin: 'round' }
- const edge = { fill: 'none', stroke: 'rgba(0,0,0,0.4)', strokeWidth: 1.4, strokeLinejoin: 'round', strokeLinecap: 'round' }
- const face = { fill: color, stroke: 'rgba(0,0,0,0.4)', strokeWidth: 1.4, strokeLinejoin: 'round' }
-
switch (shape) {
// ── platonic solids ──
case 'tetrahedron':
- return jsxs('g', {
- children: [
- jsx('path', { d: 'M20 5 L36 33 L4 33 Z', ...face }),
- jsx('path', { d: 'M20 5 L20 25 M4 33 L20 25 M36 33 L20 25', ...edge })
- ]
- })
+ return (
+ <g>
+ <path d="M20 5 L36 33 L4 33 Z" {...face} />
+ <path d="M20 5 L20 25 M4 33 L20 25 M36 33 L20 25" {...edge} />
+ </g>
+ )
case 'cube':
- return jsxs('g', {
- children: [
- jsx('path', { d: 'M20 4 L33 11 L33 29 L20 36 L7 29 L7 11 Z', ...face }),
- jsx('path', { d: 'M7 11 L20 18 L33 11 M20 18 L20 36', ...edge })
- ]
- })
+ return (
+ <g>
+ <path d="M20 4 L33 11 L33 29 L20 36 L7 29 L7 11 Z" {...face} />
+ <path d="M7 11 L20 18 L33 11 M20 18 L20 36" {...edge} />
+ </g>
+ )
case 'octahedron':
- return jsxs('g', {
- children: [
- jsx('path', { d: 'M20 3 L36 20 L20 37 L4 20 Z', ...face }),
- jsx('path', { d: 'M4 20 L36 20 M20 3 L20 37', ...edge })
- ]
- })
+ return (
+ <g>
+ <path d="M20 3 L36 20 L20 37 L4 20 Z" {...face} />
+ <path d="M4 20 L36 20 M20 3 L20 37" {...edge} />
+ </g>
+ )
case 'dodecahedron':
- return jsxs('g', {
- children: [
- jsx('path', {
- d: 'M20 3 L30 6.2 L36.2 14.7 L36.2 25.3 L30 33.8 L20 37 L10 33.8 L3.8 25.3 L3.8 14.7 L10 6.2 Z',
- ...face
- }),
- jsx('path', {
- d:
+ return (
+ <g>
+ <path
+ d="M20 3 L30 6.2 L36.2 14.7 L36.2 25.3 L30 33.8 L20 37 L10 33.8 L3.8 25.3 L3.8 14.7 L10 6.2 Z"
+ {...face}
+ />
+ <path
+ d={
'M20 12 L27.6 17.5 L24.7 26.5 L15.3 26.5 L12.4 17.5 Z ' +
- 'M20 12 L20 3 M27.6 17.5 L36.2 14.7 M24.7 26.5 L30 33.8 M15.3 26.5 L10 33.8 M12.4 17.5 L3.8 14.7',
- ...edge
- })
- ]
- })
+ 'M20 12 L20 3 M27.6 17.5 L36.2 14.7 M24.7 26.5 L30 33.8 M15.3 26.5 L10 33.8 M12.4 17.5 L3.8 14.7'
+ }
+ {...edge}
+ />
+ </g>
+ )
case 'icosahedron':
- return jsxs('g', {
- children: [
- jsx('path', { d: 'M20 3 L34.7 11.5 L34.7 28.5 L20 37 L5.3 28.5 L5.3 11.5 Z', ...face }),
- jsx('path', {
- d:
+ return (
+ <g>
+ <path d="M20 3 L34.7 11.5 L34.7 28.5 L20 37 L5.3 28.5 L5.3 11.5 Z" {...face} />
+ <path
+ d={
'M20 11 L27.8 24.5 L12.2 24.5 Z ' +
'M20 11 L20 3 M20 11 L34.7 11.5 M20 11 L5.3 11.5 ' +
'M27.8 24.5 L34.7 11.5 M27.8 24.5 L34.7 28.5 M27.8 24.5 L20 37 ' +
- 'M12.2 24.5 L5.3 11.5 M12.2 24.5 L5.3 28.5 M12.2 24.5 L20 37',
- ...edge
- })
- ]
- })
+ 'M12.2 24.5 L5.3 11.5 M12.2 24.5 L5.3 28.5 M12.2 24.5 L20 37'
+ }
+ {...edge}
+ />
+ </g>
+ )
// ── legacy flat shapes (stored picks from earlier versions) ──
case 'squircle':
- return jsx('rect', { x: 3, y: 3, width: 34, height: 34, rx: 11, fill: color })
+ return <rect x={3} y={3} width={34} height={34} rx={11} fill={color} />
case 'pill':
- return jsx('rect', { x: 2, y: 7, width: 36, height: 26, rx: 13, fill: color })
+ return <rect x={2} y={7} width={36} height={26} rx={13} fill={color} />
case 'triangle':
- return jsx('path', { d: 'M20 5.5 L36 33.5 L4 33.5 Z', ...stroke })
+ return <path d="M20 5.5 L36 33.5 L4 33.5 Z" {...stroke} />
case 'hexagon':
- return jsx('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 })
+ 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 jsx('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
- })
+ 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 jsx('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 })
+ 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 jsx('circle', { cx: 20, cy: 20, r: 17.5, fill: color })
+ return <circle cx={20} cy={20} r={17.5} fill={color} />
}
}
-
const EYE_Y = {
// solids: eyes sit on the upper face region, clear of the busiest edges
tetrahedron: 26,
@@ -3088,7 +3160,6 @@ const EYE_X = {
dodecahedron: [16.5, 23.5],
icosahedron: [16.5, 23.5]
}
-
function cubicAt(p0, p1, p2, p3, t) {
const u = 1 - t
return [
@@ -3101,23 +3172,18 @@ function cubicAt(p0, p1, p2, p3, t) {
function sampleDropRing(steps) {
const pts = []
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
}
-
function svgArc(x1, y1, rx, ry, fa, fs, x2, y2) {
const dx = (x1 - x2) / 2
const dy = (y1 - y2) / 2
@@ -3137,8 +3203,8 @@ function svgArc(x1, y1, rx, ry, fa, fs, x2, y2) {
if (fa === fs) {
sq = -sq
}
- const cx = sq * (rx * dy / ry) + (x1 + x2) / 2
- const cy = sq * (-ry * dx / rx) + (y1 + y2) / 2
+ const cx = sq * ((rx * dy) / ry) + (x1 + x2) / 2
+ const cy = sq * ((-ry * dx) / rx) + (y1 + y2) / 2
const ang = (ux, uy, vx, vy) => {
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)))
@@ -3155,9 +3221,15 @@ function svgArc(x1, y1, rx, ry, fa, fs, x2, y2) {
if (fs && dtheta < 0) {
dtheta += Math.PI * 2
}
- return { cx, cy, rx, ry, theta1, dtheta }
+ return {
+ cx,
+ cy,
+ rx,
+ ry,
+ theta1,
+ dtheta
+ }
}
-
function sampleArc(arc, n) {
const pts = []
for (let i = 0; i < n; i++) {
@@ -3178,9 +3250,9 @@ function sampleCloudRing(steps) {
const len4 = 19
const total = len1 + len2 + len3 + len4
const n = Math.max(64, steps)
- const n1 = Math.max(8, Math.round(n * len1 / total))
- const n2 = Math.max(10, Math.round(n * len2 / total))
- const n3 = Math.max(10, Math.round(n * len3 / total))
+ const n1 = Math.max(8, Math.round((n * len1) / total))
+ const n2 = Math.max(10, Math.round((n * len2) / total))
+ const n3 = Math.max(10, Math.round((n * len3) / total))
const n4 = Math.max(4, n - n1 - n2 - n3)
const pts = []
pts.push(...sampleArc(a1, n1))
@@ -3197,7 +3269,6 @@ function sampleCloudRing(steps) {
* a dumped point cloud. */
function sampleFaceRing(shape, steps = 52) {
const kind = (shape || '').startsWith('sigil-') ? 'circle' : shape
-
if (kind === 'drop' || kind === 'teardrop') {
return sampleDropRing(steps)
}
@@ -3205,7 +3276,6 @@ function sampleFaceRing(shape, steps = 52) {
return sampleCloudRing(steps)
}
const pts = []
-
for (let i = 0; i < steps; i++) {
const a = (i / steps) * Math.PI * 2 - Math.PI / 2
const c = Math.cos(a)
@@ -3225,7 +3295,7 @@ function sampleFaceRing(shape, steps = 52) {
rx = ry = 16 / d
} else if (kind === 'triangle' || kind === 'tetrahedron' || kind === 'wedge') {
const u = (a + Math.PI / 2 + Math.PI * 2) % (Math.PI * 2)
- const sector = (u / (Math.PI * 2 / 3)) % 1
+ const sector = (u / ((Math.PI * 2) / 3)) % 1
rx = ry = 13.5 / Math.max(0.42, Math.cos((sector - 0.5) * 1.9))
} else if (kind === 'hexagon' || kind === 'hex' || kind === 'icosahedron' || kind === 'dodecahedron') {
const seg = Math.PI / 3
@@ -3241,13 +3311,10 @@ function sampleFaceRing(shape, steps = 52) {
} else {
rx = ry = 16.2
}
-
pts.push([20 + rx * c, 20 + ry * s])
}
-
return pts
}
-
function projectFacePoint(x, y, turn, tilt, roll) {
const dx = x - 20
const dy = y - 20
@@ -3258,18 +3325,14 @@ function projectFacePoint(x, y, turn, tilt, roll) {
const sy = 0.8 + 0.2 * Math.abs(Math.cos((tilt * Math.PI) / 180))
return [20 + xr * sx, 20 + yr * sy]
}
-
function ringToPath(pts) {
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'
}
@@ -3288,7 +3351,6 @@ function facePose(mood, t) {
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),
@@ -3301,7 +3363,6 @@ function facePose(mood, t) {
d2: 0
}
}
-
function paintMathFace(svg, t) {
const mood = svg.getAttribute('data-hb-mood') || 'idle'
const shape = svg.getAttribute('data-hb-shape') || 'circle'
@@ -3312,7 +3373,6 @@ function paintMathFace(svg, t) {
const el = svg.querySelector('[data-hb-el]')
const er = 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')
@@ -3321,16 +3381,13 @@ function paintMathFace(svg, t) {
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)
@@ -3341,40 +3398,35 @@ function paintMathFace(svg, t) {
// lower-set eyes.
const hl = svg.querySelector('[data-hb-hl-l]')
const hr = 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', `M${eyeL - 2.6} ${eyeY} L${eyeL + 2.6} ${eyeY} M${eyeR - 2.6} ${eyeY} L${eyeR + 2.6} ${eyeY}`)
+ shut.setAttribute(
+ 'd',
+ `M${eyeL - 2.6} ${eyeY} L${eyeL + 2.6} ${eyeY} M${eyeR - 2.6} ${eyeY} L${eyeR + 2.6} ${eyeY}`
+ )
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))
})
-
svg.style.transform = `rotate(${pose.tilt}deg)`
svg.style.transformOrigin = '50% 70%'
}
-
function walkMathFaces(root, acc) {
if (!root || !root.querySelectorAll) {
return acc
}
-
root.querySelectorAll('svg[data-hb-math]').forEach(node => acc.push(node))
root.querySelectorAll('*').forEach(el => {
if (el.shadowRoot) {
@@ -3383,20 +3435,16 @@ function walkMathFaces(root, acc) {
})
return acc
}
-
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.
@@ -3408,7 +3456,6 @@ function startFaceClock() {
typeof IntersectionObserver === 'function'
? new IntersectionObserver(entries => {
let becameVisible = false
-
for (const entry of entries) {
if (entry.isIntersecting) {
visibleFaces.add(entry.target)
@@ -3424,16 +3471,12 @@ 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)
@@ -3441,7 +3484,6 @@ function startFaceClock() {
visibleFaces.delete(svg)
}
}
-
for (const svg of faces) {
if (!observedFaces.has(svg)) {
observedFaces.add(svg)
@@ -3459,7 +3501,6 @@ function startFaceClock() {
}
const t = (now - t0) / 1000
const facesToPaint = observer ? visibleFaces : faces
-
for (const svg of facesToPaint) {
if (svg.isConnected) {
paintMathFace(svg, t)
@@ -3470,12 +3511,10 @@ function startFaceClock() {
// Nothing worth animating: no faces mounted (BotFace wakes us on the next
// mount) or none visible (the observer wakes us when one scrolls in).
const idle = () => faces.length === 0 || (observer && visibleFaces.size === 0)
-
const teardownCaches = () => {
if (observer) {
observer.disconnect()
}
-
visibleFaces.clear()
observedFaces.clear()
faces = []
@@ -3486,8 +3525,10 @@ function startFaceClock() {
// hidden/minimized/unfocused pause, dormancy, teardown). typeof-guarded so
// older shells and the vm test harness use the hand-rolled path below.
if (typeof createBudgetedLoop === 'function' && createBudgetedLoop) {
- const loop = createBudgetedLoop(paint, { fps: 15, idleWhen: idle })
-
+ const loop = createBudgetedLoop(paint, {
+ fps: 15,
+ idleWhen: idle
+ })
window.__hbFaceClock = {
stop: () => {
loop.dispose()
@@ -3499,7 +3540,6 @@ function startFaceClock() {
loop.wake()
}
}
-
return
}
@@ -3508,12 +3548,10 @@ function startFaceClock() {
let rafId = 0
let dormant = false
let stopped = false
-
const tick = now => {
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.
@@ -3525,36 +3563,31 @@ 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 }
+ window.__hbFaceClock = {
+ stop,
+ wake
+ }
rafId = window.requestAnimationFrame(tick)
}
@@ -3572,14 +3605,21 @@ function stopFaceClock() {
*/
function BotFace({ shape, color, image, size = 36, name = 'agent', mood = 'idle' }) {
startFaceClock()
-
if (image) {
- return jsx('img', {
- src: image,
- alt: '',
- 'aria-hidden': true,
- style: { width: size, height: size, borderRadius: '22%', objectFit: 'cover', display: 'block' }
- })
+ return (
+ <img
+ src={image}
+ alt=""
+ aria-hidden
+ style={{
+ width: size,
+ height: size,
+ borderRadius: '22%',
+ objectFit: 'cover',
+ display: 'block'
+ }}
+ />
+ )
}
// Blobatar shapes: the library draws the whole face (body + eyes + its own
@@ -3589,13 +3629,21 @@ function BotFace({ shape, color, image, size = 36, name = 'agent', mood = 'idle'
// SDK predates the export.
if (isBlobShape(shape)) {
const markup = blobMarkup(shape, name, size)
-
if (markup) {
- return jsx('span', {
- 'aria-hidden': true,
- style: { width: size, height: size, display: 'block', lineHeight: 0 },
- dangerouslySetInnerHTML: { __html: markup }
- })
+ return (
+ <span
+ aria-hidden
+ style={{
+ width: size,
+ height: size,
+ display: 'block',
+ lineHeight: 0
+ }}
+ dangerouslySetInnerHTML={{
+ __html: markup
+ }}
+ />
+ )
}
// Older SDK without blobatar: legacy deterministic shape from the name.
@@ -3606,22 +3654,19 @@ function BotFace({ shape, color, image, size = 36, name = 'agent', mood = 'idle'
// outlines, which would turn a stored sigil pick into a blank circle.
// Keep the legacy static render for them so old picks still draw.
if (shape.startsWith('sigil-')) {
- const eyes = jsxs('g', {
- children: [
- jsx('circle', { cx: 16, cy: 14, r: 2.4, fill: color }),
- jsx('circle', { cx: 24, cy: 14, r: 2.4, fill: color })
- ]
- })
- return jsxs('svg', {
- 'data-bot-face': name,
- viewBox: '0 0 40 40',
- width: size,
- height: size,
- 'aria-hidden': true,
- children: [shapeNode(shape, color, name), eyes]
- })
+ const eyes = (
+ <g>
+ <circle cx={16} cy={14} r={2.4} fill={color} />
+ <circle cx={24} cy={14} r={2.4} fill={color} />
+ </g>
+ )
+ return (
+ <svg data-bot-face={name} viewBox="0 0 40 40" width={size} height={size} aria-hidden>
+ {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
@@ -3635,54 +3680,54 @@ function BotFace({ shape, color, image, size = 36, name = 'agent', mood = 'idle'
// (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 jsxs('svg', {
- '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': true,
- style: { overflow: 'visible', display: 'block' },
- children: [
- jsx('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),
- fill: color
- }),
- jsxs('g', {
- 'data-hb-open': '1',
- children: [
- jsx('ellipse', { 'data-hb-el': '1', cx: 15.4, cy: eyeY0, rx: 2.2, ry: working ? 2.6 : 2.3, fill: eyeFill }),
- jsx('ellipse', { 'data-hb-er': '1', cx: 24.6, cy: eyeY0, rx: 2.2, ry: working ? 2.6 : 2.3, fill: eyeFill }),
- jsx('circle', { 'data-hb-hl-l': '1', cx: 14.8, cy: eyeY0 - 0.7, r: 0.65, fill: hlFill }),
- jsx('circle', { 'data-hb-hl-r': '1', cx: 24, cy: eyeY0 - 0.7, r: 0.65, fill: hlFill })
- ]
- }),
- jsx('path', {
- 'data-hb-shut': '1',
- d: `M12.8 ${eyeY0} L18 ${eyeY0} M22 ${eyeY0} L27.2 ${eyeY0}`,
- stroke: eyeFill,
- strokeWidth: 2,
- strokeLinecap: 'round',
- fill: 'none',
- opacity: 0
- }),
- working
- ? jsxs('g', {
- children: [
- jsx('circle', { 'data-hb-dot': '1', cx: 16.4, cy: 41.2, r: 1.15, fill: color, opacity: rest.d0 }),
- jsx('circle', { 'data-hb-dot': '1', cx: 20, cy: 41.2, r: 1.15, fill: color, opacity: rest.d1 }),
- jsx('circle', { 'data-hb-dot': '1', cx: 23.6, cy: 41.2, r: 1.15, fill: color, opacity: rest.d2 })
- ]
- })
- : null
- ]
- })
+ return (
+ <svg
+ 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'
+ }}
+ >
+ <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)
+ }
+ 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} />
+ </g>
+ <path
+ data-hb-shut="1"
+ d={`M12.8 ${eyeY0} L18 ${eyeY0} M22 ${eyeY0} L27.2 ${eyeY0}`}
+ stroke={eyeFill}
+ strokeWidth={2}
+ strokeLinecap="round"
+ fill="none"
+ opacity={0}
+ />
+ {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} />
+ </g>
+ ) : null}
+ </svg>
+ )
}
// -- inline MCP setup (per-profile), driven by the mcp.servers.* gateway RPCs --
@@ -3695,13 +3740,22 @@ async function mcpRpc(method, params) {
// doesn't know the method (older backend) vs a real error.
try {
const res = await host.request(method, params)
- return { ok: true, result: res }
+ return {
+ ok: true,
+ result: res
+ }
} catch (err) {
const msg = String((err && err.message) || err || '')
if (/unknown method/i.test(msg)) {
- return { ok: false, unsupported: true }
+ return {
+ ok: false,
+ unsupported: true
+ }
+ }
+ return {
+ ok: false,
+ error: msg
}
- return { ok: false, error: msg }
}
}
@@ -3715,7 +3769,6 @@ async function mcpSetupSupported() {
_mcpRpcSupported = !(r.ok === false && r.unsupported)
return _mcpRpcSupported
}
-
function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
// entry: { name, requires:[env keys], auth?, fromCatalog, installed }
// profile may be null at first (New Bot: the profile isn't created yet).
@@ -3727,7 +3780,6 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
const [message, setMessage] = useState('')
const pollRef = useRef(null)
const profileRef = useRef(profile || null)
-
useEffect(() => {
if (profile) {
profileRef.current = profile
@@ -3748,7 +3800,6 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
}
return null
}
-
useEffect(() => {
let alive = true
mcpSetupSupported().then(ok => {
@@ -3762,10 +3813,8 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
}
}
}, [])
-
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')
@@ -3776,7 +3825,11 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
return
}
if (entry.fromCatalog && !entry.installed) {
- const add = await mcpRpc('mcp.servers.add', { profile, name: entry.name, preset: entry.name })
+ 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')
@@ -3785,7 +3838,6 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
}
setPhase(isOAuth ? 'oauth' : 'keys')
}
-
const submitKeys = async () => {
setPhase('busy')
const profile = profileRef.current
@@ -3799,25 +3851,37 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
if (!val) {
continue
}
- const r = await mcpRpc('mcp.servers.set_api_key', { profile, name: entry.name, env_var: k, value: val })
+ const r = await mcpRpc('mcp.servers.set_api_key', {
+ profile,
+ name: entry.name,
+ env_var: k,
+ value: val
+ })
if (!r.ok) {
setPhase('error')
- setMessage(r.error || ('Failed to set ' + k))
+ setMessage(r.error || 'Failed to set ' + k)
return
}
}
// Verify via test.
- const t = await mcpRpc('mcp.servers.test', { profile, name: entry.name })
+ const t = await mcpRpc('mcp.servers.test', {
+ profile,
+ name: entry.name
+ })
if (t.ok && t.result && (t.result.ok || (t.result.result && t.result.result.ok))) {
setPhase('done')
- host.notify({ kind: 'success', message: entry.name + ' configured' })
+ host.notify({
+ kind: 'success',
+ message: entry.name + ' configured'
+ })
onDone && onDone()
} else {
setPhase('error')
- setMessage((t.result && (t.result.error || (t.result.result && t.result.result.error))) || 'Server test failed after setup')
+ setMessage(
+ (t.result && (t.result.error || (t.result.result && t.result.result.error))) || 'Server test failed after setup'
+ )
}
}
-
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
@@ -3834,20 +3898,27 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
return
}
if (entry.fromCatalog && !entry.installed) {
- const add = await mcpRpc('mcp.servers.add', { profile, name: entry.name, preset: entry.name })
+ 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 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')
+ setMessage(start.error || 'Could not start OAuth')
return
}
// Open the auth URL in the native browser, same as provider OAuth.
@@ -3865,14 +3936,21 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
setPhase('oauth')
setMessage('Complete sign-in in your browser...')
pollRef.current = setInterval(async () => {
- const poll = await mcpRpc('mcp.servers.oauth.poll', { profile, name: entry.name, session_id: sessionId })
+ const poll = await mcpRpc('mcp.servers.oauth.poll', {
+ profile,
+ 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
setPhase('done')
- host.notify({ kind: 'success', message: entry.name + ' authenticated' })
+ host.notify({
+ kind: 'success',
+ message: entry.name + ' authenticated'
+ })
onDone && onDone()
} else if (status === 'error') {
clearInterval(pollRef.current)
@@ -3882,60 +3960,72 @@ function McpSetupButton({ profile, entry, onDone, ensureProfile }) {
}
}, 2000)
}
-
if (supported === false) {
- return jsx('span', {
- className: 'ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)',
- children: 'needs setup (' + requires.join(', ') + ') \u2014 restart the gateway to enable in-app setup'
- })
+ return (
+ <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">
+ {'needs setup (' + requires.join(', ') + ') \u2014 restart the gateway to enable in-app setup'}
+ </span>
+ )
}
if (phase === 'done') {
- return jsx('span', { className: 'ml-1.5 text-[0.65rem] text-(--ui-success,#22c55e)', children: 'set up \u2713' })
+ return <span className="ml-1.5 text-[0.65rem] text-(--ui-success,#22c55e)">set up ✓</span>
}
if (phase === 'keys') {
- return jsxs('div', {
- className: 'mt-1 grid gap-1',
- children: [
- ...requires.map(k =>
- jsx(Input, {
- key: k,
- type: 'password',
- className: 'h-6 text-[0.7rem]',
- placeholder: k,
- value: keyValues[k] || '',
- onChange: e => setKeyValues(prev => ({ ...prev, [k]: e.target.value }))
- }, k)
- ),
- jsxs('div', {
- className: 'flex gap-1',
- children: [
- jsx(Button, { size: 'xs', variant: 'secondary', onClick: () => void submitKeys(), children: 'Save & test' }),
- jsx(Button, { size: 'xs', variant: 'ghost', onClick: () => setPhase('idle'), children: 'Cancel' })
- ]
- })
- ]
- })
+ return (
+ <div className="mt-1 grid gap-1">
+ {requires.map(k => (
+ <Input
+ key={k}
+ key={k}
+ type="password"
+ className="h-6 text-[0.7rem]"
+ placeholder={k}
+ value={keyValues[k] || ''}
+ onChange={e =>
+ setKeyValues(prev => ({
+ ...prev,
+ [k]: e.target.value
+ }))
+ }
+ />
+ ))}
+ <div className="flex gap-1">
+ <Button size="xs" variant="secondary" onClick={() => void submitKeys()}>
+ Save & test
+ </Button>
+ <Button size="xs" variant="ghost" onClick={() => setPhase('idle')}>
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )
}
if (phase === 'oauth') {
- return jsx('span', { className: 'ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)', children: message || 'Authorizing\u2026' })
+ return <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">{message || 'Authorizing\u2026'}</span>
}
if (phase === 'busy') {
- return jsx('span', { className: 'ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)', children: 'Working\u2026' })
+ return <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">Working…</span>
}
if (phase === 'error') {
- return jsxs('span', {
- className: 'ml-1.5 text-[0.65rem] text-(--ui-danger,#ef4444)',
- children: [(message || 'Setup failed') + ' ', jsx('button', { className: 'underline', onClick: () => setPhase('idle'), children: 'retry' })]
- })
+ return (
+ <span className="ml-1.5 text-[0.65rem] text-(--ui-danger,#ef4444)">
+ {(message || 'Setup failed') + ' '}
+ <button className="underline" onClick={() => setPhase('idle')}>
+ retry
+ </button>
+ </span>
+ )
}
// idle
- return jsx('button', {
- className: 'ml-1.5 text-[0.65rem] text-(--ui-accent,#4f9cf9) underline',
- onClick: () => void (isOAuth ? beginOAuth() : beginKeys()),
- children: isOAuth ? 'Sign in\u2026' : 'Set up\u2026'
- })
+ return (
+ <button
+ className="ml-1.5 text-[0.65rem] text-(--ui-accent,#4f9cf9) underline"
+ onClick={() => void (isOAuth ? beginOAuth() : beginKeys())}
+ >
+ {isOAuth ? 'Sign in\u2026' : 'Set up\u2026'}
+ </button>
+ )
}
-
function botAppearance(name, meta) {
// The primary profile is literally named "default"; the SDK's profileColor
// can hand it a near-black that renders as an ugly black square, and any
@@ -3946,7 +4036,11 @@ function botAppearance(name, meta) {
const isPrimary = (name || '').trim().toLowerCase() === 'default'
const userCustomized = Boolean(meta?.custom)
if (isPrimary && !userCustomized) {
- return { shape: 'squircle', color: '#8b5cf6', image: meta?.image || null }
+ return {
+ shape: 'squircle',
+ color: '#8b5cf6',
+ image: meta?.image || null
+ }
}
return {
shape: meta?.shape || defaultShapeFor(name),
@@ -3978,7 +4072,6 @@ function normalizeAvatarImage(dataUrl, edge = 256) {
img.src = dataUrl
})
}
-
function pickImageFromDevice() {
return new Promise(resolve => {
const input = document.createElement('input')
@@ -3986,16 +4079,16 @@ function pickImageFromDevice() {
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: 'Image too large (max 15MB).' })
+ host.notify({
+ kind: 'error',
+ message: '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)
@@ -4012,11 +4105,9 @@ function groupAttachmentKind(file) {
if (/^image\//.test(file.type || '')) {
return 'image'
}
-
if (file.type === 'application/pdf' || /\.pdf$/i.test(file.name || '')) {
return 'pdf'
}
-
return 'file'
}
@@ -4026,28 +4117,26 @@ function groupAttachmentKind(file) {
* picker button, the composer paste handler, and room drag & drop. */
async function filesToGroupAttachments(files) {
const picked = []
-
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).` })
+ host.notify({
+ kind: 'error',
+ message: `${file.name || 'attachment'}: too large (max 15MB).`
+ })
continue
}
-
const data = await new Promise(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'),
@@ -4055,7 +4144,6 @@ async function filesToGroupAttachments(files) {
kind
})
}
-
return picked
}
@@ -4081,11 +4169,9 @@ function normalizeGroupAttachment(dataUrl, maxEdge = 1568) {
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))
@@ -4107,23 +4193,21 @@ function normalizeGroupAttachment(dataUrl, maxEdge = 1568) {
* Only `true` is sticky. */
const $imagenAvailable = atom(null)
let imagenProbeInflight = null
-
function probeImagen() {
if (imagenProbeInflight) {
return imagenProbeInflight
}
-
imagenProbeInflight = host
- .request('image.generate', { probe: true })
+ .request('image.generate', {
+ probe: true
+ })
.then(res => $imagenAvailable.set(Boolean(res?.available)))
.catch(() => $imagenAvailable.set(false))
.finally(() => {
imagenProbeInflight = null
})
-
return imagenProbeInflight
}
-
async function generateAvatarImage(bot, title, description) {
const who = [title || bot, description].filter(Boolean).join(' — ')
const res = await host.request('image.generate', {
@@ -4132,7 +4216,6 @@ async function generateAvatarImage(bot, title, description) {
'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')
}
@@ -4152,7 +4235,6 @@ function AvatarPicker({ shape, color, image, onShape, onColor, onImage, generate
const [tab, setTab] = useState('bot')
const [describe, setDescribe] = useState('')
const [genBusy, setGenBusy] = useState(false)
-
if (imagen === null) {
void probeImagen()
}
@@ -4161,28 +4243,22 @@ function AvatarPicker({ shape, color, image, onShape, onColor, onImage, generate
// tab — the gateway may have restarted with image.generate since.
const goTab = id => {
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
@@ -4191,15 +4267,12 @@ function AvatarPicker({ shape, color, image, onShape, onColor, onImage, 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))
}
@@ -4209,237 +4282,226 @@ function AvatarPicker({ shape, color, image, onShape, onColor, onImage, generate
setGenBusy(false)
}
}
-
- const tabButton = (id, label) =>
- jsx(
- 'button',
- {
- type: 'button',
- className: cn(
- 'rounded-full px-3 py-1 text-xs font-medium transition-colors',
- tab === id
- ? 'bg-(--chrome-action-hover) text-foreground'
- : 'text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)'
- ),
- onClick: () => goTab(id),
- children: label
- },
- id
- )
-
- return jsxs('div', {
- className: 'grid justify-items-center gap-3',
- children: [
- // Tab pills: Bot | Generate | Upload | Pet
- jsxs('div', {
- className: 'flex items-center gap-1',
- children: [tabButton('bot', 'Bot'), tabButton('generate', 'Generate'), tabButton('upload', 'Upload'), tabButton('pet', 'Pet')]
- }),
-
- image && tab !== 'generate'
- ? jsx(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- onClick: () => onImage(null),
- children: 'Remove image — use shape'
- })
- : null,
-
- tab === 'bot'
- ? isBlobShape(shape) && blobatarSvg
- ? (() => {
- const { seedPart, kind } = parseBlobShape(shape, pickerName)
- const locked = Boolean(seedPart)
- return jsxs('div', {
- className: 'grid justify-items-center gap-3',
- children: [
- // Silhouette pins: Auto (name decides) + the six blob kinds.
- jsx('div', {
- style: {
- display: 'grid',
- gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
- gap: '6px',
- justifyItems: 'center'
- },
- children: ['', ...BLOB_KINDS].map(k =>
- jsx(
- 'button',
- {
- type: 'button',
- 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 },
- onClick: () => {
- onImage(null)
- onShape(blobShapeString(seedPart, k))
- },
- children: k
- ? jsx(BotFace, { shape: blobShapeString(seedPart, k), color, size: 32, name: pickerName })
- : jsx('span', { className: 'text-[0.6rem] text-(--ui-text-tertiary)', children: 'Auto' })
- },
- k || 'auto'
- )
- )
- }),
- jsxs('div', {
- className: 'flex items-center gap-1',
- children: [
- jsxs(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- onClick: () => {
- onImage(null)
- onShape(blobShapeString(Math.random().toString(36).slice(2, 10), kind))
- },
- children: [jsx(Codicon, { name: 'refresh', className: 'mr-1 text-[0.8rem]' }), 'Randomize']
- }),
- jsxs(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- title: locked
- ? 'Unlock — the face follows the agent\u2019s name again'
- : 'Keep this exact face even if the name changes',
- onClick: () => onShape(blobShapeString(locked ? '' : pickerName, kind)),
- children: [
- jsx(Codicon, { name: locked ? 'unlock' : 'lock', className: 'mr-1 text-[0.8rem]' }),
- locked ? 'Unlock' : 'Lock face'
- ]
- })
- ]
- }),
- jsx('div', {
- className: 'text-center text-[0.65rem] text-(--ui-text-quaternary)',
- children: locked ? 'Face locked — renaming won\u2019t change it.' : 'Face follows the name.'
- }),
- jsx(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- className: 'text-(--ui-text-tertiary)',
- onClick: () => onShape(defaultShapeFor(pickerName)),
- children: 'Classic shapes'
- })
- ]
- })
- })()
- : jsxs('div', {
- className: 'grid justify-items-center gap-3',
- children: [
- jsx('div', {
- style: {
- display: 'grid',
- gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
- gap: '6px',
- justifyItems: 'center'
- },
- children: (blobatarSvg ? ['blobatar', ...AVATAR_PICKER_SHAPES] : AVATAR_PICKER_SHAPES).map(s =>
- jsx(
- 'button',
- {
- type: 'button',
- title: s === 'blobatar' ? 'Blob face — drawn from the agent\u2019s name' : undefined,
- className: cn(
+ const tabButton = (id, label) => (
+ <button
+ key={id}
+ type="button"
+ className={cn(
+ 'rounded-full px-3 py-1 text-xs font-medium transition-colors',
+ tab === id
+ ? 'bg-(--chrome-action-hover) text-foreground'
+ : 'text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)'
+ )}
+ onClick={() => goTab(id)}
+ >
+ {label}
+ </button>
+ )
+ return (
+ <div className="grid justify-items-center gap-3">
+ {/* Tab pills: Bot | Generate | Upload | Pet */}
+ <div className="flex items-center gap-1">
+ {tabButton('bot', 'Bot')}
+ {tabButton('generate', 'Generate')}
+ {tabButton('upload', 'Upload')}
+ {tabButton('pet', 'Pet')}
+ </div>
+ {image && tab !== 'generate' ? (
+ <Button type="button" variant="ghost" size="sm" onClick={() => onImage(null)}>
+ Remove image — use shape
+ </Button>
+ ) : null}
+ {tab === 'bot' ? (
+ isBlobShape(shape) && blobatarSvg ? (
+ (() => {
+ 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
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
+ gap: '6px',
+ justifyItems: 'center'
+ }}
+ >
+ {['', ...BLOB_KINDS].map(k => (
+ <button
+ key={k || 'auto'}
+ type="button"
+ title={k || 'Auto — the name decides'}
+ 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 },
- onClick: () => {
+ k === kind && !image && 'ring-1 ring-(--ui-accent)'
+ )}
+ style={{
+ width: 44,
+ height: 44
+ }}
+ onClick={() => {
onImage(null)
- onShape(s)
- },
- children: jsx(BotFace, { shape: s, color, size: 32, name: pickerName })
- },
- s
- )
- )
- }),
- jsx('div', {
- style: {
- display: 'grid',
- gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
- gap: '8px',
- justifyItems: 'center'
- },
- children: AVATAR_COLORS.map(c =>
- jsx(
- 'button',
- {
- type: 'button',
- className: cn(
- 'rounded-full transition-transform hover:scale-110',
- c === color && 'ring-2 ring-(--ui-accent) ring-offset-1 ring-offset-(--ui-bg, transparent)'
- ),
- style: { width: 22, height: 22, backgroundColor: c },
- onClick: () => onColor(c)
- },
- c
- )
- )
- })
- ]
- })
- : null,
-
- tab === 'generate'
- ? imagen
- ? jsxs('div', {
- className: 'grid w-full gap-2',
- children: [
- jsx(Textarea, {
- className: 'min-h-16 text-xs',
- placeholder: 'Describe your avatar…',
- value: describe,
- onChange: event => setDescribe(event.target.value)
- }),
- jsxs(Button, {
- type: 'button',
- variant: 'secondary',
- className: 'w-full justify-center',
- disabled: genBusy,
- onClick: generate,
- children: [
- genBusy
- ? jsx(GlyphSpinner, { spinner: 'breathe', className: 'mr-1 text-[0.8rem]' })
- : jsx(Codicon, { name: 'sparkle', className: 'mr-1 text-[0.8rem]' }),
- genBusy ? 'Generating…' : 'Generate'
- ]
- }),
- describe.trim()
- ? null
- : jsx('div', {
- className: 'text-center text-[0.65rem] text-(--ui-text-quaternary)',
- children: 'Leave blank to generate from the agent\u2019s name and description.'
- })
- ]
- })
- : jsx('div', {
- className: 'px-2 py-3 text-center text-xs leading-5 text-(--ui-text-tertiary)',
- children:
- imagen === false
- ? 'No image model available. If you just enabled one (or updated Hermes), restart the gateway: Ctrl+K → "Restart gateway".'
- : 'Checking image backend…'
- })
- : null,
-
- tab === 'upload'
- ? jsxs(Button, {
- type: 'button',
- variant: 'secondary',
- className: 'w-full justify-center',
- onClick: upload,
- children: [jsx(Codicon, { name: 'device-camera', className: 'mr-1 text-[0.8rem]' }), 'Choose an image…']
- })
- : null,
-
- tab === 'pet' ? jsx(PetTab, { image, onImage }) : null
- ]
- })
+ onShape(blobShapeString(seedPart, k))
+ }}
+ >
+ {k ? (
+ <BotFace shape={blobShapeString(seedPart, k)} color={color} size={32} name={pickerName} />
+ ) : (
+ <span className="text-[0.6rem] text-(--ui-text-tertiary)">Auto</span>
+ )}
+ </button>
+ ))}
+ </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))
+ }}
+ >
+ <Codicon name="refresh" className="mr-1 text-[0.8rem]" />
+ Randomize
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ title={
+ locked
+ ? 'Unlock — the face follows the agent\u2019s name again'
+ : 'Keep this exact face even if the name changes'
+ }
+ onClick={() => onShape(blobShapeString(locked ? '' : pickerName, kind))}
+ >
+ <Codicon name={locked ? 'unlock' : 'lock'} className="mr-1 text-[0.8rem]" />
+ {locked ? 'Unlock' : 'Lock face'}
+ </Button>
+ </div>
+ <div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">
+ {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))}
+ >
+ Classic shapes
+ </Button>
+ </div>
+ )
+ })()
+ ) : (
+ <div className="grid justify-items-center gap-3">
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
+ gap: '6px',
+ justifyItems: 'center'
+ }}
+ >
+ {(blobatarSvg ? ['blobatar', ...AVATAR_PICKER_SHAPES] : AVATAR_PICKER_SHAPES).map(s => (
+ <button
+ key={s}
+ type="button"
+ title={s === 'blobatar' ? 'Blob face — drawn from the agent\u2019s name' : 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
+ }}
+ onClick={() => {
+ onImage(null)
+ onShape(s)
+ }}
+ >
+ <BotFace shape={s} color={color} size={32} name={pickerName} />
+ </button>
+ ))}
+ </div>
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(5, minmax(0, 1fr))',
+ gap: '8px',
+ justifyItems: 'center'
+ }}
+ >
+ {AVATAR_COLORS.map(c => (
+ <button
+ key={c}
+ type="button"
+ className={cn(
+ 'rounded-full transition-transform hover:scale-110',
+ c === color && 'ring-2 ring-(--ui-accent) ring-offset-1 ring-offset-(--ui-bg, transparent)'
+ )}
+ style={{
+ width: 22,
+ height: 22,
+ backgroundColor: c
+ }}
+ onClick={() => onColor(c)}
+ />
+ ))}
+ </div>
+ </div>
+ )
+ ) : null}
+ {tab === 'generate' ? (
+ imagen ? (
+ <div className="grid w-full gap-2">
+ <Textarea
+ className="min-h-16 text-xs"
+ placeholder="Describe your avatar…"
+ value={describe}
+ onChange={event => setDescribe(event.target.value)}
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ className="w-full justify-center"
+ disabled={genBusy}
+ onClick={generate}
+ >
+ {genBusy ? (
+ <GlyphSpinner spinner="breathe" className="mr-1 text-[0.8rem]" />
+ ) : (
+ <Codicon name="sparkle" className="mr-1 text-[0.8rem]" />
+ )}
+ {genBusy ? 'Generating…' : 'Generate'}
+ </Button>
+ {describe.trim() ? null : (
+ <div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">
+ Leave blank to generate from the agent’s name and description.
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="px-2 py-3 text-center text-xs leading-5 text-(--ui-text-tertiary)">
+ {imagen === false
+ ? 'No image model available. If you just enabled one (or updated Hermes), restart the gateway: Ctrl+K → "Restart gateway".'
+ : 'Checking image backend…'}
+ </div>
+ )
+ ) : 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]" />
+ Choose an image…
+ </Button>
+ ) : null}
+ {tab === 'pet' ? <PetTab image={image} onImage={onImage} /> : null}
+ </div>
+ )
}
// ── pet tab: attach a petdex companion that lives beside the avatar ─────────
@@ -4454,7 +4516,6 @@ const PET_FRAME_H = 208
const petFrameCache = new Map()
let petFetchActive = 0
const petFetchQueue = []
-
function pumpPetQueue() {
while (petFetchActive < 4 && petFetchQueue.length) {
const job = petFetchQueue.shift()
@@ -4465,19 +4526,19 @@ function pumpPetQueue() {
})
}
}
-
function petFrameIcon(spriteUrl) {
if (!spriteUrl) {
return Promise.resolve(null)
}
-
if (!petFrameCache.has(spriteUrl)) {
petFrameCache.set(
spriteUrl,
new Promise(resolve => {
petFetchQueue.push(async () => {
try {
- const resp = await fetch(spriteUrl, { signal: AbortSignal.timeout(15000) })
+ 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)
@@ -4496,14 +4557,12 @@ function petFrameIcon(spriteUrl) {
})
)
}
-
return petFrameCache.get(spriteUrl)
}
/** One pet tile image: frame 0 only, resolved lazily through the cache. */
function PetThumb({ spriteUrl, size = 40 }) {
const [icon, setIcon] = useState(null)
-
useEffect(() => {
let alive = true
petFrameIcon(spriteUrl).then(url => {
@@ -4515,20 +4574,32 @@ function PetThumb({ spriteUrl, size = 40 }) {
alive = false
}
}, [spriteUrl])
-
if (!icon) {
- return jsx('div', {
- style: { width: size, height: size, borderRadius: 6, background: 'var(--chrome-action-hover, rgba(255,255,255,0.06))' }
- })
+ return (
+ <div
+ style={{
+ width: size,
+ height: size,
+ borderRadius: 6,
+ background: 'var(--chrome-action-hover, rgba(255,255,255,0.06))'
+ }}
+ />
+ )
}
-
- return jsx('img', {
- src: icon,
- alt: '',
- style: { width: size, height: size, objectFit: 'contain', imageRendering: 'pixelated', borderRadius: 6 }
- })
+ return (
+ <img
+ src={icon}
+ alt=""
+ style={{
+ width: size,
+ height: size,
+ objectFit: 'contain',
+ imageRendering: 'pixelated',
+ borderRadius: 6
+ }}
+ />
+ )
}
-
function PetTab({ image, onImage }) {
// Selection is dialog-local: committed by the dialog's Save like any
// uploaded/generated image (a direct meta write here gets clobbered by
@@ -4544,21 +4615,20 @@ function PetTab({ image, onImage }) {
// 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 jsx('div', {
- className: 'flex justify-center py-4',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
+ return (
+ <div className="flex justify-center py-4">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ )
}
-
if (!pets.length) {
- return jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: 'No pets in the petdex gallery. Run `hermes pets` to explore.'
- })
+ return (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ No pets in the petdex gallery. Run `hermes pets` to explore.
+ </div>
+ )
}
-
const q = query.trim().toLowerCase()
const filtered = q
? pets.filter(pet => (pet.displayName || '').toLowerCase().includes(q) || (pet.slug || '').includes(q))
@@ -4569,104 +4639,97 @@ function PetTab({ image, onImage }) {
return rank(a) - rank(b)
})
const visible = ranked.slice(0, limit)
-
const onScroll = event => {
const el = event.currentTarget
-
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120 && limit < ranked.length) {
setLimit(prev => Math.min(prev + 24, ranked.length))
}
}
-
- return jsxs('div', {
- className: 'grid w-full gap-2',
- children: [
- jsx('div', {
- className: 'text-center text-[0.65rem] text-(--ui-text-quaternary)',
- children: 'Pick a pet as this agent’s profile picture.'
- }),
- jsx(Input, {
- className: 'h-7 text-xs',
- placeholder: `Search ${pets.length} pets…`,
- value: query,
- onChange: event => {
+ return (
+ <div className="grid w-full gap-2">
+ <div className="text-center text-[0.65rem] text-(--ui-text-quaternary)">
+ Pick a pet as this agent’s profile picture.
+ </div>
+ <Input
+ className="h-7 text-xs"
+ placeholder={`Search ${pets.length} pets…`}
+ value={query}
+ onChange={event => {
setQuery(event.target.value)
setLimit(24)
- }
- }),
- image && selectedSlug
- ? jsx(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- className: 'justify-center',
- onClick: () => {
- setSelectedSlug(null)
- onImage(null)
- },
- children: 'Remove — back to shape avatar'
- })
- : null,
- filtered.length === 0
- ? jsx('div', {
- className: 'py-3 text-center text-xs text-(--ui-text-quaternary)',
- children: 'No pets match.'
- })
- : jsxs('div', {
- onScroll,
- style: { maxHeight: 220, overflowY: 'auto' },
- children: [
- jsx('div', {
- style: {
- display: 'grid',
- gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
- gap: '6px'
- },
- children: visible.map(pet =>
- jsxs(
- 'button',
- {
- type: 'button',
- 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)'
- ),
- onClick: () => {
- // The pet IS the profile picture: extract frame 0
- // and hand it to the dialog as the avatar image.
- // Persisted when the user hits Save.
- setSelectedSlug(pet.slug)
- void petFrameIcon(pet.spritesheetUrl).then(icon => {
- if (icon) {
- onImage(icon)
- } else {
- setSelectedSlug(null)
- host.notify({ kind: 'error', message: 'Could not load that pet — try another.' })
- }
- })
- },
- children: [
- jsx(PetThumb, { spriteUrl: pet.spritesheetUrl, size: 40 }),
- jsx('span', {
- className: 'w-full truncate text-center text-[0.6rem] text-(--ui-text-tertiary)',
- children: pet.displayName
- })
- ]
- },
- pet.slug
- )
- )
- }),
- limit < ranked.length
- ? jsx('div', {
- className: 'py-2 text-center text-[0.65rem] text-(--ui-text-quaternary)',
- children: `Scroll for more (${limit} of ${ranked.length})`
+ }}
+ />
+ {image && selectedSlug ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="justify-center"
+ onClick={() => {
+ setSelectedSlug(null)
+ onImage(null)
+ }}
+ >
+ Remove — back to shape avatar
+ </Button>
+ ) : null}
+ {filtered.length === 0 ? (
+ <div className="py-3 text-center text-xs text-(--ui-text-quaternary)">No pets match.</div>
+ ) : (
+ <div
+ onScroll={onScroll}
+ style={{
+ maxHeight: 220,
+ overflowY: 'auto'
+ }}
+ >
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
+ gap: '6px'
+ }}
+ >
+ {visible.map(pet => (
+ <button
+ key={pet.slug}
+ type="button"
+ 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)'
+ )}
+ onClick={() => {
+ // The pet IS the profile picture: extract frame 0
+ // and hand it to the dialog as the avatar image.
+ // Persisted when the user hits Save.
+ setSelectedSlug(pet.slug)
+ void petFrameIcon(pet.spritesheetUrl).then(icon => {
+ if (icon) {
+ onImage(icon)
+ } else {
+ setSelectedSlug(null)
+ host.notify({
+ kind: 'error',
+ message: 'Could not load that pet — try another.'
+ })
+ }
})
- : null
- ]
- })
- ]
- })
+ }}
+ >
+ <PetThumb spriteUrl={pet.spritesheetUrl} size={40} />
+ <span className="w-full truncate text-center text-[0.6rem] text-(--ui-text-tertiary)">
+ {pet.displayName}
+ </span>
+ </button>
+ ))}
+ </div>
+ {limit < ranked.length ? (
+ <div className="py-2 text-center text-[0.65rem] text-(--ui-text-quaternary)">{`Scroll for more (${limit} of ${ranked.length})`}</div>
+ ) : null}
+ </div>
+ )}
+ </div>
+ )
}
// ── data ─────────────────────────────────────────────────────────────────────
@@ -4675,10 +4738,8 @@ function PetTab({ image, onImage }) {
* protocol into the system prompt itself (hermes-agent bot_mode_probe).
* Gates every SOUL.md protocol append below. */
let serverInjectsProtocol = false
-
function useRoster() {
const activeConnectionId = useValue(host.state.connectionId)
-
return useQuery({
queryKey: [...ROSTER_KEY, activeConnectionId],
queryFn: async () => {
@@ -4705,7 +4766,9 @@ function useRoster() {
}
// 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 activeBot = {
+ name: String(host.state.profile?.get?.() || 'default').trim() || 'default'
+ }
const local = await requestForBot(activeBot, 'profiles.list', {})
// Newer backends inject the teammate-messaging protocol into every
// session's system prompt (agent.bot_mode_protocol) — SOUL.md must not
@@ -4723,7 +4786,6 @@ function useRoster() {
const previous = $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)),
@@ -4734,8 +4796,10 @@ function useRoster() {
/* older build or roster failure — single-source list stands */
}
}
-
- return { ...(local && typeof local === 'object' ? local : {}), fetchedAt: issuedAt }
+ return {
+ ...(local && typeof local === 'object' ? local : {}),
+ fetchedAt: issuedAt
+ }
},
refetchInterval: 5000,
staleTime: 5000,
@@ -4756,37 +4820,29 @@ function cachedUnionRoster() {
if (typeof queryClient === 'undefined' || !queryClient || typeof queryClient.getQueryData !== 'function') {
return null
}
-
try {
- const connectionId = String(
- host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local'
- )
+ const connectionId = String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
const exact = queryClient.getQueryData([...ROSTER_KEY, connectionId])
-
if (Array.isArray(exact?.profiles)) {
return exact
}
-
if (typeof queryClient.getQueriesData === 'function') {
let best = null
// v5 takes a filters object; a legacy v3 queryClient treats the same
// object as the key itself and simply matches nothing — harmless.
- for (const [, data] of queryClient.getQueriesData({ queryKey: ROSTER_KEY })) {
- if (
- Array.isArray(data?.profiles) &&
- (!best || Number(data.fetchedAt || 0) > Number(best.fetchedAt || 0))
- ) {
+ for (const [, data] of queryClient.getQueriesData({
+ queryKey: ROSTER_KEY
+ })) {
+ if (Array.isArray(data?.profiles) && (!best || Number(data.fetchedAt || 0) > Number(best.fetchedAt || 0))) {
best = data
}
}
-
return best
}
} catch {
/* cache hiccup — caller falls back (middleware refetches) */
}
-
return null
}
@@ -4826,9 +4882,9 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])
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())
+ agent =>
+ String(agent?.connectionId || '').trim() === primaryId && richNames.has(String(agent?.profile || '').trim())
)
-
if (!localMatches && primaryId && primaryMatches) {
activeId = primaryId
}
@@ -4841,36 +4897,32 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])
// 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, name })
+ activeByName.set(name, {
+ ...profile,
+ name
+ })
}
}
-
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()
-
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
@@ -4881,7 +4933,6 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])
// 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.
@@ -4899,13 +4950,11 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])
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,
@@ -4936,34 +4985,35 @@ function mergeMultiSourceRoster(local, union, activeConnectionId, previous = [])
.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, remoteSource: true, sourceScoped: true })
+ profiles.push({
+ ...row,
+ remoteSource: true,
+ sourceScoped: true
+ })
present.add(key)
}
}
}
-
- return { ...local, profiles }
+ return {
+ ...local,
+ profiles
+ }
}
/** The @handle users tag a bot with. Multi-source rosters precompute the
@@ -4975,7 +5025,6 @@ function botHandle(name, bot) {
if (bot?.handle && bot.handle !== name) {
return bot.handle
}
-
return (name || '').trim().toLowerCase() === 'default' ? 'hermes' : name
}
@@ -4986,15 +5035,14 @@ function botHandle(name, bot) {
* (researchbuddy). Reserved tokens are dropped so a bot renamed "Hermes"
* can never hijack the primary profile's @hermes alias. */
function mentionNameForms(value) {
- const name = String(value || '').trim().toLowerCase()
-
+ 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)
)
@@ -5015,7 +5063,6 @@ function botFriendlyNames(bot) {
? 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]
}
@@ -5025,64 +5072,61 @@ function botFriendlyNames(bot) {
function botMentionTag(bot) {
for (const friendly of botFriendlyNames(bot)) {
const forms = mentionNameForms(friendly)
-
if (forms.length) {
return forms[0]
}
}
-
return botHandle(bot?.name, bot)
}
-
function isActiveRosterBot(bot, active) {
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
}
-
function botSelectionKey(bot) {
return bot?.sourceScoped || bot?.remoteSource ? botRosterKey(bot) : bot?.name
}
-
function isDefaultBot(bot) {
const route = botConnectionRoute(bot)
-
- return String(route?.profile || bot?.name || '').trim().toLowerCase() === 'default'
+ return (
+ String(route?.profile || bot?.name || '')
+ .trim()
+ .toLowerCase() === 'default'
+ )
}
-
function newBotChat(bot) {
if (typeof host.newChat !== 'function') {
- host.notify?.({ kind: 'error', message: 'Update Hermes Desktop to open another Bot chat.' })
-
+ host.notify?.({
+ kind: 'error',
+ message: 'Update Hermes Desktop to open another Bot chat.'
+ })
return
}
-
const route = botConnectionRoute(bot)
-
if (!route) {
- host.notify?.({ kind: 'error', message: 'Update Hermes Desktop to open another Bot chat.' })
-
+ host.notify?.({
+ kind: 'error',
+ message: 'Update Hermes Desktop to open another Bot chat.'
+ })
return
}
-
const ownerKey = botWorkspaceOwnerKey(bot)
setBotsWorkspaceOwner(ownerKey, bot)
- host.newChat(route, { workspaceMode: 'bots', workspaceOwnerKey: ownerKey })
+ host.newChat(route, {
+ workspaceMode: 'bots',
+ workspaceOwnerKey: ownerKey
+ })
}
/** Resolve @handles in prose against the Bot Mode roster (local + Connections).
@@ -5090,18 +5134,17 @@ function newBotChat(bot) {
* duplicate names require the @name-device handle. */
function resolveRosterMentions(text, roster, active = {}) {
const members = Array.isArray(roster) ? roster : []
- const prose = String(text || '').replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ')
+ const prose = String(text || '')
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`[^`\n]*`/g, ' ')
const byForm = new Map()
-
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())
}
@@ -5114,51 +5157,38 @@ function resolveRosterMentions(text, roster, active = {}) {
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 = []
const seen = new Set()
-
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
}
@@ -5170,29 +5200,23 @@ function resolveRosterMentions(text, roster, active = {}) {
function botRosterKey(bot) {
return `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`
}
-
function botRouteKey(route) {
return `${route.connectionId}::${route.profile}`
}
-
function botMetaKey(bot) {
const route = botConnectionRoute(bot)
-
return route ? botRouteKey(route) : bot?.name
}
-
function persistBotMetaSnapshot(value, scoped = false) {
try {
const persisted = scoped
? commitBotMetaV2(pluginCtx?.storage, value)
: Promise.resolve(pluginCtx?.storage?.set?.(BOT_META_V1_KEY, value))
-
return persisted.catch(() => undefined)
} catch {
return Promise.resolve()
}
}
-
function sourceByConnection(sources) {
return new Map(
(Array.isArray(sources) ? sources : [])
@@ -5204,18 +5228,20 @@ function sourceByConnection(sources) {
/** Copy current source health onto a row without changing its owner. */
function annotateBotSource(bot, sources) {
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 ? { ...bot, sourceMissing: true, sourceReachable: false } : bot
+ return list.length && bot?.sourceScoped
+ ? {
+ ...bot,
+ sourceMissing: true,
+ sourceReachable: false
+ }
+ : bot
}
-
return {
...bot,
connectionKind: bot.connectionKind || source.kind,
@@ -5225,27 +5251,46 @@ function annotateBotSource(bot, sources) {
sourceReachable: source.reachable
}
}
-
function botSourceStatus(bot) {
const error = String(bot?.sourceError || '').trim()
-
if (bot?.sourceMissing) {
- return { available: false, key: 'missing', label: 'Gateway removed', tone: 'bad' }
+ return {
+ available: false,
+ key: 'missing',
+ label: 'Gateway removed',
+ tone: 'bad'
+ }
}
-
if (error === 'connect-on-demand') {
- return { available: true, key: 'on-demand', label: 'On demand', tone: 'muted' }
+ return {
+ available: true,
+ key: 'on-demand',
+ label: 'On demand',
+ tone: 'muted'
+ }
}
-
if (error || bot?.sourceReachable === false) {
- return { available: false, key: 'unavailable', label: 'Unavailable', tone: 'warn' }
+ return {
+ available: false,
+ key: 'unavailable',
+ label: 'Unavailable',
+ tone: 'warn'
+ }
}
-
if (bot?.sourceReachable === true) {
- return { available: true, key: 'ready', label: 'Ready', tone: 'good' }
+ return {
+ available: true,
+ key: 'ready',
+ label: 'Ready',
+ tone: 'good'
+ }
+ }
+ return {
+ available: true,
+ key: 'unknown',
+ label: 'Status unknown',
+ tone: 'muted'
}
-
- return { available: true, key: 'unknown', label: 'Status unknown', tone: 'muted' }
}
/** Drop unreachable same-name copies from the top-level agent list.
@@ -5263,13 +5308,11 @@ function botSourceStatus(bot) {
function preferReachableSameNameRows(bots) {
const rows = Array.isArray(bots) ? bots : []
const reachableNames = new Set()
-
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))
}
// ── cross-connection routing ─────────────────────────────────────────────────
@@ -5284,9 +5327,11 @@ function preferReachableSameNameRows(bots) {
* exception the strict wrapper below happens to throw. */
function resolveBotConnectionRoute(bot) {
if (!bot?.sourceScoped && !bot?.remoteSource) {
- return { status: 'not_scoped', route: null }
+ return {
+ status: 'not_scoped',
+ route: null
+ }
}
-
const candidate = bot.route || {
connectionId: bot.connectionId,
mode: bot.connectionKind === 'local' ? 'local' : 'remote',
@@ -5296,11 +5341,13 @@ function resolveBotConnectionRoute(bot) {
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', route: null, profile }
+ return {
+ status: 'owner_removed',
+ route: null,
+ profile
+ }
}
-
return {
status: 'resolved',
route: Object.freeze({
@@ -5320,47 +5367,44 @@ function resolveBotConnectionRoute(bot) {
* resolveBotConnectionRoute() directly instead of catching this throw. */
function botConnectionRoute(bot) {
const resolved = resolveBotConnectionRoute(bot)
-
if (resolved.status === 'owner_removed') {
throw new Error(`Bot ${resolved.profile} has no connection owner`)
}
-
return resolved.route
}
-
const BOTS_HOME_OWNER_KEY = 'bots:home'
-
function botWorkspaceOwnerKey(bot) {
// Render-reachable (sidebar sync, Bots home open, 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')}`
}
-
function groupWorkspaceOwnerKey(group) {
return `group:${groupChatRoomKey(group, $groupChats.get()[group])}`
}
-
function setBotsWorkspaceOwner(ownerKey, bot = null, blockedMessage = 'Select a Bot or group first.') {
// 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 = route ? { kind: 'route', route } : { kind: 'blocked', message: blockedMessage }
-
+ const target = route
+ ? {
+ kind: 'route',
+ route
+ }
+ : {
+ kind: 'blocked',
+ message: blockedMessage
+ }
host.setWorkspaceScope?.('bots', ownerKey || BOTS_HOME_OWNER_KEY, target)
}
function backendTargetProfile(route, fallbackProfile = 'default') {
if (!route) {
return fallbackProfile
}
-
return route.targetProfile || route.profile
}
-
function rewriteCliProfileOperands(argv, logical, target) {
const next = [...argv]
-
for (let index = 0; index < next.length; index += 1) {
if (next[index] === '--profile' && next[index + 1] === logical) {
next[index + 1] = target
@@ -5369,58 +5413,61 @@ function rewriteCliProfileOperands(argv, logical, target) {
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, method, params) {
const logical = route.profile
const target = backendTargetProfile(route, logical)
let next = params
-
if (Object.prototype.hasOwnProperty.call(params, 'profile')) {
- next = { ...next, profile: target }
+ next = {
+ ...next,
+ profile: target
+ }
}
-
if (method.startsWith('profiles.') && method !== 'profiles.create' && params.name === logical) {
- next = { ...next, name: target }
+ next = {
+ ...next,
+ name: target
+ }
}
-
if (params.clone_from === logical) {
- next = { ...next, clone_from: target }
+ next = {
+ ...next,
+ clone_from: target
+ }
}
-
if (method === 'cli.exec' && Array.isArray(params.argv)) {
- next = { ...next, argv: rewriteCliProfileOperands(params.argv, logical, target) }
+ next = {
+ ...next,
+ argv: rewriteCliProfileOperands(params.argv, logical, target)
+ }
}
-
return next
}
-
function botBackendProfileScope(route, fallbackProfile = 'default') {
if (!route) {
return fallbackProfile
}
-
- return { connectionId: route.connectionId, profile: backendTargetProfile(route, fallbackProfile) }
+ return {
+ connectionId: route.connectionId,
+ profile: backendTargetProfile(route, fallbackProfile)
+ }
}
/** Gateway RPC on the bot's OWN source. Source-scoped rows always use the
* explicit descriptor, including a registered local source. */
async function requestForBot(bot, method, params = {}) {
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) {
@@ -5430,7 +5477,6 @@ async function requestForBot(bot, method, params = {}) {
throw asRpcError(error, `Gateway request ${method} failed`)
}
}
-
try {
return await host.request(method, params)
} catch (error) {
@@ -5457,18 +5503,15 @@ function asRpcError(value, fallback) {
const hasStringName = typeof name === 'string'
const hasStringMessage = typeof message === 'string'
const hasStack = isObject && typeof value.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))
}
@@ -5484,17 +5527,19 @@ function groupMemberKey(member) {
function groupSessionOwner(member) {
const route = botConnectionRoute(member)
const name = String(route?.profile || member?.name || '').trim() || 'default'
-
if (!route) {
- return { name }
+ return {
+ name
+ }
}
-
return {
connectionId: route.connectionId,
name,
sourceScoped: true,
remoteSource: route.mode !== 'local',
- route: { ...route }
+ route: {
+ ...route
+ }
}
}
@@ -5521,28 +5566,29 @@ let aliasRouteIndex = new Map()
* genuine aliases (route.profile !== route.targetProfile) participate. */
function indexAliasRoutes(routes) {
const next = new Map()
-
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
// may claim the identity.
- next.set(key, next.has(key) ? null : {
- name: profile,
- // Alias meta can live under the source-qualified v2 key or the bare
- // v1 name key (aliases predate the v2 migration on mixed setups).
- metaKeys: [`${connectionId}::${profile}`, profile]
- })
+ next.set(
+ key,
+ next.has(key)
+ ? null
+ : {
+ name: profile,
+ // Alias meta can live under the source-qualified v2 key or the bare
+ // v1 name key (aliases predate the v2 migration on mixed setups).
+ metaKeys: [`${connectionId}::${profile}`, profile]
+ }
+ )
}
-
aliasRouteIndex = next
}
@@ -5553,7 +5599,6 @@ function aliasIdentityFor(bot) {
if (!aliasRouteIndex.size) {
return null
}
-
const connectionId = String(
bot?.connectionId ||
bot?.route?.connectionId ||
@@ -5561,14 +5606,11 @@ function aliasIdentityFor(bot) {
// 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
}
@@ -5586,15 +5628,11 @@ function botRosterMeta(bot, metaByName) {
// route" without masking an unrelated failure under the same catch.
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]) {
@@ -5602,18 +5640,13 @@ function botRosterMeta(bot, metaByName) {
}
}
}
-
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]) {
@@ -5621,12 +5654,15 @@ function botRosterMeta(bot, metaByName) {
}
}
}
-
return own
}
-
function showsHandle(name, meta, bot) {
- const display = displayName({ name }, meta)
+ const display = displayName(
+ {
+ name
+ },
+ meta
+ )
return Boolean(name && display.toLowerCase() !== botHandle(name, bot).toLowerCase())
}
@@ -5652,17 +5688,13 @@ let botOpenGeneration = 0
/** The one canonical title. (profile, CANONICAL_CHAT_TITLE) IS the bot's
* forever-chat identity — see the header above. */
const CANONICAL_CHAT_TITLE = 'Bot Chat'
-
async function openStoredBotChat(owner, storedId, summary) {
if (!storedId || typeof host.openSession !== 'function') {
throw new Error('This Hermes Desktop version cannot open stored sessions')
}
-
const { bot, name, route } = botOwner(owner)
const ownerKey = botWorkspaceOwnerKey(bot)
-
- const hasAuthoritativeCount =
- typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
+ const hasAuthoritativeCount = typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
const expectHistory = hasAuthoritativeCount ? summary.message_count > 0 : true
// Current SDKs export the Bot-specific budget. The fallback preserves
// compatibility with older hosts and isolated plugin test harnesses.
@@ -5685,7 +5717,11 @@ async function openStoredBotChat(owner, storedId, summary) {
// until an app restart (hermes-agent#93604). A resume is cheap and
// idempotent, so on this explicit user navigation we always request one.
await host.openSession(storedId, {
- ...(route ? { route } : {}),
+ ...(route
+ ? {
+ route
+ }
+ : {}),
profile: name,
intent: 'tab',
awaitHydration: true,
@@ -5698,7 +5734,6 @@ async function openStoredBotChat(owner, storedId, summary) {
retryHydrationTimeoutOnce: true,
tabTitle: CANONICAL_CHAT_TITLE
})
-
return storedId
}
@@ -5710,26 +5745,20 @@ function isCanonicalBotChatHistory(history) {
const title = String(history?.title || '').trim()
return rootTitle === CANONICAL_CHAT_TITLE || (!rootTitle && title === CANONICAL_CHAT_TITLE)
}
-
function botModeGatewayNeedsUpdate(error) {
const message = String(error?.message || error || '')
-
return /(?:method not found|no handler for|unknown method|unsupported rpc)/i.test(message)
}
-
function notifyBotOpenFailure(error, bot, fallbackMessage) {
if (botModeGatewayNeedsUpdate(error)) {
const gateway = bot.connectionLabel || bot.connectionId || 'this gateway'
-
host.notify?.({
kind: 'error',
title: 'Update this gateway to use Bot Mode',
message: `Update ${gateway}, then try again.`
})
-
return
}
-
host.notifyError?.(error, fallbackMessage)
}
@@ -5771,7 +5800,6 @@ async function findExistingCanonicalChat(owner) {
const detail = message ? ` (${message})` : ''
throw new Error(`Could not check ${name}'s Bot Chat registry${detail} — not starting a new chat`)
}
-
const rows = res?.sessions ?? []
return rows.find(row => isCanonicalBotChatHistory(row)) || null
}
@@ -5802,16 +5830,18 @@ async function findExistingCanonicalChat(owner) {
function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = null } = {}) {
const { bot, name, key, route } = botOwner(owner)
const inflight = canonicalCreations.get(key)
-
if (inflight) {
if (!openingStillCurrent) {
return inflight.run
}
-
return inflight.run.then(async sid => {
if (sid && openingStillCurrent() && typeof host.openSession === 'function') {
await host.openSession(sid, {
- ...(route ? { route } : {}),
+ ...(route
+ ? {
+ route
+ }
+ : {}),
profile: name,
intent: 'main',
keepAllProfilesScope: route ? true : false,
@@ -5823,23 +5853,20 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
return sid
})
}
-
- const flight = { run: null }
+ const flight = {
+ run: null
+ }
const canNavigate = () => !openingStillCurrent || openingStillCurrent()
-
const run = (async () => {
const existing = await findExistingCanonicalChat(owner)
-
if (existing?.id) {
if (typeof host.openSession === 'function' && canNavigate()) {
// The exact-lookup gateway reports the compression-lineage tip as
// resolved_id; open the tip, the registry row stays the identity.
await openStoredBotChat(owner, existing.resolved_id || existing.id, existing)
}
-
return existing.id
}
-
const res = await requestForBot(bot, 'session.create', {
profile: backendTargetProfile(route, name),
title: CANONICAL_CHAT_TITLE,
@@ -5863,10 +5890,12 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// untitled window. Older gateways may not support the eager write; retain
// the kickoff-and-retry fallback below.
let titled = false
-
if (runtime) {
try {
- await requestForBot(bot, 'session.title', { session_id: runtime, title: CANONICAL_CHAT_TITLE })
+ await requestForBot(bot, 'session.title', {
+ session_id: runtime,
+ title: CANONICAL_CHAT_TITLE
+ })
titled = true
} catch (error) {
// ADOPT-BEFORE-MINT: a title-uniqueness rejection is not an old
@@ -5879,12 +5908,10 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// (the gateway prunes it).
if (/already in use/i.test(String(error?.message || ''))) {
const winner = await findExistingCanonicalChat(owner)
-
if (winner?.id) {
if (typeof host.openSession === 'function') {
await openStoredBotChat(owner, winner.resolved_id || winner.id, winner)
}
-
return winner.id
}
}
@@ -5895,16 +5922,23 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// Mount the session view FIRST, then send the kickoff — submitting into
// an unmounted session left the intro reply invisible until reopen.
let opened = false
-
if (sid && typeof host.openSession === 'function' && canNavigate()) {
try {
await host.openSession(sid, {
- ...(route ? { route } : {}),
+ ...(route
+ ? {
+ route
+ }
+ : {}),
profile: name,
intent: 'main',
keepAllProfilesScope: route ? true : false,
...(openingStillCurrent
- ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }
+ ? {
+ workspaceMode: 'bots',
+ workspaceOwnerKey: botWorkspaceOwnerKey(bot),
+ tabTitle: CANONICAL_CHAT_TITLE
+ }
: {})
})
opened = true
@@ -5913,7 +5947,6 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// after prompt.submit below instead of leaving the chat off-screen.
}
}
-
if (runtime) {
// Intro turn: only on genuine New Agent creation (`kickoff`), or as the
// COMPAT persistence write when the eager title failed — an old gateway
@@ -5921,21 +5954,29 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// the chat never survives its own creation. A titled row needs neither:
// the user speaks first.
const submitIntro = kickoff || !titled
-
if (submitIntro) {
await new Promise(resolve => window.setTimeout(resolve, 400))
-
try {
- await requestForBot(bot, 'prompt.submit', { session_id: runtime, text: 'Hey, tell me about yourself!' })
-
+ await requestForBot(bot, 'prompt.submit', {
+ session_id: runtime,
+ text: 'Hey, tell me about yourself!'
+ })
if (!opened && sid && typeof host.openSession === 'function' && canNavigate()) {
await host.openSession(sid, {
- ...(route ? { route } : {}),
+ ...(route
+ ? {
+ route
+ }
+ : {}),
profile: name,
intent: 'main',
keepAllProfilesScope: route ? true : false,
...(openingStillCurrent
- ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }
+ ? {
+ workspaceMode: 'bots',
+ workspaceOwnerKey: botWorkspaceOwnerKey(bot),
+ tabTitle: CANONICAL_CHAT_TITLE
+ }
: {})
})
}
@@ -5948,12 +5989,20 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
// raced the (now titled) row.
try {
await host.openSession(sid, {
- ...(route ? { route } : {}),
+ ...(route
+ ? {
+ route
+ }
+ : {}),
profile: name,
intent: 'main',
keepAllProfilesScope: route ? true : false,
...(openingStillCurrent
- ? { workspaceMode: 'bots', workspaceOwnerKey: botWorkspaceOwnerKey(bot), tabTitle: CANONICAL_CHAT_TITLE }
+ ? {
+ workspaceMode: 'bots',
+ workspaceOwnerKey: botWorkspaceOwnerKey(bot),
+ tabTitle: CANONICAL_CHAT_TITLE
+ }
: {})
})
} catch {
@@ -5961,17 +6010,14 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
}
}
}
-
return sid || null
})().finally(() => {
if (canonicalCreations.get(key) === flight) {
canonicalCreations.delete(key)
}
})
-
flight.run = run
canonicalCreations.set(key, flight)
-
return run
}
@@ -5985,7 +6031,6 @@ function createCanonicalChat(owner, { kickoff = false, openingStillCurrent = nul
* bot's chat opens without re-homing Desktop's chrome. */
async function openBotCanonicalChat(owner, openingStillCurrent = null) {
const existing = await findExistingCanonicalChat(owner)
-
if (existing?.id && typeof host.openSession === 'function') {
if (openingStillCurrent && !openingStillCurrent()) {
return null
@@ -5996,13 +6041,21 @@ async function openBotCanonicalChat(owner, openingStillCurrent = null) {
// chat; the resolved lineage tip is what actually takes session focus.
// Callers matching focus against only the registry id mistook every
// compressed Bot Chat for a stale open (first click bounced to the home).
- return { registryId: String(existing.id), openedId: String(openedId) }
+ return {
+ registryId: String(existing.id),
+ openedId: String(openedId)
+ }
}
-
- const created = await createCanonicalChat(owner, { openingStillCurrent })
- return created ? { registryId: String(created), openedId: String(created) } : null
+ const created = await createCanonicalChat(owner, {
+ openingStillCurrent
+ })
+ return created
+ ? {
+ registryId: String(created),
+ openedId: String(created)
+ }
+ : null
}
-
async function prepareBotSource(bot) {
if (!bot.sourceScoped) {
return
@@ -6013,35 +6066,35 @@ async function prepareBotSource(bot) {
// activation is a UI concern that never authorizes the calls. All this
// gate does is refuse when the desktop predates routed profile requests.
const route = botConnectionRoute(bot)
-
if (route && typeof host.requestProfile !== 'function') {
throw new Error('Update Hermes Desktop to chat with agents on other connections.')
}
-
if (!route && typeof host.ensureAgent === 'function') {
// Source-annotated row on the ACTIVE connection (no captured route):
// legacy activation path, unchanged.
await host.ensureAgent(bot.connectionId, bot.name)
}
}
-
async function ensureBotMetadata(bot) {
if (!bot?.sourceScoped) {
return botRosterMeta(bot, $botMeta.get()) || {}
}
-
const route = botConnectionRoute(bot)
const backendProfile = backendTargetProfile(route, bot.name)
const result = await requestForBot(bot, 'profiles.list', {})
const row = (result?.profiles || []).find(profile => profile?.name === backendProfile)
const server = row?.ui_meta?.['hermes-bots']
-
if (server && typeof server === 'object') {
const key = botMetaKey(bot)
- $botMeta.set({ ...$botMeta.get(), [key]: { ...($botMeta.get()[key] || {}), ...server } })
+ $botMeta.set({
+ ...$botMeta.get(),
+ [key]: {
+ ...($botMeta.get()[key] || {}),
+ ...server
+ }
+ })
persistBotMetaSnapshot($botMeta.get(), true)
}
-
return botRosterMeta(bot, $botMeta.get()) || {}
}
@@ -6058,45 +6111,43 @@ async function openRosterBot(bot) {
// center from a group the user was reading.
const previousGroup = $groupChatWorkspace.get()
const previousGroupRef = previousGroup
- ? { group: previousGroup, roomId: String($groupChats.get()[previousGroup]?.roomId || '') }
+ ? {
+ 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)
+ ? Object.keys(rooms).find(
+ name => !rooms[name]?.tombstone && String(rooms[name]?.roomId || '') === restoreRef.roomId
+ )
: liveGroupChatNames().includes(restoreRef.group)
? restoreRef.group
: null
-
if (!currentGroup) {
return
}
-
openGroupChat(currentGroup)
}
-
if ($botUnread.get()[key]) {
- const next = { ...$botUnread.get() }
+ const next = {
+ ...$botUnread.get()
+ }
delete next[key]
$botUnread.set(next)
}
-
try {
// Activation selects this row's source only. Canonical identity is resolved
// after that by the owner profile's "Bot Chat" title registry.
@@ -6106,24 +6157,18 @@ async function openRosterBot(bot) {
$openBotChat.set(null)
restorePreviousGroup()
syncBotsHomeWorkspace()
-
notifyBotOpenFailure(error, bot, `Could not reach ${bot.connectionLabel || 'the gateway'}`)
}
-
return false
}
-
if (generation !== botOpenGeneration) {
return false
}
-
try {
const opened = await openBotCanonicalChat(bot, () => generation === botOpenGeneration)
-
if (generation !== botOpenGeneration) {
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
@@ -6146,10 +6191,8 @@ async function openRosterBot(bot) {
$openBotChat.set(null)
restorePreviousGroup()
syncBotsHomeWorkspace()
-
notifyBotOpenFailure(error, bot, `Could not open ${displayName(bot, meta)}'s chat — try again`)
}
-
return false
}
@@ -6161,13 +6204,14 @@ async function openRosterBot(bot) {
syncBotsHomeWorkspace()
return false
}
-
- $openBotChat.set({ key, openedRegistryId: '' })
+ $openBotChat.set({
+ key,
+ openedRegistryId: ''
+ })
closeBotsHomeWorkspace()
newBotChat(bot)
return true
}
-
function displayName(bot, meta) {
// A configured alias route claiming this row overrides source-derived
// identity: the friendly alias name must survive hosted-session
@@ -6179,10 +6223,15 @@ function displayName(bot, meta) {
// "Hermes". Annotated active rows carry sourceScoped too, and keying this
// off sourceScoped renamed the user's main agent to an IP-derived label
// (community report, Aug 17 2026).
- if (bot?.remoteSource && (bot.name || '').trim().toLowerCase() === 'default' && bot.connectionLabel && !alias && !meta?.title?.trim()) {
+ if (
+ bot?.remoteSource &&
+ (bot.name || '').trim().toLowerCase() === 'default' &&
+ bot.connectionLabel &&
+ !alias &&
+ !meta?.title?.trim()
+ ) {
return bot.connectionLabel
}
-
if (meta?.title?.trim()) {
return meta.title.trim()
}
@@ -6198,7 +6247,6 @@ function displayName(bot, meta) {
// 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())
}
@@ -6208,7 +6256,6 @@ function displayName(bot, meta) {
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())
}
@@ -6218,11 +6265,9 @@ function displayName(bot, meta) {
* activity order — search narrows the roster, it never re-ranks it. */
function filterBots(roster, metaByName, query) {
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()
@@ -6243,19 +6288,15 @@ function filterBots(roster, metaByName, query) {
)
})
}
-
function filterBotsByGateway(roster, connectionId) {
if (!connectionId || connectionId === 'all') {
return roster
}
-
return (roster || []).filter(bot => String(bot?.connectionId || '') === connectionId)
}
-
function botNeedsHandleLabel(bot, roster, metaByName) {
const identity = displayName(bot, botRosterMeta(bot, metaByName)).trim().toLowerCase()
const connectionId = String(bot?.connectionId || '')
-
return (roster || []).some(
candidate =>
botRosterKey(candidate) !== botRosterKey(bot) &&
@@ -6264,37 +6305,40 @@ function botNeedsHandleLabel(bot, roster, metaByName) {
botHandle(candidate.name, candidate) !== botHandle(bot.name, bot)
)
}
-
function groupMatchesRosterFilters(name, members, metaByName, query, connectionId) {
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 || '').toLowerCase().includes(needle) || filterBots(inGateway, metaByName, needle).length > 0
+ const needle = String(query || '')
+ .trim()
+ .toLowerCase()
+ .replace(/^@/, '')
+ return (
+ !needle ||
+ String(name || '')
+ .toLowerCase()
+ .includes(needle) ||
+ filterBots(inGateway, metaByName, needle).length > 0
+ )
}
-
function rosterGatewayOptions(sources, roster) {
const byId = new Map()
-
for (const source of Array.isArray(sources) ? sources : []) {
const id = String(source?.connectionId || '').trim()
-
if (id) {
- byId.set(id, { ...source, connectionId: id, count: 0 })
+ byId.set(id, {
+ ...source,
+ connectionId: id,
+ count: 0
+ })
}
}
-
for (const bot of roster || []) {
const id = String(bot?.connectionId || '').trim()
-
if (!id) {
continue
}
-
const source = byId.get(id) || {
connectionId: id,
kind: bot.connectionKind,
@@ -6306,24 +6350,28 @@ function rosterGatewayOptions(sources, roster) {
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'
})
)
}
-
function rosterGatewaySections(botRows, gatewayOptions, gatewayFilter = 'all') {
const rows = Array.isArray(botRows) ? botRows : []
const options = Array.isArray(gatewayOptions) ? gatewayOptions : []
-
if (gatewayFilter !== 'all' || options.length <= 1) {
- return { sectioned: false, sections: [{ id: 'all', option: null, rows }] }
+ return {
+ sectioned: false,
+ sections: [
+ {
+ id: 'all',
+ option: null,
+ rows
+ }
+ ]
+ }
}
-
const byId = new Map()
-
for (const row of rows) {
const bot = row?.bot || row
const id = String(bot?.connectionId || 'legacy').trim() || 'legacy'
@@ -6331,27 +6379,25 @@ function rosterGatewaySections(botRows, gatewayOptions, gatewayFilter = 'all') {
bucket.push(row)
byId.set(id, bucket)
}
-
const known = new Set()
const sections = []
-
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, option, rows: sectionRows })
+ sections.push({
+ id,
+ option,
+ rows: sectionRows
+ })
}
-
for (const [id, sectionRows] of byId) {
if (known.has(id)) {
continue
}
-
const bot = sectionRows[0]?.bot || sectionRows[0]
sections.push({
id,
@@ -6365,19 +6411,18 @@ function rosterGatewaySections(botRows, gatewayOptions, gatewayFilter = 'all') {
rows: sectionRows
})
}
-
- return { sectioned: true, sections }
+ return {
+ sectioned: true,
+ sections
+ }
}
-
function gatewayKindIcon(kind) {
const 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
return icons.Network
}
-
function gatewayKindCodicon(kind) {
if (kind === 'local') return 'device-desktop'
if (kind === 'cloud') return 'cloud'
@@ -6389,18 +6434,17 @@ function gatewayKindCodicon(kind) {
* usable until they expose the shared icon namespace. */
function GatewayKindGlyph({ className, kind }) {
const Icon = gatewayKindIcon(kind)
-
- return jsx('span', {
- 'aria-hidden': true,
- className: cn('grid size-3.5 shrink-0 place-items-center', className),
- 'data-connection-kind': kind || 'remote',
- 'data-slot': 'connection-glyph',
- children: Icon
- ? jsx(Icon, { className: 'size-3' })
- : jsx(Codicon, { name: gatewayKindCodicon(kind), className: 'text-[0.75rem]' })
- })
+ return (
+ <span
+ aria-hidden
+ className={cn('grid size-3.5 shrink-0 place-items-center', className)}
+ data-connection-kind={kind || 'remote'}
+ data-slot="connection-glyph"
+ >
+ {Icon ? <Icon className="size-3" /> : <Codicon name={gatewayKindCodicon(kind)} className="text-[0.75rem]" />}
+ </span>
+ )
}
-
function slugify(value) {
return value
.toLowerCase()
@@ -6435,27 +6479,21 @@ function botGroups(meta) {
const groups = []
const seen = new Set()
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
}
-
function groupMembershipPatch(meta, group, enabled) {
const name = String(group || '').trim()
let groups = botGroups(meta)
-
if (enabled) {
if (name && !groups.includes(name)) {
groups = [...groups, name]
@@ -6463,8 +6501,10 @@ function groupMembershipPatch(meta, group, enabled) {
} else {
groups = groups.filter(existing => existing !== name)
}
-
- return { groups, group: groups[0] || null }
+ return {
+ groups,
+ group: groups[0] || null
+ }
}
/** Build the exact metadata cleanup for a room disband. The rendered member
@@ -6476,30 +6516,25 @@ function groupMembershipPatch(meta, group, enabled) {
function groupDisbandMetadataPlan(group, members, room, roster, metaByName) {
const owners = new Map()
const patches = new Map()
-
const rememberOwner = (owner, required = false) => {
if (!owner?.name) {
return
}
-
let key
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)
}
@@ -6519,8 +6554,10 @@ function groupDisbandMetadataPlan(group, members, room, roster, metaByName) {
patches.set(key, groupMembershipPatch(meta, group, false))
}
}
-
- return { owners, patches }
+ return {
+ owners,
+ patches
+ }
}
/** Group chats that should hold a roster row: every group named in bot meta
@@ -6528,17 +6565,14 @@ function groupDisbandMetadataPlan(group, members, room, roster, metaByName) {
* log — cross-connection rooms whose members can't ride bot-meta. */
function groupChatNames(metaByName, rooms) {
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]
}
@@ -6555,7 +6589,6 @@ function liveGroupChatNames() {
* the group's recency key, competing in the same ordering as bot rows. */
function groupLastActivity(room) {
const log = Array.isArray(room?.log) ? room.log : []
-
return log.length ? log[log.length - 1].at || 0 : 0
}
@@ -6563,13 +6596,10 @@ function groupLastActivity(room) {
* the room record's stored descriptors (remote members can't ride bot-meta).
* Prefers the LIVE roster row for a stored descriptor when present. */
function groupChatMemberBots(group, roster, metaByName) {
- const local = (roster || []).filter(
- bot => botGroups(botRosterMeta(bot, metaByName)).includes(group)
- )
+ const local = (roster || []).filter(bot => botGroups(botRosterMeta(bot, metaByName)).includes(group))
const stored = ($groupChats.get()[group] || {}).members || []
const seated = new Set(local.map(botRosterKey))
const remote = []
-
for (const descriptor of stored) {
// Legacy descriptors can carry a FRIENDLY name as `name` (older builds
// persisted display names — #92794: `name: '大司命'` for slug `taiyi`).
@@ -6582,18 +6612,15 @@ function groupChatMemberBots(group, roster, metaByName) {
// 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]
}
@@ -6605,13 +6632,12 @@ function groupChatMemberBots(group, roster, metaByName) {
* never be used as a `profile:` target. */
function resolveLegacyMemberDescriptor(descriptor, roster) {
const rows = roster || []
-
if (rows.some(bot => botRosterKey(bot) === botRosterKey(descriptor))) {
return descriptor
}
-
- const wanted = String(descriptor?.name || '').trim().toLowerCase()
-
+ const wanted = String(descriptor?.name || '')
+ .trim()
+ .toLowerCase()
if (!wanted) {
return descriptor
}
@@ -6626,19 +6652,22 @@ function resolveLegacyMemberDescriptor(descriptor, roster) {
if (bot?.ghost) {
return false
}
-
- return descriptorConnection
- ? String(bot?.connectionId || '') === descriptorConnection
- : !bot?.remoteSource
+ return descriptorConnection ? String(bot?.connectionId || '') === descriptorConnection : !bot?.remoteSource
})
const match = candidates.find(
bot =>
// Case-drifted slug ('Testbot' persisted for profile 'testbot') …
- String(bot?.name || '').trim().toLowerCase() === wanted ||
+ String(bot?.name || '')
+ .trim()
+ .toLowerCase() === wanted ||
// … or a friendly name persisted as `name` ('大司命' for 'taiyi').
- botFriendlyNames(bot).some(name => String(name || '').trim().toLowerCase() === wanted)
+ botFriendlyNames(bot).some(
+ name =>
+ String(name || '')
+ .trim()
+ .toLowerCase() === wanted
+ )
)
-
return match || descriptor
}
@@ -6655,20 +6684,39 @@ function durableGroupChatMembers(bots) {
// 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()
-
+ 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,
- ...(title ? { title } : {}),
- ...(bot.display_name ? { display_name: bot.display_name } : {}),
+ ...(title
+ ? {
+ title
+ }
+ : {}),
+ ...(bot.display_name
+ ? {
+ display_name: bot.display_name
+ }
+ : {}),
connectionId: bot.connectionId,
connectionKind: bot.connectionKind,
connectionLabel: bot.connectionLabel,
- ...(route ? { route, targetProfile: route.targetProfile } : {}),
+ ...(route
+ ? {
+ route,
+ targetProfile: route.targetProfile
+ }
+ : {}),
// A swept/annotated member keeps its degraded mark across the rebuild —
// otherwise the next room send would silently un-mark an orphaned row.
- ...(bot.sourceMissing ? { sourceMissing: true, sourceReachable: false } : {}),
+ ...(bot.sourceMissing
+ ? {
+ sourceMissing: true,
+ sourceReachable: false
+ }
+ : {}),
remoteSource: true,
sourceScoped: Boolean(route)
}
@@ -6678,14 +6726,16 @@ function durableGroupChatMembers(bots) {
/** Existing group names, alphabetical — feeds the Manage-groups dialog. */
function knownGroups(metaByName) {
const names = new Set()
-
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' }))
+ return [...names].sort((a, b) =>
+ a.localeCompare(b, undefined, {
+ sensitivity: 'base'
+ })
+ )
}
// ── group chats: bounded round-robin coordination over a shared room log ─────
@@ -6712,11 +6762,9 @@ const GROUP_CHAT_MAX_MEMBERS = 6
/** "(pass)" (loosely: pass / (pass) / pass.) or empty = the member stayed silent. */
function isGroupPassText(text) {
const trimmed = String(text || '').trim()
-
if (!trimmed) {
return true
}
-
return /^\(?\s*pass\s*\)?\.?$/i.test(trimmed)
}
@@ -6730,31 +6778,26 @@ function isGroupPassText(text) {
* assistant message appears in that range. */
function pickGroupTurnReply(messages, before) {
let passText = 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 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
}
@@ -6766,7 +6809,6 @@ function parseGroupChatMentions(text, members) {
const mentioned = new Set()
let everyone = false
const handles = new Map()
-
for (const member of members) {
const title = String(member.title || '').trim()
// Cross-connection members are also addressable by their @name-device
@@ -6790,34 +6832,30 @@ function parseGroupChatMentions(text, members) {
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 }
+ return {
+ everyone,
+ mentioned
+ }
}
/** Members that should take a turn this round: everyone when no member is
@@ -6826,33 +6864,26 @@ function parseGroupChatMentions(text, members) {
* pulled in mid-conversation joins the next round. */
function resolveGroupResponders(log, members) {
let sinceLastUser = []
-
for (let i = log.length - 1; i >= 0; i--) {
if (log[i].from.kind === 'user') {
sinceLastUser = log.slice(i)
break
}
}
-
const mentioned = new Set()
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)))
}
@@ -6861,9 +6892,7 @@ function rotateGroupSpeakers(members, round) {
if (members.length < 2) {
return members
}
-
const shift = round % members.length
-
return [...members.slice(shift), ...members.slice(0, shift)]
}
@@ -6878,14 +6907,12 @@ function rotateGroupSpeakers(members, round) {
* @hermes handle) so the main agent never loses its name in rooms. */
function groupSpeakerLabel(name) {
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
}
@@ -6898,11 +6925,9 @@ function groupSpeakerLabel(name) {
? 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
}
@@ -6911,24 +6936,22 @@ function groupSpeakerLabel(name) {
function formatGroupChatLine(entry, viewerName) {
// 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 = Array.isArray(entry.images) && entry.images.length
- ? ` ${entry.images
- .map(img => {
- const label = img.kind === 'pdf' ? 'attached PDF' : img.kind === 'file' ? 'attached file' : 'attached image'
- return `[${label}: ${img.name || 'image'}]`
- })
- .join(' ')}`
- : ''
-
+ const attached =
+ Array.isArray(entry.images) && entry.images.length
+ ? ` ${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}`
}
@@ -6944,7 +6967,6 @@ function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }) {
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.`,
'',
@@ -6963,34 +6985,47 @@ function buildGroupChatTurnPrompt({ groupName, members, viewer, deltaLines }) {
* watermark indices consistent with the trimmed array. */
function trimGroupChatLog(log, watermarks, limit = GROUP_CHAT_HISTORY_LIMIT * 4) {
if (log.length <= limit) {
- return { log, watermarks }
+ return {
+ log,
+ watermarks
+ }
}
-
const drop = log.length - limit
const trimmed = {}
-
for (const [name, index] of Object.entries(watermarks || {})) {
trimmed[name] = Math.max(0, index - drop)
}
-
- return { log: log.slice(drop), watermarks: trimmed }
+ return {
+ log: log.slice(drop),
+ watermarks: trimmed
+ }
}
/** Mutate one group's room state through the atom + persist the durable part. */
function updateGroupChat(group, mutate, { sync = true } = {}) {
- const all = { ...$groupChats.get() }
- const current = all[group] || { log: [], watermarks: {}, epoch: 0, running: false }
- const next = mutate({ ...current, log: [...current.log], watermarks: { ...current.watermarks } })
+ const all = {
+ ...$groupChats.get()
+ }
+ const current = all[group] || {
+ log: [],
+ watermarks: {},
+ epoch: 0,
+ running: false
+ }
+ const next = mutate({
+ ...current,
+ log: [...current.log],
+ watermarks: {
+ ...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 = {}
-
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
@@ -6999,7 +7034,6 @@ function updateGroupChat(group, mutate, { sync = true } = {}) {
if (room.tombstone) {
continue
}
-
durable[name] = {
log: room.log,
watermarks: room.watermarks,
@@ -7023,15 +7057,15 @@ function updateGroupChat(group, mutate, { sync = true } = {}) {
syncRevision: Math.max(0, Number(room.syncRevision || 0))
}
}
-
Promise.resolve(pluginCtx?.storage?.set?.('group-chats', durable)).catch(() => undefined)
} catch {
/* storage unavailable — room survives for this window only */
}
if (sync) {
- scheduleGroupChatServerSync(all, { changedRooms: [group] })
+ scheduleGroupChatServerSync(all, {
+ changedRooms: [group]
+ })
}
-
return next
}
@@ -7044,17 +7078,22 @@ async function disbandGroupChat(group, members) {
// Invalidate any in-flight round-robin FIRST: bump the epoch so a running
// drive bails at its next member boundary instead of appending to a room
// the user just discarded.
- const all = { ...$groupChats.get() }
+ const all = {
+ ...$groupChats.get()
+ }
const prior = all[group] || {}
const metaBefore = $botMeta.get()
const cleanup = groupDisbandMetadataPlan(group, members, prior, $lastRoster.get(), metaBefore)
let metadataPersistence = Promise.resolve()
-
if (cleanup.patches.size) {
- const nextMeta = { ...metaBefore }
-
+ const nextMeta = {
+ ...metaBefore
+ }
for (const [key, patch] of cleanup.patches) {
- nextMeta[key] = { ...(nextMeta[key] || {}), ...patch }
+ nextMeta[key] = {
+ ...(nextMeta[key] || {}),
+ ...patch
+ }
noteBotMetaWrite(key)
}
@@ -7066,7 +7105,6 @@ async function disbandGroupChat(group, members) {
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 —
@@ -7074,20 +7112,25 @@ async function disbandGroupChat(group, members) {
// would be persisted by the next unrelated room write and its name would
// count as taken, suffixing a same-name recreate to "<name> 2" forever.
if (prior.running) {
- all[group] = { log: [], watermarks: {}, sessions: {}, epoch: (prior.epoch || 0) + 1, running: false, tombstone: true }
+ all[group] = {
+ log: [],
+ watermarks: {},
+ sessions: {},
+ epoch: (prior.epoch || 0) + 1,
+ running: false,
+ 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() }
-
+ const needs = {
+ ...$groupNeedsYou.get()
+ }
delete needs[group]
$groupNeedsYou.set(needs)
clearGroupClarify(group)
@@ -7096,7 +7139,6 @@ async function disbandGroupChat(group, members) {
// on the next window load.
try {
const durable = {}
-
for (const [name, room] of Object.entries($groupChats.get())) {
if (name !== group && Array.isArray(room.log)) {
durable[name] = {
@@ -7111,12 +7153,14 @@ async function disbandGroupChat(group, members) {
}
}
}
-
await Promise.resolve(pluginCtx?.storage?.set?.('group-chats', durable))
} catch {
/* storage unavailable — the atom reset above still empties the room */
}
- scheduleGroupChatServerSync($groupChats.get(), { allowEmpty: true, deletedRooms: [group] })
+ scheduleGroupChatServerSync($groupChats.get(), {
+ allowEmpty: true,
+ deletedRooms: [group]
+ })
await metadataPersistence
// Persist the cleanup to every exact owner we can prove. saveBotMeta never
@@ -7133,7 +7177,9 @@ async function disbandGroupChat(group, members) {
// ui_meta (the write-fence in mergeServerMeta keeps it from resurrecting
// the membership, but a fresh snapshot is what makes every surface agree).
if (typeof queryClient !== 'undefined' && queryClient?.invalidateQueries) {
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
}
}
@@ -7155,8 +7201,9 @@ function setGroupChatImage(group, image) {
* "Group: <roomId>" title lookup instead of a fresh "Group: <new name>".
* Returns the new name, or null when the target name is taken. */
async function renameGroupChat(oldName, newName, members) {
- const next = String(newName || '').trim().slice(0, 64)
-
+ const next = String(newName || '')
+ .trim()
+ .slice(0, 64)
if (!next || next === oldName) {
return oldName
}
@@ -7165,39 +7212,37 @@ async function renameGroupChat(oldName, newName, members) {
// 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.` })
+ host.notify({
+ kind: 'error',
+ message: `A group named “${next}” already exists.`
+ })
return null
}
// Move the room record wholesale — log, watermarks, sessions, members,
// picture, and runtime flags all belong to the same room under its new name.
- const all = { ...$groupChats.get() }
+ const all = {
+ ...$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 = { ...$groupNeedsYou.get() }
-
+ const needs = {
+ ...$groupNeedsYou.get()
+ }
if (oldName in needs) {
needs[next] = needs[oldName]
delete needs[oldName]
@@ -7215,15 +7260,18 @@ async function renameGroupChat(oldName, newName, members) {
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, { groups, group: groups[0] || null })
+ await saveBotMeta(member, {
+ groups,
+ group: groups[0] || null
+ })
}
// Persist the re-keyed map (updateGroupChat writes the whole durable map).
- updateGroupChat(next, r => r, { sync: false })
+ updateGroupChat(next, r => r, {
+ sync: false
+ })
// A rename is one revisioned state transition: the new identity is updated
// and the old identity is tombstoned together, so cold hydration cannot
// merge the pre-rename room back into the roster.
@@ -7236,7 +7284,6 @@ async function renameGroupChat(oldName, newName, members) {
if ($groupChatWorkspace.get() === oldName) {
$groupChatWorkspace.set(next)
}
-
if (groupChatMainTabs.has(oldName)) {
closeGroupChatMainTab(oldName)
openGroupChat(next)
@@ -7245,12 +7292,12 @@ async function renameGroupChat(oldName, newName, members) {
// Same convergence as disband: drop the pre-rename roster snapshot so the
// old name can't linger anywhere the fence doesn't cover.
if (typeof queryClient !== 'undefined' && queryClient?.invalidateQueries) {
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
}
-
return next
}
-
function groupChatEntryId() {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
return globalThis.crypto.randomUUID()
@@ -7269,7 +7316,6 @@ function normalizeGroupChatText(text) {
const trimmed = String(text || '').trim()
return trimmed === GROUP_EMPTY_SENTINEL ? GROUP_EMPTY_FRIENDLY : trimmed
}
-
function appendGroupChatEntry(group, from, text, thread, images) {
const entry = {
id: groupChatEntryId(),
@@ -7278,7 +7324,6 @@ function appendGroupChatEntry(group, from, text, thread, images) {
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.
@@ -7291,11 +7336,9 @@ function appendGroupChatEntry(group, from, text, thread, images) {
// 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 => {
room.log.push(entry)
return room
@@ -7303,9 +7346,11 @@ function appendGroupChatEntry(group, from, text, thread, images) {
// Needs-you: a member addressing @user badges the group header.
if (from.kind === 'member' && /@user\b/i.test(entry.text)) {
- $groupNeedsYou.set({ ...$groupNeedsYou.get(), [group]: true })
+ $groupNeedsYou.set({
+ ...$groupNeedsYou.get(),
+ [group]: true
+ })
}
-
return entry
}
@@ -7323,16 +7368,13 @@ function uniqueGroupChatName(base, taken) {
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.')
}
@@ -7367,26 +7409,31 @@ async function ensureGroupChatSession(group, member) {
if (!target || target === true) {
continue
}
-
try {
const res = await requestForBot(member, 'session.resume', {
session_id: target,
profile: member.name,
omit_messages: true
})
-
if (res?.session_id) {
const stored = res.session_key || known
-
if (stored) {
updateGroupChat(group, current => {
- current.sessions = { ...(current.sessions || {}), [key]: stored }
- current.sessionOwners = { ...(current.sessionOwners || {}), [key]: groupSessionOwner(member) }
+ current.sessions = {
+ ...(current.sessions || {}),
+ [key]: stored
+ }
+ current.sessionOwners = {
+ ...(current.sessionOwners || {}),
+ [key]: groupSessionOwner(member)
+ }
return current
})
}
-
- return { runtime: res.session_id, stored }
+ return {
+ runtime: res.session_id,
+ stored
+ }
}
} catch (error) {
if (error?.code !== 4007) {
@@ -7396,7 +7443,6 @@ async function ensureGroupChatSession(group, member) {
/* genuinely doesn't exist (4007) — try the next target / fall through to create */
}
}
-
const created = await requestForBot(member, 'session.create', {
profile: member.name,
title,
@@ -7404,18 +7450,24 @@ async function ensureGroupChatSession(group, member) {
hidden: true
})
const stored = created?.stored_session_id || null
-
if (stored) {
updateGroupChat(group, r => {
- r.sessions = { ...(r.sessions || {}), [key]: stored }
- r.sessionOwners = { ...(r.sessionOwners || {}), [key]: groupSessionOwner(member) }
+ r.sessions = {
+ ...(r.sessions || {}),
+ [key]: stored
+ }
+ r.sessionOwners = {
+ ...(r.sessionOwners || {}),
+ [key]: groupSessionOwner(member)
+ }
return r
})
}
-
- return { runtime: created?.session_id || null, stored }
+ return {
+ runtime: created?.session_id || null,
+ stored
+ }
}
-
const GROUP_TURN_TIMEOUT_MS = 180000
const GROUP_TURN_POLL_MS = 2000
@@ -7434,14 +7486,12 @@ function isSessionGoneError(error) {
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 ---
@@ -7452,22 +7502,17 @@ function isSessionGoneError(error) {
* turn — the catch-retry on submit still covers the race. */
async function retainGroupTurnRoute(member) {
const noop = () => undefined
-
let route = 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
@@ -7481,27 +7526,28 @@ async function retainGroupTurnRoute(member) {
* the poll loop keeps a live fallback target. */
async function submitGroupTurnPrompt(member, runtime, stored, text) {
try {
- await requestForBot(member, 'prompt.submit', { session_id: runtime, text })
-
+ await requestForBot(member, 'prompt.submit', {
+ session_id: runtime,
+ text
+ })
return runtime
} catch (error) {
if (!isSessionGoneError(error) || !stored) {
throw error
}
-
const res = await requestForBot(member, 'session.resume', {
session_id: stored,
profile: member.name,
omit_messages: true
})
const fresh = res?.session_id
-
if (!fresh) {
throw error
}
-
- await requestForBot(member, 'prompt.submit', { session_id: fresh, text })
-
+ await requestForBot(member, 'prompt.submit', {
+ session_id: fresh,
+ text
+ })
return fresh
}
}
@@ -7530,14 +7576,14 @@ function syncGroupClarify(group, member, state) {
const requestId = pending?.request_id || null
const all = $groupClarify.get()
const current = all[key]
-
if (!requestId) {
if (current) {
- const next = { ...all }
+ const next = {
+ ...all
+ }
delete next[key]
$groupClarify.set(next)
}
-
return false
}
@@ -7546,7 +7592,6 @@ function syncGroupClarify(group, member, state) {
if (current?.requestId === requestId) {
return true
}
-
const base = {
requestId,
group,
@@ -7557,7 +7602,6 @@ function syncGroupClarify(group, member, state) {
sessionId: state?.session_id || null,
at: Date.now()
}
-
$groupClarify.set({
...all,
[key]: clarify
@@ -7578,16 +7622,19 @@ function syncGroupClarify(group, member, state) {
command: typeof approval.command === 'string' ? approval.command : '',
// The server precomputes the choice set from allow_permanent
// (once/session/always/deny); fall back to the minimal pair.
- choices: Array.isArray(approval.choices) && approval.choices.length
- ? approval.choices.filter(c => typeof c === 'string' && c)
- : ['once', 'deny'],
+ choices:
+ Array.isArray(approval.choices) && approval.choices.length
+ ? approval.choices.filter(c => typeof c === 'string' && c)
+ : ['once', 'deny'],
multiSelect: false,
questions: null
}
})
// A blocked member is a question for the human — badge the room.
- $groupNeedsYou.set({ ...$groupNeedsYou.get(), [group]: true })
-
+ $groupNeedsYou.set({
+ ...$groupNeedsYou.get(),
+ [group]: true
+ })
return true
}
@@ -7596,7 +7643,6 @@ function clearGroupClarify(group) {
const all = $groupClarify.get()
const next = {}
let changed = false
-
for (const [key, value] of Object.entries(all)) {
if (value?.group === group) {
changed = true
@@ -7604,7 +7650,6 @@ function clearGroupClarify(group) {
next[key] = value
}
}
-
if (changed) {
$groupClarify.set(next)
}
@@ -7641,12 +7686,12 @@ async function answerGroupClarify(entry, member, answers) {
answer: typeof answers === 'string' ? answers : ''
})
}
-
const all = $groupClarify.get()
const key = `${entry.group}::${entry.memberKey}`
-
if (all[key]?.requestId === entry.requestId) {
- const next = { ...all }
+ const next = {
+ ...all
+ }
delete next[key]
$groupClarify.set(next)
}
@@ -7665,17 +7710,14 @@ async function runGroupChatMemberTurn(group, member, prompt, thread, images) {
// 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, member, prompt, thread, images) {
const { runtime, stored } = await ensureGroupChatSession(group, member)
-
if (!runtime) {
return null
}
@@ -7684,12 +7726,14 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// poll loop below can tell an explicit stop from ordinary room churn.
const dispatchEpoch = ($groupChats.get()[group] || {}).epoch || 0
const memberKey = groupMemberKey(member)
-
- recordGroupActivity(group, { kind: 'working', member: member.name, thread })
+ recordGroupActivity(group, {
+ kind: 'working',
+ member: member.name,
+ thread
+ })
// Baseline: how many messages exist before our submit.
let before = 0
-
try {
const pre = await requestForBot(member, 'session.resume', {
session_id: stored || runtime,
@@ -7710,12 +7754,10 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// member to text-only; the transcript line still names the attachment so
// the member knows something was shared.
const fileRefs = []
-
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', {
@@ -7729,7 +7771,6 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
data_url: img.data,
name: img.name || 'attachment'
})
-
if (res?.ref_text) {
fileRefs.push(`${img.name || 'attachment'} → ${res.ref_text}`)
}
@@ -7744,7 +7785,6 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
/* text-only fallback for this member */
}
}
-
const turnText = fileRefs.length
? `${prompt}\n\nAttached files staged in your session workspace:\n${fileRefs.join('\n')}`
: prompt
@@ -7753,10 +7793,8 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// minting and submitting. Tracks the runtime id the submit landed on so
// the poll fallback below targets a live session.
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))
@@ -7767,13 +7805,10 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// 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 = null
-
try {
state = await requestForBot(member, 'session.resume', {
session_id: stored || liveRuntime,
@@ -7782,7 +7817,6 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
} 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
@@ -7790,22 +7824,21 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// 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 })
-
+ recordGroupActivity(group, {
+ kind: 'passed',
+ member: member.name,
+ thread
+ })
return null
}
@@ -7821,13 +7854,22 @@ async function runGroupChatMemberTurnLeased(group, member, prompt, thread, image
// clarify timeout runs its own course) and read as a pass, but remember the baseline + thread
// (runtime-only) so the finished reply can be posted late into the RIGHT
// thread instead of vanishing.
- recordGroupActivity(group, { kind: 'timed-out', member: member.name, thread })
+ recordGroupActivity(group, {
+ kind: 'timed-out',
+ member: member.name,
+ thread
+ })
syncGroupClarify(group, member, null)
updateGroupChat(group, r => {
- r.stranded = { ...(r.stranded || {}), [groupMemberKey(member)]: { before, thread } }
+ r.stranded = {
+ ...(r.stranded || {}),
+ [groupMemberKey(member)]: {
+ before,
+ thread
+ }
+ }
return r
})
-
return null
}
@@ -7841,13 +7883,10 @@ async function harvestStrandedGroupReply(group, member) {
// 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 = null
-
try {
const stored = room.sessions?.[memberKey]
state = await requestForBot(member, 'session.resume', {
@@ -7857,7 +7896,6 @@ async function harvestStrandedGroupReply(group, member) {
} catch {
return // source unreachable — leave the marker for the next boundary
}
-
if (state?.inflight || state?.running) {
return // still grinding — keep waiting
}
@@ -7870,25 +7908,35 @@ async function harvestStrandedGroupReply(group, member) {
// Done (or dead): the marker is consumed either way.
updateGroupChat(group, r => {
- const next = { ...(r.stranded || {}) }
+ 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', member: member.name, thread: strandedThread })
+ recordGroupActivity(group, {
+ kind: 'delivered',
+ member: member.name,
+ thread: strandedThread
+ })
appendGroupChatEntry(
group,
- { kind: 'member', name: member.name, ...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {}) },
+ {
+ kind: 'member',
+ name: member.name,
+ ...(member.remoteSource
+ ? {
+ source: member.connectionLabel || member.connectionId
+ }
+ : {})
+ },
reply,
strandedThread
)
@@ -7916,7 +7964,6 @@ function shouldCommitMemberTurn(epochAtDispatch, currentEpoch, newerUserEntryInT
if (epochAtDispatch === currentEpoch) {
return true
}
-
return !newerUserEntryInThread
}
@@ -7926,28 +7973,22 @@ function shouldCommitMemberTurn(epochAtDispatch, currentEpoch, newerUserEntryInT
* 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, from, text, thread, now = Date.now()) {
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()
}
@@ -7970,17 +8011,29 @@ function classifyGroupHoldDirective(text, mentionedKeys, everyone) {
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 { hold: mentioned, holdAll: Boolean(everyone), release: [], releaseAll: false }
+ return {
+ hold: mentioned,
+ holdAll: Boolean(everyone),
+ release: [],
+ releaseAll: false
+ }
}
-
if (resume) {
- return { hold: [], holdAll: false, release: mentioned, releaseAll: Boolean(everyone) }
+ return {
+ hold: [],
+ holdAll: false,
+ release: mentioned,
+ releaseAll: Boolean(everyone)
+ }
+ }
+ return {
+ hold: [],
+ holdAll: false,
+ release: mentioned,
+ releaseAll: false
}
-
- return { hold: [], holdAll: false, release: mentioned, releaseAll: false }
}
/** #93129: next holds map after one user message. Holds are keyed by
@@ -7991,34 +8044,35 @@ function classifyGroupHoldDirective(text, mentionedKeys, everyone) {
function applyGroupHoldDirective(holds, mentions, text, stamp, allMemberKeys = []) {
const prior = holds && typeof holds === 'object' ? holds : {}
const action = classifyGroupHoldDirective(text, mentions?.mentioned || [], Boolean(mentions?.everyone))
-
if (action.releaseAll) {
return Object.keys(prior).length ? {} : prior
}
// "@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 = {
+ ...prior
+ }
+ }
+ next[key] = {
+ at: stamp?.at || Date.now(),
+ byMessageId: stamp?.byMessageId || null,
+ thread: stamp?.thread || null
}
-
- 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) {
- next = { ...prior }
+ next = {
+ ...prior
+ }
}
-
delete next[key]
}
}
-
return next
}
@@ -8038,7 +8092,9 @@ function heldMemberWatermarkAdvance(seen, logLength) {
* (`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, members, thread) {
- const room = $groupChats.get()[group] || { log: [] }
+ const room = $groupChats.get()[group] || {
+ log: []
+ }
const log = (room.log || []).filter(e => groupThreadOf(e) === thread)
// key → log INDEX of the entry that most recently cited this member.
@@ -8046,7 +8102,6 @@ function unaddressedGroupMentions(group, members, 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)
@@ -8055,11 +8110,9 @@ function unaddressedGroupMentions(group, members, thread) {
if (entry.from.kind !== 'member') {
continue
}
-
for (const key of parsed.mentioned) {
const citingMemberKey = (() => {
const m = members.find(mm => mm.name === entry.from?.name)
-
return m ? groupMemberKey(m) : null
})()
@@ -8073,27 +8126,21 @@ function unaddressedGroupMentions(group, members, 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 => 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
})
}
@@ -8121,8 +8168,11 @@ async function stopGroupThread(group, thread, members = null) {
const room = $groupChats.get()[group] || {}
const roster = Array.isArray(members) && members.length ? members : room.members || []
const turnName = room.turn || null
- const stamp = { at: Date.now(), byMessageId: null, thread: thread || null }
-
+ const stamp = {
+ at: Date.now(),
+ byMessageId: null,
+ thread: thread || null
+ }
updateGroupChat(group, r => {
r.epoch = (r.epoch || 0) + 1
r.running = false
@@ -8131,16 +8181,17 @@ async function stopGroupThread(group, thread, members = null) {
// Same hold shape applyGroupHoldDirective mints for "@all stop" — the
// held-skip path (watermark consume + 'held' activity note) and every
// release gesture apply unchanged. An existing hold keeps its stamp.
- const holds = { ...(r.holds || {}) }
-
+ const holds = {
+ ...(r.holds || {})
+ }
for (const member of roster) {
const key = groupMemberKey(member)
-
if (key && !holds[key]) {
- holds[key] = { ...stamp }
+ holds[key] = {
+ ...stamp
+ }
}
}
-
r.holds = holds
return r
})
@@ -8148,16 +8199,21 @@ async function stopGroupThread(group, thread, members = null) {
// Recorded AFTER the bump so the event is tagged with the new epoch — it
// stays visible as the current run's outcome instead of dropping out of
// view with the superseded run's events.
- recordGroupActivity(group, { kind: 'stopped', member: 'You', thread: thread || null })
+ recordGroupActivity(group, {
+ kind: 'stopped',
+ member: 'You',
+ thread: thread || null
+ })
// Interrupt the member actually mid-turn. room.turn is runtime-only and
// names exactly one member (the loop is serial); a settled room has none.
const onTurn = turnName ? roster.find(member => member?.name === turnName) : null
const sessionId = onTurn ? (room.sessions || {})[groupMemberKey(onTurn)] : null
-
if (onTurn && sessionId) {
try {
- await requestForBot(onTurn, 'session.interrupt', { session_id: sessionId })
+ await requestForBot(onTurn, 'session.interrupt', {
+ session_id: sessionId
+ })
} catch {
/* best-effort — the epoch/hold legs above already stopped the room;
the abandoned poll loop exits on its staleness check */
@@ -8179,7 +8235,6 @@ async function runGroupChatRounds(group, members, thread) {
// passed with nothing pending); 'capped' means a round/message/continuation
// cap forced the exit — the activity feed must tell those apart.
let exitKind = 'settled'
-
try {
for (let round = 0; round < GROUP_CHAT_MAX_ROUNDS; round++) {
// Deliver any replies that finished after their turn timed out —
@@ -8187,13 +8242,15 @@ async function runGroupChatRounds(group, members, thread) {
// late, never lost.
for (const member of members) {
if (!isCurrent()) {
- recordGroupActivity(group, { kind: 'cancelled', member: null, thread })
+ recordGroupActivity(group, {
+ kind: 'cancelled',
+ member: null,
+ thread
+ })
return
}
-
await harvestStrandedGroupReply(group, member)
}
-
const roomLog = (($groupChats.get()[group] || {}).log || []).filter(e => groupThreadOf(e) === thread)
// Exclude members the harvest pass just above confirmed are STILL
// running (their stranded marker survived harvest because
@@ -8208,28 +8265,33 @@ async function runGroupChatRounds(group, members, 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 => !Object.prototype.hasOwnProperty.call(strandedNow, groupMemberKey(member)))
+ const responders = rotateGroupSpeakers(resolveGroupResponders(roomLog, members), round).filter(
+ member => !Object.prototype.hasOwnProperty.call(strandedNow, groupMemberKey(member))
+ )
let spokeThisRound = 0
-
for (const member of responders) {
if (!isCurrent() || posted >= GROUP_CHAT_MAX_MESSAGES) {
if (!isCurrent()) {
- recordGroupActivity(group, { kind: 'cancelled', member: null, thread })
+ recordGroupActivity(group, {
+ kind: 'cancelled',
+ member: null,
+ thread
+ })
} else {
exitKind = 'capped' // message cap, not consensus (#94478)
}
return
}
-
- const room = $groupChats.get()[group] || { log: [], watermarks: {} }
+ 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 => groupThreadOf(e) === thread)
-
if (!delta.length) {
continue
}
@@ -8240,29 +8302,32 @@ async function runGroupChatRounds(group, members, 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 => {
if (advance !== null) {
r.watermarks[markKey] = advance
}
-
if (r.holds?.[memberKey] && !r.holds[memberKey].noted) {
- r.holds = { ...r.holds, [memberKey]: { ...r.holds[memberKey], noted: true } }
+ r.holds = {
+ ...r.holds,
+ [memberKey]: {
+ ...r.holds[memberKey],
+ noted: true
+ }
+ }
}
-
return r
})
-
if (!heldEntry.noted) {
- recordGroupActivity(group, { kind: 'held', member: member.name, thread })
+ recordGroupActivity(group, {
+ kind: 'held',
+ member: member.name,
+ thread
+ })
}
-
continue
}
-
const prompt = buildGroupChatTurnPrompt({
groupName: group,
members,
@@ -8283,9 +8348,7 @@ async function runGroupChatRounds(group, members, thread) {
r.turn = member.name
return r
})
-
let reply = null
-
try {
reply = await runGroupChatMemberTurn(group, member, prompt, thread, deltaImages)
@@ -8302,7 +8365,11 @@ async function runGroupChatRounds(group, members, thread) {
kind: 'failed',
member: member.name,
thread,
- ...(reason ? { reason } : {})
+ ...(reason
+ ? {
+ reason
+ }
+ : {})
})
noteBotAttention(groupMemberKey(member), reason || error?.message || error)
reply = null // a failed turn is a pass, never a room error
@@ -8319,19 +8386,22 @@ async function runGroupChatRounds(group, members, thread) {
// during-turn tail is anchored by entry id, not index — the history
// trim drops entries from the FRONT, so an index slice could
// overshoot after a mid-turn trim and silently commit a stale turn.
- const roomNow = $groupChats.get()[group] || { log: [] }
+ 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 => 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 => e.from?.kind === 'user' && groupThreadOf(e) === thread
- )
-
+ const newerUserEntryInThread = turnTail.some(e => e.from?.kind === 'user' && groupThreadOf(e) === thread)
if (!shouldCommitMemberTurn(startEpoch, epochNow, newerUserEntryInThread)) {
- recordGroupActivity(group, { kind: 'cancelled', member: member.name, thread })
+ recordGroupActivity(group, {
+ kind: 'cancelled',
+ member: member.name,
+ thread
+ })
return
}
@@ -8340,11 +8410,18 @@ async function runGroupChatRounds(group, members, thread) {
r.watermarks[markKey] = r.log.length
return r
})
-
if (reply !== null && !isGroupPassText(reply)) {
appendGroupChatEntry(
group,
- { kind: 'member', name: member.name, ...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {}) },
+ {
+ kind: 'member',
+ name: member.name,
+ ...(member.remoteSource
+ ? {
+ source: member.connectionLabel || member.connectionId
+ }
+ : {})
+ },
reply,
thread
)
@@ -8357,7 +8434,6 @@ async function runGroupChatRounds(group, members, thread) {
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
@@ -8372,22 +8448,21 @@ async function runGroupChatRounds(group, members, 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 => pendingKeys.includes(groupMemberKey(member)))
-
if (citedMembers.length && posted < GROUP_CHAT_MAX_MESSAGES) {
const strandedNow = ($groupChats.get()[group] || {}).stranded || {}
const continuationResponders = citedMembers.filter(
member => !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 room = $groupChats.get()[group] || {
+ log: [],
+ watermarks: {}
+ }
const memberKey = groupMemberKey(member)
const markKey = `${thread}::${memberKey}`
const seen = room.watermarks[markKey] || 0
@@ -8399,13 +8474,10 @@ async function runGroupChatRounds(group, members, 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,
@@ -8415,39 +8487,44 @@ async function runGroupChatRounds(group, members, thread) {
// that cites it.
deltaLines: delta.slice(-GROUP_CHAT_HISTORY_LIMIT).map(e => formatGroupChatLine(e, member.name))
})
-
updateGroupChat(group, r => {
r.turn = member.name
return r
})
-
let continuationReply = null
-
try {
continuationReply = await runGroupChatMemberTurn(group, member, prompt, thread)
-
if (continuationReply !== null) {
clearBotAttention(memberKey)
}
} catch (error) {
- recordGroupActivity(group, { kind: 'failed', member: member.name, thread })
+ recordGroupActivity(group, {
+ kind: 'failed',
+ member: member.name,
+ thread
+ })
noteBotAttention(memberKey, error?.message || error)
continuationReply = null
}
-
if (!isCurrent()) {
return
}
-
updateGroupChat(group, r => {
r.watermarks[markKey] = r.log.length
return r
})
-
if (continuationReply !== null && !isGroupPassText(continuationReply)) {
appendGroupChatEntry(
group,
- { kind: 'member', name: member.name, ...(member.remoteSource ? { source: member.connectionLabel || member.connectionId } : {}) },
+ {
+ kind: 'member',
+ name: member.name,
+ ...(member.remoteSource
+ ? {
+ source: member.connectionLabel || member.connectionId
+ }
+ : {})
+ },
continuationReply,
thread
)
@@ -8467,14 +8544,16 @@ async function runGroupChatRounds(group, members, thread) {
}
}
}
-
if (spokeThisRound === 0) {
// Genuinely nothing left to say — including after the continuation
// attempt above produced no spoken turns. Settle honestly, but if
// cited members are STILL owed a turn and only the continuation /
// message caps stopped us from driving them, this is a capped
// exit, not consensus. (#94478)
- if (pendingKeys.length && (continuations > GROUP_CHAT_MAX_CONTINUATIONS || posted >= GROUP_CHAT_MAX_MESSAGES)) {
+ if (
+ pendingKeys.length &&
+ (continuations > GROUP_CHAT_MAX_CONTINUATIONS || posted >= GROUP_CHAT_MAX_MESSAGES)
+ ) {
exitKind = 'capped'
}
return
@@ -8487,7 +8566,11 @@ async function runGroupChatRounds(group, members, thread) {
exitKind = 'capped'
} finally {
if (isCurrent()) {
- recordGroupActivity(group, { kind: exitKind, member: null, thread })
+ recordGroupActivity(group, {
+ kind: exitKind,
+ member: null,
+ thread
+ })
updateGroupChat(group, r => {
r.running = false
r.turn = null
@@ -8500,7 +8583,6 @@ async function runGroupChatRounds(group, members, 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)
}
@@ -8515,22 +8597,16 @@ async function runGroupChatRounds(group, members, thread) {
async function harvestStrandedUntilSettled(group, members, thread) {
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 {
@@ -8541,8 +8617,11 @@ async function harvestStrandedUntilSettled(group, members, thread) {
}
}
}
-
- recordGroupActivity(group, { kind: 'failed', member: null, thread })
+ recordGroupActivity(group, {
+ kind: 'failed',
+ member: null,
+ thread
+ })
}
/** User send into a group room. `thread` continues that thread (its reply
@@ -8553,14 +8632,14 @@ async function harvestStrandedUntilSettled(group, members, thread) {
function sendToGroupChat(group, members, text, thread, images) {
const trimmed = String(text || '').trim()
const attached = Array.isArray(images) ? images.filter(img => img && img.data) : []
-
if ((!trimmed && !attached.length) || !members.length) {
return null
}
-
const target = thread || mintGroupThreadId()
-
- $groupNeedsYou.set({ ...$groupNeedsYou.get(), [group]: false })
+ $groupNeedsYou.set({
+ ...$groupNeedsYou.get(),
+ [group]: false
+ })
// Refresh the durable room roster on every send. This backfills rooms made
// by older Desktop builds and keeps the gateway mirror complete even when
// members overlap across multiple groups.
@@ -8568,10 +8647,17 @@ function sendToGroupChat(group, members, text, thread, images) {
room.members = durableGroupChatMembers(members)
return room
})
- const sent = appendGroupChatEntry(group, { kind: 'user', name: 'You' }, trimmed, target, attached)
-
+ const sent = appendGroupChatEntry(
+ group,
+ {
+ kind: 'user',
+ name: 'You'
+ },
+ trimmed,
+ target,
+ attached
+ )
const wasRunning = ($groupChats.get()[group] || {}).running === true
-
updateGroupChat(group, room => {
room.epoch = (room.epoch || 0) + 1
room.running = true
@@ -8583,14 +8669,20 @@ function sendToGroupChat(group, members, text, thread, images) {
room.holds,
parseGroupChatMentions(trimmed, members),
trimmed,
- { at: sent?.at, byMessageId: sent?.id, thread: target },
+ {
+ at: sent?.at,
+ byMessageId: sent?.id,
+ thread: target
+ },
members.map(member => groupMemberKey(member))
)
return room
})
-
- recordGroupActivity(group, { kind: 'queued', member: 'You', thread: target })
-
+ recordGroupActivity(group, {
+ kind: 'queued',
+ member: 'You',
+ thread: target
+ })
if (!wasRunning) {
void runGroupChatRounds(group, members, target).catch(() => {
updateGroupChat(group, r => {
@@ -8610,7 +8702,6 @@ function sendToGroupChat(group, members, text, thread, images) {
})
}, 250)
}
-
return target
}
@@ -8620,7 +8711,6 @@ function singleFlight(ref, start) {
if (ref.current) {
return ref.current
}
-
let flight
try {
flight = Promise.resolve(start())
@@ -8642,7 +8732,6 @@ function singleFlight(ref, start) {
function messagingProtocolSection(name, roster) {
const teammates = (roster || []).filter(b => b.name !== name)
const handle = botHandle(name)
-
return [
'## Messaging other agents',
'',
@@ -8652,7 +8741,11 @@ function messagingProtocolSection(name, roster) {
'into it, like a DM. To message a teammate, run:',
'',
'```',
- 'hermes -p <agent-name> chat --in ~ -c "Bot Chat" --create-if-missing -Q -q "Message from \uD83E\uDD16 ' + handle + ' (@' + handle + '): your message"',
+ 'hermes -p <agent-name> chat --in ~ -c "Bot Chat" --create-if-missing -Q -q "Message from \uD83E\uDD16 ' +
+ handle +
+ ' (@' +
+ handle +
+ '): your message"',
'',
'Run the send with background=true and notify_on_complete=true on the',
'terminal tool, then finish your turn — the reply arrives later as a',
@@ -8701,7 +8794,6 @@ function ensureMessagingProtocol(soul, name, roster) {
const section = messagingProtocolSection(name, roster)
return text ? text + '\n\n' + section : section
}
-
const soulProtocolChecked = new Set()
const soulProtocolInflight = new Set()
@@ -8714,16 +8806,16 @@ function backfillMessagingProtocol(roster) {
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('profiles.describe', { name })
+ .request('profiles.describe', {
+ name
+ })
.then(res => {
const soul = (res && res.soul) || ''
if (hasMessagingProtocol(soul)) {
@@ -8731,7 +8823,10 @@ function backfillMessagingProtocol(roster) {
return null
}
return host
- .request('profiles.configure', { name, soul: ensureMessagingProtocol(soul, name, roster) })
+ .request('profiles.configure', {
+ name,
+ soul: ensureMessagingProtocol(soul, name, roster)
+ })
.then(() => {
soulProtocolChecked.add(name)
})
@@ -8753,19 +8848,22 @@ function composeSoul({ name, title, description, roster, customSoul }) {
if (customSoul && customSoul.trim()) {
return ensureMessagingProtocol(customSoul, name, roster)
}
-
const lines = [
- `# ${displayName({ name, title })}`,
+ `# ${displayName({
+ name,
+ title
+ })}`,
'',
title ? `**Role:** ${title}` : null,
description ? `**Mission:** ${description}` : null,
'',
- `You are ${displayName({ name, title })}, a persistent named agent (profile \`${name}\`) on this machine.`,
+ `You are ${displayName({
+ name,
+ title
+ })}, 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)
}
@@ -8785,7 +8883,9 @@ const A2A_PREFIX_RE = /^Message from (?:agent '[^']+'|🤖[^:]+):\s*/i
function previewKind(preview) {
const text = (preview || '').trim()
if (!text) {
- return { fromBot: null }
+ return {
+ fromBot: null
+ }
}
const match = text.match(A2A_RE)
if (match) {
@@ -8793,14 +8893,17 @@ function previewKind(preview) {
// 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: sender ? botHandle(sender) : null
+ }
+ }
+ return {
+ fromBot: null
}
- return { 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) {
return GENERIC_TITLES.has((title || '').trim().toLowerCase())
}
@@ -8818,7 +8921,11 @@ function generatedSessionTitle(session, preview) {
if (!cleaned) {
return raw || 'Conversation'
}
- const words = cleaned.split(/\s+/).slice(0, 5).join(' ').replace(/[,;:.]+$/, '')
+ const words = cleaned
+ .split(/\s+/)
+ .slice(0, 5)
+ .join(' ')
+ .replace(/[,;:.]+$/, '')
if (!words) {
return raw || 'Conversation'
}
@@ -8845,11 +8952,9 @@ const BOT_ROSTER_SEARCH_THRESHOLD = 8
function botActivitySession(bot) {
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
}
@@ -8878,42 +8983,27 @@ function activeBots(roster, activeProfile, gatewayState, now = Date.now()) {
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)
})
}
-
function rosterActivityMatches(row, filter, now = Date.now()) {
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
}
-
-function botRowOwnsWorkspace(
- bot,
- activeGroup,
- botChatFocused,
- botsHomeFronted,
- focusedOwner,
- selectedRosterKey
-) {
+function botRowOwnsWorkspace(bot, activeGroup, botChatFocused, botsHomeFronted, focusedOwner, selectedRosterKey) {
if (activeGroup) {
return false
}
-
if (botsHomeFronted || !botChatFocused) {
return selectedRosterKey === botRosterKey(bot)
}
-
return isActiveRosterBot(bot, focusedOwner)
}
@@ -8953,8 +9043,13 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
selectedRosterKey
)
// Turn-busy is a SOCKET fact: only the gateway-home profile can be mid-turn.
- const isGatewayHome = !bot.remoteSource && bot.name === activeProfile &&
- isActiveRosterBot(bot, { name: activeProfile, connectionId: activeConnectionId })
+ const isGatewayHome =
+ !bot.remoteSource &&
+ bot.name === activeProfile &&
+ isActiveRosterBot(bot, {
+ 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))
@@ -8999,9 +9094,7 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
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 || ''
+ 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' : '')
@@ -9009,7 +9102,6 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
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') {
@@ -9018,14 +9110,11 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
} catch {
/* warm is best-effort */
}
-
return
}
-
if (typeof host.warmProfile !== 'function') {
return
}
-
try {
host.warmProfile(bot.name)
} catch {
@@ -9036,196 +9125,172 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
// 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 = jsxs('button', {
- type: 'button',
- onPointerEnter: warm,
- onClick: open,
- 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,
- children: [
- jsx('div', {
- className: cn('shrink-0', !sourceStatus.available && 'grayscale opacity-60'),
- children: jsx(BotFace, {
- shape,
- color,
- image: photo ? image : null,
- size: 34,
- name: bot.name,
- mood: botMood
- })
- }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsxs('div', {
- className: 'flex items-baseline justify-between gap-2',
- children: [
- jsxs('div', {
- className: 'flex min-w-0 items-center gap-1.5',
- children: [
- pinned
- ? jsx(Tip, {
- label: 'Pinned',
- children: jsx(Codicon, {
- name: 'pinned',
- className: 'shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)'
- })
- })
- : null,
- hidden
- ? jsx(Tip, {
- label: 'Hidden from the roster',
- children: jsx(Codicon, {
- name: 'eye-closed',
- className: 'shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)'
- })
- })
- : null,
- jsx(Tip, {
- label: rowTooltip,
- children: jsx('span', {
- className: 'min-w-0 truncate text-[0.8125rem] font-medium',
- children: displayName(bot, meta)
- })
- }),
- ]
- }),
- attention
- ? jsx(Tip, {
- label: BOT_ATTENTION_HINTS[attention.reason] || 'Needs attention',
- children: jsx(Codicon, {
- name: 'warning',
- className: 'shrink-0 text-[0.6875rem] text-(--ui-warning,#f59e0b)',
- 'aria-label': 'needs attention'
- })
- })
- : null,
- unread
- ? jsx('span', {
- className: 'size-2 shrink-0 rounded-full bg-(--ui-accent)',
- 'aria-label': 'unread'
- })
- : null,
- rowAgeTs
- ? jsx('span', {
- className: 'shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)',
- children: relativeTime(rowAgeTs * 1000)
- })
- : null
- ]
- }),
- showDetailsRow
- ? jsxs('div', {
- className: 'flex min-w-0 items-center gap-1.5 text-xs text-(--ui-text-tertiary)',
- children: [
- showHandle
- ? jsx('span', {
- className: 'shrink-0 font-mono text-[0.6875rem] text-(--ui-text-quaternary)',
- children: `@${handle}`
- })
- : null,
- showHandle && displayPreview
- ? jsx('span', { className: 'shrink-0 text-(--ui-text-quaternary)', children: '·' })
- : null,
- displayPreview
- ? jsx('span', {
- className: cn('min-w-0 truncate', fromBot && 'italic'),
- children: displayPreview
- })
- : null
- ]
- })
- : null
- ]
- })
- ]
- })
-
- return jsxs(ContextMenu, {
- children: [
- jsx(ContextMenuTrigger, { asChild: true, children: row }),
- jsxs(ContextMenuContent, {
- children: [
- jsx(ContextMenuItem, {
- onSelect: () => {
- void ensureBotMetadata(bot).then(current => {
+ const row = (
+ <button
+ type="button"
+ onPointerEnter={warm}
+ onClick={open}
+ 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}
+ >
+ <div className={cn('shrink-0', !sourceStatus.available && 'grayscale opacity-60')}>
+ <BotFace shape={shape} color={color} image={photo ? image : null} size={34} name={bot.name} mood={botMood} />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-1.5">
+ {pinned ? (
+ <Tip label="Pinned">
+ <Codicon name="pinned" className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" />
+ </Tip>
+ ) : null}
+ {hidden ? (
+ <Tip label="Hidden from the roster">
+ <Codicon name="eye-closed" className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)" />
+ </Tip>
+ ) : null}
+ <Tip label={rowTooltip}>
+ <span className="min-w-0 truncate text-[0.8125rem] font-medium">{displayName(bot, meta)}</span>
+ </Tip>
+ </div>
+ {attention ? (
+ <Tip label={BOT_ATTENTION_HINTS[attention.reason] || 'Needs attention'}>
+ <Codicon
+ name="warning"
+ className="shrink-0 text-[0.6875rem] text-(--ui-warning,#f59e0b)"
+ aria-label="needs attention"
+ />
+ </Tip>
+ ) : null}
+ {unread ? <span className="size-2 shrink-0 rounded-full bg-(--ui-accent)" aria-label="unread" /> : null}
+ {rowAgeTs ? (
+ <span className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)">
+ {relativeTime(rowAgeTs * 1000)}
+ </span>
+ ) : null}
+ </div>
+ {showDetailsRow ? (
+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-(--ui-text-tertiary)">
+ {showHandle ? (
+ <span className="shrink-0 font-mono text-[0.6875rem] text-(--ui-text-quaternary)">{`@${handle}`}</span>
+ ) : null}
+ {showHandle && displayPreview ? <span className="shrink-0 text-(--ui-text-quaternary)">·</span> : null}
+ {displayPreview ? (
+ <span className={cn('min-w-0 truncate', fromBot && 'italic')}>{displayPreview}</span>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </button>
+ )
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem
+ onSelect={() => {
+ void ensureBotMetadata(bot)
+ .then(current => {
const pinned = Boolean(current.pinned)
- void saveBotMeta(bot, { pinned: !pinned })
+ void saveBotMeta(bot, {
+ pinned: !pinned
+ })
host.notify({
kind: 'info',
message: `${displayName(bot, current)} ${pinned ? 'unpinned' : 'pinned to top'}`
})
- }).catch(error => host.notifyError?.(error, 'Could not load bot metadata'))
- },
- children: pinned ? 'Unpin' : 'Pin to top'
- }),
- jsx(ContextMenuItem, {
- onSelect: () => {
- void ensureBotMetadata(bot).then(current => {
+ })
+ .catch(error => host.notifyError?.(error, 'Could not load bot metadata'))
+ }}
+ >
+ {pinned ? 'Unpin' : 'Pin to top'}
+ </ContextMenuItem>
+ <ContextMenuItem
+ onSelect={() => {
+ void ensureBotMetadata(bot)
+ .then(current => {
const hidden = Boolean(current.hidden)
- void saveBotMeta(bot, { hidden: !hidden })
-
+ void saveBotMeta(bot, {
+ hidden: !hidden
+ })
if (!hidden) {
fallbackSelectionAfterHide(botSelectionKey(bot))
}
-
host.notify({
kind: 'info',
message: hidden
? `${displayName(bot, current)} is back in the roster`
: `${displayName(bot, current)} hidden — use the eye button in the Bots header to see hidden bots`
})
- }).catch(error => host.notifyError?.(error, 'Could not load bot metadata'))
- },
- children: hidden ? 'Unhide' : 'Hide'
- }),
- jsx(ContextMenuSeparator, {}),
- jsx(ContextMenuItem, {
- onSelect: () => void ensureBotMetadata(bot).then(() => onEdit(bot)).catch(error => host.notifyError?.(error, 'Could not load bot')),
- children: 'Edit Profile'
- }),
- jsx(ContextMenuItem, {
- onSelect: () => void ensureBotMetadata(bot).then(() => onGroup(bot)).catch(error => host.notifyError?.(error, 'Could not load bot groups')),
- children: groups.length ? `Groups: ${groups.join(', ')}…` : 'Manage groups…'
- }),
- jsx(ContextMenuItem, {
- onSelect: () => {
- host.notify({ kind: 'info', message: `Duplicating ${displayName(bot, meta)}…` })
- duplicateBot(bot, $lastRoster.get())
- .then(name => {
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
- host.notify({ kind: 'success', message: `Created ${name} — full copy of ${bot.name}` })
+ })
+ .catch(error => host.notifyError?.(error, 'Could not load bot metadata'))
+ }}
+ >
+ {hidden ? 'Unhide' : 'Hide'}
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ onSelect={() =>
+ void ensureBotMetadata(bot)
+ .then(() => onEdit(bot))
+ .catch(error => host.notifyError?.(error, 'Could not load bot'))
+ }
+ >
+ Edit Profile
+ </ContextMenuItem>
+ <ContextMenuItem
+ onSelect={() =>
+ void ensureBotMetadata(bot)
+ .then(() => onGroup(bot))
+ .catch(error => host.notifyError?.(error, 'Could not load bot groups'))
+ }
+ >
+ {groups.length ? `Groups: ${groups.join(', ')}…` : 'Manage groups…'}
+ </ContextMenuItem>
+ <ContextMenuItem
+ onSelect={() => {
+ host.notify({
+ kind: 'info',
+ message: `Duplicating ${displayName(bot, meta)}…`
+ })
+ duplicateBot(bot, $lastRoster.get())
+ .then(name => {
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
+ host.notify({
+ kind: 'success',
+ message: `Created ${name} — full copy of ${bot.name}`
})
- .catch(err => host.notifyError(err, 'Duplicate failed'))
- },
- children: 'Duplicate'
- }),
- jsx(ContextMenuSeparator, {}),
- jsx(ContextMenuItem, {
- onSelect: () => {
- saveSelectedRosterBot(bot)
- setBotsWorkspaceOwner(botWorkspaceOwnerKey(bot), bot)
- newBotChat(bot)
- },
- children: 'New chat with this agent'
- }),
- isDefaultBot(bot) ? null : jsx(ContextMenuSeparator, {}),
- isDefaultBot(bot)
- ? null
- : jsx(ContextMenuItem, {
- onSelect: () => onDelete(bot),
- variant: 'destructive',
- children: 'Delete'
})
- ]
- })
- ]
- })
+ .catch(err => host.notifyError(err, 'Duplicate failed'))
+ }}
+ >
+ Duplicate
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ onSelect={() => {
+ saveSelectedRosterBot(bot)
+ setBotsWorkspaceOwner(botWorkspaceOwnerKey(bot), bot)
+ newBotChat(bot)
+ }}
+ >
+ New chat with this agent
+ </ContextMenuItem>
+ {isDefaultBot(bot) ? null : <ContextMenuSeparator />}
+ {isDefaultBot(bot) ? null : (
+ <ContextMenuItem onSelect={() => onDelete(bot)} variant="destructive">
+ Delete
+ </ContextMenuItem>
+ )}
+ </ContextMenuContent>
+ </ContextMenu>
+ )
}
// ── model picker (provider/model dropdowns via model.options) ───────────────
@@ -9237,34 +9302,28 @@ function BotRow({ bot, onDelete, onEdit, onGroup, showHandle }) {
// 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(fetch, settleMs = MODEL_OPTIONS_SETTLE_MS) {
// 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
}
-
let timerId = null
const deadline = new Promise((_, 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))
}
-
function useModelOptions(bot = 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({
queryKey: [ID, 'model-options', route ? botRouteKey(route) : 'active'],
// No forced `refresh`: forcing a network read on EVERY mount bypassed the
@@ -9298,146 +9357,189 @@ function ModelPicker({ bot = null, value, onChange, placeholderModel = 'gateway
const NONE = '__default__'
const CUSTOM = '__custom__'
const providers = (data?.providers || []).filter(p => p && p.slug)
- const isKnown =
- !value.provider || value.provider === NONE || providers.some(p => p.slug === value.provider)
+ const isKnown = !value.provider || value.provider === NONE || providers.some(p => p.slug === value.provider)
const [useFreeText, setUseFreeText] = useState(!isKnown)
-
if (isLoading) {
- return jsx('div', {
- className: 'flex justify-center py-2',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
+ return (
+ <div className="flex justify-center py-2">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ )
}
-
if (error || !providers.length) {
// Fallback: free text (older gateway or empty inventory).
- return jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' },
- children: [
- labeled(
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '10px'
+ }}
+ >
+ {labeled(
'Provider',
- jsx(Input, {
- placeholder: 'omnirouter / 9router / nous \u2026',
- value: value.provider,
- onChange: event => onChange({ provider: event.target.value })
- })
- ),
- labeled(
+ <Input
+ placeholder="omnirouter / 9router / nous …"
+ value={value.provider}
+ onChange={event =>
+ onChange({
+ provider: event.target.value
+ })
+ }
+ />
+ )}
+ {labeled(
'Model',
- jsx(Input, {
- placeholder: 'antigravity/gemini-3.6-flash-high',
- value: value.model,
- onChange: event => onChange({ model: event.target.value })
- })
- )
- ]
- })
+ <Input
+ placeholder="antigravity/gemini-3.6-flash-high"
+ value={value.model}
+ onChange={event =>
+ onChange({
+ model: event.target.value
+ })
+ }
+ />
+ )}
+ </div>
+ )
}
-
if (useFreeText) {
- return jsxs('div', {
- style: { display: 'flex', flexDirection: 'column', gap: '8px' },
- children: [
- jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' },
- children: [
- labeled(
- 'Provider (Custom)',
- jsx(Input, {
- placeholder: 'e.g. omnirouter, inferx, 9router',
- value: value.provider,
- onChange: event => onChange({ provider: event.target.value })
- })
- ),
- labeled(
- 'Model (Custom)',
- jsx(Input, {
- placeholder: 'e.g. antigravity/gemini-3.6-flash-high',
- value: value.model,
- onChange: event => onChange({ model: event.target.value })
- })
- )
- ]
- }),
- jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- className: 'h-6 self-start text-xs text-(--ui-text-tertiary)',
- onClick: () => setUseFreeText(false),
- children: '← Back to dropdowns'
- })
- ]
- })
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px'
+ }}
+ >
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '10px'
+ }}
+ >
+ {labeled(
+ 'Provider (Custom)',
+ <Input
+ placeholder="e.g. omnirouter, inferx, 9router"
+ value={value.provider}
+ onChange={event =>
+ onChange({
+ provider: event.target.value
+ })
+ }
+ />
+ )}
+ {labeled(
+ 'Model (Custom)',
+ <Input
+ placeholder="e.g. antigravity/gemini-3.6-flash-high"
+ value={value.model}
+ onChange={event =>
+ onChange({
+ model: event.target.value
+ })
+ }
+ />
+ )}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 self-start text-xs text-(--ui-text-tertiary)"
+ onClick={() => setUseFreeText(false)}
+ >
+ ← 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 jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: '10px' },
- children: [
- labeled(
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1.4fr',
+ gap: '10px'
+ }}
+ >
+ {labeled(
'Provider',
- jsxs(Select, {
- value: value.provider || NONE,
- onValueChange: v => {
+ <Select
+ value={value.provider || NONE}
+ onValueChange={v => {
if (v === NONE) {
- onChange({ provider: '', model: '' })
+ onChange({
+ provider: '',
+ model: ''
+ })
} else if (v === CUSTOM) {
setUseFreeText(true)
} else {
const prov = providers.find(p => p.slug === v)
- const provModels = (prov?.models || []).map(m =>
- typeof m === 'string' ? m : m.id || m.name || ''
- )
+ const provModels = (prov?.models || []).map(m => (typeof m === 'string' ? m : m.id || m.name || ''))
const first = provModels[0] || ''
onChange({
provider: v,
model: prov && provModels.includes(value.model) ? value.model : first
})
}
- },
- children: [
- jsx(SelectTrigger, { className: 'h-8 rounded-md', children: jsx(SelectValue, {}) }),
- jsxs(SelectContent, {
- children: [
- jsx(SelectItem, { value: NONE, children: 'Inherit (launch profile)' }),
- ...providers.map(p =>
- jsx(
- SelectItem,
- { value: p.slug, children: p.name ? `${p.name} (${p.slug})` : p.slug },
- p.slug
- )
- ),
- jsx(SelectItem, { value: CUSTOM, children: '✏️ Enter manually…' })
- ]
- })
- ]
- })
- ),
- labeled(
+ }}
+ >
+ <SelectTrigger className="h-8 rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE}>Inherit (launch profile)</SelectItem>
+ {providers.map(p => (
+ <SelectItem key={p.slug} value={p.slug}>
+ {p.name ? `${p.name} (${p.slug})` : p.slug}
+ </SelectItem>
+ ))}
+ <SelectItem value={CUSTOM}>✏️ Enter manually…</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ {labeled(
'Model',
- activeProvider && models.length > 0
- ? jsxs(Select, {
- value: value.model || (models[0] ?? ''),
- onValueChange: v => onChange({ model: v }),
- children: [
- jsx(SelectTrigger, { className: 'h-8 rounded-md', children: jsx(SelectValue, {}) }),
- jsx(SelectContent, {
- children: models.map(m => jsx(SelectItem, { value: m, children: m }, m))
- })
- ]
- })
- : jsx(Input, {
- placeholder: placeholderModel || 'e.g. model name',
- value: value.model,
- onChange: event => onChange({ model: event.target.value })
- })
- )
- ]
- })
+ activeProvider && models.length > 0 ? (
+ <Select
+ value={value.model || (models[0] ?? '')}
+ onValueChange={v =>
+ onChange({
+ model: v
+ })
+ }
+ >
+ <SelectTrigger className="h-8 rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {models.map(m => (
+ <SelectItem key={m} value={m}>
+ {m}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ ) : (
+ <Input
+ placeholder={placeholderModel || 'e.g. model name'}
+ value={value.model}
+ onChange={event =>
+ onChange({
+ model: event.target.value
+ })
+ }
+ />
+ )
+ )}
+ </div>
+ )
}
// ── advanced profile config (skills / toolsets / model / SOUL) ──────────────
@@ -9447,38 +9549,30 @@ function ModelPicker({ bot = null, value, onChange, placeholderModel = 'gateway
// profiles.describe / profiles.configure; feature-detects older gateways.
function CheckList({ items, onToggle, columns = 2 }) {
- return jsx('div', {
- style: {
- display: 'grid',
- gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
- gap: '2px 12px'
- },
- children: items.map(item =>
- jsxs(
- 'label',
- {
- className: 'flex min-w-0 cursor-pointer items-center gap-1.5 py-0.5 text-xs text-(--ui-text-secondary)',
- title: item.description || item.name,
- children: [
- jsx(Checkbox, {
- checked: item.enabled,
- onCheckedChange: value => onToggle(item.name, Boolean(value))
- }),
- jsx('span', { className: 'truncate', children: item.name }),
- item.tool_count
- ? jsx('span', {
- className: 'shrink-0 text-[0.6rem] text-(--ui-text-quaternary)',
- children: `${item.tool_count}`
- })
- : null
- ]
- },
- item.name
- )
- )
- })
+ return (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
+ gap: '2px 12px'
+ }}
+ >
+ {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)"
+ title={item.description || item.name}
+ >
+ <Checkbox checked={item.enabled} onCheckedChange={value => onToggle(item.name, Boolean(value))} />
+ <span className="truncate">{item.name}</span>
+ {item.tool_count ? (
+ <span className="shrink-0 text-[0.6rem] text-(--ui-text-quaternary)">{`${item.tool_count}`}</span>
+ ) : null}
+ </label>
+ ))}
+ </div>
+ )
}
-
function AdvancedProfileConfig({ bot, state, setState }) {
const [loaded, setLoaded] = useState(false)
const [unsupported, setUnsupported] = useState(false)
@@ -9488,12 +9582,15 @@ function AdvancedProfileConfig({ bot, state, setState }) {
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([
- requestForBot(bot, 'profiles.describe', { name: bot.name }),
- requestForBot(bot, 'mcp.catalog', { profile: bot.name }).catch(() => null)
+ requestForBot(bot, 'profiles.describe', {
+ name: bot.name
+ }),
+ requestForBot(bot, 'mcp.catalog', {
+ profile: bot.name
+ }).catch(() => null)
])
.then(([res, cat]) => {
const configured = res.mcp_servers || []
@@ -9507,7 +9604,10 @@ function AdvancedProfileConfig({ bot, state, setState }) {
skills: res.skills || [],
toolsets: res.toolsets || [],
mcp: [
- ...configured.map(m => ({ ...m, enabled: m.enabled !== false })),
+ ...configured.map(m => ({
+ ...m,
+ enabled: m.enabled !== false
+ })),
...catalog.map(s => ({
name: s.name,
enabled: false,
@@ -9523,46 +9623,62 @@ function AdvancedProfileConfig({ bot, state, setState }) {
})
.catch(() => setUnsupported(true))
}
-
if (unsupported) {
- return jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: 'Full configuration needs a newer gateway (restart it after updating Hermes).'
- })
+ return (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ Full configuration needs a newer gateway (restart it after updating Hermes).
+ </div>
+ )
}
-
if (!state.loaded) {
- return jsx('div', {
- className: 'flex justify-center py-4',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
+ return (
+ <div className="flex justify-center py-4">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ )
}
-
const visibleSkills = skillFilter.trim()
? state.skills.filter(s => s.name.toLowerCase().includes(skillFilter.trim().toLowerCase()))
: state.skills
-
const toggleSkill = (name, enabled) =>
setState(prev => ({
...prev,
dirtySkills: true,
- skills: prev.skills.map(s => (s.name === name ? { ...s, enabled } : s))
+ skills: prev.skills.map(s =>
+ s.name === name
+ ? {
+ ...s,
+ enabled
+ }
+ : s
+ )
}))
-
const toggleToolset = (name, enabled) =>
setState(prev => ({
...prev,
dirtyToolsets: true,
- toolsets: prev.toolsets.map(t => (t.name === name ? { ...t, enabled } : t))
+ toolsets: prev.toolsets.map(t =>
+ t.name === name
+ ? {
+ ...t,
+ enabled
+ }
+ : t
+ )
}))
-
const toggleMcp = (name, enabled) =>
setState(prev => ({
...prev,
dirtyMcp: true,
- mcp: (prev.mcp || []).map(m => (m.name === name ? { ...m, enabled } : m))
+ mcp: (prev.mcp || []).map(m =>
+ m.name === name
+ ? {
+ ...m,
+ enabled
+ }
+ : m
+ )
}))
-
const enabledSkills = state.skills.filter(s => s.enabled).length
const enabledToolsets = state.toolsets.filter(t => t.enabled).length
const mcpList = state.mcp || []
@@ -9576,221 +9692,261 @@ function AdvancedProfileConfig({ bot, state, setState }) {
// bot's backend, so the dirty-section staging below only carries
// model + SOUL on these builds. Older builds keep the full checklist UI.
if (SkillsView && (!botRoute || skillsViewRoutesConnections)) {
- return jsxs('div', {
- className: 'grid gap-4',
- children: [
- jsx(ModelPicker, {
- bot,
- value: { provider: state.provider, model: state.model },
- onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))
- }),
- labeled(
+ return (
+ <div className="grid gap-4">
+ <ModelPicker
+ bot={bot}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
+ onChange={patch =>
+ setState(prev => ({
+ ...prev,
+ dirtyModel: true,
+ ...patch
+ }))
+ }
+ />
+ {labeled(
'Capabilities (applies immediately — skills, tools, MCP)',
- jsx('div', {
- className: 'overflow-hidden rounded-md border border-(--ui-stroke-secondary)',
- style: { height: 460, minHeight: 300, resize: 'vertical', overflow: 'auto' },
- children: jsx(SkillsView, {
- embedded: true,
- fixedProfile: backendProfile,
- ...(botRoute ? { fixedConnection: botRoute.connectionId } : {})
- })
- })
- ),
- labeled(
+ <div
+ className="overflow-hidden rounded-md border border-(--ui-stroke-secondary)"
+ style={{
+ height: 460,
+ minHeight: 300,
+ resize: 'vertical',
+ overflow: 'auto'
+ }}
+ >
+ <SkillsView
+ embedded
+ fixedProfile={backendProfile}
+ {...(botRoute
+ ? {
+ fixedConnection: botRoute.connectionId
+ }
+ : {})}
+ />
+ </div>
+ )}
+ {labeled(
'SOUL.md (persona + agent-messaging protocol)',
- jsx(Textarea, {
- className: 'min-h-28 font-mono text-xs leading-5',
- value: state.soul,
- onChange: event => setState(prev => ({ ...prev, dirtySoul: true, soul: event.target.value }))
- })
- )
- ]
- })
+ <Textarea
+ className="min-h-28 font-mono text-xs leading-5"
+ value={state.soul}
+ onChange={event =>
+ setState(prev => ({
+ ...prev,
+ dirtySoul: true,
+ soul: event.target.value
+ }))
+ }
+ />
+ )}
+ </div>
+ )
}
-
if (bot?.sourceScoped && botRoute?.mode === 'remote' && !skillsViewRoutesConnections) {
- return jsxs('div', {
- className: 'grid gap-4',
- children: [
- jsx(ModelPicker, {
- bot,
- value: { provider: state.provider, model: state.model },
- onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))
- }),
- jsx('div', {
- className: 'rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-text-tertiary)',
- children: 'Remote capabilities require a newer desktop. Model and SOUL changes remain staged until you save.'
- }),
- labeled(
+ return (
+ <div className="grid gap-4">
+ <ModelPicker
+ bot={bot}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
+ onChange={patch =>
+ setState(prev => ({
+ ...prev,
+ dirtyModel: true,
+ ...patch
+ }))
+ }
+ />
+ <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.
+ </div>
+ {labeled(
'SOUL.md (persona + agent-messaging protocol)',
- jsx(Textarea, {
- className: 'min-h-28 font-mono text-xs leading-5',
- value: state.soul,
- onChange: event => setState(prev => ({ ...prev, dirtySoul: true, soul: event.target.value }))
- })
- )
- ]
- })
+ <Textarea
+ className="min-h-28 font-mono text-xs leading-5"
+ value={state.soul}
+ onChange={event =>
+ setState(prev => ({
+ ...prev,
+ dirtySoul: true,
+ soul: event.target.value
+ }))
+ }
+ />
+ )}
+ </div>
+ )
}
-
- return jsxs('div', {
- className: 'grid gap-4',
- children: [
- jsx(ModelPicker, {
- bot,
- value: { provider: state.provider, model: state.model },
- onChange: patch => setState(prev => ({ ...prev, dirtyModel: true, ...patch }))
- }),
- labeled(
+ return (
+ <div className="grid gap-4">
+ <ModelPicker
+ bot={bot}
+ value={{
+ provider: state.provider,
+ model: state.model
+ }}
+ onChange={patch =>
+ setState(prev => ({
+ ...prev,
+ dirtyModel: true,
+ ...patch
+ }))
+ }
+ />
+ {labeled(
`Skills (${enabledSkills}/${state.skills.length} enabled)`,
- jsxs('div', {
- className: 'grid gap-1.5 rounded-md border border-(--ui-stroke-secondary) p-2',
- children: [
- jsx(Input, {
- className: 'h-7 text-xs',
- placeholder: 'Filter skills…',
- value: skillFilter,
- onChange: event => setSkillFilter(event.target.value)
- }),
- jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 180 },
- children: jsx(CheckList, { items: visibleSkills, onToggle: toggleSkill, columns: 2 })
- }),
- jsx(HubSkillsSection, {
- forProfile: backendScope,
- onInstalled: name =>
- setState(prev =>
- prev.skills.some(s => s.name === name)
- ? prev
- : { ...prev, skills: [...prev.skills, { name, enabled: true }] }
- )
- })
- ]
- })
- ),
- labeled(
- `Toolsets (${enabledToolsets}/${state.toolsets.length} enabled — unchecking all restores the default)`,
- jsx('div', {
- className: 'rounded-md border border-(--ui-stroke-secondary) p-2',
- children: jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 320 },
- children: jsx('div', {
- className: 'grid gap-1.5',
- children: state.toolsets.map(tset =>
- jsxs(
- 'div',
- {
- className: 'rounded-md border border-(--ui-stroke-secondary) p-2',
- children: [
- jsxs('label', {
- className: 'flex items-center gap-2 text-xs font-medium text-(--ui-text-secondary)',
- children: [
- jsx(Checkbox, {
- checked: !!tset.enabled,
- onCheckedChange: value => toggleToolset(tset.name, Boolean(value))
- }),
- jsx('span', { children: tset.name })
- ]
- }),
- // The REAL per-toolset config (env vars / API keys / model
- // picker / post-setup), scoped to THIS bot's profile, when
- // the desktop build exposes it. Older builds: just the toggle.
- ToolsetConfigPanel
- ? jsx('div', {
- className: 'mt-1.5 border-t border-(--ui-stroke-secondary) pt-1.5',
- children: jsx(ToolsetConfigPanel, { toolset: tset.name, profile: backendScope })
- })
- : null
- ]
- },
- tset.name
- )
+ <div className="grid gap-1.5 rounded-md border border-(--ui-stroke-secondary) p-2">
+ <Input
+ className="h-7 text-xs"
+ placeholder="Filter skills…"
+ value={skillFilter}
+ onChange={event => setSkillFilter(event.target.value)}
+ />
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 180
+ }}
+ >
+ <CheckList items={visibleSkills} onToggle={toggleSkill} columns={2} />
+ </ScrollArea>
+ <HubSkillsSection
+ forProfile={backendScope}
+ onInstalled={name =>
+ setState(prev =>
+ prev.skills.some(s => s.name === name)
+ ? prev
+ : {
+ ...prev,
+ skills: [
+ ...prev.skills,
+ {
+ name,
+ enabled: true
+ }
+ ]
+ }
)
- })
- })
- })
- ),
- labeled(
+ }
+ />
+ </div>
+ )}
+ {labeled(
+ `Toolsets (${enabledToolsets}/${state.toolsets.length} enabled — unchecking all restores the default)`,
+ <div className="rounded-md border border-(--ui-stroke-secondary) p-2">
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 320
+ }}
+ >
+ <div className="grid gap-1.5">
+ {state.toolsets.map(tset => (
+ <div key={tset.name} className="rounded-md border border-(--ui-stroke-secondary) p-2">
+ <label className="flex items-center gap-2 text-xs font-medium text-(--ui-text-secondary)">
+ <Checkbox
+ checked={!!tset.enabled}
+ onCheckedChange={value => toggleToolset(tset.name, Boolean(value))}
+ />
+ <span>{tset.name}</span>
+ </label>
+ {/* The REAL per-toolset config (env vars / API keys / model */
+ /* picker / post-setup), scoped to THIS bot's profile, when */
+ /* 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} />
+ </div>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ </ScrollArea>
+ </div>
+ )}
+ {labeled(
'MCP servers',
- jsx('div', {
- className: 'overflow-hidden rounded-md border border-(--ui-stroke-secondary)',
- // The REAL MCP tab core Settings renders — per-server enable + OAuth
- // sign-in + API-key setup + live probes — scoped to this bot's profile.
- // Feature-detected: older desktop builds without the SDK export fall
- // back to the plugin's own checkbox list + inline setup buttons.
- children: McpTab && typeof host.getGateway === 'function'
- ? jsx('div', {
- style: { minHeight: 220, maxHeight: 360 },
- children: jsx(McpTab, { gateway: host.getGateway(), profile: backendScope })
- })
- : mcpList.length === 0
- ? jsx('div', {
- className: 'px-1 py-2 text-center text-xs text-(--ui-text-tertiary)',
- children: 'No MCP servers configured or in the catalog.'
- })
- : jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 180 },
- children: jsx('div', {
- className: 'grid gap-1 p-2',
- children: mcpList.map(m => {
- const needsSetup = m.fromCatalog && !m.installed && ((m.requires || []).length > 0 || (m.auth || '').toLowerCase() === 'oauth')
- return jsxs(
- 'label',
- {
- className: 'flex items-start gap-2 text-xs text-(--ui-text-secondary)',
- children: [
- jsx(Checkbox, {
- checked: !!m.enabled,
- disabled: needsSetup,
- onCheckedChange: value => toggleMcp(m.name, Boolean(value))
- }),
- jsxs('span', {
- className: 'min-w-0',
- children: [
- jsx('span', { children: m.name }),
- m.fromCatalog && !needsSetup
- ? jsx('span', {
- className: 'ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)',
- children: m.installed ? 'catalog · installed' : 'catalog'
- })
- : null,
- needsSetup
- ? jsx(McpSetupButton, {
- profile: backendScope,
- entry: m,
- onDone: () => toggleMcp(m.name, true)
- })
- : null,
- m.description
- ? jsx('div', {
- className: 'truncate text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children: m.description
- })
- : null
- ]
- })
- ]
- },
- m.name
- )
- })
- })
- })
- })
- ),
- labeled(
+ <div className="overflow-hidden rounded-md border border-(--ui-stroke-secondary)">
+ {McpTab && typeof host.getGateway === 'function' ? (
+ <div
+ style={{
+ minHeight: 220,
+ maxHeight: 360
+ }}
+ >
+ <McpTab gateway={host.getGateway()} profile={backendScope} />
+ </div>
+ ) : mcpList.length === 0 ? (
+ <div className="px-1 py-2 text-center text-xs text-(--ui-text-tertiary)">
+ No MCP servers configured or in the catalog.
+ </div>
+ ) : (
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 180
+ }}
+ >
+ <div className="grid gap-1 p-2">
+ {mcpList.map(m => {
+ const needsSetup =
+ 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)">
+ <Checkbox
+ checked={!!m.enabled}
+ disabled={needsSetup}
+ onCheckedChange={value => toggleMcp(m.name, Boolean(value))}
+ />
+ <span className="min-w-0">
+ <span>{m.name}</span>
+ {m.fromCatalog && !needsSetup ? (
+ <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">
+ {m.installed ? 'catalog · installed' : 'catalog'}
+ </span>
+ ) : null}
+ {needsSetup ? (
+ <McpSetupButton profile={backendScope} entry={m} onDone={() => toggleMcp(m.name, true)} />
+ ) : null}
+ {m.description ? (
+ <div className="truncate text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
+ {m.description}
+ </div>
+ ) : null}
+ </span>
+ </label>
+ )
+ })}
+ </div>
+ </ScrollArea>
+ )}
+ </div>
+ )}
+ {labeled(
'SOUL.md (persona + agent-messaging protocol)',
- jsx(Textarea, {
- className: 'min-h-28 font-mono text-xs leading-5',
- value: state.soul,
- onChange: event => setState(prev => ({ ...prev, dirtySoul: true, soul: event.target.value }))
- })
- )
- ]
- })
+ <Textarea
+ className="min-h-28 font-mono text-xs leading-5"
+ value={state.soul}
+ onChange={event =>
+ setState(prev => ({
+ ...prev,
+ dirtySoul: true,
+ soul: event.target.value
+ }))
+ }
+ />
+ )}
+ </div>
+ )
}
// ── skills hub section: the REAL hub page (docs) embedded as a picker ──────
@@ -9802,7 +9958,6 @@ function AdvancedProfileConfig({ bot, state, setState }) {
const HUB_ORIGIN = 'https://hermes-agent.nousresearch.com'
const HUB_PICKER_URL = HUB_ORIGIN + '/docs/skills?embed=picker'
-
function HubSkillsSection({ forProfile, onInstalled }) {
const [query, setQuery] = useState('')
const [results, setResults] = useState(null)
@@ -9821,22 +9976,17 @@ function HubSkillsSection({ forProfile, onInstalled }) {
if (!browseHub) {
return undefined
}
-
const onMessage = event => {
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
@@ -9844,29 +9994,25 @@ function HubSkillsSection({ forProfile, onInstalled }) {
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 = await host.request('skills.manage', { action: 'search', query: q })
+ const res = await host.request('skills.manage', {
+ action: 'search',
+ query: q
+ })
setResults(res.results || [])
} catch {
setResults([])
@@ -9874,16 +10020,12 @@ function HubSkillsSection({ forProfile, onInstalled }) {
setSearching(false)
}
}
-
const install = async (name, displayName) => {
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,
@@ -9891,11 +10033,20 @@ function HubSkillsSection({ forProfile, onInstalled }) {
await host.request('skills.manage', {
action: 'install',
query: name,
- ...(forProfile ? { profile: forProfile } : {})
+ ...(forProfile
+ ? {
+ profile: forProfile
+ }
+ : {})
+ })
+ setInstalled(prev => ({
+ ...prev,
+ [label]: true
+ }))
+ host.notify({
+ kind: 'success',
+ message: `Skill "${label}" installed`
})
- setInstalled(prev => ({ ...prev, [label]: true }))
- host.notify({ kind: 'success', message: `Skill "${label}" installed` })
-
if (typeof onInstalled === 'function') {
onInstalled(label)
}
@@ -9905,163 +10056,128 @@ function HubSkillsSection({ forProfile, onInstalled }) {
setInstalling(null)
}
}
-
installRef.current = install
-
- return jsxs('div', {
- className: 'grid gap-1.5 border-t border-(--ui-stroke-secondary) pt-2',
- children: [
- jsxs('div', {
- className: 'flex items-baseline justify-between gap-2',
- children: [
- jsx('div', {
- className: 'text-[0.7rem] font-medium text-(--ui-text-secondary)',
- children: 'Skills Hub'
- }),
- jsx('button', {
- type: 'button',
- className: 'text-[0.65rem] text-(--ui-text-quaternary) hover:text-(--ui-text-secondary)',
- onClick: () => setBrowseHub(v => !v),
- children: browseHub ? 'hide the hub browser' : 'browse the full hub ▾'
- })
- ]
- }),
- browseHub
- ? jsxs('div', {
- className: 'grid gap-1',
- children: [
- // Resizable viewport: native CSS resize handle (bottom-right
- // corner) lets the user drag it larger/smaller. The iframe
- // inside is rendered oversized and scaled DOWN (133% × 0.75)
- // so the hub page starts zoomed out — we can't style the
- // cross-origin page itself, but scaling the frame is ours.
- jsx('div', {
- style: {
- width: '100%',
- height: 560,
- minHeight: 240,
- minWidth: 320,
- maxWidth: '100%',
- resize: 'both',
- overflow: 'hidden',
- border: '1px solid var(--ui-stroke-secondary)',
- borderRadius: 8,
- position: 'relative'
- },
- children: jsx('iframe', {
- src: HUB_PICKER_URL,
- title: 'Hermes Skills Hub',
- ref: frameRef,
- style: {
- width: '133.34%',
- height: '133.34%',
- border: 'none',
- background: 'transparent',
- transform: 'scale(0.75)',
- transformOrigin: 'top left'
- },
- sandbox: 'allow-scripts allow-same-origin'
- })
- }),
- jsx('div', {
- className: 'px-1 text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children:
- installing
- ? `Installing "${installing}"…`
- : 'Hit "+ Add to this Agent" on any skill — it installs and appears in the list above. Drag the corner to resize.'
- })
- ]
- })
- : null,
- jsxs('div', {
- className: 'flex gap-1.5',
- children: [
- jsx(Input, {
- className: 'h-7 flex-1 text-xs',
- placeholder: 'Search the hub (community + well-known sources)…',
- 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()
- }
+ return (
+ <div className="grid gap-1.5 border-t border-(--ui-stroke-secondary) pt-2">
+ <div className="flex items-baseline justify-between gap-2">
+ <div className="text-[0.7rem] font-medium text-(--ui-text-secondary)">Skills Hub</div>
+ <button
+ type="button"
+ className="text-[0.65rem] text-(--ui-text-quaternary) hover:text-(--ui-text-secondary)"
+ onClick={() => setBrowseHub(v => !v)}
+ >
+ {browseHub ? 'hide the hub browser' : 'browse the full hub ▾'}
+ </button>
+ </div>
+ {browseHub ? (
+ <div className="grid gap-1">
+ {/* Resizable viewport: native CSS resize handle (bottom-right */
+ /* corner) lets the user drag it larger/smaller. The iframe */
+ /* inside is rendered oversized and scaled DOWN (133% × 0.75) */
+ /* so the hub page starts zoomed out — we can't style the */
+ /* cross-origin page itself, but scaling the frame is ours. */}
+ <div
+ style={{
+ width: '100%',
+ height: 560,
+ minHeight: 240,
+ minWidth: 320,
+ maxWidth: '100%',
+ resize: 'both',
+ overflow: 'hidden',
+ border: '1px solid var(--ui-stroke-secondary)',
+ borderRadius: 8,
+ position: 'relative'
+ }}
+ >
+ <iframe
+ src={HUB_PICKER_URL}
+ title="Hermes Skills Hub"
+ ref={frameRef}
+ style={{
+ width: '133.34%',
+ height: '133.34%',
+ border: 'none',
+ background: 'transparent',
+ transform: 'scale(0.75)',
+ transformOrigin: 'top left'
+ }}
+ sandbox="allow-scripts allow-same-origin"
+ />
+ </div>
+ <div className="px-1 text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
+ {installing
+ ? `Installing "${installing}"…`
+ : 'Hit "+ Add to this Agent" on any skill — it installs and appears in the list above. Drag the corner to resize.'}
+ </div>
+ </div>
+ ) : null}
+ <div className="flex gap-1.5">
+ <Input
+ className="h-7 flex-1 text-xs"
+ placeholder="Search the hub (community + well-known sources)…"
+ 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
}
- }),
- jsx(Button, {
- size: 'sm',
- variant: 'secondary',
- disabled: searching || !query.trim(),
- onClick: () => void search(),
- children: searching ? 'Searching…' : 'Search'
- })
- ]
- }),
- searching
- ? jsx('div', {
- className: 'px-1 text-[0.65rem] text-(--ui-text-quaternary)',
- children: 'Searching community + well-known sources — can take ~10s…'
- })
- : null,
- results === null
- ? null
- : results.length === 0
- ? jsx('div', {
- className: 'px-1 py-1.5 text-[0.7rem] text-(--ui-text-quaternary)',
- children: 'No hub skills matched.'
- })
- : jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 150 },
- children: jsx('div', {
- className: 'grid gap-1',
- children: results.map(r =>
- jsxs(
- 'div',
- {
- className: 'flex items-center gap-2 text-xs',
- children: [
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsx('div', { className: 'truncate font-medium', children: r.name }),
- r.description
- ? jsx('div', {
- className: 'truncate text-[0.65rem] text-(--ui-text-quaternary)',
- children: r.description
- })
- : null
- ]
- }),
- installed[r.name]
- ? jsx('span', {
- className: 'shrink-0 text-[0.65rem] text-(--ui-text-tertiary)',
- children: '✓ added'
- })
- : jsx(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),
- children: installing === r.name ? '…' : '+'
- })
- ]
- },
- r.name
- )
- )
- })
- })
- ]
- })
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ void search()
+ }
+ }}
+ />
+ <Button size="sm" variant="secondary" disabled={searching || !query.trim()} onClick={() => void search()}>
+ {searching ? 'Searching…' : 'Search'}
+ </Button>
+ </div>
+ {searching ? (
+ <div className="px-1 text-[0.65rem] text-(--ui-text-quaternary)">
+ Searching community + well-known sources — can take ~10s…
+ </div>
+ ) : null}
+ {results === null ? null : results.length === 0 ? (
+ <div className="px-1 py-1.5 text-[0.7rem] text-(--ui-text-quaternary)">No hub skills matched.</div>
+ ) : (
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 150
+ }}
+ >
+ <div className="grid gap-1">
+ {results.map(r => (
+ <div key={r.name} className="flex items-center gap-2 text-xs">
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{r.name}</div>
+ {r.description ? (
+ <div className="truncate text-[0.65rem] text-(--ui-text-quaternary)">{r.description}</div>
+ ) : null}
+ </div>
+ {installed[r.name] ? (
+ <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)}
+ >
+ {installing === r.name ? '…' : '+'}
+ </Button>
+ )}
+ </div>
+ ))}
+ </div>
+ </ScrollArea>
+ )}
+ </div>
+ )
}
-
function emptyAdvancedState() {
return {
loaded: false,
@@ -10081,17 +10197,16 @@ function emptyAdvancedState() {
/** Persist only the dirty sections of the advanced editor. */
async function applyAdvancedConfig(bot, state) {
- const payload = { name: bot.name }
+ const payload = {
+ name: bot.name
+ }
const applied = {}
-
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
@@ -10108,28 +10223,29 @@ async function applyAdvancedConfig(bot, state) {
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 }
+ return {
+ ok: Object.values(applied).every(Boolean),
+ applied
+ }
}
-
const result = await requestForBot(bot, 'profiles.configure', payload)
- const merged = { ...applied, ...(result?.applied || {}) }
+ const merged = {
+ ...applied,
+ ...(result?.applied || {})
+ }
// #95293 remainder: the gateway now guards data-policy / expensive models
// on THIS surface too — `confirm_required` means the model section is
@@ -10143,7 +10259,10 @@ async function applyAdvancedConfig(bot, state) {
confirmLabel: 'Confirm',
confirmMessage: result.confirm_message,
failureMessage: 'Model switch failed',
- finish: () => queryClient.invalidateQueries({ queryKey: ROSTER_KEY }),
+ finish: () =>
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ }),
requestConfirmed: () =>
requestForBot(bot, 'profiles.configure', {
name: bot.name,
@@ -10153,29 +10272,32 @@ async function applyAdvancedConfig(bot, state) {
})
})
}
-
- return { ...result, ok: Object.values(merged).every(Boolean), applied: merged }
+ return {
+ ...result,
+ ok: Object.values(merged).every(Boolean),
+ applied: merged
+ }
}
// ── edit profile dialog ──────────────────────────────────────────────────────
function labeled(label, control) {
- return jsxs('div', {
- className: 'grid gap-1.5',
- children: [
- jsx('label', {
- className: 'text-xs font-medium text-(--ui-text-secondary)',
- children: label
- }),
- control
- ]
- })
+ return (
+ <div className="grid gap-1.5">
+ <label className="text-xs font-medium text-(--ui-text-secondary)">{label}</label>
+ {control}
+ </div>
+ )
}
-
function EditProfileDialog({ bot, open, onClose }) {
const metaAll = useValue($botMeta)
const meta = bot ? botRosterMeta(bot, metaAll) : null
- const appearance = bot ? botAppearance(bot.name, meta) : { shape: 'circle', color: AVATAR_COLORS[3] }
+ const appearance = bot
+ ? botAppearance(bot.name, meta)
+ : {
+ shape: 'circle',
+ color: AVATAR_COLORS[3]
+ }
const [shape, setShape] = useState(appearance.shape)
const [color, setColor] = useState(appearance.color)
const [image, setImage] = useState(appearance.image)
@@ -10201,16 +10323,13 @@ function EditProfileDialog({ bot, open, onClose }) {
setAdv(emptyAdvancedState())
}
}
-
if (!bot) {
return null
}
-
const submit = async () => {
if (busy) {
return
}
-
setBusy(true)
let advancedFailed = false
const persistence = await saveBotMeta(bot, {
@@ -10225,124 +10344,137 @@ function EditProfileDialog({ bot, open, onClose }) {
// 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: 'Saved look locally; remote persistence failed' })
+ host.notify({
+ kind: 'error',
+ message: 'Saved look locally; remote persistence failed'
+ })
}
if (persistence.serverOutcome === 'persisted') {
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
}
-
const desc = description.trim()
if (desc !== (bot.description || '').trim()) {
try {
await requestForBot(bot, 'cli.exec', {
argv: ['profile', 'describe', bot.name, '--text', desc]
})
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
} catch (err) {
host.notifyError(err, 'Saved look locally; description update failed')
}
}
-
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({ kind: 'error', message: `Some sections failed: ${failed.map(([k]) => k).join(', ')}` })
+ host.notify({
+ kind: 'error',
+ message: `Some sections failed: ${failed.map(([k]) => k).join(', ')}`
+ })
}
} catch (err) {
advancedFailed = true
host.notifyError(err, 'Advanced configuration failed')
}
}
-
if (!advancedFailed && !lookFailed) {
- host.notify({ kind: 'success', message: `${displayName(bot, { title })} updated` })
+ host.notify({
+ kind: 'success',
+ message: `${displayName(bot, {
+ title
+ })} updated`
+ })
}
setBusy(false)
onClose()
}
-
- return jsx(Dialog, {
- open,
- onOpenChange: value => !value && !busy && onClose(),
- children: jsxs(DialogContent, {
- className: advanced ? 'max-w-3xl' : 'max-w-sm',
- // Same resizable-window treatment as the create dialog.
- style: advanced
- ? { resize: 'both', overflow: 'auto', minWidth: 420, minHeight: 360, maxWidth: '95vw', maxHeight: '90vh' }
- : undefined,
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'Edit Profile' }),
- jsx(DialogDescription, { children: `Appearance and role for ${displayName(bot, null)} (${bot.name}).` })
- ]
- }),
- jsxs('div', {
- className: 'grid gap-4',
- children: [
- jsx('div', {
- className: 'flex justify-center py-1',
- children: jsx(BotFace, { shape, color, image, size: 64, name: bot.name })
- }),
- jsx(AvatarPicker, {
- shape,
- color,
- image,
- onShape: setShape,
- onColor: setColor,
- onImage: setImage,
- generateSeed: { name: bot.name, title, description }
- }),
- labeled(
- 'Title',
- jsx(Input, {
- placeholder: displayName(bot, null),
- value: title,
- onChange: event => setTitle(event.target.value)
- })
- ),
- labeled(
- 'Description',
- jsx(Textarea, {
- className: 'min-h-16',
- placeholder: 'What should this agent help with?',
- value: description,
- onChange: event => setDescription(event.target.value)
- })
- ),
- jsxs('button', {
- type: 'button',
- className:
- 'flex items-center gap-1 text-xs font-medium text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)',
- onClick: () => setAdvanced(v => !v),
- children: [
- jsx(Codicon, { name: advanced ? 'chevron-down' : 'chevron-right', className: 'text-[0.8rem]' }),
- 'Advanced — model, skills, toolsets, SOUL.md'
- ]
- }),
- advanced
- ? jsx('div', {
- className: 'rounded-md border border-(--ui-stroke-secondary) p-3',
- children: jsx(AdvancedProfileConfig, { bot, state: adv, setState: setAdv })
- })
- : null
- ]
- }),
- jsxs(DialogFooter, {
- children: [
- jsx(Button, { variant: 'ghost', disabled: busy, onClick: onClose, children: 'Cancel' }),
- jsx(Button, { disabled: busy, onClick: submit, children: busy ? 'Saving…' : 'Save' })
- ]
- })
- ]
- })
- })
+ return (
+ <Dialog open={open} onOpenChange={value => !value && !busy && onClose()}>
+ <DialogContent
+ className={advanced ? 'max-w-3xl' : 'max-w-sm'} // Same resizable-window treatment as the create dialog.
+ style={
+ advanced
+ ? {
+ resize: 'both',
+ overflow: 'auto',
+ minWidth: 420,
+ minHeight: 360,
+ maxWidth: '95vw',
+ maxHeight: '90vh'
+ }
+ : undefined
+ }
+ >
+ <DialogHeader>
+ <DialogTitle>Edit Profile</DialogTitle>
+ <DialogDescription>{`Appearance and role for ${displayName(bot, null)} (${bot.name}).`}</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4">
+ <div className="flex justify-center py-1">
+ <BotFace shape={shape} color={color} image={image} size={64} name={bot.name} />
+ </div>
+ <AvatarPicker
+ shape={shape}
+ color={color}
+ image={image}
+ onShape={setShape}
+ onColor={setColor}
+ onImage={setImage}
+ generateSeed={{
+ name: bot.name,
+ title,
+ description
+ }}
+ />
+ {labeled(
+ 'Title',
+ <Input
+ placeholder={displayName(bot, null)}
+ value={title}
+ onChange={event => setTitle(event.target.value)}
+ />
+ )}
+ {labeled(
+ 'Description',
+ <Textarea
+ className="min-h-16"
+ placeholder="What should this agent help with?"
+ value={description}
+ onChange={event => setDescription(event.target.value)}
+ />
+ )}
+ <button
+ type="button"
+ className="flex items-center gap-1 text-xs font-medium text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)"
+ onClick={() => setAdvanced(v => !v)}
+ >
+ <Codicon name={advanced ? 'chevron-down' : 'chevron-right'} className="text-[0.8rem]" />
+ Advanced — model, skills, toolsets, SOUL.md
+ </button>
+ {advanced ? (
+ <div className="rounded-md border border-(--ui-stroke-secondary) p-3">
+ <AdvancedProfileConfig bot={bot} state={adv} setState={setAdv} />
+ </div>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" disabled={busy} onClick={onClose}>
+ Cancel
+ </Button>
+ <Button disabled={busy} onClick={submit}>
+ {busy ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
// ── create dialog ────────────────────────────────────────────────────────────
@@ -10379,21 +10511,25 @@ function CreateAgentDialog({ open, onClose, roster }) {
// rendered when the desktop has a multi-connection registry.
const [targetConnection, setTargetConnection] = useState('')
const [connections, setConnections] = useState(null)
-
useEffect(() => {
- if (!open || connections !== null || typeof host.connections !== 'function' || typeof host.requestProfile !== 'function') {
+ if (
+ !open ||
+ connections !== null ||
+ typeof host.connections !== 'function' ||
+ typeof host.requestProfile !== 'function'
+ ) {
return
}
-
host
.connections()
// host.connections() returns the registry ROWS on current SDKs, but the
// envelope object ({version, primary, connections: [...]}) on desktops
// that predate the SDK-side unwrap — accept both shapes.
- .then(value => setConnections(Array.isArray(value) ? value : Array.isArray(value?.connections) ? value.connections : []))
+ .then(value =>
+ setConnections(Array.isArray(value) ? value : Array.isArray(value?.connections) ? value.connections : [])
+ )
.catch(() => setConnections([]))
}, [open, connections])
-
const activeConnectionId = String(host.state?.connectionId?.get?.() || '').trim()
// Remote target = an explicitly picked registry connection that is not the
// one this window is already on.
@@ -10407,7 +10543,12 @@ function CreateAgentDialog({ open, onClose, roster }) {
const requestForTarget = (method, params = {}) =>
remoteTarget
? host.requestProfile(
- { connectionId: targetConnection, mode: 'remote', profile: 'default', targetProfile: 'default' },
+ {
+ connectionId: targetConnection,
+ mode: 'remote',
+ profile: 'default',
+ targetProfile: 'default'
+ },
method,
params
)
@@ -10419,11 +10560,14 @@ function CreateAgentDialog({ open, onClose, roster }) {
const [createdForCaps, setCreatedForCaps] = useState(null)
const [caps, setCaps] = useState(null)
const [capsFailed, setCapsFailed] = useState(false)
- const [dirtyCaps, setDirtyCaps] = useState({ skills: false, toolsets: false, mcp: 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)
-
const slug = slugify(name)
const valid = slug.length > 0 && NAME_RE.test(slug)
// Once the draft profile is materialized (Capabilities tab / MCP setup) it
@@ -10432,7 +10576,9 @@ function CreateAgentDialog({ open, onClose, roster }) {
// name clash is fine there, and the remote's own duplicate check rejects
// real collisions at profiles.create time.
const taken = remoteTarget
- ? roster.some(b => b.remoteSource && b.connectionId === targetConnection && b.name === slug && b.name !== createdRef.current)
+ ? roster.some(
+ b => b.remoteSource && b.connectionId === targetConnection && b.name === slug && b.name !== createdRef.current
+ )
: roster.some(b => !b.remoteSource && b.name === slug && b.name !== createdRef.current)
// Draft semantics for the lazily-created profile: opening the Capabilities
@@ -10443,21 +10589,27 @@ function CreateAgentDialog({ open, onClose, roster }) {
// 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'] })
- : deleteBot({ name: draft })
+ ? requestForTarget('cli.exec', {
+ argv: ['profile', 'delete', draft, '--yes']
+ })
+ : deleteBot({
+ name: draft
+ })
void Promise.resolve(discard)
- .then(() => host.notify({ kind: 'success', message: `Draft agent "${draft}" discarded` }))
+ .then(() =>
+ host.notify({
+ kind: 'success',
+ message: `Draft agent "${draft}" discarded`
+ })
+ )
.catch(err => host.notifyError(err, `Could not clean up draft profile "${draft}"`))
}
-
const reset = () => {
setName('')
setTitle('')
@@ -10479,7 +10631,11 @@ function CreateAgentDialog({ open, onClose, roster }) {
setCreatedForCaps(null)
setCaps(null)
setCapsFailed(false)
- setDirtyCaps({ skills: false, toolsets: false, mcp: false })
+ setDirtyCaps({
+ skills: false,
+ toolsets: false,
+ mcp: false
+ })
setCapFilter('')
setTargetConnection('')
setBusy(false)
@@ -10495,9 +10651,10 @@ function CreateAgentDialog({ open, onClose, roster }) {
if ((caps && caps.source === capSource) || capsFailed) {
return
}
-
Promise.all([
- requestForTarget('profiles.describe', { name: remoteTarget ? 'default' : capSource }),
+ requestForTarget('profiles.describe', {
+ name: remoteTarget ? 'default' : capSource
+ }),
requestForTarget('mcp.catalog', {}).catch(() => null)
])
.then(([res, cat]) => {
@@ -10506,7 +10663,6 @@ function CreateAgentDialog({ open, onClose, roster }) {
const configured = res.mcp_servers || []
const have = new Set(configured.map(m => m.name))
const catalog = ((cat && cat.servers) || []).filter(s => !have.has(s.name))
-
setCaps({
source: capSource,
skills: res.skills || [],
@@ -10527,12 +10683,24 @@ function CreateAgentDialog({ open, onClose, roster }) {
})
.catch(() => setCapsFailed(true))
}
-
const toggleCap = (kind, name, enabled) => {
- setDirtyCaps(prev => ({ ...prev, [kind === 'mcp' ? 'mcp' : kind]: true }))
+ setDirtyCaps(prev => ({
+ ...prev,
+ [kind === 'mcp' ? 'mcp' : kind]: true
+ }))
setCaps(prev =>
prev
- ? { ...prev, [kind]: prev[kind].map(x => (x.name === name ? { ...x, enabled } : x)) }
+ ? {
+ ...prev,
+ [kind]: prev[kind].map(x =>
+ x.name === name
+ ? {
+ ...x,
+ enabled
+ }
+ : x
+ )
+ }
: prev
)
}
@@ -10550,18 +10718,14 @@ function CreateAgentDialog({ open, onClose, roster }) {
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,
description: descriptionText,
@@ -10575,35 +10739,45 @@ function CreateAgentDialog({ open, onClose, roster }) {
// profile, so refreshes can't invalidate each other. Older gateways
// ignore the param and copy — still functional, just forked.
share_auth: shareAuth,
- soul: composeSoul({ name: slug, title, description, roster, customSoul: soul }),
- ...(model.trim() && provider.trim() ? { model: model.trim(), provider: provider.trim() } : {})
+ soul: composeSoul({
+ name: slug,
+ title,
+ description,
+ roster,
+ customSoul: soul
+ }),
+ ...(model.trim() && provider.trim()
+ ? {
+ model: model.trim(),
+ provider: provider.trim()
+ }
+ : {})
})
-
createdRef.current = slug
// Apply capability picks from the Advanced tabs (best-effort; the
// profile exists either way and Edit Profile can finish the job).
try {
const capPayload = {}
-
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)
+ 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, ...capPayload })
+ await requestForTarget('profiles.configure', {
+ name: slug,
+ ...capPayload
+ })
}
} 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
@@ -10617,35 +10791,46 @@ function CreateAgentDialog({ open, onClose, roster }) {
title: title.trim(),
created: Date.now()
}
-
try {
- void requestForTarget('profiles.configure', { name: slug, ui_meta: { 'hermes-bots': look } }).catch(() => undefined)
-
+ void requestForTarget('profiles.configure', {
+ name: slug,
+ ui_meta: {
+ 'hermes-bots': look
+ }
+ }).catch(() => undefined)
if (avatarImage) {
- void requestForTarget('profiles.set_asset', { name: slug, asset: 'avatar', data: avatarImage }).catch(() => undefined)
+ void requestForTarget('profiles.set_asset', {
+ name: slug,
+ asset: 'avatar',
+ data: avatarImage
+ }).catch(() => undefined)
}
} catch {
/* older remote gateway */
}
} else {
- saveBotMeta(slug, { shape, color, image, imageKind: image ? 'photo' : 'shape', title: title.trim(), created: Date.now() })
+ saveBotMeta(slug, {
+ shape,
+ color,
+ image,
+ imageKind: image ? 'photo' : 'shape',
+ title: title.trim(),
+ created: Date.now()
+ })
}
-
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ 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) {
@@ -10653,25 +10838,30 @@ function CreateAgentDialog({ open, onClose, roster }) {
setError('Could not create the agent.')
return
}
-
host.notify({
kind: 'success',
message: remoteTarget
- ? `Bot "${displayName({ name: slug, title })}" created on ${targetLabel}`
- : `Bot "${displayName({ name: slug, title })}" created`
+ ? `Bot "${displayName({
+ name: slug,
+ title
+ })}" created on ${targetLabel}`
+ : `Bot "${displayName({
+ name: slug,
+ title
+ })}" created`
})
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
// canonical chat to birth here.
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
return
}
-
$selectedBot.set(slug)
// Birth the bot's forever chat right away: it introduces itself as
@@ -10681,8 +10871,9 @@ function CreateAgentDialog({ open, onClose, roster }) {
// the ONE caller allowed to request the intro turn — genuine New
// Agent creation. Click-path resolution (openBotCanonicalChat) mints
// silently so a resolution miss never burns a turn (ScottFive).
- const sid = await createCanonicalChat(slug, { kickoff: true })
-
+ const sid = await createCanonicalChat(slug, {
+ kickoff: true
+ })
if (!sid && typeof host.newChat === 'function') {
host.newChat(slug)
}
@@ -10696,513 +10887,457 @@ function CreateAgentDialog({ open, onClose, roster }) {
setError(err instanceof Error ? err.message : String(err))
}
}
-
- return jsx(Dialog, {
- open,
- onOpenChange: value => {
- if (!value && !busy) {
- // Cancel path (esc / overlay click): a materialized draft profile is
- // discarded — preconfigure-then-back-out leaves nothing behind.
- discardDraft()
- reset()
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: advanced ? 'max-w-3xl' : 'max-w-md',
- // Native resize handle (bottom-right corner): the dialog becomes a
- // window the user can grow/shrink. overflow:auto is required for CSS
- // resize to engage; caps keep it on screen.
- style: advanced
- ? { resize: 'both', overflow: 'auto', minWidth: 420, minHeight: 360, maxWidth: '95vw', maxHeight: '90vh' }
- : undefined,
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'New Bot' }),
- jsx(DialogDescription, {
- children: 'A named teammate with its own memory, skills, and chat. It can message your other agents.'
- })
- ]
- }),
- jsxs('div', {
- className: 'grid gap-3.5',
- children: [
- jsx('div', {
- className: 'flex justify-center py-1',
- children: jsx(BotFace, { shape, color, image, size: 56, name: slug || 'agent' })
- }),
- jsx(AvatarPicker, {
- shape,
- color,
- image,
- onShape: setShape,
- onColor: setColor,
- onImage: setImage,
- generateSeed: { name: slug || 'agent', title, description }
- }),
- labeled(
- 'Name',
- jsx(Input, {
- autoFocus: true,
- placeholder: 'inbox-triage',
- value: name,
- onChange: event => setName(event.target.value)
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={value => {
+ if (!value && !busy) {
+ // Cancel path (esc / overlay click): a materialized draft profile is
+ // discarded — preconfigure-then-back-out leaves nothing behind.
+ discardDraft()
+ reset()
+ onClose()
+ }
+ }}
+ >
+ <DialogContent
+ className={advanced ? 'max-w-3xl' : 'max-w-md'} // Native resize handle (bottom-right corner): the dialog becomes a
+ // window the user can grow/shrink. overflow:auto is required for CSS
+ // resize to engage; caps keep it on screen.
+ style={
+ advanced
+ ? {
+ resize: 'both',
+ overflow: 'auto',
+ minWidth: 420,
+ minHeight: 360,
+ maxWidth: '95vw',
+ maxHeight: '90vh'
+ }
+ : undefined
+ }
+ >
+ <DialogHeader>
+ <DialogTitle>New Bot</DialogTitle>
+ <DialogDescription>
+ A named teammate with its own memory, skills, and chat. It can message your other agents.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-3.5">
+ <div className="flex justify-center py-1">
+ <BotFace shape={shape} color={color} image={image} size={56} name={slug || 'agent'} />
+ </div>
+ <AvatarPicker
+ shape={shape}
+ color={color}
+ image={image}
+ onShape={setShape}
+ onColor={setColor}
+ onImage={setImage}
+ generateSeed={{
+ name: slug || 'agent',
+ title,
+ description
+ }}
+ />
+ {labeled(
+ 'Name',
+ <Input autoFocus placeholder="inbox-triage" value={name} onChange={event => setName(event.target.value)} />
+ )}
+ {taken ? (
+ <div className="text-xs text-(--ui-accent)">
+ {remoteTarget
+ ? `An agent named "${slug}" already exists on ${targetLabel}.`
+ : `An agent named "${slug}" already exists.`}
+ </div>
+ ) : null}
+ {/* Multi-connection desktops choose WHERE the agent lives. Hidden */
+ /* on single-connection setups — the active gateway is the only */
+ /* possible home, exactly the old behavior. */}
+ {Array.isArray(connections) && connections.length > 1
+ ? labeled(
+ 'Create on',
+ <Select
+ value={targetConnection || activeConnectionId || 'local'}
+ onValueChange={value => {
+ setTargetConnection(value === (activeConnectionId || 'local') ? '' : value)
+ // The capability catalog and clone list belong to the
+ // target backend — refetch for the new home. The live
+ // Capabilities tab re-pins to it via fixedConnection on
+ // builds that route it (staged checklists otherwise).
+ setCaps(null)
+ setCapsFailed(false)
+ setAdvTab('general')
+ }}
+ >
+ <SelectTrigger className="h-8 rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {connections.map(connection => (
+ <SelectItem key={connection.id} value={connection.id}>
+ {connection.id === (activeConnectionId || 'local')
+ ? `${connection.label || connection.id} (current)`
+ : connection.label || connection.id}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
+ : null}
+ {remoteTarget ? (
+ <div className="text-[0.7rem] leading-5 text-(--ui-text-tertiary)">{`The agent is created on ${targetLabel} and appears in the roster as a Connections bot. Chat routes to that machine.`}</div>
+ ) : null}
+ {labeled(
+ 'Title',
+ <Input placeholder="Inbox Triage" value={title} onChange={event => setTitle(event.target.value)} />
+ )}
+ {labeled(
+ 'Description',
+ <Textarea
+ className="min-h-16"
+ placeholder="What should this Bot help with?"
+ value={description}
+ onChange={event => setDescription(event.target.value)}
+ />
+ )}
+ <button
+ type="button"
+ className="flex items-center gap-1 text-xs font-medium text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)"
+ onClick={() => {
+ setAdvanced(v => {
+ if (!v) {
+ ensureCaps()
+ }
+ return !v
})
- ),
- taken
- ? jsx('div', {
- className: 'text-xs text-(--ui-accent)',
- children: remoteTarget
- ? `An agent named "${slug}" already exists on ${targetLabel}.`
- : `An agent named "${slug}" already exists.`
- })
- : null,
- // Multi-connection desktops choose WHERE the agent lives. Hidden
- // on single-connection setups — the active gateway is the only
- // possible home, exactly the old behavior.
- Array.isArray(connections) && connections.length > 1
- ? labeled(
- 'Create on',
- jsxs(Select, {
- value: targetConnection || activeConnectionId || 'local',
- onValueChange: value => {
- setTargetConnection(value === (activeConnectionId || 'local') ? '' : value)
- // The capability catalog and clone list belong to the
- // target backend — refetch for the new home. The live
- // Capabilities tab re-pins to it via fixedConnection on
- // builds that route it (staged checklists otherwise).
- setCaps(null)
- setCapsFailed(false)
- setAdvTab('general')
- },
- children: [
- jsx(SelectTrigger, {
- className: 'h-8 rounded-md',
- children: jsx(SelectValue, {})
- }),
- jsx(SelectContent, {
- children: connections.map(connection =>
- jsx(
- SelectItem,
- {
- value: connection.id,
- children:
- connection.id === (activeConnectionId || 'local')
- ? `${connection.label || connection.id} (current)`
- : connection.label || connection.id
- },
- connection.id
- )
- )
- })
+ }}
+ >
+ <Codicon name={advanced ? 'chevron-down' : 'chevron-right'} className="text-[0.8rem]" />
+ Advanced
+ </button>
+ {advanced ? (
+ <div className="grid gap-3 rounded-md border border-(--ui-stroke-secondary) p-3">
+ <div className="flex gap-1">
+ {(SkillsView && (!remoteTarget || skillsViewRoutesConnections)
+ ? [
+ ['general', 'General'],
+ ['capabilities', 'Capabilities']
]
- })
+ : [
+ ['general', 'General'],
+ ['skills', 'Skills'],
+ ['toolsets', 'Tools'],
+ ['mcp', 'MCP']
+ ]
+ ).map(([id, label]) => (
+ <button
+ key={id}
+ type="button"
+ className={cn(
+ 'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
+ advTab === id
+ ? 'bg-(--chrome-action-hover) text-(--ui-text-primary)'
+ : 'text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)'
+ )}
+ onClick={() => {
+ setAdvTab(id)
+ setCapFilter('')
+ if (id === 'capabilities') {
+ // The live surface needs a real profile —
+ // materialize it now (same lazy-create door
+ // the MCP setup buttons use).
+ void ensureAgentCreated()
+ .then(created => created && setCreatedForCaps(created))
+ .catch(err => host.notifyError(err, 'Could not create the profile yet'))
+ } else if (id !== 'general') {
+ ensureCaps()
+ }
+ }}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ {advTab === 'general' ? (
+ <div className="grid gap-3.5">
+ {labeled(
+ remoteTarget ? `Clone from profile (on ${targetLabel})` : 'Clone from profile',
+ <Select
+ disabled={remoteTarget}
+ value={remoteTarget ? 'default' : cloneFrom}
+ onValueChange={value => {
+ setCloneFrom(value)
+ setCaps(null)
+ setCapsFailed(false)
+ }}
+ >
+ <SelectTrigger className="h-8 rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="__none__">Fresh profile (bundled skills)</SelectItem>
+ {roster.map(b => (
+ <SelectItem key={b.name} value={b.name}>
+ {b.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </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"
+ />
+ {labeled(
+ 'SOUL.md (optional — replaces the generated persona)',
+ <Textarea
+ className="min-h-24 font-mono text-xs leading-5"
+ placeholder="Leave blank to auto-generate from name/title/description + agent-messaging roster."
+ value={soul}
+ onChange={event => setSoul(event.target.value)}
+ />
+ )}
+ <label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)">
+ <Checkbox checked={shareAuth} onCheckedChange={value => setShareAuth(Boolean(value))} />
+ Share keys & accounts with the main profile
+ </label>
+ <div className="pl-6 pt-0.5 text-[0.7rem] leading-5 text-(--ui-text-tertiary)">
+ Subscriptions, OAuth logins, and API keys stay shared (not copied), so token refreshes never
+ invalidate each other. Uncheck for an isolated snapshot copy.
+ </div>
+ <label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)">
+ <Checkbox checked={noSkills} onCheckedChange={value => setNoSkills(Boolean(value))} />
+ Create empty (skip bundled skills)
+ </label>
+ </div>
+ ) : advTab === 'capabilities' ? (
+ !valid || taken ? (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ {taken
+ ? 'That name is taken — pick another before configuring capabilities.'
+ : 'Name the bot first — a draft profile is created when you open this tab (discarded if you cancel).'}
+ </div>
+ ) : !createdForCaps ? (
+ <div className="flex justify-center py-4">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ ) : (
+ <div
+ className="overflow-hidden rounded-md border border-(--ui-stroke-secondary)"
+ style={{
+ height: 440,
+ minHeight: 280,
+ resize: 'vertical',
+ overflow: 'auto'
+ }}
+ >
+ <SkillsView
+ embedded
+ fixedProfile={createdForCaps}
+ {...(remoteTarget
+ ? {
+ fixedConnection: targetConnection
+ }
+ : {})}
+ />
+ </div>
)
- : null,
- remoteTarget
- ? jsx('div', {
- className: 'text-[0.7rem] leading-5 text-(--ui-text-tertiary)',
- children: `The agent is created on ${targetLabel} and appears in the roster as a Connections bot. Chat routes to that machine.`
- })
- : null,
- labeled(
- 'Title',
- jsx(Input, {
- placeholder: 'Inbox Triage',
- value: title,
- onChange: event => setTitle(event.target.value)
- })
- ),
- labeled(
- 'Description',
- jsx(Textarea, {
- className: 'min-h-16',
- placeholder: 'What should this Bot help with?',
- value: description,
- onChange: event => setDescription(event.target.value)
- })
- ),
- jsxs('button', {
- type: 'button',
- className:
- 'flex items-center gap-1 text-xs font-medium text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)',
- onClick: () => {
- setAdvanced(v => {
- if (!v) {
- ensureCaps()
- }
- return !v
- })
- },
- children: [
- jsx(Codicon, { name: advanced ? 'chevron-down' : 'chevron-right', className: 'text-[0.8rem]' }),
- 'Advanced'
- ]
- }),
- advanced
- ? jsxs('div', {
- className: 'grid gap-3 rounded-md border border-(--ui-stroke-secondary) p-3',
- children: [
- jsx('div', {
- className: 'flex gap-1',
- // Newer desktops export the whole Capabilities surface —
- // one live tab replaces the three staged checklists.
- // The live Capabilities surface (SkillsView) binds to
- // the ACTIVE gateway's backend unless this build routes
- // fixedConnection (skillsViewRoutesConnections) — then a
- // remote-target draft gets the live surface pinned to
- // ITS machine. Builds without that routing keep the
- // staged checklists for remote targets (their catalog
- // reads already route to the target).
- children: (SkillsView && (!remoteTarget || skillsViewRoutesConnections)
- ? [
- ['general', 'General'],
- ['capabilities', 'Capabilities']
- ]
- : [
- ['general', 'General'],
- ['skills', 'Skills'],
- ['toolsets', 'Tools'],
- ['mcp', 'MCP']
- ]
- ).map(([id, label]) =>
- jsx(
- 'button',
- {
- type: 'button',
- className: cn(
- 'rounded-md px-2.5 py-1 text-xs font-medium transition-colors',
- advTab === id
- ? 'bg-(--chrome-action-hover) text-(--ui-text-primary)'
- : 'text-(--ui-text-tertiary) hover:text-(--ui-text-secondary)'
- ),
- onClick: () => {
- setAdvTab(id)
- setCapFilter('')
- if (id === 'capabilities') {
- // The live surface needs a real profile —
- // materialize it now (same lazy-create door
- // the MCP setup buttons use).
- void ensureAgentCreated()
- .then(created => created && setCreatedForCaps(created))
- .catch(err => host.notifyError(err, 'Could not create the profile yet'))
- } else if (id !== 'general') {
- ensureCaps()
+ ) : capsFailed ? (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ Capability catalog needs a newer gateway (restart it after updating Hermes).
+ </div>
+ ) : !caps ? (
+ <div className="flex justify-center py-4">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ ) : advTab === 'skills' ? (
+ noSkills ? (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ “Create empty” is checked — no bundled skills will be installed.
+ </div>
+ ) : (
+ <div className="grid gap-1.5">
+ <Input
+ className="h-7 text-xs"
+ placeholder="Filter skills…"
+ value={capFilter}
+ onChange={event => setCapFilter(event.target.value)}
+ />
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 200
+ }}
+ >
+ <CheckList
+ 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}
+ />
+ </ScrollArea>
+ <div className="text-[0.65rem] leading-4 text-(--ui-text-quaternary)">{`Catalog from ${caps.source} — unchecked skills are disabled after creation.`}</div>
+ <HubSkillsSection
+ forProfile={null}
+ onInstalled={name =>
+ setCaps(prev =>
+ !prev || prev.skills.some(s => s.name === name)
+ ? prev
+ : {
+ ...prev,
+ skills: [
+ ...prev.skills,
+ {
+ name,
+ enabled: true
+ }
+ ]
}
- },
- children: label
- },
- id
)
- )
- }),
- advTab === 'general'
- ? jsxs('div', {
- className: 'grid gap-3.5',
- children: [
- labeled(
- remoteTarget ? `Clone from profile (on ${targetLabel})` : 'Clone from profile',
- jsxs(Select, {
- disabled: remoteTarget,
- value: remoteTarget ? 'default' : cloneFrom,
- onValueChange: value => {
- setCloneFrom(value)
- setCaps(null)
- setCapsFailed(false)
- },
- children: [
- jsx(SelectTrigger, {
- className: 'h-8 rounded-md',
- children: jsx(SelectValue, {})
- }),
- jsxs(SelectContent, {
- children: [
- jsx(SelectItem, {
- value: '__none__',
- children: 'Fresh profile (bundled skills)'
- }),
- ...roster.map(b => jsx(SelectItem, { value: b.name, children: b.name }, b.name))
- ]
- })
- ]
- })
- ),
- jsx(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'
- }),
- labeled(
- 'SOUL.md (optional — replaces the generated persona)',
- jsx(Textarea, {
- className: 'min-h-24 font-mono text-xs leading-5',
- placeholder:
- 'Leave blank to auto-generate from name/title/description + agent-messaging roster.',
- value: soul,
- onChange: event => setSoul(event.target.value)
- })
- ),
- jsxs('label', {
- className: 'flex items-center gap-2 text-xs text-(--ui-text-secondary)',
- children: [
- jsx(Checkbox, {
- checked: shareAuth,
- onCheckedChange: value => setShareAuth(Boolean(value))
- }),
- 'Share keys & accounts with the main profile'
- ]
- }),
- jsx('div', {
- className: 'pl-6 pt-0.5 text-[0.7rem] leading-5 text-(--ui-text-tertiary)',
- children:
- 'Subscriptions, OAuth logins, and API keys stay shared (not copied), so token refreshes never invalidate each other. Uncheck for an isolated snapshot copy.'
- }),
- jsxs('label', {
- className: 'flex items-center gap-2 text-xs text-(--ui-text-secondary)',
- children: [
- jsx(Checkbox, {
- checked: noSkills,
- onCheckedChange: value => setNoSkills(Boolean(value))
- }),
- 'Create empty (skip bundled skills)'
- ]
- })
- ]
- })
- : advTab === 'capabilities'
- ? !valid || taken
- ? jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: taken
- ? 'That name is taken — pick another before configuring capabilities.'
- : 'Name the bot first — a draft profile is created when you open this tab (discarded if you cancel).'
- })
- : !createdForCaps
- ? jsx('div', {
- className: 'flex justify-center py-4',
- children: jsx(GlyphSpinner, {
- spinner: 'breathe',
- className: 'text-(--ui-text-tertiary)'
- })
- })
- : jsx('div', {
- className: 'overflow-hidden rounded-md border border-(--ui-stroke-secondary)',
- style: { height: 440, minHeight: 280, resize: 'vertical', overflow: 'auto' },
- // The REAL core Capabilities surface (skills +
- // one-click hub installs + tools + MCP), pinned
- // to the just-created profile — and, for a
- // remote-target draft, to the target machine's
- // backend via fixedConnection. Writes land
- // immediately — no staging needed.
- children: jsx(SkillsView, {
- embedded: true,
- fixedProfile: createdForCaps,
- ...(remoteTarget ? { fixedConnection: targetConnection } : {})
- })
- })
- : capsFailed
- ? jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children:
- 'Capability catalog needs a newer gateway (restart it after updating Hermes).'
- })
- : !caps
- ? jsx('div', {
- className: 'flex justify-center py-4',
- children: jsx(GlyphSpinner, {
- spinner: 'breathe',
- className: 'text-(--ui-text-tertiary)'
- })
- })
- : advTab === 'skills'
- ? noSkills
- ? jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: '“Create empty” is checked — no bundled skills will be installed.'
- })
- : jsxs('div', {
- className: 'grid gap-1.5',
- children: [
- jsx(Input, {
- className: 'h-7 text-xs',
- placeholder: 'Filter skills…',
- value: capFilter,
- onChange: event => setCapFilter(event.target.value)
- }),
- jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 200 },
- children: jsx(CheckList, {
- 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
- })
- }),
- jsx('div', {
- className: 'text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children: `Catalog from ${caps.source} — unchecked skills are disabled after creation.`
- }),
- jsx(HubSkillsSection, {
- forProfile: null,
- onInstalled: name =>
- setCaps(prev =>
- !prev || prev.skills.some(s => s.name === name)
- ? prev
- : { ...prev, skills: [...prev.skills, { name, enabled: true }] }
- )
- })
- ]
- })
- : advTab === 'toolsets'
- ? jsxs('div', {
- className: 'grid gap-1.5',
- children: [
- jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 200 },
- children: jsx(CheckList, {
- items: caps.toolsets,
- onToggle: (name, enabled) => toggleCap('toolsets', name, enabled),
- columns: 2
- })
- }),
- jsx('div', {
- className: 'text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children: 'Leaving all (or none) checked keeps the default toolset behavior.'
- })
- ]
- })
- : caps.mcp.length === 0
- ? jsx('div', {
- className: 'px-2 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: 'No MCP servers configured or in the catalog.'
- })
- : jsxs('div', {
- className: 'grid gap-1.5',
- children: [
- jsx(ScrollArea, {
- className: 'hermes-scroll-cap',
- style: { maxHeight: 200 },
- children: jsx('div', {
- className: 'grid gap-1',
- children: caps.mcp.map(m => {
- const needsSetup =
- m.fromCatalog && !m.installed && ((m.requires || []).length > 0 || (m.auth || '').toLowerCase() === 'oauth')
-
- return jsxs(
- 'label',
- {
- className: 'flex items-start gap-2 text-xs text-(--ui-text-secondary)',
- children: [
- jsx(Checkbox, {
- checked: !!m.enabled,
- disabled: needsSetup,
- onCheckedChange: value => toggleCap('mcp', m.name, Boolean(value))
- }),
- jsxs('span', {
- className: 'min-w-0',
- children: [
- jsx('span', { children: m.name }),
- m.fromCatalog && !needsSetup
- ? jsx('span', {
- className: 'ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)',
- children: m.installed
- ? 'catalog · installed'
- : 'catalog'
- })
- : null,
- needsSetup
- ? jsx(McpSetupButton, {
- profile: createdRef.current,
- entry: m,
- ensureProfile: ensureAgentCreated,
- onDone: () => {
- // Setup done: mark installed so the row's
- // checkbox un-disables, and enable it.
- setCaps(prev =>
- prev
- ? {
- ...prev,
- mcp: prev.mcp.map(x =>
- x.name === m.name
- ? { ...x, installed: true, enabled: true }
- : x
- )
- }
- : prev
- )
- setDirtyCaps(prev => ({ ...prev, mcp: true }))
- }
- })
- : null,
- m.description
- ? jsx('div', {
- className:
- 'truncate text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children: m.description
- })
- : null
- ]
- })
- ]
- },
- m.name
+ }
+ />
+ </div>
+ )
+ ) : advTab === 'toolsets' ? (
+ <div className="grid gap-1.5">
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 200
+ }}
+ >
+ <CheckList
+ items={caps.toolsets}
+ onToggle={(name, enabled) => toggleCap('toolsets', name, enabled)}
+ columns={2}
+ />
+ </ScrollArea>
+ <div className="text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
+ Leaving all (or none) checked keeps the default toolset behavior.
+ </div>
+ </div>
+ ) : caps.mcp.length === 0 ? (
+ <div className="px-2 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ No MCP servers configured or in the catalog.
+ </div>
+ ) : (
+ <div className="grid gap-1.5">
+ <ScrollArea
+ className="hermes-scroll-cap"
+ style={{
+ maxHeight: 200
+ }}
+ >
+ <div className="grid gap-1">
+ {caps.mcp.map(m => {
+ const needsSetup =
+ 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)">
+ <Checkbox
+ checked={!!m.enabled}
+ disabled={needsSetup}
+ onCheckedChange={value => toggleCap('mcp', m.name, Boolean(value))}
+ />
+ <span className="min-w-0">
+ <span>{m.name}</span>
+ {m.fromCatalog && !needsSetup ? (
+ <span className="ml-1.5 text-[0.65rem] text-(--ui-text-quaternary)">
+ {m.installed ? 'catalog · installed' : 'catalog'}
+ </span>
+ ) : null}
+ {needsSetup ? (
+ <McpSetupButton
+ profile={createdRef.current}
+ entry={m}
+ ensureProfile={ensureAgentCreated}
+ onDone={() => {
+ // Setup done: mark installed so the row's
+ // checkbox un-disables, and enable it.
+ setCaps(prev =>
+ prev
+ ? {
+ ...prev,
+ mcp: prev.mcp.map(x =>
+ x.name === m.name
+ ? {
+ ...x,
+ installed: true,
+ enabled: true
+ }
+ : x
)
- })
- })
- }),
- jsx('div', {
- className: 'text-[0.65rem] leading-4 text-(--ui-text-quaternary)',
- children:
- 'Configured servers copy from the main profile; catalog entries are the bundled MCP menu. Entries needing API keys route through setup first (credentials follow the shared keys setting).'
- })
- ]
- })
- ]
- })
- : null,
- error
- ? jsx('div', {
- className: 'rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-accent)',
- children: error
- })
- : null
- ]
- }),
- jsxs(DialogFooter, {
- children: [
- jsx(Button, {
- variant: 'ghost',
- disabled: busy,
- onClick: () => {
- discardDraft()
- reset()
- onClose()
- },
- children: 'Cancel'
- }),
- jsx(Button, {
- disabled: busy || !valid || taken,
- onClick: submit,
- children: busy ? 'Creating…' : 'Create Bot'
- })
- ]
- })
- ]
- })
- })
+ }
+ : prev
+ )
+ setDirtyCaps(prev => ({
+ ...prev,
+ mcp: true
+ }))
+ }}
+ />
+ ) : null}
+ {m.description ? (
+ <div className="truncate text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
+ {m.description}
+ </div>
+ ) : null}
+ </span>
+ </label>
+ )
+ })}
+ </div>
+ </ScrollArea>
+ <div className="text-[0.65rem] leading-4 text-(--ui-text-quaternary)">
+ Configured servers copy from the main profile; catalog entries are the bundled MCP menu. Entries
+ needing API keys route through setup first (credentials follow the shared keys setting).
+ </div>
+ </div>
+ )}
+ </div>
+ ) : null}
+ {error ? (
+ <div className="rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-accent)">
+ {error}
+ </div>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ disabled={busy}
+ onClick={() => {
+ discardDraft()
+ reset()
+ onClose()
+ }}
+ >
+ Cancel
+ </Button>
+ <Button disabled={busy || !valid || taken} onClick={submit}>
+ {busy ? 'Creating…' : 'Create Bot'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
// ── routines (cron) ──────────────────────────────────────────────────────────
@@ -11214,30 +11349,39 @@ function CreateAgentDialog({ open, onClose, roster }) {
const BOT_TAG_RE = /^\[bot:([a-z0-9][a-z0-9_-]*)\]\s*/i
const SAFE_ROUTINE_MARKER = '[bot-mode:routine:v2] '
const LEGACY_DELEGATED_ROUTINE_PREFIX = 'You are running the scheduled routine "'
-
function routineBot(job) {
const match = BOT_TAG_RE.exec(job?.name || '')
return match ? match[1].toLowerCase() : null
}
-
function routineTitle(job) {
return (job?.name || '').replace(BOT_TAG_RE, '') || 'Untitled cronjob'
}
-
function isLegacyDelegatedRoutine(job) {
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) {
- const bot = typeof owner === 'string' ? { name: owner } : owner
+ 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
// remains the graceful fallback there.
- const scope = profile ? { profile } : {}
- const data = await requestForBot(bot, 'cron.manage', { action: 'list', include_disabled: true, ...scope })
+ const scope = profile
+ ? {
+ profile
+ }
+ : {}
+ const data = await requestForBot(bot, 'cron.manage', {
+ action: 'list',
+ include_disabled: true,
+ ...scope
+ })
const jobs = Array.isArray(data?.jobs) ? data.jobs : []
const activeLegacyJobs = jobs.filter(
job => isLegacyDelegatedRoutine(job) && job.enabled !== false && job.state !== 'paused'
@@ -11250,28 +11394,41 @@ async function loadRoutines(owner) {
// actually paused, and the next poll retries the rest.
const pauses = await Promise.all(
activeLegacyJobs.map(job =>
- requestForBot(bot, 'cron.manage', { action: 'pause', name: job.job_id, ...scope })
+ requestForBot(bot, 'cron.manage', {
+ action: 'pause',
+ name: job.job_id,
+ ...scope
+ })
.then(() => true)
.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 => (pausedIds.has(job.job_id) ? { ...job, enabled: false, state: 'paused' } : job))
+ jobs: jobs.map(job =>
+ pausedIds.has(job.job_id)
+ ? {
+ ...job,
+ enabled: false,
+ state: 'paused'
+ }
+ : job
+ )
}
}
-
function useRoutines(owner) {
- const bot = typeof owner === 'string' ? { name: owner } : owner
+ const bot =
+ typeof owner === 'string'
+ ? {
+ name: owner
+ }
+ : owner
const route = botConnectionRoute(bot)
const key = route ? botRosterKey(bot) : bot?.name || ''
-
return useQuery({
queryKey: [...ROUTINES_KEY, key],
queryFn: () => loadRoutines(bot),
@@ -11280,16 +11437,18 @@ function useRoutines(owner) {
staleTime: 8000
})
}
-
function routineCreateTarget(owner, activeBot) {
return owner || activeBot
}
-
async function invalidateRoutineOwner(owner) {
- const bot = typeof owner === 'string' ? { name: owner } : owner
+ const bot =
+ typeof owner === 'string'
+ ? {
+ name: owner
+ }
+ : owner
const route = botConnectionRoute(bot)
const key = route ? botRosterKey(bot) : bot?.name || ''
-
await queryClient.invalidateQueries({
queryKey: [...ROUTINES_KEY, key],
exact: true
@@ -11322,35 +11481,30 @@ function routineFilterHint(all, jobs) {
if (jobs.length !== 0 || !Array.isArray(all) || all.length === 0) {
return null
}
- return 'Cronjobs exist in this profile but none are tagged for this bot. ' +
+ return (
+ 'Cronjobs 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) {
return typeof profile === 'string' ? profile.trim().toLowerCase() : ''
}
-
function shellQuote(value) {
return `'${String(value).replaceAll("'", "'\"'\"'")}'`
}
-
function routineInputError(title, instruction) {
if (String(title).includes('\0')) {
return 'Cronjob name cannot contain NUL (U+0000).'
}
-
if (String(instruction).includes('\0')) {
return 'Cronjob instruction cannot contain NUL (U+0000).'
}
-
return null
}
-
function routinePrompt(bot, title, instruction, activeProfile) {
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` +
@@ -11360,35 +11514,26 @@ function routinePrompt(bot, title, instruction, activeProfile) {
}
function scheduleLabel(schedule) {
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 || ''
}
@@ -11407,7 +11552,6 @@ function routineDetailRows(job) {
const paused = job?.enabled === false || job?.state === 'paused'
const label = scheduleLabel(job?.schedule)
const raw = String(job?.schedule || '').trim()
-
return [
['Status', paused ? 'Paused' : 'Active'],
['Schedule', label],
@@ -11423,7 +11567,10 @@ function routineDetailRows(job) {
['Working directory', job?.workdir]
]
.filter(([, value]) => typeof value === 'string' && value.trim())
- .map(([name, value]) => ({ label: name, value: value.trim() }))
+ .map(([name, value]) => ({
+ label: name,
+ value: value.trim()
+ }))
}
/** Why a job is not doing what the user expects. The row only ever showed
@@ -11432,7 +11579,6 @@ function routineDetailRows(job) {
function routineDetailIssue(job) {
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
}
@@ -11443,65 +11589,52 @@ function RoutineDetailDialog({ job, onClose, open }) {
const rows = job ? routineDetailRows(job) : []
const issue = job ? routineDetailIssue(job) : null
const instruction = String(job?.prompt_preview || '').trim()
-
- return jsx(Dialog, {
- open: Boolean(open && job),
- onOpenChange: value => {
- if (!value) {
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: 'max-w-md',
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { className: 'truncate', children: routineTitle(job) }),
- jsx(DialogDescription, { children: 'What this cronjob runs, and when it runs next.' })
- ]
- }),
- jsxs('div', {
- className: 'grid gap-3.5',
- children: [
- issue
- ? jsx('div', {
- className:
- 'rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs leading-5 text-(--ui-accent)',
- children: issue
- })
- : null,
- jsx('div', {
- className: 'grid gap-1.5',
- children: rows.map(row =>
- jsxs('div', {
- className: 'flex items-baseline justify-between gap-3 text-xs',
- children: [
- jsx('span', { className: 'shrink-0 text-(--ui-text-tertiary)', children: row.label }),
- jsx('span', { className: 'min-w-0 truncate text-right', children: row.value })
- ]
- }, row.label)
+ return (
+ <Dialog
+ open={Boolean(open && job)}
+ onOpenChange={value => {
+ if (!value) {
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle className="truncate">{routineTitle(job)}</DialogTitle>
+ <DialogDescription>What this cronjob runs, and when it runs next.</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-3.5">
+ {issue ? (
+ <div className="rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs leading-5 text-(--ui-accent)">
+ {issue}
+ </div>
+ ) : null}
+ <div className="grid gap-1.5">
+ {rows.map(row => (
+ <div key={row.label} className="flex items-baseline justify-between gap-3 text-xs">
+ <span className="shrink-0 text-(--ui-text-tertiary)">{row.label}</span>
+ <span className="min-w-0 truncate text-right">{row.value}</span>
+ </div>
+ ))}
+ </div>
+ {instruction
+ ? labeled(
+ 'Instruction',
+ <div className="max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs leading-5 text-(--ui-text-secondary)">
+ {instruction}
+ </div>
)
- }),
- instruction
- ? labeled(
- 'Instruction',
- jsx('div', {
- className:
- 'max-h-48 overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs leading-5 text-(--ui-text-secondary)',
- children: instruction
- })
- )
- : null
- ]
- }),
- jsx(DialogFooter, {
- children: jsx(Button, { variant: 'secondary', onClick: onClose, children: 'Close' })
- })
- ]
- })
- })
+ : null}
+ </div>
+ <DialogFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Close
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
-
function RoutineRow({ job, onOpen, owner }) {
const profile = typeof owner === 'string' ? owner : owner?.name
const [busy, setBusy] = useState(false)
@@ -11511,24 +11644,27 @@ function RoutineRow({ job, onOpen, owner }) {
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 => {
if (busy) {
return
}
-
setBusy(true)
-
if (action === 'pause' || action === 'resume') {
setPendingActive(action === 'resume')
}
-
try {
- await requestForBot(owner, 'cron.manage', { action, name: job.job_id, ...(profile ? { profile } : {}) })
+ await requestForBot(owner, 'cron.manage', {
+ action,
+ name: job.job_id,
+ ...(profile
+ ? {
+ profile
+ }
+ : {})
+ })
await invalidateRoutineOwner(owner)
} catch (err) {
setPendingActive(null)
@@ -11537,109 +11673,144 @@ function RoutineRow({ job, onOpen, owner }) {
setBusy(false)
}
}
-
- return jsxs('div', {
- className: cn(
- 'group grid gap-1.5 rounded-lg border border-(--ui-stroke-secondary) p-2.5 transition-colors',
- 'hover:border-(--ui-stroke-primary, var(--ui-stroke-secondary))'
- ),
- children: [
- jsxs('div', {
- className: 'flex items-center gap-2',
- children: [
- // The row's own button, not a click handler on the card: the switch
- // and delete control are siblings, so opening the details can never
- // swallow a toggle (and a nested button would be invalid markup).
- jsxs('button', {
- type: 'button',
- title: 'Cronjob details',
- className: 'flex min-w-0 flex-1 items-center gap-2 text-left transition-colors hover:text-foreground',
- onClick: () => onOpen?.(job),
- children: [
- jsx('span', {
- 'aria-hidden': true,
- className: cn('size-1.5 shrink-0 rounded-full', active ? 'bg-emerald-500' : 'bg-(--ui-text-quaternary)')
- }),
- jsx('span', {
- className: cn('min-w-0 flex-1 truncate text-xs font-medium', !active && 'text-(--ui-text-tertiary)'),
- children: routineTitle(job)
- })
- ]
- }),
- jsx(Switch, {
- checked: active,
- disabled: busy || legacyUnsafe,
- onCheckedChange: value => act(value ? 'resume' : 'pause')
- }),
- jsx(Tip, {
- label: 'Delete cronjob',
- children: jsx('button', {
- type: 'button',
- disabled: busy,
- className:
- 'flex size-5 items-center justify-center rounded text-(--ui-text-quaternary) opacity-0 transition-opacity group-hover:opacity-100 hover:bg-(--chrome-action-hover) hover:text-foreground',
- onClick: () => act('remove'),
- children: jsx(Codicon, { name: 'trash', className: 'text-[0.75rem]' })
- })
- })
- ]
- }),
- jsxs('div', {
- className: 'flex items-center justify-between gap-2 pl-3.5',
- children: [
- jsxs('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)',
- children: [jsx(Codicon, { name: 'calendar', className: 'text-[0.7rem]' }), scheduleLabel(job.schedule)]
- }),
- jsx('span', {
- className: 'truncate text-[0.65rem] text-(--ui-text-quaternary)',
- children: active && job.next_run_at ? `next ${relativeTime(new Date(job.next_run_at).getTime())}` : 'paused'
- })
- ]
- }),
- legacyUnsafe
- ? jsx('div', {
- className:
- 'rounded-md border border-(--ui-stroke-secondary) px-2 py-1.5 text-[0.65rem] leading-4 text-(--ui-accent)',
- children: 'Paused for security: delete and recreate this legacy cronjob before running it again.'
- })
- : null
- ]
- })
+ return (
+ <div
+ className={cn(
+ 'group grid gap-1.5 rounded-lg border border-(--ui-stroke-secondary) p-2.5 transition-colors',
+ 'hover:border-(--ui-stroke-primary, var(--ui-stroke-secondary))'
+ )}
+ >
+ <div className="flex items-center gap-2">
+ {/* The row's own button, not a click handler on the card: the switch */
+ /* and delete control are siblings, so opening the details can never */
+ /* swallow a toggle (and a nested button would be invalid markup). */}
+ <button
+ type="button"
+ title="Cronjob details"
+ className="flex min-w-0 flex-1 items-center gap-2 text-left transition-colors hover:text-foreground"
+ onClick={() => onOpen?.(job)}
+ >
+ <span
+ aria-hidden
+ className={cn('size-1.5 shrink-0 rounded-full', active ? 'bg-emerald-500' : 'bg-(--ui-text-quaternary)')}
+ />
+ <span className={cn('min-w-0 flex-1 truncate text-xs font-medium', !active && 'text-(--ui-text-tertiary)')}>
+ {routineTitle(job)}
+ </span>
+ </button>
+ <Switch
+ checked={active}
+ disabled={busy || legacyUnsafe}
+ onCheckedChange={value => act(value ? 'resume' : 'pause')}
+ />
+ <Tip label="Delete cronjob">
+ <button
+ type="button"
+ disabled={busy}
+ className="flex size-5 items-center justify-center rounded text-(--ui-text-quaternary) opacity-0 transition-opacity group-hover:opacity-100 hover:bg-(--chrome-action-hover) hover:text-foreground"
+ onClick={() => act('remove')}
+ >
+ <Codicon name="trash" className="text-[0.75rem]" />
+ </button>
+ </Tip>
+ </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]" />
+ {scheduleLabel(job.schedule)}
+ </span>
+ <span className="truncate text-[0.65rem] text-(--ui-text-quaternary)">
+ {active && job.next_run_at ? `next ${relativeTime(new Date(job.next_run_at).getTime())}` : 'paused'}
+ </span>
+ </div>
+ {legacyUnsafe ? (
+ <div className="rounded-md border border-(--ui-stroke-secondary) px-2 py-1.5 text-[0.65rem] leading-4 text-(--ui-accent)">
+ Paused for security: delete and recreate this legacy cronjob before running it again.
+ </div>
+ ) : null}
+ </div>
+ )
}
// Structured schedule picker: frequency first, then only the detail that
// frequency needs (time of day, weekday, day of month, interval). Emits a
// Hermes-native schedule string; Advanced exposes it raw.
const FREQUENCIES = [
- { id: 'once', label: 'Once, in\u2026' },
- { id: 'hourly', label: 'Every hour' },
- { id: 'daily', label: 'Every day' },
- { id: 'weekdays', label: 'Weekdays' },
- { id: 'weekly', label: 'Every week' },
- { id: 'monthly', label: 'Every month' },
- { id: 'interval', label: 'Interval' },
- { id: 'advanced', label: 'Advanced\u2026' }
+ {
+ id: 'once',
+ label: 'Once, in\u2026'
+ },
+ {
+ id: 'hourly',
+ label: 'Every hour'
+ },
+ {
+ id: 'daily',
+ label: 'Every day'
+ },
+ {
+ id: 'weekdays',
+ label: 'Weekdays'
+ },
+ {
+ id: 'weekly',
+ label: 'Every week'
+ },
+ {
+ id: 'monthly',
+ label: 'Every month'
+ },
+ {
+ id: 'interval',
+ label: 'Interval'
+ },
+ {
+ id: 'advanced',
+ label: 'Advanced\u2026'
+ }
]
-
const WEEKDAYS = [
- { id: '1', label: 'Monday' },
- { id: '2', label: 'Tuesday' },
- { id: '3', label: 'Wednesday' },
- { id: '4', label: 'Thursday' },
- { id: '5', label: 'Friday' },
- { id: '6', label: 'Saturday' },
- { id: '0', label: 'Sunday' }
+ {
+ id: '1',
+ label: 'Monday'
+ },
+ {
+ id: '2',
+ label: 'Tuesday'
+ },
+ {
+ id: '3',
+ label: 'Wednesday'
+ },
+ {
+ id: '4',
+ label: 'Thursday'
+ },
+ {
+ id: '5',
+ label: 'Friday'
+ },
+ {
+ id: '6',
+ label: 'Saturday'
+ },
+ {
+ id: '0',
+ 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'
const h12 = h % 12 === 0 ? 12 : h % 12
- out.push({ id: `${h}:${m}`, label: `${h12}:${String(m).padStart(2, '0')} ${ampm}`, h, m })
+ out.push({
+ id: `${h}:${m}`,
+ label: `${h12}:${String(m).padStart(2, '0')} ${ampm}`,
+ h,
+ m
+ })
}
}
return out
@@ -11648,7 +11819,6 @@ const TIMES = (() => {
/** Compose the Hermes schedule string from picker state. */
function composeSchedule(state) {
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)
@@ -11672,17 +11842,14 @@ function composeSchedule(state) {
return state.raw || ''
}
}
-
function scheduleSummary(state) {
const t = TIMES.find(x => x.id === state.time)
const tl = t ? t.label : '9:00 AM'
-
const unitWord = u => (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`
@@ -11702,119 +11869,210 @@ function scheduleSummary(state) {
return 'Raw schedule \u2014 every Nm/Nh/Nd or 5-field cron'
}
}
-
function pickerSelect(value, onChange, options) {
- return jsxs(Select, {
- value,
- onValueChange: onChange,
- children: [
- jsx(SelectTrigger, { className: 'h-8 rounded-md', children: jsx(SelectValue, {}) }),
- jsx(SelectContent, {
- children: options.map(o => jsx(SelectItem, { value: o.id, children: o.label }, o.id))
- })
- ]
- })
+ return (
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger className="h-8 rounded-md">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map(o => (
+ <SelectItem key={o.id} value={o.id}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
}
-
function SchedulePicker({ state, setState }) {
- const upd = patch => setState(prev => ({ ...prev, ...patch }))
+ const upd = patch =>
+ setState(prev => ({
+ ...prev,
+ ...patch
+ }))
const needsTime = ['daily', 'weekdays', 'weekly', 'monthly'].includes(state.freq)
-
- return jsxs('div', {
- className: 'grid gap-2',
- children: [
- jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: needsTime ? '1fr 1fr' : '1fr', gap: '8px' },
- children: [
- pickerSelect(state.freq, v => upd({ freq: v }), FREQUENCIES),
- needsTime ? pickerSelect(state.time, v => upd({ time: v }), TIMES) : null
- ]
- }),
- state.freq === 'once'
- ? jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' },
- children: [
- jsx(Input, {
- className: 'h-8',
- placeholder: '30',
- value: state.onceN,
- onChange: event => upd({ onceN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4) })
+ return (
+ <div className="grid gap-2">
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: needsTime ? '1fr 1fr' : '1fr',
+ gap: '8px'
+ }}
+ >
+ {pickerSelect(
+ state.freq,
+ v =>
+ upd({
+ freq: v
+ }),
+ FREQUENCIES
+ )}
+ {needsTime
+ ? pickerSelect(
+ state.time,
+ v =>
+ upd({
+ time: v
+ }),
+ TIMES
+ )
+ : null}
+ </div>
+ {state.freq === 'once' ? (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '8px'
+ }}
+ >
+ <Input
+ className="h-8"
+ placeholder="30"
+ value={state.onceN}
+ onChange={event =>
+ upd({
+ onceN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4)
+ })
+ }
+ />
+ {pickerSelect(
+ state.onceUnit,
+ v =>
+ upd({
+ onceUnit: v
}),
- pickerSelect(state.onceUnit, v => upd({ onceUnit: v }), [
- { id: 'm', label: 'minutes from now' },
- { id: 'h', label: 'hours from now' },
- { id: 'd', label: 'days from now' }
- ])
+ [
+ {
+ id: 'm',
+ label: 'minutes from now'
+ },
+ {
+ id: 'h',
+ label: 'hours from now'
+ },
+ {
+ id: 'd',
+ label: 'days from now'
+ }
]
- })
- : null,
- state.freq === 'weekly'
- ? pickerSelect(state.weekday, v => upd({ weekday: v }), WEEKDAYS)
- : null,
- state.freq === 'monthly'
+ )}
+ </div>
+ ) : null}
+ {state.freq === 'weekly'
+ ? pickerSelect(
+ state.weekday,
+ v =>
+ upd({
+ weekday: v
+ }),
+ WEEKDAYS
+ )
+ : null}
+ {state.freq === 'monthly'
? labeled(
'Day of month',
- jsx(Input, {
- className: 'h-8',
- placeholder: '1',
- value: state.monthday,
- onChange: event => upd({ monthday: event.target.value.replace(/[^0-9]/g, '').slice(0, 2) })
- })
+ <Input
+ className="h-8"
+ placeholder="1"
+ value={state.monthday}
+ onChange={event =>
+ upd({
+ monthday: event.target.value.replace(/[^0-9]/g, '').slice(0, 2)
+ })
+ }
+ />
)
- : null,
- state.freq === 'interval'
- ? jsxs('div', {
- style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' },
- children: [
- jsx(Input, {
- className: 'h-8',
- placeholder: '2',
- value: state.intervalN,
- onChange: event => upd({ intervalN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4) })
- }),
- pickerSelect(state.intervalUnit, v => upd({ intervalUnit: v }), [
- { id: 'm', label: 'minutes' },
- { id: 'h', label: 'hours' },
- { id: 'd', label: 'days' }
- ])
- ]
- })
- : null,
- state.freq === 'advanced'
- ? jsx(Input, {
- className: 'h-8 font-mono text-xs',
- placeholder: 'every 1d \u00b7 every 2h \u00b7 0 9 * * * (cron)',
- value: state.raw,
- onChange: event => upd({ raw: event.target.value })
- })
- : null,
- state.freq !== 'once' && state.freq !== 'advanced'
- ? jsxs('div', {
- className: 'flex items-center gap-2',
- children: [
- jsx('span', { className: 'text-xs text-(--ui-text-tertiary)', children: 'Stop after' }),
- jsx(Input, {
- className: 'h-7 w-16 text-xs',
- placeholder: '\u221e',
- value: state.repeatN,
- onChange: event => upd({ repeatN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4) })
+ : null}
+ {state.freq === 'interval' ? (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '8px'
+ }}
+ >
+ <Input
+ className="h-8"
+ placeholder="2"
+ value={state.intervalN}
+ onChange={event =>
+ upd({
+ intervalN: event.target.value.replace(/[^0-9]/g, '').slice(0, 4)
+ })
+ }
+ />
+ {pickerSelect(
+ state.intervalUnit,
+ v =>
+ upd({
+ intervalUnit: v
}),
- jsx('span', { className: 'text-xs text-(--ui-text-tertiary)', children: 'runs (blank = forever)' })
+ [
+ {
+ id: 'm',
+ label: 'minutes'
+ },
+ {
+ id: 'h',
+ label: 'hours'
+ },
+ {
+ id: 'd',
+ label: 'days'
+ }
]
- })
- : null,
- jsx('div', {
- className: 'text-[0.65rem] text-(--ui-text-quaternary)',
- children: `${scheduleSummary(state)} \u00b7 ${composeSchedule(state) || '\u2014'}`
- })
- ]
- })
+ )}
+ </div>
+ ) : null}
+ {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
+ })
+ }
+ />
+ ) : null}
+ {state.freq !== 'once' && state.freq !== 'advanced' ? (
+ <div className="flex items-center gap-2">
+ <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)
+ })
+ }
+ />
+ <span className="text-xs text-(--ui-text-tertiary)">runs (blank = forever)</span>
+ </div>
+ ) : null}
+ <div className="text-[0.65rem] text-(--ui-text-quaternary)">{`${scheduleSummary(state)} \u00b7 ${composeSchedule(state) || '\u2014'}`}</div>
+ </div>
+ )
}
-
function defaultScheduleState() {
- return { freq: 'daily', time: '9:0', weekday: '1', monthday: '1', intervalN: '2', intervalUnit: 'h', onceN: '30', onceUnit: 'm', repeatN: '', raw: '' }
+ return {
+ freq: 'daily',
+ time: '9:0',
+ weekday: '1',
+ monthday: '1',
+ intervalN: '2',
+ intervalUnit: 'h',
+ onceN: '30',
+ onceUnit: 'm',
+ repeatN: '',
+ raw: ''
+ }
}
-
function CreateRoutineDialog({ bot, open, onClose }) {
const [name, setName] = useState('')
const [instruction, setInstruction] = useState('')
@@ -11830,7 +12088,6 @@ function CreateRoutineDialog({ bot, open, onClose }) {
const activeProfile = useValue(host.state.profile)
const profile = typeof bot === 'string' ? bot : bot?.name
const schedule = composeSchedule(sched)
-
const reset = () => {
setName('')
setInstruction('')
@@ -11840,24 +12097,19 @@ function CreateRoutineDialog({ bot, open, onClose }) {
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()
@@ -11868,16 +12120,35 @@ function CreateRoutineDialog({ bot, open, onClose }) {
name: `[bot:${profile}] ${title}`,
schedule: schedule.trim(),
prompt: routinePrompt(profile, title, task, activeProfile),
- ...(profile ? { profile } : {}),
- ...(repeatN ? { repeat: repeatN } : {}),
- ...(continuity ? { continuity: true } : {}),
+ ...(profile
+ ? {
+ profile
+ }
+ : {}),
+ ...(repeatN
+ ? {
+ repeat: repeatN
+ }
+ : {}),
+ ...(continuity
+ ? {
+ continuity: true
+ }
+ : {}),
// 'bot-chat' (bare, no name): the job is created IN the bot's own
// cron store (profile scoping above), so the scheduler resolves the
// token to that profile — no cross-gateway name ambiguity possible.
- ...(target === 'bot-chat' ? { deliver: 'bot-chat' } : {})
+ ...(target === 'bot-chat'
+ ? {
+ deliver: 'bot-chat'
+ }
+ : {})
})
await invalidateRoutineOwner(bot)
- host.notify({ kind: 'success', message: `Cronjob "${title}" scheduled` })
+ host.notify({
+ kind: 'success',
+ message: `Cronjob "${title}" scheduled`
+ })
reset()
onClose()
} catch (err) {
@@ -11885,97 +12156,102 @@ function CreateRoutineDialog({ bot, open, onClose }) {
setError(err instanceof Error ? err.message : String(err))
}
}
-
- return jsx(Dialog, {
- open,
- onOpenChange: value => {
- if (!value && !busy) {
- reset()
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: 'max-w-md',
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'New Cronjob' }),
- jsx(DialogDescription, {
- children: `A recurring task ${displayName(typeof bot === 'string' ? { name: bot } : bot, botRosterMeta(bot, $botMeta.get()))} runs on a schedule. Runs land in its own chat history.`
- })
- ]
- }),
- jsxs('div', {
- className: 'grid gap-3.5',
- children: [
- labeled(
- 'Name',
- jsx(Input, {
- autoFocus: true,
- placeholder: 'Name this cronjob',
- value: name,
- onChange: event => setName(event.target.value)
- })
- ),
- labeled(
- 'Instruction',
- jsx(Textarea, {
- className: 'min-h-20',
- placeholder: 'What should this cronjob do each time it runs?',
- value: instruction,
- onChange: event => setInstruction(event.target.value)
- })
- ),
- labeled('When to run', jsx(SchedulePicker, { state: sched, setState: setSched })),
- labeled(
- 'Send results to',
- pickerSelect(target, setTarget, [
- { id: 'history', label: 'Run history only' },
- { id: 'bot-chat', label: `${displayName(typeof bot === 'string' ? { name: bot } : bot, botRosterMeta(bot, $botMeta.get()))}\u2019s chat (bot responds)` }
- ])
- ),
- jsxs('label', {
- className: 'flex items-center gap-2 text-xs text-(--ui-text-tertiary) cursor-pointer select-none',
- children: [
- jsx('input', {
- type: 'checkbox',
- className: 'accent-(--ui-accent)',
- checked: continuity,
- onChange: event => setContinuity(event.target.checked)
- }),
- 'Continuity: each run sees the previous run\u2019s output (dedupe, continue where it left off)'
- ]
- }),
- error
- ? jsx('div', {
- className: 'rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-accent)',
- children: error
- })
- : null
- ]
- }),
- jsxs(DialogFooter, {
- children: [
- jsx(Button, {
- variant: 'ghost',
- disabled: busy,
- onClick: () => {
- reset()
- onClose()
- },
- children: 'Cancel'
- }),
- jsx(Button, {
- disabled: busy || !name.trim() || !instruction.trim() || !schedule.trim(),
- onClick: submit,
- children: busy ? 'Scheduling…' : 'Create Cronjob'
- })
- ]
- })
- ]
- })
- })
-}
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={value => {
+ if (!value && !busy) {
+ reset()
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>New Cronjob</DialogTitle>
+ <DialogDescription>{`A recurring task ${displayName(
+ typeof bot === 'string'
+ ? {
+ name: bot
+ }
+ : bot,
+ botRosterMeta(bot, $botMeta.get())
+ )} runs on a schedule. Runs land in its own chat history.`}</DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-3.5">
+ {labeled(
+ 'Name',
+ <Input
+ autoFocus
+ placeholder="Name this cronjob"
+ value={name}
+ onChange={event => setName(event.target.value)}
+ />
+ )}
+ {labeled(
+ 'Instruction',
+ <Textarea
+ className="min-h-20"
+ placeholder="What should this cronjob do each time it runs?"
+ value={instruction}
+ onChange={event => setInstruction(event.target.value)}
+ />
+ )}
+ {labeled('When to run', <SchedulePicker state={sched} setState={setSched} />)}
+ {labeled(
+ 'Send results to',
+ pickerSelect(target, setTarget, [
+ {
+ id: 'history',
+ label: 'Run history only'
+ },
+ {
+ id: 'bot-chat',
+ label: `${displayName(
+ typeof bot === 'string'
+ ? {
+ name: bot
+ }
+ : bot,
+ botRosterMeta(bot, $botMeta.get())
+ )}\u2019s chat (bot responds)`
+ }
+ ])
+ )}
+ <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}
+ onChange={event => setContinuity(event.target.checked)}
+ />
+ Continuity: each run sees the previous run’s output (dedupe, continue where it left off)
+ </label>
+ {error ? (
+ <div className="rounded-md border border-(--ui-stroke-secondary) px-3 py-2 text-xs text-(--ui-accent)">
+ {error}
+ </div>
+ ) : null}
+ </div>
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ disabled={busy}
+ onClick={() => {
+ reset()
+ onClose()
+ }}
+ >
+ Cancel
+ </Button>
+ <Button disabled={busy || !name.trim() || !instruction.trim() || !schedule.trim()} onClick={submit}>
+ {busy ? 'Scheduling…' : 'Create Cronjob'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
/** Keeps $selectedBot in sync with the focused chat's owner profile.
* nanostores' `.listen()` never replays the current value the way
@@ -11987,22 +12263,15 @@ function CreateRoutineDialog({ bot, open, onClose }) {
function bindProfileSync(ownerStore) {
const sync = owner => {
const profile = typeof owner === 'string' ? owner : owner?.profile
-
if (!profile || typeof profile !== 'string') {
return
}
-
- const connectionId = String(
- typeof owner === 'object' ? owner?.connectionId || '' : ''
- ).trim()
+ const connectionId = String(typeof owner === 'object' ? owner?.connectionId || '' : '').trim()
$selectedBot.set(connectionId ? `${connectionId}::${profile}` : profile)
}
-
sync(ownerStore.get?.())
-
return ownerStore.listen(sync)
}
-
function resolveRoutineOwner(roster, focusedOwner, selected) {
// A null focused owner is NOT a failure: the SDK fails closed to null
// whenever the focused session has no unique bot owner (a normal chat,
@@ -12011,20 +12280,23 @@ function resolveRoutineOwner(roster, focusedOwner, selected) {
// working scope) instead of dead-ending the pane on the unavailable
// placeholder for every agent (#94516).
const selectedBot = roster.find(bot => botSelectionKey(bot) === selected)
- const focusedBot = focusedOwner
- ? roster.find(bot => isActiveRosterBot(bot, focusedOwner))
- : null
-
+ 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 || (focusedOwner ? { name: focusedOwner.name } : null)
+ return (
+ focusedBot ||
+ selectedBot ||
+ (focusedOwner
+ ? {
+ name: focusedOwner.name
+ }
+ : null)
+ )
}
-
function RoutinesPane() {
const selected = useValue($selectedBot)
const focusedOwner = focusedRosterOwner(useValue($focusedBotOwner))
@@ -12048,154 +12320,111 @@ function RoutinesPane() {
// instead of freezing the snapshot that was on screen when it opened.
const [detailJobId, setDetailJobId] = useState(null)
const createTarget = owner ? routineCreateTarget(createOwner, bot) : null
-
const openCreate = () => {
if (!owner) {
return
}
-
setCreateOwner(owner)
setCreateOpen(true)
}
-
if (!owner) {
- return jsx('div', {
- className: 'flex h-full items-center justify-center px-4 text-center text-xs text-(--ui-text-tertiary)',
- children: 'Cronjobs are unavailable until this agent appears in the roster.'
- })
+ return (
+ <div className="flex h-full items-center justify-center px-4 text-center text-xs text-(--ui-text-tertiary)">
+ Cronjobs are unavailable until this agent appears in the roster.
+ </div>
+ )
}
-
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 cronjobs. Showing the last list we had.'
- : null
+ const staleNotice =
+ error && !view.live && view.all.length ? 'Could not refresh cronjobs. Showing the last list we had.' : null
const filterHint = routineFilterHint(view.all, jobs)
-
- return jsxs('div', {
- className: 'flex h-full flex-col',
- children: [
- jsxs('div', {
- className: 'flex items-center gap-2 px-3 pt-3 pb-2',
- children: [
- jsx(BotFace, { shape, color, image, size: 22, name: bot }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsxs('div', {
- className: 'flex min-w-0 items-baseline gap-1.5 truncate',
- children: [
- jsx('div', {
- className: 'truncate text-xs font-semibold',
- children: displayName({ name: bot }, meta)
- }),
- showsHandle(bot, meta)
- ? jsx('span', {
- className: 'shrink-0 font-mono text-[0.65rem] text-(--ui-text-quaternary)',
- children: `@${botHandle(bot)}`
- })
- : null
- ]
- }),
- jsx('div', {
- className: 'text-[0.65rem] uppercase tracking-wider text-(--ui-text-quaternary)',
- children: 'Cronjobs'
- })
- ]
- }),
- jsx(Tip, {
- label: 'New Cronjob',
- children: jsx('button', {
- type: 'button',
- className:
- 'flex size-6 shrink-0 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
- onClick: openCreate,
- children: jsx(Codicon, { name: 'add' })
- })
- })
- ]
- }),
- jsx('div', { className: 'mx-3 border-t border-(--ui-stroke-secondary)' }),
- staleNotice
- ? jsx('div', {
- className: 'mx-3 mt-2 rounded-md bg-(--chrome-action-hover) px-2 py-1.5 text-[0.6875rem] text-(--ui-text-tertiary)',
- children: staleNotice
- })
- : null,
- isLoading && !view.all.length
- ? jsx('div', {
- className: 'flex flex-1 items-center justify-center',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
- : error && !view.all.length
- ? jsxs('div', {
- className: 'flex flex-1 flex-col items-center justify-center gap-3 px-4 text-center',
- children: [
- jsx(Codicon, { name: 'warning', className: 'text-[1.6rem] text-(--ui-text-quaternary)' }),
- jsx('div', {
- className: 'text-xs leading-5 text-(--ui-text-tertiary)',
- children: 'Could not load cronjobs. The list may still be there.'
- }),
- jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- onClick: () => void refetch(),
- children: 'Retry'
- })
- ]
- })
- : jobs.length === 0
- ? jsxs('div', {
- className: 'flex flex-1 flex-col items-center justify-center gap-3 px-4 text-center',
- children: [
- // No generic placeholder here: an icon + "cronjobs are…" blurb and the
- // create button both just said "empty" (Teknium, Aug 2026). The hint
- // text stays only when jobs exist but are hidden by the bot filter —
- // that carries real information, not an empty-state marker.
- filterHint
- ? jsx('div', {
- className: 'text-xs leading-5 text-(--ui-text-tertiary)',
- children: filterHint
- })
- : null,
- jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- onClick: openCreate,
- children: filterHint ? 'Create a cronjob for this bot' : 'Create Cronjob'
- })
- ]
- })
- : jsx(ScrollArea, {
- className: 'min-h-0 flex-1',
- children: jsx('div', {
- className: 'grid gap-1.5 px-2.5 py-2',
- children: jobs.map(job =>
- jsx(RoutineRow, { job, onOpen: opened => setDetailJobId(opened.job_id), owner }, job.job_id)
- )
- })
- }),
- jsx(RoutineDetailDialog, {
- job: detailJob,
- open: Boolean(detailJob),
- onClose: () => setDetailJobId(null)
- }),
- jsx(CreateRoutineDialog, {
- bot: createTarget,
- open: createOpen,
- onClose: () => {
+ 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={color} image={image} size={22} name={bot} />
+ <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">
+ {displayName(
+ {
+ name: bot
+ },
+ meta
+ )}
+ </div>
+ {showsHandle(bot, meta) ? (
+ <span className="shrink-0 font-mono text-[0.65rem] text-(--ui-text-quaternary)">{`@${botHandle(bot)}`}</span>
+ ) : null}
+ </div>
+ <div className="text-[0.65rem] uppercase tracking-wider text-(--ui-text-quaternary)">Cronjobs</div>
+ </div>
+ <Tip label="New Cronjob">
+ <button
+ type="button"
+ className="flex size-6 shrink-0 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground"
+ onClick={openCreate}
+ >
+ <Codicon name="add" />
+ </button>
+ </Tip>
+ </div>
+ <div className="mx-3 border-t border-(--ui-stroke-secondary)" />
+ {staleNotice ? (
+ <div className="mx-3 mt-2 rounded-md bg-(--chrome-action-hover) px-2 py-1.5 text-[0.6875rem] text-(--ui-text-tertiary)">
+ {staleNotice}
+ </div>
+ ) : null}
+ {isLoading && !view.all.length ? (
+ <div className="flex flex-1 items-center justify-center">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ ) : error && !view.all.length ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-4 text-center">
+ <Codicon name="warning" className="text-[1.6rem] text-(--ui-text-quaternary)" />
+ <div className="text-xs leading-5 text-(--ui-text-tertiary)">
+ Could not load cronjobs. The list may still be there.
+ </div>
+ <Button variant="secondary" size="sm" onClick={() => void refetch()}>
+ Retry
+ </Button>
+ </div>
+ ) : jobs.length === 0 ? (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-4 text-center">
+ {/* No generic placeholder here: an icon + "cronjobs are…" blurb and the */
+ /* create button both just said "empty" (Teknium, Aug 2026). The hint */
+ /* text stays only when jobs exist but are hidden by the bot filter — */
+ /* that carries real information, not an empty-state marker. */}
+ {filterHint ? <div className="text-xs leading-5 text-(--ui-text-tertiary)">{filterHint}</div> : null}
+ <Button variant="secondary" size="sm" onClick={openCreate}>
+ {filterHint ? 'Create a cronjob for this bot' : 'Create Cronjob'}
+ </Button>
+ </div>
+ ) : (
+ <ScrollArea className="min-h-0 flex-1">
+ <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} />
+ ))}
+ </div>
+ </ScrollArea>
+ )}
+ <RoutineDetailDialog job={detailJob} open={Boolean(detailJob)} onClose={() => setDetailJobId(null)} />
+ <CreateRoutineDialog
+ key={createTarget}
+ bot={createTarget}
+ open={createOpen}
+ onClose={() => {
setCreateOpen(false)
setCreateOwner(null)
- }
- // key is the jsx() THIRD argument — as a prop it is silently ignored
- // and the dialog kept stale per-bot form state when the target changed.
- }, createTarget)
- ]
- })
+ }}
+ />
+ </div>
+ )
}
// ── roster pane ──────────────────────────────────────────────────────────────
@@ -12207,60 +12436,43 @@ function RoutinesPane() {
* is active, and never reorders the roster below it. */
function ActiveNowStrip({ roster, activeProfile, gatewayState, metaByName, onOpen }) {
const active = activeBots(roster, activeProfile, gatewayState)
-
if (!active.length) {
return null
}
-
- return jsxs('div', {
- role: 'status',
- 'aria-live': 'polite',
- 'aria-label': 'Active now',
- className: 'flex flex-wrap items-center gap-1.5 px-2.5 pb-1.5',
- children: [
- jsx('span', {
- className: 'text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)',
- children: 'Active now'
- }),
- ...active.map(bot => {
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-label="Active now"
+ className="flex flex-wrap items-center gap-1.5 px-2.5 pb-1.5"
+ >
+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)">
+ Active now
+ </span>
+ {active.map(bot => {
const meta = botRosterMeta(bot, metaByName)
const { shape, color, image } = botAppearance(bot.name, meta)
const photo = Boolean(image && !isBackfilledFacePng(image))
const label = displayName(bot, meta)
-
- return jsx(
- Tip,
- {
- label: `Open ${label}'s chat`,
- children: jsx('button', {
- type: 'button',
- 'aria-label': `Open ${label}'s chat`,
- className: cn(
+ return (
+ <Tip key={botRosterKey(bot)} label={`Open ${label}'s chat`}>
+ <button
+ type="button"
+ aria-label={`Open ${label}'s chat`}
+ className={cn(
'flex items-center gap-1.5 rounded-md bg-(--chrome-action-hover) px-1.5 py-1 text-left transition-colors',
'hover:bg-(--chrome-action-hover) hover:text-foreground'
- ),
- onClick: () => onOpen(bot),
- children: [
- jsx(BotFace, {
- shape,
- color,
- image: photo ? image : null,
- size: 24,
- name: bot.name,
- mood: 'work'
- }),
- jsx('span', {
- className: 'max-w-28 truncate text-xs font-medium',
- children: label
- })
- ]
- })
- },
- botRosterKey(bot)
+ )}
+ onClick={() => onOpen(bot)}
+ >
+ <BotFace shape={shape} color={color} image={photo ? image : null} size={24} name={bot.name} mood="work" />
+ <span className="max-w-28 truncate text-xs font-medium">{label}</span>
+ </button>
+ </Tip>
)
- })
- ]
- })
+ })}
+ </div>
+ )
}
/** Assign a bot to a group-chat membership without replacing its others.
@@ -12271,7 +12483,6 @@ function GroupDialog({ bot, onClose }) {
const [name, setName] = useState('')
const current = botGroups(botRosterMeta(bot, meta))
const groups = knownGroups(meta)
-
const setMembership = (group, enabled) => {
void saveBotMeta(bot, groupMembershipPatch(botRosterMeta(bot, meta), group, enabled))
host.notify({
@@ -12281,82 +12492,75 @@ function GroupDialog({ bot, onClose }) {
: `${displayName(bot, botRosterMeta(bot, meta))} removed from “${group}”`
})
}
-
- return jsx(Dialog, {
- open: Boolean(bot),
- onOpenChange: value => {
- if (!value) {
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: 'max-w-sm',
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'Manage groups' }),
- jsx(DialogDescription, {
- children: 'A bot can join multiple group chats. Memberships sync to every machine.'
- })
- ]
- }),
- groups.length
- ? jsx('div', {
- className: 'grid gap-1.5',
- children: groups.map(group => {
- const enabled = current.includes(group)
-
- return jsxs(
- 'label',
- {
- className:
- 'flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm hover:bg-(--chrome-action-hover)',
- children: [
- jsx(Checkbox, {
- checked: enabled,
- onCheckedChange: checked => setMembership(group, checked === true)
- }),
- jsx('span', { children: group })
- ]
- },
- group
- )
- })
- })
- : null,
- jsxs('form', {
- className: 'flex items-center gap-1.5',
- onSubmit: event => {
+ return (
+ <Dialog
+ open={Boolean(bot)}
+ onOpenChange={value => {
+ if (!value) {
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Manage groups</DialogTitle>
+ <DialogDescription>A bot can join multiple group chats. Memberships sync to every machine.</DialogDescription>
+ </DialogHeader>
+ {groups.length ? (
+ <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)"
+ >
+ <Checkbox checked={enabled} onCheckedChange={checked => setMembership(group, checked === true)} />
+ <span>{group}</span>
+ </label>
+ )
+ })}
+ </div>
+ ) : null}
+ <form
+ className="flex items-center gap-1.5"
+ onSubmit={event => {
event.preventDefault()
const trimmed = name.trim()
-
if (trimmed) {
setMembership(trimmed, true)
setName('')
}
- },
- children: [
- jsx(Input, {
- autoFocus: true,
- placeholder: groups.length ? 'New group…' : 'Group name (e.g. Research)',
- value: name,
- onChange: event => setName(event.target.value)
- }),
- jsx(Button, { type: 'submit', size: 'sm', disabled: !name.trim(), children: 'Create & join' })
- ]
- }),
- current.length
- ? jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- className: 'justify-self-start',
- onClick: () => void saveBotMeta(bot, { groups: [], group: null }),
- children: 'Remove from all groups'
- })
- : null
- ]
- })
- })
+ }}
+ >
+ <Input
+ autoFocus
+ 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()}>
+ Create & join
+ </Button>
+ </form>
+ {current.length ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="justify-self-start"
+ onClick={() =>
+ void saveBotMeta(bot, {
+ groups: [],
+ group: null
+ })
+ }
+ >
+ Remove from all groups
+ </Button>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ )
}
/** Compact picture controls shared by group-chat creation and settings:
@@ -12366,26 +12570,20 @@ function GroupDialog({ bot, onClose }) {
function GroupImageControls({ image, onImage, seedName, seedMembers }) {
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)
@@ -12396,13 +12594,10 @@ function GroupImageControls({ image, onImage, seedName, seedMembers }) {
'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))
}
@@ -12412,33 +12607,30 @@ function GroupImageControls({ image, onImage, seedName, seedMembers }) {
setBusy(false)
}
}
-
- return jsxs('div', {
- className: 'flex items-center gap-2',
- children: [
- jsx('div', {
- className:
- 'flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-(--chrome-action-hover)',
- children: image
- ? jsx('img', { src: image, alt: '', className: 'size-full object-cover' })
- : jsx(Codicon, { name: 'organization', className: 'text-(--ui-text-tertiary)' })
- }),
- jsx(Button, { type: 'button', variant: 'secondary', size: 'sm', onClick: upload, children: 'Upload' }),
- imagen
- ? jsx(Button, {
- type: 'button',
- variant: 'secondary',
- size: 'sm',
- disabled: busy,
- onClick: generate,
- children: busy ? 'Generating…' : 'Generate'
- })
- : null,
- image
- ? jsx(Button, { type: 'button', variant: 'ghost', size: 'sm', onClick: () => onImage(null), children: 'Remove' })
- : null
- ]
- })
+ 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" />
+ ) : (
+ <Codicon name="organization" className="text-(--ui-text-tertiary)" />
+ )}
+ </div>
+ <Button type="button" variant="secondary" size="sm" onClick={upload}>
+ Upload
+ </Button>
+ {imagen ? (
+ <Button type="button" variant="secondary" size="sm" disabled={busy} onClick={generate}>
+ {busy ? 'Generating…' : 'Generate'}
+ </Button>
+ ) : null}
+ {image ? (
+ <Button type="button" variant="ghost" size="sm" onClick={() => onImage(null)}>
+ Remove
+ </Button>
+ ) : null}
+ </div>
+ )
}
/** Edit an existing group chat's name and picture. Renames re-key the room
@@ -12449,7 +12641,6 @@ function GroupChatSettingsDialog({ group, members, open, onClose, onRenamed }) {
const current = (rooms[group] || {}).image || null
const [name, setName] = useState(group)
const [image, setImage] = useState(current)
-
useEffect(() => {
if (open) {
setName(group)
@@ -12457,71 +12648,64 @@ function GroupChatSettingsDialog({ group, members, open, onClose, onRenamed }) {
}
// 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 jsx(Dialog, {
- open,
- onOpenChange: value => {
- if (!value) {
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: 'max-w-sm',
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'Group settings' }),
- jsx(DialogDescription, {
- children: 'Rename the group or set a room picture. Members and history are kept.'
- })
- ]
- }),
- jsx(GroupImageControls, {
- image,
- onImage: setImage,
- seedName: name.trim() || group,
- seedMembers: (members || []).map(b => b.name)
- }),
- jsx('form', {
- onSubmit: event => {
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={value => {
+ if (!value) {
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Group settings</DialogTitle>
+ <DialogDescription>Rename the group or set a room picture. Members and history are kept.</DialogDescription>
+ </DialogHeader>
+ <GroupImageControls
+ image={image}
+ onImage={setImage}
+ seedName={name.trim() || group}
+ seedMembers={(members || []).map(b => b.name)}
+ />
+ <form
+ onSubmit={event => {
event.preventDefault()
void save()
- },
- children: jsx(Input, {
- 'aria-label': 'Group name',
- autoFocus: true,
- maxLength: 64,
- value: name,
- onChange: event => setName(event.target.value)
- })
- }),
- jsxs(DialogFooter, {
- children: [
- jsx(Button, { variant: 'secondary', onClick: onClose, children: 'Cancel' }),
- jsx(Button, { disabled: !name.trim(), onClick: () => void save(), children: 'Save' })
- ]
- })
- ]
- })
- })
+ }}
+ >
+ <Input
+ aria-label="Group name"
+ autoFocus
+ maxLength={64}
+ value={name}
+ onChange={event => setName(event.target.value)}
+ />
+ </form>
+ <DialogFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button disabled={!name.trim()} onClick={() => void save()}>
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
/** Discord-style group chat creation: pick 2+ bots via checkboxes (with
@@ -12555,10 +12739,8 @@ function CreateGroupChatDialog({ open, roster, onClose, onCreated }) {
? selected.map(bot => displayName(bot, botRosterMeta(bot, allMeta))).join(', ')
: 'Group name'
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
}
@@ -12572,16 +12754,13 @@ function CreateGroupChatDialog({ open, roster, onClose, onCreated }) {
// 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))
}
@@ -12590,157 +12769,155 @@ function CreateGroupChatDialog({ open, roster, onClose, onCreated }) {
// member becomes remote after a source switch and cannot rely on the new
// gateway's name-keyed bot metadata to remain seated in this room.
const roomMembers = durableGroupChatMembers(selected)
-
updateGroupChat(groupName, room => {
room.members = roomMembers
room.roomId = roomId
-
if (image) {
room.image = image
}
-
return room
})
-
- host.notify({ kind: 'info', message: `“${groupName}” created with ${selected.length} bots` })
+ host.notify({
+ kind: 'info',
+ message: `“${groupName}” created with ${selected.length} bots`
+ })
onClose()
onCreated?.(groupName)
}
-
- return jsx(Dialog, {
- open,
- onOpenChange: value => {
- if (!value) {
- onClose()
- }
- },
- children: jsxs(DialogContent, {
- className: 'max-w-md',
- children: [
- jsxs(DialogHeader, {
- children: [
- jsx(DialogTitle, { children: 'New Group Chat' }),
- jsx(DialogDescription, {
- children: `Pick 2–${GROUP_CHAT_MAX_MEMBERS} bots. Local memberships sync through each Bot profile; cross-machine members stay scoped to this room.`
- })
- ]
- }),
- jsx(SearchField, {
- 'aria-label': 'Search bots to add',
- autoFocus: true,
- containerClassName: 'w-full',
- inputClassName: 'w-full',
- placeholder: 'Search bots to add…',
- value: query,
- onChange: setQuery
- }),
- selected.length
- ? jsx('div', {
- className: 'flex flex-wrap gap-1',
- children: selected.map(bot =>
- jsxs('button', {
- type: 'button',
- className:
- 'flex items-center gap-1 rounded-full bg-(--chrome-action-hover) py-0.5 pl-2 pr-1.5 text-[0.6875rem] text-(--ui-text-secondary) transition-colors hover:text-foreground',
- title: 'Remove from selection',
- onClick: () => setChecked(prev => ({ ...prev, [botRosterKey(bot)]: false })),
- children: [displayName(bot, botRosterMeta(bot, allMeta)), jsx(Codicon, { name: 'close', className: 'text-[0.6rem]' })]
- }, botRosterKey(bot))
- )
- })
- : null,
- jsx(ScrollArea, {
- className: 'max-h-64 min-h-0',
- children: jsx('div', {
- className: 'grid gap-0.5 pr-2',
- children: visible.length
- ? visible.map(bot => {
- const meta = botRosterMeta(bot, allMeta)
- const { shape, color, image } = botAppearance(bot.name, meta)
- const isChecked = Boolean(checked[botRosterKey(bot)])
- const disabled = !isChecked && atCap
- const currentGroups = botGroups(meta)
-
- return jsxs('label', {
- className: cn(
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={value => {
+ if (!value) {
+ onClose()
+ }
+ }}
+ >
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>New Group Chat</DialogTitle>
+ <DialogDescription>{`Pick 2–${GROUP_CHAT_MAX_MEMBERS} bots. Local memberships sync through each Bot profile; cross-machine members stay scoped to this room.`}</DialogDescription>
+ </DialogHeader>
+ <SearchField
+ aria-label="Search bots to add"
+ autoFocus
+ containerClassName="w-full"
+ inputClassName="w-full"
+ placeholder="Search bots to add…"
+ value={query}
+ onChange={setQuery}
+ />
+ {selected.length ? (
+ <div className="flex flex-wrap gap-1">
+ {selected.map(bot => (
+ <button
+ key={botRosterKey(bot)}
+ type="button"
+ className="flex items-center gap-1 rounded-full bg-(--chrome-action-hover) py-0.5 pl-2 pr-1.5 text-[0.6875rem] text-(--ui-text-secondary) transition-colors hover:text-foreground"
+ title="Remove from selection"
+ onClick={() =>
+ setChecked(prev => ({
+ ...prev,
+ [botRosterKey(bot)]: false
+ }))
+ }
+ >
+ {displayName(bot, botRosterMeta(bot, allMeta))}
+ <Codicon name="close" className="text-[0.6rem]" />
+ </button>
+ ))}
+ </div>
+ ) : null}
+ <ScrollArea className="max-h-64 min-h-0">
+ <div className="grid gap-0.5 pr-2">
+ {visible.length ? (
+ visible.map(bot => {
+ const meta = botRosterMeta(bot, allMeta)
+ const { shape, color, image } = botAppearance(bot.name, meta)
+ 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'
- ),
- children: [
- jsx(BotFace, {
- shape,
- color,
- image: image && !isBackfilledFacePng(image) ? image : null,
- size: 24,
- name: bot.name
- }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsx('div', { className: 'truncate text-xs text-foreground', children: displayName(bot, meta) }),
- jsx('div', {
- className: 'truncate text-[0.625rem] text-(--ui-text-quaternary)',
- children: [
- currentGroups.length
- ? `@${botHandle(bot.name, bot)} · in ${currentGroups.map(group => `“${group}”`).join(', ')}`
- : `@${botHandle(bot.name, bot)}`,
- bot.remoteSource && bot.connectionLabel ? ` · ${bot.connectionLabel}` : ''
- ].join('')
- })
- ]
- }),
- jsx(Checkbox, {
- checked: isChecked,
- disabled,
- onCheckedChange: value => setChecked(prev => ({ ...prev, [botRosterKey(bot)]: Boolean(value) }))
- })
- ]
- }, botRosterKey(bot))
- })
- : jsx('div', {
- className: 'px-1.5 py-3 text-center text-xs text-(--ui-text-tertiary)',
- children: query.trim() ? `No bots match “${query.trim()}”` : 'No bots yet — create one first.'
- })
- })
- }),
- jsxs('div', {
- className: 'grid gap-2',
- children: [
- jsx(GroupImageControls, {
- image,
- onImage: setImage,
- seedName: name.trim() || (selected.length ? placeholder : ''),
- seedMembers: selected.map(bot => displayName(bot, botRosterMeta(bot, allMeta)))
- }),
- jsx('form', {
- onSubmit: event => {
- event.preventDefault()
- create()
- },
- children: jsx(Input, {
- 'aria-label': 'Group name',
- maxLength: 64,
- placeholder,
- value: name,
- onChange: event => setName(event.target.value)
+ )}
+ >
+ <BotFace
+ shape={shape}
+ color={color}
+ image={image && !isBackfilledFacePng(image) ? image : null}
+ size={24}
+ name={bot.name}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-xs text-foreground">{displayName(bot, meta)}</div>
+ <div className="truncate text-[0.625rem] text-(--ui-text-quaternary)">
+ {[
+ currentGroups.length
+ ? `@${botHandle(bot.name, bot)} · in ${currentGroups.map(group => `“${group}”`).join(', ')}`
+ : `@${botHandle(bot.name, bot)}`,
+ bot.remoteSource && bot.connectionLabel ? ` · ${bot.connectionLabel}` : ''
+ ].join('')}
+ </div>
+ </div>
+ <Checkbox
+ checked={isChecked}
+ disabled={disabled}
+ onCheckedChange={value =>
+ setChecked(prev => ({
+ ...prev,
+ [botRosterKey(bot)]: Boolean(value)
+ }))
+ }
+ />
+ </label>
+ )
})
- })
- ]
- }),
- jsxs(DialogFooter, {
- children: [
- jsx(Button, { variant: 'secondary', onClick: onClose, children: 'Cancel' }),
- jsx(Button, {
- disabled: !canCreate,
- title: selected.length < 2 ? 'Pick at least 2 bots' : undefined,
- onClick: create,
- children: `Create Group${selected.length ? ` (${selected.length})` : ''}`
- })
- ]
- })
- ]
- })
- })
+ ) : (
+ <div className="px-1.5 py-3 text-center text-xs text-(--ui-text-tertiary)">
+ {query.trim() ? `No bots match “${query.trim()}”` : 'No bots yet — create one first.'}
+ </div>
+ )}
+ </div>
+ </ScrollArea>
+ <div className="grid gap-2">
+ <GroupImageControls
+ image={image}
+ onImage={setImage}
+ seedName={name.trim() || (selected.length ? placeholder : '')}
+ seedMembers={selected.map(bot => displayName(bot, botRosterMeta(bot, allMeta)))}
+ />
+ <form
+ onSubmit={event => {
+ event.preventDefault()
+ create()
+ }}
+ >
+ <Input
+ aria-label="Group name"
+ maxLength={64}
+ placeholder={placeholder}
+ value={name}
+ onChange={event => setName(event.target.value)}
+ />
+ </form>
+ </div>
+ <DialogFooter>
+ <Button variant="secondary" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button
+ disabled={!canCreate}
+ title={selected.length < 2 ? 'Pick at least 2 bots' : undefined}
+ onClick={create}
+ >{`Create Group${selected.length ? ` (${selected.length})` : ''}`}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
}
// ── threads: the Slack/Discord shape ─────────────────────────────────────────
@@ -12752,7 +12929,6 @@ function CreateGroupChatDialog({ open, roster, onClose, onCreated }) {
function groupThreadOf(entry) {
return entry?.thread || 'legacy'
}
-
function mintGroupThreadId() {
return `t${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`
}
@@ -12761,26 +12937,23 @@ function mintGroupThreadId() {
// 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
-
function assignLegacyThreads(log) {
let current = 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 }
+ return {
+ ...entry,
+ thread: current
+ }
})
}
@@ -12795,12 +12968,13 @@ function assignLegacyThreads(log) {
function mentionTokenAt(text, caret) {
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 }
+ return {
+ query: match[2].toLowerCase(),
+ start: caret - match[2].length - 1
+ }
}
/** Mention-aware composer input for group rooms. The core composer's
@@ -12815,26 +12989,24 @@ function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...inputPr
const inputRef = useRef(null)
const [token, setToken] = useState(null)
const [selected, setSelected] = useState(0)
-
const options = []
-
if (token) {
for (const pick of ['everyone', 'all']) {
if (pick.startsWith(token.query)) {
- options.push({ handle: pick, meta: 'Every bot in the room' })
+ options.push({
+ handle: pick,
+ meta: 'Every bot in the room'
+ })
}
}
-
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) &&
@@ -12843,27 +13015,22 @@ function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...inputPr
) {
continue
}
-
options.push({
handle: tag,
meta: display
})
}
}
-
const open = Boolean(token) && options.length > 0
const active = open ? Math.min(selected, options.length - 1) : 0
-
const refreshToken = target => {
setToken(mentionTokenAt(target.value, target.selectionStart ?? target.value.length))
setSelected(0)
}
-
const insert = handle => {
if (!token) {
return
}
-
const caret = inputRef.current?.selectionStart ?? value.length
const next = `${value.slice(0, token.start)}@${handle} ${value.slice(caret)}`
onChange(next)
@@ -12873,7 +13040,6 @@ function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...inputPr
const pos = token.start + handle.length + 2
requestAnimationFrame(() => {
const el = inputRef.current
-
if (el) {
el.focus()
try {
@@ -12884,51 +13050,45 @@ function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...inputPr
}
})
}
-
- return jsxs('div', {
- className: 'relative min-w-0 flex-1',
- children: [
- open
- ? jsx('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,#111) py-1 shadow-lg',
- children: options.map((option, index) =>
- jsxs('button', {
- type: 'button',
- 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.
- onMouseDown: event => {
- event.preventDefault()
- insert(option.handle)
- },
- onMouseEnter: () => setSelected(index),
- children: [
- jsx('span', { className: 'font-medium', children: `@${option.handle}` }),
- jsx('span', { className: 'truncate text-[0.65rem] text-(--ui-text-quaternary)', children: option.meta })
- ]
- }, option.handle)
- )
- })
- : null,
- jsx(Textarea, {
- ...inputProps,
- ref: inputRef,
- value,
- rows: 1,
- // Multi-line room prompts (#89884): the composer was a single-line
+ 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,#111) py-1 shadow-lg">
+ {options.map((option, index) => (
+ <button
+ key={option.handle}
+ type="button"
+ 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.
+ onMouseDown={event => {
+ event.preventDefault()
+ insert(option.handle)
+ }}
+ onMouseEnter={() => setSelected(index)}
+ >
+ <span className="font-medium">{`@${option.handle}`}</span>
+ <span className="truncate text-[0.65rem] text-(--ui-text-quaternary)">{option.meta}</span>
+ </button>
+ ))}
+ </div>
+ ) : 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),
- onChange: event => {
+ className={cn('max-h-40 min-h-9 resize-none', inputProps.className)}
+ onChange={event => {
onChange(event.target.value)
refreshToken(event.target)
- },
- onClick: event => refreshToken(event.target),
- onKeyDown: event => {
+ }}
+ onClick={event => refreshToken(event.target)}
+ onKeyDown={event => {
// IME composition guard (same as the core composer): Enter here
// confirms the composed Chinese/Japanese/Korean text — it must not
// insert a mention nor submit the draft. nativeEvent.isComposing
@@ -12941,41 +13101,33 @@ function GroupMentionInput({ members, onChange, onSubmitDraft, value, ...inputPr
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)
- })
- ]
- })
+ }}
+ onBlur={() => setToken(null)}
+ />
+ </div>
+ )
}
/** One member's pending prompt, rendered in the room (#90694).
@@ -12992,162 +13144,164 @@ function GroupClarifyCard({ entry, members }) {
const [drafts, setDrafts] = useState({})
const [picked, setPicked] = useState({})
const [sending, setSending] = useState(false)
- const questions = entry.questions && entry.questions.length
- ? entry.questions.map((q, i) => ({
- qid: q?.qid ?? q?.id ?? `q${i}`,
- question: typeof q?.question === 'string' ? q.question : '',
- choices: Array.isArray(q?.choices) ? q.choices.filter(c => typeof c === 'string' && c) : [],
- multiSelect: Boolean(q?.multi_select ?? q?.multiSelect)
- }))
- : [{ qid: '__single__', question: entry.question, choices: entry.choices, multiSelect: entry.multiSelect }]
-
+ const questions =
+ entry.questions && entry.questions.length
+ ? entry.questions.map((q, i) => ({
+ qid: q?.qid ?? q?.id ?? `q${i}`,
+ question: typeof q?.question === 'string' ? q.question : '',
+ choices: Array.isArray(q?.choices) ? q.choices.filter(c => typeof c === 'string' && c) : [],
+ multiSelect: Boolean(q?.multi_select ?? q?.multiSelect)
+ }))
+ : [
+ {
+ qid: '__single__',
+ question: entry.question,
+ choices: entry.choices,
+ multiSelect: entry.multiSelect
+ }
+ ]
const answerFor = q => {
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 = {}
-
for (const q of questions) {
answers[q.qid] = answerFor(q)
}
-
await answerGroupClarify(entry, member, answers)
}
// Echo the exchange into the room log so the thread reads complete.
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, { kind: 'user', name: 'You' }, summary, entry.thread || 'legacy')
+ : questions.map(q => (questions.length > 1 ? `${q.question}: ${answerFor(q)}` : answerFor(q))).join('\n')
+ appendGroupChatEntry(
+ group,
+ {
+ kind: 'user',
+ name: 'You'
+ },
+ summary,
+ entry.thread || 'legacy'
+ )
} catch (err) {
- host.notify({ kind: 'error', message: `Could not send the answer to @${botHandle(entry.member, member)}: ${err?.message || err}` })
+ host.notify({
+ kind: 'error',
+ message: `Could not send the answer to @${botHandle(entry.member, member)}: ${err?.message || err}`
+ })
} finally {
setSending(false)
}
}
-
- return jsxs('div', {
- className:
- 'grid gap-1.5 rounded-md border border-(--ui-accent,#4f9cf9)/50 bg-(--ui-accent,#4f9cf9)/5 px-2.5 py-2',
- children: [
- jsxs('div', {
- className: 'flex items-center gap-1.5 text-xs font-medium',
- children: [
- jsx(Codicon, {
- name: isApproval ? 'shield' : 'question',
- className: 'shrink-0 text-(--ui-accent,#4f9cf9)'
- }),
- isApproval
- ? `@${botHandle(entry.member, member)} wants to run a command:`
- : `@${botHandle(entry.member, member)} asks:`
- ]
- }),
- isApproval && entry.command
- ? jsx('code', {
- className:
- 'block overflow-x-auto rounded bg-(--ui-bg-secondary,rgba(0,0,0,0.25)) px-2 py-1 font-mono text-[0.7rem] whitespace-pre-wrap break-all',
- children: entry.command
- })
- : null,
- ...questions.map(q =>
- jsxs('div', {
- className: 'grid gap-1',
- children: [
- q.question
- ? jsx('div', { className: 'text-xs whitespace-pre-wrap', children: q.question })
- : null,
- q.choices.length
- ? jsx('div', {
- className: 'flex flex-wrap gap-1',
- children: q.choices.map(choice => {
- const chosen = (picked[q.qid] || []).includes(choice)
-
- return jsx(Button, {
- size: 'sm',
- variant: chosen ? 'default' : 'secondary',
- className: cn(
- 'h-6 px-2 text-[0.7rem]',
- isApproval && choice === 'deny' && !chosen && 'text-destructive'
- ),
- onClick: () => {
- setDrafts(prev => ({ ...prev, [q.qid]: '' }))
- setPicked(prev => {
- const current = prev[q.qid] || []
- const next = q.multiSelect
- ? chosen
- ? current.filter(c => c !== choice)
- : [...current, choice]
- : chosen
- ? []
- : [choice]
-
- return { ...prev, [q.qid]: next }
- })
- },
- children: choice
- }, `choice:${q.qid}:${choice}`)
- })
- })
- : null,
- // Approvals are a closed choice set — no free-text input.
- isApproval
- ? null
- : jsx(Input, {
- 'aria-label': `Answer @${entry.member}`,
- placeholder: q.choices.length ? 'Or type your own answer…' : 'Type your answer…',
- value: drafts[q.qid] || '',
- onChange: event => {
- const value = event.target.value
- setPicked(prev => ({ ...prev, [q.qid]: [] }))
- setDrafts(prev => ({ ...prev, [q.qid]: value }))
- },
- onKeyDown: event => {
- // IME guard: Enter confirming a composed word must not submit.
- if (event.nativeEvent?.isComposing || event.keyCode === 229) {
- return
- }
- if (event.key === 'Enter' && questions.length === 1) {
- event.preventDefault()
- void submit()
- }
- },
- className: 'h-7 text-xs'
- }, `input:${q.qid}`)
- ]
- }, `q:${q.qid}`)
- ),
- jsx('div', {
- className: 'flex justify-end',
- children: jsx(Button, {
- size: 'sm',
- disabled: sending || !allAnswered || !member,
- onClick: () => void submit(),
- children: sending ? 'Sending…' : isApproval ? 'Respond' : 'Answer'
- })
- })
- ]
- })
+ return (
+ <div className="grid gap-1.5 rounded-md border border-(--ui-accent,#4f9cf9)/50 bg-(--ui-accent,#4f9cf9)/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,#4f9cf9)" />
+ {isApproval
+ ? `@${botHandle(entry.member, member)} wants to run a command:`
+ : `@${botHandle(entry.member, member)} asks:`}
+ </div>
+ {isApproval && entry.command ? (
+ <code className="block overflow-x-auto rounded bg-(--ui-bg-secondary,rgba(0,0,0,0.25)) px-2 py-1 font-mono text-[0.7rem] whitespace-pre-wrap break-all">
+ {entry.command}
+ </code>
+ ) : null}
+ {questions.map(q => (
+ <div key={`q:${q.qid}`} className="grid gap-1">
+ {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'
+ )}
+ onClick={() => {
+ setDrafts(prev => ({
+ ...prev,
+ [q.qid]: ''
+ }))
+ setPicked(prev => {
+ const current = prev[q.qid] || []
+ const next = q.multiSelect
+ ? chosen
+ ? current.filter(c => c !== choice)
+ : [...current, choice]
+ : chosen
+ ? []
+ : [choice]
+ return {
+ ...prev,
+ [q.qid]: next
+ }
+ })
+ }}
+ >
+ {choice}
+ </Button>
+ )
+ })}
+ </div>
+ ) : null}
+ {/* 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] || ''}
+ onChange={event => {
+ const value = event.target.value
+ setPicked(prev => ({
+ ...prev,
+ [q.qid]: []
+ }))
+ setDrafts(prev => ({
+ ...prev,
+ [q.qid]: value
+ }))
+ }}
+ onKeyDown={event => {
+ // IME guard: Enter confirming a composed word must not submit.
+ if (event.nativeEvent?.isComposing || event.keyCode === 229) {
+ return
+ }
+ if (event.key === 'Enter' && questions.length === 1) {
+ event.preventDefault()
+ void submit()
+ }
+ }}
+ className="h-7 text-xs"
+ />
+ )}
+ </div>
+ ))}
+ <div className="flex justify-end">
+ <Button size="sm" disabled={sending || !allAnswered || !member} onClick={() => void submit()}>
+ {sending ? 'Sending…' : isApproval ? 'Respond' : 'Answer'}
+ </Button>
+ </div>
+ </div>
+ )
}
// Group composer drafts are window-local UI state. They must survive pane
@@ -13156,19 +13310,21 @@ function GroupClarifyCard({ entry, members }) {
// bytes). Current rooms key by immutable roomId; legacy rooms fall back to the
// display name until they are upgraded.
const groupComposerDrafts = new Map()
-
function emptyGroupComposerDraft() {
- return { activeReplyThread: null, main: '', pendingAttachments: {}, replies: {}, revision: 0 }
+ return {
+ activeReplyThread: null,
+ main: '',
+ pendingAttachments: {},
+ replies: {},
+ revision: 0
+ }
}
-
function groupComposerDraftKey(group, room) {
return groupChatRoomKey(group, room)
}
-
function groupComposerDraftSnapshot(key) {
return groupComposerDrafts.get(key) || emptyGroupComposerDraft()
}
-
function updateGroupComposerDraft(key, mutate) {
const current = groupComposerDraftSnapshot(key)
const next = mutate({
@@ -13179,23 +13335,20 @@ function updateGroupComposerDraft(key, mutate) {
[...(attachments || [])]
])
),
- replies: { ...(current.replies || {}) }
+ replies: {
+ ...(current.replies || {})
+ }
})
-
next.revision = current.revision + 1
groupComposerDrafts.delete(key)
groupComposerDrafts.set(key, next)
-
return next
}
-
function restoreGroupComposerDraft(key, expectedRevision, snapshot) {
const current = groupComposerDraftSnapshot(key)
-
if (current.revision !== expectedRevision) {
return null
}
-
const restored = {
...snapshot,
pendingAttachments: Object.fromEntries(
@@ -13204,51 +13357,45 @@ function restoreGroupComposerDraft(key, expectedRevision, snapshot) {
[...(attachments || [])]
])
),
- replies: { ...(snapshot.replies || {}) },
+ replies: {
+ ...(snapshot.replies || {})
+ },
revision: current.revision + 1
}
-
groupComposerDrafts.set(key, restored)
-
return restored
}
-
function clearGroupComposerDraft(key) {
groupComposerDrafts.delete(key)
}
-
function migrateGroupComposerDraft(oldKey, newKey) {
if (oldKey === newKey || !groupComposerDrafts.has(oldKey)) {
return
}
-
if (!groupComposerDrafts.has(newKey)) {
groupComposerDrafts.set(newKey, groupComposerDrafts.get(oldKey))
}
-
groupComposerDrafts.delete(oldKey)
}
-
function GroupChatWorkspace({ group, members, onBack, visible = true }) {
const rooms = useValue($groupChats)
const allMeta = useValue($botMeta)
- const room = rooms[group] || { log: [], running: false }
+ const room = 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 => {
const next = updateGroupComposerDraft(composerKeyRef.current, mutate)
setComposerDraft(next)
-
return next
}
-
const draft = composerDraft.main || ''
const replyDrafts = composerDraft.replies || {}
const replyThread = composerDraft.activeReplyThread || null
@@ -13266,14 +13413,12 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
const setReplyThread = value =>
updateComposerDraft(current => ({
...current,
- activeReplyThread:
- typeof value === 'function' ? value(current.activeReplyThread || null) : value
+ activeReplyThread: typeof value === 'function' ? value(current.activeReplyThread || null) : value
}))
const setPendingImages = value =>
updateComposerDraft(current => ({
...current,
- pendingAttachments:
- typeof value === 'function' ? value(current.pendingAttachments || {}) : value
+ pendingAttachments: typeof value === 'function' ? value(current.pendingAttachments || {}) : value
}))
const [confirmDisband, setConfirmDisband] = useState(false)
const [settingsOpen, setSettingsOpen] = useState(false)
@@ -13297,30 +13442,27 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// already near the bottom, so reading history is never yanked away.
const bottomSentinelRef = useRef(null)
const stickToBottomRef = useRef(true)
-
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 })
-
+ viewport.addEventListener('scroll', onScroll, {
+ passive: true
+ })
return () => viewport.removeEventListener('scroll', onScroll)
}
}, [])
-
useEffect(() => {
if (stickToBottomRef.current) {
- bottomSentinelRef.current?.scrollIntoView({ block: 'end' })
+ bottomSentinelRef.current?.scrollIntoView({
+ block: 'end'
+ })
}
}, [room.log.length, room.running])
@@ -13330,40 +13472,40 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// hidden → visible edge — an explicit reopen, so it overrides a stale
// read-position and mirrors what a fresh open does.
const wasVisibleRef = useRef(visible)
-
useEffect(() => {
if (visible && !wasVisibleRef.current) {
stickToBottomRef.current = true
- bottomSentinelRef.current?.scrollIntoView({ block: 'end' })
+ bottomSentinelRef.current?.scrollIntoView({
+ block: 'end'
+ })
}
-
wasVisibleRef.current = visible
}, [visible])
-
const imagesFor = thread => pendingImages[thread ?? 'main'] || []
-
const addImages = (thread, picked) => {
if (!picked.length) {
return
}
-
const key = thread ?? 'main'
- setPendingImages(prev => ({ ...prev, [key]: [...(prev[key] || []), ...picked] }))
+ setPendingImages(prev => ({
+ ...prev,
+ [key]: [...(prev[key] || []), ...picked]
+ }))
}
-
const removeImage = (thread, index) => {
const key = thread ?? 'main'
- setPendingImages(prev => ({ ...prev, [key]: (prev[key] || []).filter((_, i) => i !== index) }))
+ setPendingImages(prev => ({
+ ...prev,
+ [key]: (prev[key] || []).filter((_, i) => i !== index)
+ }))
}
// Ctrl/⌘-V a screenshot (or any file) into any composer in this room.
const pasteImages = (thread, event) => {
const files = [...(event.clipboardData?.files || [])]
-
if (!files.length) {
return
}
-
event.preventDefault()
void filesToGroupAttachments(files).then(picked => addImages(thread, picked))
}
@@ -13372,16 +13514,12 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// 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 => {
const files = [...(event.dataTransfer?.files || [])]
-
setDragOver(false)
-
if (!files.length) {
return
}
-
event.preventDefault()
void filesToGroupAttachments(files).then(picked => addImages(replyThread, picked))
}
@@ -13398,69 +13536,61 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
.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 = jsxs('div', {
- className: 'flex items-center gap-2 px-2.5 pt-2.5 pb-2',
- children: [
- jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- onClick: () => (onBack ? onBack() : $groupChatWorkspace.set(null)),
- children: 'Back'
- }),
- // Room picture (set via Group settings) leads the title when present.
- room.image
- ? jsx('img', {
- src: room.image,
- alt: '',
- className: 'size-6 shrink-0 rounded-md object-cover ring-1 ring-(--ui-stroke-secondary)'
- })
- : jsx('span', {
- className:
- 'flex size-6 shrink-0 items-center justify-center rounded-md bg-(--chrome-action-hover) text-(--ui-text-tertiary)',
- children: jsx(Codicon, { name: 'organization' })
- }),
- jsx('div', {
- className: 'min-w-0 flex-1 truncate text-sm font-semibold',
- children: group
- }),
- jsx(Tip, {
- label: memberNames,
- children: jsx('span', {
- className: cn(
+ 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))}>
+ 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)"
+ />
+ ) : (
+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-(--chrome-action-hover) text-(--ui-text-tertiary)">
+ <Codicon name="organization" />
+ </span>
+ )}
+ <div className="min-w-0 flex-1 truncate text-sm font-semibold">{group}</div>
+ <Tip label={memberNames}>
+ <span
+ 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,
- children: members.length > 0 && availableMembers < members.length ? availabilityLabel : `${members.length} bots`
- })
- }),
- jsx(Tip, {
- label: `Group settings — rename ${group} or set a room picture`,
- children: jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- className: 'shrink-0 text-(--ui-text-tertiary) hover:text-foreground',
- 'aria-label': `Group settings for ${group}`,
- onClick: () => setSettingsOpen(true),
- children: jsx(Codicon, { name: 'gear' })
- })
- }),
- jsx(Tip, {
- label: `Disband the ${group} group chat`,
- children: jsx(Button, {
- variant: 'ghost',
- size: 'sm',
- className: 'shrink-0 text-(--ui-text-tertiary) hover:text-destructive',
- 'aria-label': `Disband ${group}`,
- onClick: () => setConfirmDisband(true),
- children: jsx(Codicon, { name: 'trash' })
- })
- })
- ]
- })
-
+ )}
+ 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}`}
+ onClick={() => setSettingsOpen(true)}
+ >
+ <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}`}
+ onClick={() => setConfirmDisband(true)}
+ >
+ <Codicon name="trash" />
+ </Button>
+ </Tip>
+ </div>
+ )
const memberDescriptors = () =>
members.map(b => ({
...b,
@@ -13478,153 +13608,134 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// the run being stopped is the one the latest activity belongs to.
const stopRoomRun = async () => {
await stopGroupThread(group, latestActivity?.thread || null, memberDescriptors())
- host.notify({ kind: 'success', message: `Stopped ${group} — remaining turns are held until you resume` })
- }
-
- const activityPanel = jsxs('div', {
- className: 'border-b border-(--ui-stroke-secondary)',
- children: [
- jsxs('div', {
- className: 'flex items-center gap-1',
- children: [
- jsxs('button', {
- type: 'button',
- 'aria-expanded': activityOpen,
- 'aria-controls': `group-activity:${group}`,
- title: activityOpen ? 'Hide room activity' : 'Show room activity',
- 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),
- children: [
- jsx(Codicon, {
- name: activityOpen ? 'chevron-down' : 'chevron-right',
- className: 'shrink-0 text-[0.65rem]'
- }),
- jsx('span', { className: 'shrink-0 font-medium', children: 'Activity' }),
- latestActivity
- ? jsx('span', {
- className: 'min-w-0 flex-1 truncate',
- children: `${groupActivityLabel(latestActivity)} · ${relativeTime(latestActivity.at)}`
- })
- : null
- ]
- }),
- room.running
- ? jsx('button', {
- type: 'button',
- title: 'Stop this run — interrupts the member on turn and holds the rest',
- className:
- 'inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[0.7rem] font-medium text-(--ui-accent) transition-colors hover:bg-(--chrome-action-hover)',
- onClick: () => void stopRoomRun(),
- children: [
- jsx(Codicon, { name: 'debug-stop', className: 'shrink-0 text-[0.75rem]' }),
- 'Stop'
- ]
- })
- : null
- ]
- }),
- activityOpen
- ? jsx('div', {
- id: `group-activity:${group}`,
- className: 'grid gap-0.5 px-2.5 pb-1.5',
- children: activityEvents.length
- ? [...activityEvents]
- .reverse()
- .map((event, i) =>
- jsxs('div', {
- className: 'flex items-center gap-1.5 text-[0.7rem]',
- children: [
- jsx(Codicon, {
- name: GROUP_ACTIVITY_GLYPHS[event.kind] || 'circle-outline',
- className: cn('shrink-0 text-[0.65rem]', groupActivityTone(event.kind))
- }),
- jsx('span', {
- className: cn('min-w-0 flex-1 truncate', groupActivityTone(event.kind)),
- children: groupActivityLabel(event)
- }),
- jsx('span', {
- className: 'shrink-0 text-[0.625rem] text-(--ui-text-quaternary)',
- children: relativeTime(event.at)
- }),
- event.kind === 'working'
- ? jsx('button', {
- type: 'button',
- title: 'Stop this run — interrupts the member on turn and holds the rest',
- className:
- 'inline-flex shrink-0 items-center gap-0.5 rounded px-1 py-px text-[0.65rem] font-medium text-(--ui-accent) transition-colors hover:bg-(--chrome-action-hover)',
- onClick: () => void stopRoomRun(),
- children: [
- jsx(Codicon, { name: 'debug-stop', className: 'shrink-0 text-[0.7rem]' }),
- 'Stop'
- ]
- })
- : null
- ]
- }, `${event.at}:${i}`)
- )
- : jsx('div', {
- className: 'px-0.5 pb-0.5 text-[0.625rem] text-(--ui-text-quaternary)',
- children: 'No activity in this turn yet.'
- })
- })
- : null
- ]
- })
-
+ host.notify({
+ kind: 'success',
+ 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">
+ <button
+ type="button"
+ aria-expanded={activityOpen}
+ aria-controls={`group-activity:${group}`}
+ title={activityOpen ? 'Hide room activity' : 'Show room activity'}
+ 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)}
+ >
+ <Codicon name={activityOpen ? 'chevron-down' : 'chevron-right'} className="shrink-0 text-[0.65rem]" />
+ <span className="shrink-0 font-medium">Activity</span>
+ {latestActivity ? (
+ <span className="min-w-0 flex-1 truncate">{`${groupActivityLabel(latestActivity)} · ${relativeTime(latestActivity.at)}`}</span>
+ ) : null}
+ </button>
+ {room.running ? (
+ <button
+ type="button"
+ title="Stop this run — interrupts the member on turn and holds the rest"
+ className="inline-flex shrink-0 items-center gap-1 rounded px-1.5 py-0.5 text-[0.7rem] font-medium text-(--ui-accent) transition-colors hover:bg-(--chrome-action-hover)"
+ onClick={() => void stopRoomRun()}
+ >
+ <Codicon name="debug-stop" className="shrink-0 text-[0.75rem]" />
+ Stop
+ </button>
+ ) : null}
+ </div>
+ {activityOpen ? (
+ <div id={`group-activity:${group}`} className="grid gap-0.5 px-2.5 pb-1.5">
+ {activityEvents.length ? (
+ [...activityEvents].reverse().map((event, i) => (
+ <div key={`${event.at}:${i}`} className="flex items-center gap-1.5 text-[0.7rem]">
+ <Codicon
+ name={GROUP_ACTIVITY_GLYPHS[event.kind] || 'circle-outline'}
+ className={cn('shrink-0 text-[0.65rem]', groupActivityTone(event.kind))}
+ />
+ <span className={cn('min-w-0 flex-1 truncate', groupActivityTone(event.kind))}>
+ {groupActivityLabel(event)}
+ </span>
+ <span className="shrink-0 text-[0.625rem] text-(--ui-text-quaternary)">{relativeTime(event.at)}</span>
+ {event.kind === 'working' ? (
+ <button
+ type="button"
+ title="Stop this run — interrupts the member on turn and holds the rest"
+ className="inline-flex shrink-0 items-center gap-0.5 rounded px-1 py-px text-[0.65rem] font-medium text-(--ui-accent) transition-colors hover:bg-(--chrome-action-hover)"
+ onClick={() => void stopRoomRun()}
+ >
+ <Codicon name="debug-stop" className="shrink-0 text-[0.7rem]" />
+ Stop
+ </button>
+ ) : null}
+ </div>
+ ))
+ ) : (
+ <div className="px-0.5 pb-0.5 text-[0.625rem] text-(--ui-text-quaternary)">
+ No activity in this turn yet.
+ </div>
+ )}
+ </div>
+ ) : 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: '',
- pendingAttachments: { ...(current.pendingAttachments || {}), main: [] }
+ pendingAttachments: {
+ ...(current.pendingAttachments || {}),
+ 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, [minted]: true }))
+ setOpenThreads(prev => ({
+ ...prev,
+ [minted]: true
+ }))
} else {
const restored = restoreGroupComposerDraft(composerKeyRef.current, cleared.revision, before)
-
if (restored) {
setComposerDraft(restored)
}
}
}
-
const submitReply = thread => {
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: { ...(current.pendingAttachments || {}), [thread]: [] },
- replies: { ...(current.replies || {}), [thread]: '' }
+ pendingAttachments: {
+ ...(current.pendingAttachments || {}),
+ [thread]: []
+ },
+ replies: {
+ ...(current.replies || {}),
+ [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, [thread]: true }))
+ setOpenThreads(prev => ({
+ ...prev,
+ [thread]: true
+ }))
} else {
const restored = restoreGroupComposerDraft(composerKeyRef.current, cleared.revision, before)
-
if (restored) {
setComposerDraft(restored)
}
@@ -13636,181 +13747,166 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
* X removes it. */
const attachmentRow = thread => {
const images = imagesFor(thread)
-
if (!images.length) {
return null
}
-
- return jsx('div', {
- className: 'flex flex-wrap items-center gap-1.5 px-1 pb-1',
- children: images.map((img, index) =>
- jsxs('div', {
- className:
- 'flex items-center gap-1 rounded-md border border-(--ui-stroke-secondary) bg-(--ui-bg-secondary,#181818) px-1 py-0.5',
- children: [
- img.kind === 'pdf' || img.kind === 'file'
- ? jsx(Codicon, {
- name: img.kind === 'pdf' ? 'file-pdf' : 'file',
- className: 'text-[0.9rem] text-(--ui-text-tertiary)'
- })
- : jsx('img', { src: img.data, alt: '', className: 'size-6 rounded object-cover' }),
- jsx('span', {
- className: 'max-w-32 truncate text-[0.65rem] text-(--ui-text-tertiary)',
- children: img.name || 'image'
- }),
- jsx('button', {
- type: 'button',
- className: 'cursor-pointer border-0 bg-transparent p-0 text-(--ui-text-quaternary) hover:text-foreground',
- title: 'Remove attachment',
- onClick: () => removeImage(thread, index),
- children: jsx(Codicon, { name: 'close', className: 'text-[0.65rem]' })
- })
- ]
- }, `${img.name || 'img'}:${index}`)
- )
- })
+ 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,#181818) px-1 py-0.5"
+ >
+ {img.kind === 'pdf' || img.kind === 'file' ? (
+ <Codicon
+ name={img.kind === 'pdf' ? 'file-pdf' : 'file'}
+ className="text-[0.9rem] text-(--ui-text-tertiary)"
+ />
+ ) : (
+ <img src={img.data} alt="" className="size-6 rounded object-cover" />
+ )}
+ <span className="max-w-32 truncate text-[0.65rem] text-(--ui-text-tertiary)">{img.name || 'image'}</span>
+ <button
+ type="button"
+ className="cursor-pointer border-0 bg-transparent p-0 text-(--ui-text-quaternary) hover:text-foreground"
+ title="Remove attachment"
+ onClick={() => removeImage(thread, index)}
+ >
+ <Codicon name="close" className="text-[0.65rem]" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )
}
-
- const attachButton = thread =>
- jsx(Button, {
- type: 'button',
- variant: 'ghost',
- size: 'sm',
- className: 'shrink-0 text-(--ui-text-tertiary) hover:text-foreground',
- title: 'Attach files — every responding bot sees them',
- onClick: () => void pickGroupAttachments().then(picked => addImages(thread, picked)),
- children: jsx(Codicon, { name: 'attach' })
- })
+ const attachButton = thread => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="shrink-0 text-(--ui-text-tertiary) hover:text-foreground"
+ title="Attach files — every responding bot sees them"
+ onClick={() => void pickGroupAttachments().then(picked => addImages(thread, picked))}
+ >
+ <Codicon name="attach" />
+ </Button>
+ )
// One log entry, rendered exactly as before conversation folding existed.
const renderEntry = (entry, index) => {
- 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
- // carry their @name-device handle) instead of raw profile ids.
- const member = isUser
- ? null
- : members.find(b =>
- b.name === entry.from.name &&
- (entry.from.source
- ? (b.connectionLabel || b.connectionId) === entry.from.source
- : !b.remoteSource)
- ) || null
- const display = isUser ? 'You' : displayName(member || { name: entry.from.name }, 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
- ? 'You'
- : 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
- // deterministic face for their name — stable per bot.
- const { shape, color, image } = isUser
- ? { shape: null, color: null, image: null }
- : botAppearance(entry.from.name, meta)
- const photo = Boolean(image && !isBackfilledFacePng(image))
-
- return jsxs('div', {
- className: cn(
- 'group flex items-start gap-2',
- isUser ? 'rounded-md bg-(--chrome-action-hover) px-2 py-1.5' : 'px-2 py-1'
- ),
- children: [
- isUser
- ? null
- : jsx('div', {
- className: 'mt-0.5 shrink-0',
- children: jsx(BotFace, {
- shape,
- color,
- image: photo ? image : null,
- size: 24,
- name: entry.from.name
- })
- }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsxs('div', {
- className: 'flex items-center gap-2',
- children: [
- isUser
- ? jsx('span', {
- className: 'text-[0.7rem] font-semibold text-foreground',
- children: label
- })
- : jsx('button', {
- type: 'button',
- className:
- 'cursor-pointer border-0 bg-transparent p-0 text-left text-[0.7rem] font-semibold text-(--ui-accent,#4f9cf9)',
- title: revealed ? 'Hide full handle' : 'Show full handle',
- onClick: () => setRevealedSpeaker(revealed ? null : entryKey),
- children: label
- }),
- jsx('span', {
- className: 'text-[0.625rem] text-(--ui-text-quaternary)',
- children: relativeTime(entry.at)
- }),
- entry.text.trim()
- ? jsx('div', {
- className:
- 'ml-auto shrink-0 opacity-0 pointer-events-none group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100',
- children: jsx(CopyButton, {
- appearance: 'icon',
- buttonSize: 'icon',
- stopPropagation: true,
- text: entry.text
- })
- })
- : null
- ]
- }),
- jsx('div', {
- className:
- 'text-xs text-(--ui-text-secondary) [&_p]:mb-1 [&_p:last-child]:mb-0 [&_ul]:mb-1 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:mb-1 [&_ol]:list-decimal [&_ol]:pl-4 [&_pre]:overflow-x-auto',
- // The app shell sets user-select: none globally; message bodies opt
- // back in so drag-select and ⌘C work in group chat logs.
- 'data-selectable-text': 'true',
- children: Streamdown ? jsx(Streamdown, { children: entry.text }) : entry.text
- }),
- // User attachments: what every responding bot was
- // shown — image previews, or a named chip for
- // PDFs/files.
- Array.isArray(entry.images) && entry.images.length
- ? jsx('div', {
- className: 'mt-1 flex flex-wrap items-center gap-1.5',
- children: entry.images.map((img, imgIndex) =>
- img.kind === 'pdf' || img.kind === 'file'
- ? jsxs('div', {
- 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)',
- title: img.name || 'attached file',
- children: [
- jsx(Codicon, { name: img.kind === 'pdf' ? 'file-pdf' : 'file', className: 'text-[0.8rem]' }),
- jsx('span', { className: 'max-w-48 truncate', children: img.name || 'attached file' })
- ]
- }, `${entryKey}:img:${imgIndex}`)
- : jsx('img', {
- 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'
- }, `${entryKey}:img:${imgIndex}`)
- )
- })
- : null
- ]
- })
- ]
- }, entryKey)
+ 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
+ // carry their @name-device handle) instead of raw profile ids.
+ const member = isUser
+ ? null
+ : members.find(
+ b =>
+ b.name === entry.from.name &&
+ (entry.from.source ? (b.connectionLabel || b.connectionId) === entry.from.source : !b.remoteSource)
+ ) || null
+ const display = isUser
+ ? 'You'
+ : displayName(
+ member || {
+ name: entry.from.name
+ },
+ 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
+ ? 'You'
+ : 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
+ // deterministic face for their name — stable per bot.
+ const { shape, color, image } = isUser
+ ? {
+ shape: null,
+ color: null,
+ image: null
+ }
+ : botAppearance(entry.from.name, meta)
+ 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'
+ )}
+ >
+ {isUser ? null : (
+ <div className="mt-0.5 shrink-0">
+ <BotFace shape={shape} color={color} image={photo ? image : null} size={24} name={entry.from.name} />
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ {isUser ? (
+ <span className="text-[0.7rem] font-semibold text-foreground">{label}</span>
+ ) : (
+ <button
+ type="button"
+ className="cursor-pointer border-0 bg-transparent p-0 text-left text-[0.7rem] font-semibold text-(--ui-accent,#4f9cf9)"
+ title={revealed ? 'Hide full handle' : 'Show full handle'}
+ onClick={() => setRevealedSpeaker(revealed ? null : entryKey)}
+ >
+ {label}
+ </button>
+ )}
+ <span className="text-[0.625rem] text-(--ui-text-quaternary)">{relativeTime(entry.at)}</span>
+ {entry.text.trim() ? (
+ <div className="ml-auto shrink-0 opacity-0 pointer-events-none group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100">
+ <CopyButton appearance="icon" buttonSize="icon" stopPropagation text={entry.text} />
+ </div>
+ ) : null}
+ </div>
+ <div
+ className="text-xs text-(--ui-text-secondary) [&_p]:mb-1 [&_p:last-child]:mb-0 [&_ul]:mb-1 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:mb-1 [&_ol]:list-decimal [&_ol]:pl-4 [&_pre]:overflow-x-auto" // The app shell sets user-select: none globally; message bodies opt
+ // back in so drag-select and ⌘C work in group chat logs.
+ data-selectable-text="true"
+ >
+ {Streamdown ? <Streamdown>{entry.text}</Streamdown> : entry.text}
+ </div>
+ {/* User attachments: what every responding bot was */
+ /* shown — image previews, or a named chip for */
+ /* PDFs/files. */}
+ {Array.isArray(entry.images) && entry.images.length ? (
+ <div className="mt-1 flex flex-wrap items-center gap-1.5">
+ {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)"
+ title={img.name || 'attached file'}
+ >
+ <Codicon name={img.kind === 'pdf' ? 'file-pdf' : 'file'} className="text-[0.8rem]" />
+ <span className="max-w-48 truncate">{img.name || 'attached file'}</span>
+ </div>
+ ) : (
+ <img
+ 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"
+ />
+ )
+ )}
+ </div>
+ ) : null}
+ </div>
+ </div>
+ )
}
// Threads: group entries by thread id (hydration assigned legacy ids, but
@@ -13820,74 +13916,79 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// Slack-style summary row unless explicitly opened. Every open thread gets
// its own reply box, which continues THAT thread.
const threadsById = new Map()
-
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: [], id, startIndex: i }
+ bucket = {
+ entries: [],
+ id,
+ startIndex: i
+ }
threadsById.set(id, bucket)
}
-
- bucket.entries.push({ entry, index: i })
+ 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 = []
-
threads.forEach(threadBucket => {
const { entries, id } = threadBucket
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(
- jsxs('button', {
- type: 'button',
- 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: 'Open this thread',
- onClick: () => setOpenThreads(prev => ({ ...prev, [id]: true })),
- children: [
- jsx(Codicon, { name: 'chevron-right', className: 'shrink-0 text-[0.65rem]' }),
- jsx('span', { className: 'min-w-0 flex-1 truncate', children: headText || 'Thread' }),
- jsx('span', {
- className: 'shrink-0 text-[0.625rem] text-(--ui-text-quaternary)',
- children: `${replies} ${replies === 1 ? 'reply' : 'replies'} · ${relativeTime(entries[entries.length - 1].entry.at)}`
- })
- ]
- }, `fold:${id}`)
+ <button
+ key={`fold:${id}`}
+ type="button"
+ 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="Open this thread"
+ onClick={() =>
+ setOpenThreads(prev => ({
+ ...prev,
+ [id]: true
+ }))
+ }
+ >
+ <Codicon name="chevron-right" className="shrink-0 text-[0.65rem]" />
+ <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>
+ </button>
)
-
return
}
// Open thread: a rail-indented block — collapse affordance, its entries,
// and its own reply box (Slack's "reply in thread").
const threadRows = []
-
if (!isNewest || openThreads[id] !== undefined) {
threadRows.push(
- jsxs('button', {
- type: 'button',
- 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: 'Collapse this thread',
- onClick: () => setOpenThreads(prev => ({ ...prev, [id]: false })),
- children: [jsx(Codicon, { name: 'chevron-down', className: 'text-[0.6rem]' }), 'Collapse thread']
- }, `unfold:${id}`)
+ <button
+ key={`unfold:${id}`}
+ type="button"
+ 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="Collapse this thread"
+ onClick={() =>
+ setOpenThreads(prev => ({
+ ...prev,
+ [id]: false
+ }))
+ }
+ >
+ <Codicon name="chevron-down" className="text-[0.6rem]" />
+ Collapse thread
+ </button>
)
}
-
for (const { entry, index } of entries) {
threadRows.push(renderEntry(entry, index))
}
@@ -13895,182 +13996,172 @@ function GroupChatWorkspace({ group, members, onBack, visible = true }) {
// Reply-in-thread: the newest thread's continuation ALSO lives here, so
// the main composer below can stay "new thread" without ambiguity.
threadRows.push(
- replyThread === id
- ? jsxs('form', {
- className: 'grid gap-0 px-2 pb-1',
- onSubmit: event => {
- event.preventDefault()
- submitReply(id)
- },
- children: [
- attachmentRow(id),
- jsxs('div', {
- className: 'flex items-center gap-1.5',
- children: [
- jsx(GroupMentionInput, {
- 'aria-label': 'Reply in thread',
- autoFocus: true,
- placeholder: 'Reply in thread…',
- members,
- value: replyDrafts[id] || '',
- onChange: text => setReplyDrafts(prev => ({ ...prev, [id]: text })),
- onSubmitDraft: () => submitReply(id),
- onPaste: event => pasteImages(id, event)
- }),
- attachButton(id),
- jsx(Button, {
- type: 'submit',
- size: 'sm',
- disabled: !(replyDrafts[id] || '').trim() && !imagesFor(id).length,
- children: 'Reply'
- })
- ]
- })
- ]
- }, `replybox:${id}`)
- : jsx('button', {
- type: 'button',
- className:
- 'w-fit px-2 pb-1 text-left text-[0.65rem] text-(--ui-accent,#4f9cf9) transition-colors hover:underline',
- onClick: () => setReplyThread(id),
- children: 'Reply in thread'
- }, `replylink:${id}`)
+ replyThread === id ? (
+ <form
+ key={`replybox:${id}`}
+ className="grid gap-0 px-2 pb-1"
+ onSubmit={event => {
+ event.preventDefault()
+ submitReply(id)
+ }}
+ >
+ {attachmentRow(id)}
+ <div className="flex items-center gap-1.5">
+ <GroupMentionInput
+ aria-label="Reply in thread"
+ autoFocus
+ placeholder="Reply in thread…"
+ members={members}
+ value={replyDrafts[id] || ''}
+ onChange={text =>
+ setReplyDrafts(prev => ({
+ ...prev,
+ [id]: text
+ }))
+ }
+ onSubmitDraft={() => submitReply(id)}
+ onPaste={event => pasteImages(id, event)}
+ />
+ {attachButton(id)}
+ <Button type="submit" size="sm" disabled={!(replyDrafts[id] || '').trim() && !imagesFor(id).length}>
+ Reply
+ </Button>
+ </div>
+ </form>
+ ) : (
+ <button
+ key={`replylink:${id}`}
+ type="button"
+ className="w-fit px-2 pb-1 text-left text-[0.65rem] text-(--ui-accent,#4f9cf9) transition-colors hover:underline"
+ onClick={() => setReplyThread(id)}
+ >
+ Reply in thread
+ </button>
+ )
)
-
logChildren.push(
- jsx('div', {
- className: 'grid gap-1.5 border-l-2 border-(--ui-stroke-secondary) pl-1.5',
- children: threadRows
- }, `thread:${id}`)
+ <div key={`thread:${id}`} className="grid gap-1.5 border-l-2 border-(--ui-stroke-secondary) pl-1.5">
+ {threadRows}
+ </div>
)
})
-
- return jsxs('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.
- if (!event.currentTarget.contains(event.relatedTarget)) {
- setDragOver(false)
- }
- },
- onDrop: dropFiles,
- children: [
- dragOver
- ? jsx('div', {
- className:
- 'pointer-events-none absolute inset-0 z-40 flex items-center justify-center border-2 border-dashed border-(--ui-accent,#4f9cf9) text-sm font-medium text-(--ui-accent,#4f9cf9)',
- children: replyThread ? 'Drop to attach to this thread reply' : 'Drop to attach — every responding bot sees it'
- }, 'dropzone')
- : null,
- header,
- activityPanel,
- jsx(ScrollArea, {
- className: 'min-h-0 flex-1',
- children: jsxs('div', {
- className: 'grid gap-1.5 px-2.5 pb-2',
- children: [
- ...(room.log.length
- ? logChildren
- : [
- jsx('div', {
- className: 'px-2 py-4 text-center text-xs text-(--ui-text-tertiary)',
- children: 'Say something — every bot in this group hears the room.'
- }, 'empty')
- ]),
- ...roomClarifies.map(entry =>
- jsx(GroupClarifyCard, { entry, members }, `clarify:${entry.memberKey}:${entry.requestId}`)
- ),
- room.running
- ? jsx('div', {
- className: 'px-2 py-1 text-[0.7rem] italic text-(--ui-text-quaternary)',
- children: roomClarifies.length
- ? 'Waiting for your answer…'
- : room.turn
- ? `${groupSpeakerLabel(room.turn)} is thinking…`
- : 'The room is working…'
- }, 'working')
- : null,
- // 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.
- jsx('div', { ref: bottomSentinelRef, 'aria-hidden': true }, 'bottom-sentinel')
- ]
- })
- }),
- jsx('div', {
- className: 'border-t border-(--ui-stroke-secondary) p-2',
- children: jsxs('form', {
- className: 'grid gap-0',
- onSubmit: event => {
+ 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.
+ if (!event.currentTarget.contains(event.relatedTarget)) {
+ setDragOver(false)
+ }
+ }}
+ 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,#4f9cf9) text-sm font-medium text-(--ui-accent,#4f9cf9)"
+ >
+ {replyThread ? 'Drop to attach to this thread reply' : 'Drop to attach — every responding bot sees it'}
+ </div>
+ ) : null}
+ {header}
+ {activityPanel}
+ <ScrollArea className="min-h-0 flex-1">
+ <div className="grid gap-1.5 px-2.5 pb-2">
+ {room.log.length
+ ? logChildren
+ : [
+ <div key={'empty'} className="px-2 py-4 text-center text-xs text-(--ui-text-tertiary)">
+ Say something — every bot in this group hears the room.
+ </div>
+ ]}
+ {roomClarifies.map(entry => (
+ <GroupClarifyCard key={`clarify:${entry.memberKey}:${entry.requestId}`} entry={entry} members={members} />
+ ))}
+ {room.running ? (
+ <div key={'working'} className="px-2 py-1 text-[0.7rem] italic text-(--ui-text-quaternary)">
+ {roomClarifies.length
+ ? 'Waiting for your answer…'
+ : room.turn
+ ? `${groupSpeakerLabel(room.turn)} is thinking…`
+ : 'The room is working…'}
+ </div>
+ ) : null}
+ {/* 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>
+ </ScrollArea>
+ <div className="border-t border-(--ui-stroke-secondary) p-2">
+ <form
+ className="grid gap-0"
+ onSubmit={event => {
event.preventDefault()
submit()
- },
- children: [
- attachmentRow(null),
- jsxs('div', {
- className: 'flex items-center gap-1.5',
- children: [
- jsx(GroupMentionInput, {
- 'aria-label': `Message ${group}`,
- placeholder: `New thread in ${group}… (@name to direct, @everyone for all)`,
- members,
- value: draft,
- onChange: setDraft,
- onSubmitDraft: submit,
- onPaste: event => pasteImages(null, event)
- }),
- attachButton(null),
- jsx(Button, {
- type: 'submit',
- size: 'sm',
- disabled: !draft.trim() && !imagesFor(null).length,
- children: 'New Thread'
- })
- ]
- })
- ]
- })
- }),
- jsx(GroupChatSettingsDialog, {
- group,
- members,
- open: settingsOpen,
- onClose: () => setSettingsOpen(false)
- }),
- jsx(ConfirmDialog, {
- open: confirmDisband,
- title: 'Disband group chat?',
- description: jsxs('span', {
- children: [
- 'This removes the ',
- jsx('span', { className: 'font-medium text-foreground', children: group }),
- ' grouping from its ',
- String(members.length),
- // New rooms title member sessions by roomId, legacy rooms by name —
- // so the copy names the concept, not a literal session title.
- ' bots and clears the shared room log. The bots themselves and their per-group sessions are kept.'
- ]
- }),
- destructive: true,
- confirmLabel: 'Disband',
- busyLabel: 'Disbanding…',
- doneLabel: 'Disbanded',
- onClose: () => setConfirmDisband(false),
- onConfirm: async () => {
+ }}
+ >
+ {attachmentRow(null)}
+ <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)}
+ />
+ {attachButton(null)}
+ <Button type="submit" size="sm" disabled={!draft.trim() && !imagesFor(null).length}>
+ New Thread
+ </Button>
+ </div>
+ </form>
+ </div>
+ <GroupChatSettingsDialog
+ group={group}
+ members={members}
+ open={settingsOpen}
+ onClose={() => setSettingsOpen(false)}
+ />
+ <ConfirmDialog
+ open={confirmDisband}
+ title="Disband group chat?"
+ description={
+ <span>
+ {'This removes the '}
+ <span className="font-medium text-foreground">{group}</span>
+ {' grouping from its '}
+ {String(members.length)}
+ {/* New rooms title member sessions by roomId, legacy rooms by name — */
+ /* so the copy names the concept, not a literal session title. */}
+ {' bots and clears the shared room log. The bots themselves and their per-group sessions are kept.'}
+ </span>
+ }
+ destructive
+ confirmLabel="Disband"
+ busyLabel="Disbanding…"
+ doneLabel="Disbanded"
+ onClose={() => setConfirmDisband(false)}
+ onConfirm={async () => {
clearGroupComposerDraft(composerKeyRef.current)
await disbandGroupChat(group, members)
- host.notify({ kind: 'success', message: `Disbanded “${group}”` })
- }
- })
- ]
- })
+ host.notify({
+ kind: 'success',
+ message: `Disbanded “${group}”`
+ })
+ }}
+ />
+ </div>
+ )
}
/** Live closers for group-chat MAIN-window tabs, by group name — so a
@@ -14084,12 +14175,10 @@ const groupChatMainTabs = new Map()
* nothing). Every map mutation goes through the two helpers below so the
* rev bump re-evaluates the gate. */
const $groupMainTabsRev = atom(0)
-
function recordGroupMainTab(group, close) {
groupChatMainTabs.set(group, close)
$groupMainTabsRev.set($groupMainTabsRev.get() + 1)
}
-
function dropGroupMainTab(group) {
if (groupChatMainTabs.delete(group)) {
$groupMainTabsRev.set($groupMainTabsRev.get() + 1)
@@ -14106,16 +14195,12 @@ function dropGroupMainTab(group) {
function shouldRenderGroupChatInPane(group) {
return Boolean(group && !groupChatMainTabs.has(group))
}
-
function closeGroupChatMainTab(group) {
const close = groupChatMainTabs.get(group)
-
dropGroupMainTab(group)
-
if ($groupChatWorkspace.get() === group) {
$groupChatWorkspace.set(null)
}
-
if (typeof close === 'function') {
try {
close()
@@ -14124,7 +14209,6 @@ function closeGroupChatMainTab(group) {
}
}
}
-
function selectedRosterBot(roster, key) {
return (Array.isArray(roster) ? roster : []).find(bot => botRosterKey(bot) === key) || null
}
@@ -14139,18 +14223,14 @@ function selectedRosterBot(roster, key) {
* while other sources are live. Unknown (no sources yet) is NOT proof. */
function ghostRosterOwner(key, sources) {
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,
@@ -14171,13 +14251,10 @@ function ghostRosterOwner(key, sources) {
* (or reconciliation clears it when the bot was actually removed). */
function rosterWithSelectedOwner(roster, sources, key) {
const rows = Array.isArray(roster) ? roster : []
-
if (!key || selectedRosterBot(rows, key)) {
return rows
}
-
const ghost = ghostRosterOwner(key, sources)
-
return ghost ? [...rows, ghost] : rows
}
@@ -14189,26 +14266,20 @@ function reconcileRosterSelection(roster, sources, metaByName) {
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)
}
}
-
function BotsHomeView() {
const roster = useValue($lastRoster)
const sources = useValue($lastSources)
@@ -14217,29 +14288,28 @@ function BotsHomeView() {
const selectionHydrated = useValue($selectedRosterHydrated)
const allMeta = useValue($botMeta)
const live = selectedRosterBot(roster, selectedKey)
-
if (!rosterHydrated || !selectionHydrated) {
- return jsx('div', {
- className: 'flex h-full items-center justify-center',
- 'aria-label': 'Loading bots',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
+ return (
+ <div className="flex h-full items-center justify-center" aria-label="Loading bots">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ )
}
-
const ghost = live ? null : ghostRosterOwner(selectedKey, sources)
const bot = live ? annotateBotSource(live, sources) : ghost
-
if (!bot) {
- return jsx('div', {
- className: 'flex h-full items-center justify-center px-6',
- children: jsx(EmptyState, {
- icon: roster.length ? 'hubot' : 'add',
- title: roster.length ? 'Choose a bot or group chat' : 'No bots yet',
- description: roster.length ? 'Pick one from the Bots sidebar.' : 'Create your first bot from the Bots sidebar.'
- })
- })
+ return (
+ <div className="flex h-full items-center justify-center px-6">
+ <EmptyState
+ icon={roster.length ? 'hubot' : 'add'}
+ title={roster.length ? 'Choose a bot or group chat' : 'No bots yet'}
+ description={
+ roster.length ? 'Pick one from the Bots sidebar.' : 'Create your first bot from the Bots sidebar.'
+ }
+ />
+ </div>
+ )
}
-
const meta = botRosterMeta(bot, allMeta)
const status = botSourceStatus(bot)
// A ghost is reconstructed from a persisted owner key while its gateway is
@@ -14257,111 +14327,71 @@ function BotsHomeView() {
// same key and this view reconciles onto it.
const retrySource = () => {
haptic('tap')
- queryClient.invalidateQueries({ queryKey: ROSTER_KEY })
- }
-
- return jsxs('div', {
- className: 'flex h-full min-h-0 flex-col bg-background',
- children: [
- jsxs('header', {
- className:
- 'flex min-w-0 items-center gap-3 border-b border-(--ui-stroke-tertiary) px-5 py-3.5',
- children: [
- jsx(BotFace, { shape, color, image: photo, size: 38, name: bot.name, mood: 'idle' }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsx('h1', {
- className: 'truncate text-sm font-semibold text-foreground',
- children: displayName(bot, meta)
- }),
- jsxs('div', {
- className: 'flex min-w-0 items-center gap-1.5 text-xs text-(--ui-text-tertiary)',
- children: [
- jsx('span', { children: 'Bot' }),
- handle
- ? jsx('span', { className: 'truncate font-mono', children: `· @${handle}` })
- : null
- ]
- })
- ]
- }),
- // Tip wraps ONE element (Radix asChild) — the screen-reader text
- // rides inside the trigger, not beside it.
- jsx(Tip, {
- label: `${gateway} · ${gatewayKind} · ${status.label}`,
- children: jsxs('div', {
- className: 'flex max-w-[45%] items-center gap-1.5 text-xs text-(--ui-text-tertiary)',
- children: [
- jsx('span', { className: 'sr-only', children: `${gateway}, ${status.label}` }),
- jsx(GatewayKindGlyph, { kind: gatewayKind }),
- jsx('span', { className: 'min-w-0 truncate', children: gateway }),
- unavailable
- ? jsx(Codicon, {
- name: 'debug-disconnect',
- className: 'shrink-0 text-amber-600 dark:text-amber-300',
- 'aria-hidden': true
- })
- : null
- ]
- })
- })
- ]
- }),
- jsx('main', {
- className: 'flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 py-10',
- children: jsxs('div', {
- className: 'flex w-full max-w-2xl flex-col items-center text-center',
- children: [
- jsx(BotFace, { shape, color, image: photo, size: 76, name: bot.name, mood: 'idle' }),
- jsx('h2', {
- className: 'mt-5 text-xl font-semibold text-foreground',
- children: displayName(bot, meta)
- }),
- description
- ? jsx('p', {
- className: 'mt-2 max-w-xl text-sm leading-6 text-(--ui-text-tertiary)',
- children: description
- })
- : null,
- jsx('p', {
- className: cn(
- 'mt-4 max-w-lg text-xs leading-5',
- unavailable ? 'text-amber-700 dark:text-amber-300' : 'text-(--ui-text-tertiary)'
- ),
- children: unavailable
- ? sourceRemoved
- ? `${gateway} was removed. Choose another bot from the sidebar.`
- : `${gateway} is unavailable. Retry when it is back online.`
- : 'Open this bot’s continuous chat. Its background work keeps running when you switch away.'
- }),
- unavailable && !sourceRemoved
- ? jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- className: 'mt-5',
- onClick: retrySource,
- children: 'Retry'
- })
- : jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- className: 'mt-5',
- onClick: () => void openRosterBot(bot),
- children: 'Open chat'
- })
- ]
- })
- })
- ]
- })
+ queryClient.invalidateQueries({
+ queryKey: ROSTER_KEY
+ })
+ }
+ return (
+ <div className="flex h-full min-h-0 flex-col bg-background">
+ <header className="flex min-w-0 items-center gap-3 border-b border-(--ui-stroke-tertiary) px-5 py-3.5">
+ <BotFace shape={shape} color={color} image={photo} size={38} name={bot.name} mood="idle" />
+ <div className="min-w-0 flex-1">
+ <h1 className="truncate text-sm font-semibold text-foreground">{displayName(bot, meta)}</h1>
+ <div className="flex min-w-0 items-center gap-1.5 text-xs text-(--ui-text-tertiary)">
+ <span>Bot</span>
+ {handle ? <span className="truncate font-mono">{`· @${handle}`}</span> : null}
+ </div>
+ </div>
+ {/* Tip wraps ONE element (Radix asChild) — the screen-reader text */
+ /* rides inside the trigger, not beside it. */}
+ <Tip label={`${gateway} · ${gatewayKind} · ${status.label}`}>
+ <div className="flex max-w-[45%] items-center gap-1.5 text-xs text-(--ui-text-tertiary)">
+ <span className="sr-only">{`${gateway}, ${status.label}`}</span>
+ <GatewayKindGlyph kind={gatewayKind} />
+ <span className="min-w-0 truncate">{gateway}</span>
+ {unavailable ? (
+ <Codicon name="debug-disconnect" className="shrink-0 text-amber-600 dark:text-amber-300" aria-hidden />
+ ) : null}
+ </div>
+ </Tip>
+ </header>
+ <main className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 py-10">
+ <div className="flex w-full max-w-2xl flex-col items-center text-center">
+ <BotFace shape={shape} color={color} image={photo} size={76} name={bot.name} mood="idle" />
+ <h2 className="mt-5 text-xl font-semibold text-foreground">{displayName(bot, meta)}</h2>
+ {description ? (
+ <p className="mt-2 max-w-xl text-sm leading-6 text-(--ui-text-tertiary)">{description}</p>
+ ) : null}
+ <p
+ className={cn(
+ 'mt-4 max-w-lg text-xs leading-5',
+ unavailable ? 'text-amber-700 dark:text-amber-300' : 'text-(--ui-text-tertiary)'
+ )}
+ >
+ {unavailable
+ ? sourceRemoved
+ ? `${gateway} was removed. Choose another bot from the sidebar.`
+ : `${gateway} is unavailable. Retry when it is back online.`
+ : 'Open this bot’s continuous chat. Its background work keeps running when you switch away.'}
+ </p>
+ {unavailable && !sourceRemoved ? (
+ <Button variant="secondary" size="sm" className="mt-5" onClick={retrySource}>
+ Retry
+ </Button>
+ ) : (
+ <Button variant="secondary" size="sm" className="mt-5" onClick={() => void openRosterBot(bot)}>
+ Open chat
+ </Button>
+ )}
+ </div>
+ </main>
+ </div>
+ )
}
-
function closeBotsHomeWorkspace() {
if (typeof botsHomeClose !== 'function') {
return
}
-
const close = botsHomeClose
botsHomeClose = null
suppressBotsHomeReopen = true
@@ -14369,7 +14399,6 @@ function closeBotsHomeWorkspace() {
// new surface, and it gets its own re-front chance. The re-front path sets
// the latch again AFTER calling us, so this cannot erase its own attempt.
botsHomeRefrontTried = false
-
try {
close()
} catch {
@@ -14390,13 +14419,10 @@ function botsHomeEnabled() {
* harnesses with neither atom drive $botChatFocused directly. */
function sessionOwnsWorkspace() {
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)
}
@@ -14405,7 +14431,6 @@ function botsHomeVisible() {
if (typeof host.paneVisibility !== 'function') {
return false
}
-
try {
return host.paneVisibility(BOTS_HOME_PANE_ID).get() === true
} catch {
@@ -14433,18 +14458,13 @@ function botChatOwnsWorkspace() {
* polls) never cover a chat the user left in the center. */
function botsHomeMayOpen(explicit) {
return (
- $botsPaneVisible.get() &&
- !$groupChatWorkspace.get() &&
- !$openBotChat.get() &&
- (explicit || !sessionOwnsWorkspace())
+ $botsPaneVisible.get() && !$groupChatWorkspace.get() && !$openBotChat.get() && (explicit || !sessionOwnsWorkspace())
)
}
-
function openBotsHomeWorkspace(explicit = false) {
if (!botsHomeEnabled() || !botsHomeMayOpen(explicit)) {
return false
}
-
const selected = selectedRosterBot($lastRoster.get(), $selectedRosterKey.get())
const ownerKey = selected ? botWorkspaceOwnerKey(selected) : BOTS_HOME_OWNER_KEY
setBotsWorkspaceOwner(ownerKey, selected)
@@ -14457,7 +14477,6 @@ function openBotsHomeWorkspace(explicit = false) {
if (botsHomeClose) {
if (botsHomeVisible()) {
botsHomeRefrontTried = false
-
return true
}
@@ -14474,16 +14493,14 @@ function openBotsHomeWorkspace(explicit = false) {
if (botsHomeRefrontTried && !explicit) {
return true
}
-
closeBotsHomeWorkspace()
botsHomeRefrontTried = true
}
-
try {
botsHomeClose = host.openWorkspace(`${ID}:home`, {
title: 'Bots',
minWidth: '24rem',
- render: () => jsx(BotsHomeView, {}),
+ render: () => <BotsHomeView />,
// Closing the tab is a decision, not a glitch: drop the handle and
// leave the center alone. The home returns on the next real signal
// (Bots tab regains focus, a chat closes, a group is left).
@@ -14502,7 +14519,6 @@ function openBotsHomeWorkspace(explicit = false) {
if (botsHomeVisible()) {
botsHomeRefrontTried = false
}
-
return typeof botsHomeClose === 'function'
} catch {
botsHomeClose = null
@@ -14521,7 +14537,6 @@ function syncBotsHomeWorkspace() {
closeBotsHomeWorkspace()
return
}
-
openBotsHomeWorkspace(false)
}
@@ -14534,11 +14549,9 @@ function syncBotsHomeWorkspace() {
* session actually takes focus. */
function releaseStaleOpenBotChat(focusedStoredId) {
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
@@ -14546,7 +14559,6 @@ function releaseStaleOpenBotChat(focusedStoredId) {
// the very focus edge the open itself caused (first-click home bounce).
const owned = [open.openedSessionId, open.openedRegistryId].filter(Boolean)
const stale = owned.length ? !owned.includes(focused) : Boolean(focused)
-
if (stale) {
$openBotChat.set(null)
}
@@ -14557,14 +14569,15 @@ function releaseStaleOpenBotChat(focusedStoredId) {
* canonical open. */
function dismissGroupChatForLocalBotOpen() {
const group = $groupChatWorkspace.get()
-
if (!group) {
return null
}
-
const roomId = String($groupChats.get()[group]?.roomId || '')
closeGroupChatMainTab(group)
- return { group, roomId }
+ return {
+ group,
+ roomId
+ }
}
/** Main-window wrapper: seats the member roster reactively (live roster +
@@ -14582,12 +14595,16 @@ function GroupChatMainView({ group }) {
// 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(
- () => (typeof host.paneVisibility === 'function' ? host.paneVisibility(`plugin-workspace:${ID}:group:${slugify(group)}`) : atom(true)),
+ () =>
+ typeof host.paneVisibility === 'function'
+ ? host.paneVisibility(`plugin-workspace:${ID}:group:${slugify(group)}`)
+ : atom(true),
[group]
)
const visible = useValue($visible)
-
- return jsx(GroupChatWorkspace, { group, members, visible, onBack: () => closeGroupChatMainTab(group) })
+ return (
+ <GroupChatWorkspace group={group} members={members} visible={visible} onBack={() => closeGroupChatMainTab(group)} />
+ )
}
/** Open a group chat the Discord way: a tab taking over the MAIN chat window
@@ -14605,30 +14622,29 @@ function openGroupChat(group) {
// The in-flight host navigation may complete underneath this workspace,
// but it may not later close or visually steal the room the user chose.
botOpenGeneration += 1
- $groupNeedsYou.set({ ...$groupNeedsYou.get(), [group]: false })
+ $groupNeedsYou.set({
+ ...$groupNeedsYou.get(),
+ [group]: false
+ })
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)}`, {
title: group,
minWidth: '24rem',
- render: () => jsx(GroupChatMainView, { group }),
+ 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.
@@ -14645,180 +14661,151 @@ function openGroupChat(group) {
* with bot avatars in the narrow sidebar. */
function GroupRow({ active, group, members, needsYou, onOpen, onDisband }) {
const rooms = useValue($groupChats)
- const room = rooms[group] || { log: [] }
+ 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 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 = jsxs('button', {
- type: 'button',
- onClick: () => {
- haptic('tap')
- onOpen(group)
- },
- 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}`,
- children: [
- jsxs('div', {
- className: 'relative flex w-[34px] shrink-0 items-center justify-center',
- children: [
- room.image
- ? jsx('img', {
- src: room.image,
- alt: '',
- className: cn(
- 'size-8 rounded-md object-cover ring-1 ring-(--ui-stroke-tertiary)',
- availableMembers === 0 && 'grayscale opacity-60'
- )
- })
- : jsx('span', {
- className: cn(
- 'flex size-8 items-center justify-center rounded-md bg-(--chrome-action-hover) text-(--ui-text-tertiary)',
- availableMembers === 0 && 'opacity-60'
- ),
- children: jsx(Codicon, { name: 'organization' })
- }),
- members.length > 0 && availableMembers < members.length
- ? jsx(Tip, {
- label: availabilityLabel,
- children: jsx('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,
- children: jsx(Codicon, { name: 'debug-disconnect' })
- })
- })
- : null
- ]
- }),
- jsxs('div', {
- className: 'min-w-0 flex-1',
- children: [
- jsxs('div', {
- className: 'flex items-baseline justify-between gap-2',
- children: [
- jsx('span', {
- className: 'min-w-0 flex-1 truncate text-[0.8125rem] font-medium',
- children: group
- }),
- needsYou
- ? jsx(Tip, {
- label: 'A bot in this group chat needs your input',
- children: jsx(Codicon, {
- name: 'question',
- className: 'shrink-0 text-(--ui-accent)',
- 'aria-label': 'Needs your input'
- })
- })
- : null,
- lastAt
- ? jsx('span', {
- className: 'shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)',
- children: relativeTime(lastAt)
- })
- : null
- ]
- }),
- jsx('div', {
- className: 'min-w-0 truncate text-xs text-(--ui-text-tertiary)',
- children: preview
- })
- ]
- })
- ]
- })
-
- return jsxs(ContextMenu, {
- children: [
- jsx(ContextMenuTrigger, { asChild: true, children: row }),
- jsxs(ContextMenuContent, {
- children: [
- jsx(ContextMenuItem, {
- onSelect: () => onOpen(group),
- children: 'Open Group Chat'
- }),
- jsx(ContextMenuSeparator, {}),
- jsx(ContextMenuItem, {
- className: 'text-destructive focus:text-destructive',
- onSelect: () => onDisband({ name: group, members }),
- children: 'Delete Group'
- })
- ]
- })
- ]
- })
+ const row = (
+ <button
+ type="button"
+ onClick={() => {
+ haptic('tap')
+ onOpen(group)
+ }}
+ 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}`}
+ >
+ <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'
+ )}
+ />
+ ) : (
+ <span
+ className={cn(
+ 'flex size-8 items-center justify-center rounded-md bg-(--chrome-action-hover) text-(--ui-text-tertiary)',
+ availableMembers === 0 && 'opacity-60'
+ )}
+ >
+ <Codicon name="organization" />
+ </span>
+ )}
+ {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}
+ >
+ <Codicon name="debug-disconnect" />
+ </span>
+ </Tip>
+ ) : null}
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="min-w-0 flex-1 truncate text-[0.8125rem] font-medium">{group}</span>
+ {needsYou ? (
+ <Tip label="A bot in this group chat needs your input">
+ <Codicon name="question" className="shrink-0 text-(--ui-accent)" aria-label="Needs your input" />
+ </Tip>
+ ) : null}
+ {lastAt ? (
+ <span className="shrink-0 text-[0.6875rem] text-(--ui-text-quaternary)">{relativeTime(lastAt)}</span>
+ ) : null}
+ </div>
+ <div className="min-w-0 truncate text-xs text-(--ui-text-tertiary)">{preview}</div>
+ </div>
+ </button>
+ )
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger asChild>{row}</ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem onSelect={() => onOpen(group)}>Open Group Chat</ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ className="text-destructive focus:text-destructive"
+ onSelect={() =>
+ onDisband({
+ name: group,
+ members
+ })
+ }
+ >
+ Delete Group
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ )
}
/** Foldable roster heading. It organizes rows visually but never supplies or
* reconstructs ownership; every action still receives the full bot row. */
function RosterSectionHeader({ collapsed, count, gatewayKind, icon, label, onToggle, status, tip }) {
- const button = jsxs('button', {
- type: 'button',
- 'aria-expanded': !collapsed,
- className:
- 'mt-1 flex w-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary) transition-colors hover:bg-(--chrome-action-hover) hover:text-(--ui-text-secondary)',
- onClick: onToggle,
- children: [
- jsx(Codicon, { name: collapsed ? 'chevron-right' : 'chevron-down', className: 'shrink-0' }),
- gatewayKind
- ? jsx(GatewayKindGlyph, { kind: gatewayKind })
- : jsx(Codicon, { name: icon, className: 'shrink-0' }),
- jsxs('span', {
- className: 'flex min-w-0 items-center gap-1',
- children: [
- jsx('span', { className: 'min-w-0 truncate', children: label }),
- status && !status.available
- ? jsx('span', { className: 'sr-only', children: status.label })
- : null
- ]
- }),
- jsx('span', { className: 'min-w-0 flex-1', 'aria-hidden': true }),
- jsx('span', {
- className: 'shrink-0 font-normal tabular-nums text-(--ui-text-quaternary)',
- children: count
- }),
- status && !status.available
- ? jsx(Codicon, {
- name: 'debug-disconnect',
- className: 'shrink-0 text-amber-600 dark:text-amber-300',
- 'aria-hidden': true
- })
- : null
- ]
- })
-
- return tip ? jsx(Tip, { label: tip, children: button }) : button
+ const button = (
+ <button
+ type="button"
+ aria-expanded={!collapsed}
+ className="mt-1 flex w-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary) transition-colors hover:bg-(--chrome-action-hover) hover:text-(--ui-text-secondary)"
+ onClick={onToggle}
+ >
+ <Codicon name={collapsed ? 'chevron-right' : 'chevron-down'} className="shrink-0" />
+ {gatewayKind ? <GatewayKindGlyph kind={gatewayKind} /> : <Codicon name={icon} className="shrink-0" />}
+ <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 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 />
+ ) : null}
+ </button>
+ )
+ return tip ? <Tip label={tip}>{button}</Tip> : button
}
-
function GatewaySectionHeading({ collapsed, count, onToggle, option }) {
- const status = botSourceStatus({ sourceError: option?.error, sourceReachable: option?.reachable })
+ const status = botSourceStatus({
+ sourceError: option?.error,
+ sourceReachable: option?.reachable
+ })
const label = option?.label || option?.connectionId || 'Current gateway'
const kind = option?.kind || 'remote'
-
- return jsx(RosterSectionHeader, {
- collapsed,
- count,
- gatewayKind: kind,
- label,
- onToggle,
- status,
- tip: `${label} · ${kind} · ${status.label}`
- })
+ return (
+ <RosterSectionHeader
+ collapsed={collapsed}
+ count={count}
+ gatewayKind={kind}
+ label={label}
+ onToggle={onToggle}
+ status={status}
+ tip={`${label} · ${kind} · ${status.label}`}
+ />
+ )
}
-
function BotsPane() {
const { data, error, isLoading, refetch } = useRoster()
const gatewayState = useValue(host.state.gateway)
@@ -14865,7 +14852,6 @@ function BotsPane() {
const activityOf = bot => {
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.
@@ -14877,17 +14863,14 @@ 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 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
@@ -14898,13 +14881,11 @@ function BotsPane() {
const gatewayOptions = rosterGatewayOptions(sourceSnapshot, roster)
const selectedGateway = gatewayOptions.find(option => option.connectionId === gatewayFilter)
const gatewayFilterExists = gatewayFilter === 'all' || Boolean(selectedGateway)
-
useEffect(() => {
if (!gatewayFilterExists) {
setGatewayFilter('all')
}
}, [gatewayFilterExists])
-
const activeSourceRoster = roster.filter(bot => !bot.remoteSource)
// Hidden rows remain fully alive and recoverable at the bottom. Every
// non-display consumer continues to receive the complete roster.
@@ -14914,19 +14895,28 @@ function BotsPane() {
const gatewayRoster = filterBotsByGateway(visibleRoster, gatewayFilter)
const filteredRoster = filterBots(gatewayRoster, allMeta, query).filter(bot =>
rosterActivityMatches(
- { activity: activityOf(bot), active: activeRosterKeys.has(botRosterKey(bot)) },
+ {
+ activity: activityOf(bot),
+ active: activeRosterKeys.has(botRosterKey(bot))
+ },
activityFilter
)
)
const filteredHiddenBots = filterBots(filterBotsByGateway(hiddenBots, gatewayFilter), allMeta, query).filter(bot =>
rosterActivityMatches(
- { activity: activityOf(bot), active: activeRosterKeys.has(botRosterKey(bot)) },
+ {
+ activity: activityOf(bot),
+ active: activeRosterKeys.has(botRosterKey(bot))
+ },
activityFilter
)
)
const groupNames = groupChatNames(allMeta, groupRooms)
const groupRows = groupNames
- .map(name => ({ name, members: groupChatMemberBots(name, roster, allMeta) }))
+ .map(name => ({
+ name,
+ members: groupChatMemberBots(name, roster, allMeta)
+ }))
.filter(row => groupMatchesRosterFilters(row.name, row.members, allMeta, query, gatewayFilter))
.map(row => ({
kind: 'group',
@@ -14951,24 +14941,21 @@ function BotsPane() {
activity: activityOf(bot),
active: activeRosterKeys.has(botRosterKey(bot))
}))
- const sortRosterRows = rows => 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 sortRosterRows = rows =>
+ 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)
+ (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)
@@ -14986,35 +14973,35 @@ function BotsPane() {
const showRosterTools = showRosterSearch || showRosterFilters
const rosterSectionCollapsed = id => !hasRosterConstraint && collapsedRosterSections.has(id)
const hiddenGatewaySections = rosterGatewaySections(
- matchingHiddenBots.map(bot => ({ kind: 'bot', bot })),
+ matchingHiddenBots.map(bot => ({
+ kind: 'bot',
+ bot
+ })),
gatewayOptions,
gatewayFilter
)
-
const toggleRosterSection = id => {
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' }))
-
+ const frame = requestAnimationFrame(() =>
+ hiddenSectionRef.current?.scrollIntoView({
+ block: 'nearest'
+ })
+ )
return () => cancelAnimationFrame(frame)
}, [hiddenExpanded, hasRosterConstraint])
-
useEffect(() => {
if (!live) {
return
@@ -15046,557 +15033,425 @@ 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 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 jsx(GroupChatWorkspace, { group: groupChatName, members: groupChatMembers })
- }
-
- const renderBotRow = (bot, keyPrefix = '') =>
- jsx(
- BotRow,
- {
- bot,
- onDelete: setDeleting,
- onEdit: setEditing,
- onGroup: setGrouping,
- showHandle: botNeedsHandleLabel(bot, roster, allMeta)
- },
- `${keyPrefix}${botRosterKey(bot)}`
- )
-
- const renderGroupRow = row =>
- jsx(
- GroupRow,
- {
- active: groupChatName === row.name,
- group: row.name,
- members: row.members,
- needsYou: Boolean(groupNeedsYou[row.name]),
- onOpen: openGroupChat,
- onDisband: setDeletingGroup
- },
- `group:${row.name}`
- )
-
+ return <GroupChatWorkspace group={groupChatName} members={groupChatMembers} />
+ }
+ const renderBotRow = (bot, keyPrefix = '') => (
+ <BotRow
+ key={`${keyPrefix}${botRosterKey(bot)}`}
+ bot={bot}
+ onDelete={setDeleting}
+ onEdit={setEditing}
+ onGroup={setGrouping}
+ showHandle={botNeedsHandleLabel(bot, roster, allMeta)}
+ />
+ )
+ const renderGroupRow = row => (
+ <GroupRow
+ key={`group:${row.name}`}
+ active={groupChatName === row.name}
+ group={row.name}
+ members={row.members}
+ needsYou={Boolean(groupNeedsYou[row.name])}
+ onOpen={openGroupChat}
+ onDisband={setDeletingGroup}
+ />
+ )
const renderGatewaySection = section => {
const sectionId = `gateway:${section.id}`
const collapsed = rosterSectionCollapsed(sectionId)
-
- return jsxs(
- 'div',
- {
- className: 'min-w-0',
- children: [
- jsx(GatewaySectionHeading, {
- collapsed,
- count: section.rows.length,
- onToggle: () => toggleRosterSection(sectionId),
- option: section.option
- }),
- collapsed
- ? null
- : jsx('div', {
- className: 'grid min-w-0 gap-0.5',
- children: section.rows.map(row => renderBotRow(row.bot, `${section.id}:`))
- })
- ]
- },
- sectionId
+ return (
+ <div key={sectionId} className="min-w-0">
+ <GatewaySectionHeading
+ collapsed={collapsed}
+ count={section.rows.length}
+ onToggle={() => toggleRosterSection(sectionId)}
+ option={section.option}
+ />
+ {collapsed ? null : (
+ <div className="grid min-w-0 gap-0.5">{section.rows.map(row => renderBotRow(row.bot, `${section.id}:`))}</div>
+ )}
+ </div>
)
}
-
const renderGroupChatSection = () => {
const sectionId = 'group-chats'
const collapsed = rosterSectionCollapsed(sectionId)
-
- return jsxs(
- 'div',
- {
- className: 'min-w-0',
- children: [
- jsx(RosterSectionHeader, {
- collapsed,
- count: sortedGroupRows.length,
- icon: 'organization',
- label: 'Group chats',
- onToggle: () => toggleRosterSection(sectionId),
- tip: `${sortedGroupRows.length} global group chat${sortedGroupRows.length === 1 ? '' : 's'}`
- }),
- collapsed
- ? null
- : jsx('div', {
- className: 'grid min-w-0 gap-0.5',
- children: sortedGroupRows.map(renderGroupRow)
- })
- ]
- },
- sectionId
+ return (
+ <div key={sectionId} className="min-w-0">
+ <RosterSectionHeader
+ collapsed={collapsed}
+ count={sortedGroupRows.length}
+ icon="organization"
+ label="Group chats"
+ onToggle={() => toggleRosterSection(sectionId)}
+ tip={`${sortedGroupRows.length} global group chat${sortedGroupRows.length === 1 ? '' : 's'}`}
+ />
+ {collapsed ? null : <div className="grid min-w-0 gap-0.5">{sortedGroupRows.map(renderGroupRow)}</div>}
+ </div>
)
}
-
- const renderHiddenGatewaySection = section =>
- jsxs(
- 'div',
- {
- className: 'min-w-0',
- children: [
- jsx('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)',
- children: [
- jsx(GatewayKindGlyph, { kind: section.option?.kind }),
- jsx('span', {
- className: 'min-w-0 flex-1 truncate',
- children: section.option?.label || section.option?.connectionId || 'Current gateway'
- }),
- jsx('span', { className: 'shrink-0 font-normal tabular-nums', children: section.rows.length })
- ]
- }),
- ...section.rows.map(row => renderBotRow(row.bot, `hidden:${section.id}:`))
- ]
- },
- `hidden-gateway:${section.id}`
- )
-
- return jsxs('div', {
- className: 'flex h-full flex-col',
- children: [
- jsxs('div', {
- className: 'flex items-center justify-between gap-2 px-2.5 pt-2.5 pb-1.5',
- children: [
- jsx('span', {
- className: 'text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)',
- children: 'Bots'
- }),
- jsxs('div', {
- className: 'flex items-center gap-0.5',
- children: [
- jsx(Tip, {
- label: activityToasts ? 'Activity toasts on — click to silence' : 'Activity toasts off — click to enable',
- children: jsx('button', {
- type: 'button',
- className:
- 'flex size-6 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
- onClick: () => setActivityToasts(!activityToasts),
- children: jsx(Codicon, { name: activityToasts ? 'bell' : 'bell-slash' })
- })
- }),
- jsxs(DropdownMenu, {
- children: [
- jsx(Tip, {
- label: 'New…',
- children: jsx(DropdownMenuTrigger, {
- asChild: true,
- children: jsx('button', {
- type: 'button',
- 'aria-label': 'New bot or group chat',
- className:
- 'flex size-6 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
- children: jsx(Codicon, { name: 'add' })
- })
- })
- }),
- jsxs(DropdownMenuContent, {
- align: 'end',
- children: [
- jsxs(DropdownMenuItem, {
- onSelect: () => setCreateOpen(true),
- children: [jsx(Codicon, { name: 'hubot', className: 'mr-1.5' }), 'New Bot']
- }),
- jsxs(DropdownMenuItem, {
- disabled: activeSourceRoster.length < 2,
- onSelect: () => setGroupCreateOpen(true),
- children: [jsx(Codicon, { name: 'organization', className: 'mr-1.5' }), 'New Group Chat']
- })
- ]
- })
- ]
- })
- ]
- })
- ]
- }),
- jsx(ActiveNowStrip, {
- roster: visibleRoster,
- activeProfile,
- gatewayState,
- metaByName: allMeta,
- // Keep the Active Now strip and sidebar rows on the same exact-owner
+ const renderHiddenGatewaySection = section => (
+ <div key={`hidden-gateway:${section.id}`} className="min-w-0">
+ <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">
+ {section.option?.label || section.option?.connectionId || 'Current gateway'}
+ </span>
+ <span className="shrink-0 font-normal tabular-nums">{section.rows.length}</span>
+ </div>
+ {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">
+ <span className="text-[0.6875rem] font-semibold uppercase tracking-wider text-(--ui-text-quaternary)">
+ Bots
+ </span>
+ <div className="flex items-center gap-0.5">
+ <Tip
+ label={activityToasts ? 'Activity toasts on — click to silence' : 'Activity toasts off — click to enable'}
+ >
+ <button
+ type="button"
+ className="flex size-6 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground"
+ onClick={() => setActivityToasts(!activityToasts)}
+ >
+ <Codicon name={activityToasts ? 'bell' : 'bell-slash'} />
+ </button>
+ </Tip>
+ <DropdownMenu>
+ <Tip label="New…">
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label="New bot or group chat"
+ className="flex size-6 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground"
+ >
+ <Codicon name="add" />
+ </button>
+ </DropdownMenuTrigger>
+ </Tip>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => setCreateOpen(true)}>
+ <Codicon name="hubot" className="mr-1.5" />
+ New Bot
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled={activeSourceRoster.length < 2} onSelect={() => setGroupCreateOpen(true)}>
+ <Codicon name="organization" className="mr-1.5" />
+ New Group Chat
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ <ActiveNowStrip
+ roster={visibleRoster}
+ activeProfile={activeProfile}
+ gatewayState={gatewayState}
+ metaByName={allMeta} // Keep the Active Now strip and sidebar rows on the same exact-owner
// route: source activation first, then canonical name-registry open.
- onOpen: bot => void openRosterBot(bot)
- }),
- showRosterTools
- ? jsx('div', {
- className: 'flex min-w-0 items-center gap-1 px-2.5 pb-1.5',
- children: [
- showRosterSearch
- ? jsx(
- SearchField,
- {
- 'aria-label': 'Search bots and group chats',
- 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)',
- placeholder: 'Search bots and group chats…',
- value: query,
- onChange: setQuery
- },
- 'roster-search'
- )
- : jsx('span', { className: 'min-w-0 flex-1' }, 'roster-search-spacer'),
- showRosterFilters
- ? jsxs(
- DropdownMenu,
- {
- children: [
- jsx(Tip, {
- label: activeFilterCount ? `Filters (${activeFilterCount} active)` : 'Filter roster',
- children: jsx(DropdownMenuTrigger, {
- asChild: true,
- children: jsx('button', {
- type: 'button',
- 'aria-label': activeFilterCount ? `Filter roster, ${activeFilterCount} active` : 'Filter roster',
- className: cn(
- 'flex size-7 shrink-0 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
- activeFilterCount && 'text-(--ui-accent)'
- ),
- children: jsx(Codicon, { name: 'list-filter' })
- })
- })
- }),
- jsxs(DropdownMenuContent, {
- align: 'end',
- children: [
- ...[
- ['all', 'Bots and group chats'],
- ['bots', 'Bots only'],
- ['groups', 'Group chats only']
- ].map(([value, label]) =>
- jsxs(
- DropdownMenuItem,
- {
- onSelect: () => setRowKindFilter(value),
- children: [
- jsx('span', { className: 'min-w-0 flex-1', children: label }),
- rowKindFilter === value ? jsx(Codicon, { name: 'check' }) : null
- ]
- },
- `kind:${value}`
- )
- ),
- jsx(DropdownMenuSeparator, {}),
- ...[
- ['all', 'Any activity'],
- ['active', 'Active now'],
- ['recent', 'Recently active'],
- ['older', 'Older']
- ].map(([value, label]) =>
- jsxs(
- DropdownMenuItem,
- {
- onSelect: () => setActivityFilter(value),
- children: [
- jsx('span', { className: 'min-w-0 flex-1', children: label }),
- activityFilter === value ? jsx(Codicon, { name: 'check' }) : null
- ]
- },
- `activity:${value}`
- )
- ),
- gatewayOptions.length > 1 ? jsx(DropdownMenuSeparator, {}) : null,
- gatewayOptions.length > 1
- ? jsxs(DropdownMenuItem, {
- onSelect: () => setGatewayFilter('all'),
- children: [
- jsx(Codicon, { name: 'globe', className: 'mr-1.5' }),
- jsx('span', { className: 'min-w-0 flex-1', children: 'All gateways' }),
- gatewayFilter === 'all' ? jsx(Codicon, { name: 'check' }) : null
- ]
- })
- : null,
- ...(gatewayOptions.length > 1
- ? gatewayOptions.map(option => {
- const status = botSourceStatus({
- sourceError: option.error,
- sourceReachable: option.reachable
- })
-
- return jsxs(
- DropdownMenuItem,
- {
- onSelect: () => setGatewayFilter(option.connectionId),
- children: [
- jsx(GatewayKindGlyph, {
- kind: option.kind,
- className: cn(
- 'mr-1.5',
- !status.available && 'text-amber-600 dark:text-amber-300'
- )
- }),
- jsx('span', {
- className: 'min-w-0 flex-1 truncate',
- children: option.label || option.connectionId
- }),
- jsx('span', {
- className: 'text-[0.625rem] tabular-nums text-(--ui-text-quaternary)',
- children: option.count
- }),
- gatewayFilter === option.connectionId ? jsx(Codicon, { name: 'check' }) : null
- ]
- },
- option.connectionId
- )
- })
- : []),
- activeFilterCount ? jsx(DropdownMenuSeparator, {}) : null,
- activeFilterCount
- ? jsx(DropdownMenuItem, {
- onSelect: () => {
- setRowKindFilter('all')
- setActivityFilter('all')
- setGatewayFilter('all')
- },
- children: 'Clear filters'
- })
- : null
- ]
+ onOpen={bot => void openRosterBot(bot)}
+ />
+ {showRosterTools ? (
+ <div className="flex min-w-0 items-center gap-1 px-2.5 pb-1.5">
+ {showRosterSearch ? (
+ <SearchField
+ key={'roster-search'}
+ aria-label="Search bots and group chats"
+ 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)"
+ placeholder="Search bots and group chats…"
+ value={query}
+ onChange={setQuery}
+ />
+ ) : (
+ <span key={'roster-search-spacer'} className="min-w-0 flex-1" />
+ )}
+ {showRosterFilters ? (
+ <DropdownMenu key={'roster-filters'}>
+ <Tip label={activeFilterCount ? `Filters (${activeFilterCount} active)` : 'Filter roster'}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ aria-label={activeFilterCount ? `Filter roster, ${activeFilterCount} active` : 'Filter roster'}
+ className={cn(
+ 'flex size-7 shrink-0 items-center justify-center rounded-md text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
+ activeFilterCount && 'text-(--ui-accent)'
+ )}
+ >
+ <Codicon name="list-filter" />
+ </button>
+ </DropdownMenuTrigger>
+ </Tip>
+ <DropdownMenuContent align="end">
+ {[
+ ['all', 'Bots and group chats'],
+ ['bots', 'Bots only'],
+ ['groups', 'Group chats only']
+ ].map(([value, label]) => (
+ <DropdownMenuItem key={`kind:${value}`} onSelect={() => setRowKindFilter(value)}>
+ <span className="min-w-0 flex-1">{label}</span>
+ {rowKindFilter === value ? <Codicon name="check" /> : null}
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ {[
+ ['all', 'Any activity'],
+ ['active', 'Active now'],
+ ['recent', 'Recently active'],
+ ['older', 'Older']
+ ].map(([value, label]) => (
+ <DropdownMenuItem key={`activity:${value}`} onSelect={() => setActivityFilter(value)}>
+ <span className="min-w-0 flex-1">{label}</span>
+ {activityFilter === value ? <Codicon name="check" /> : null}
+ </DropdownMenuItem>
+ ))}
+ {gatewayOptions.length > 1 ? <DropdownMenuSeparator /> : null}
+ {gatewayOptions.length > 1 ? (
+ <DropdownMenuItem onSelect={() => setGatewayFilter('all')}>
+ <Codicon name="globe" className="mr-1.5" />
+ <span className="min-w-0 flex-1">All gateways</span>
+ {gatewayFilter === 'all' ? <Codicon name="check" /> : null}
+ </DropdownMenuItem>
+ ) : null}
+ {gatewayOptions.length > 1
+ ? gatewayOptions.map(option => {
+ const status = botSourceStatus({
+ sourceError: option.error,
+ sourceReachable: option.reachable
})
- ]
- },
- 'roster-filters'
- )
- : null
- ]
- })
- : null,
- staleNotice
- ? jsx('div', {
- className: 'mx-2.5 mb-1 rounded-md bg-(--chrome-action-hover) px-2 py-1.5 text-[0.6875rem] text-(--ui-text-tertiary)',
- children: staleNotice
- })
- : null,
- (isLoading || initialRosterLoading) && !roster.length
- ? jsx('div', {
- className: 'flex flex-1 items-center justify-center',
- children: jsx(GlyphSpinner, { spinner: 'breathe', className: 'text-(--ui-text-tertiary)' })
- })
- : error && !roster.length
- ? jsxs('div', {
- className: 'grid gap-2 px-3 py-4 text-xs text-(--ui-text-tertiary)',
- children: [
- jsx('div', {
- children: gatewayUp
- ? `Roster unavailable: ${error instanceof Error ? error.message : 'gateway error'}. If your gateway predates profiles.list, update Hermes and restart the gateway.`
- : 'Waiting for the gateway connection… (remote gateways can take a few seconds; retries automatically)'
- }),
- jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- className: 'justify-self-start',
- onClick: () => void refetch(),
- children: 'Retry now'
- })
- ]
- })
- : roster.length === 0
- ? jsx(EmptyState, {
- icon: 'hubot',
- title: 'No bots yet',
- description: 'Create your first bot.'
- })
- : allBotsHidden && !hiddenExpanded
- ? jsxs('div', {
- className: 'grid content-start gap-2 px-3 py-4 text-xs text-(--ui-text-tertiary)',
- children: [
- jsxs('div', {
- className: 'flex items-center gap-1.5 font-medium text-(--ui-text-secondary)',
- children: [
- jsx(Codicon, { name: 'eye-closed', className: 'text-(--ui-text-quaternary)' }),
- 'All bots are hidden'
- ]
- }),
- jsx('p', { className: 'leading-relaxed', children: 'They keep working and retain their history.' }),
- jsx(Button, {
- variant: 'secondary',
- size: 'sm',
- className: 'justify-self-start',
- onClick: () => $showHiddenBots.set(true),
- children: 'Show hidden bots'
- })
- ]
- })
- : rosterRows.length === 0 && matchingHiddenBots.length === 0
- ? jsx('div', {
- 'aria-live': 'polite',
- className:
- 'flex flex-1 items-center justify-center px-4 text-center text-xs text-(--ui-text-tertiary)',
- role: 'status',
- children: query.trim()
- ? `No bots or group chats match “${query.trim()}”${selectedGateway ? ` on ${selectedGateway.label}` : ''}`
- : selectedGateway
- ? `No bots or group chats match these filters on ${selectedGateway.label}`
- : 'No bots or group chats match these filters.'
- })
- : jsx(ScrollArea, {
- className: 'hermes-bots-roster min-h-0 flex-1',
- children: jsx('div', {
- className: 'grid w-full min-w-0 gap-0.5 px-1.5 pb-2',
- children: [
- ...(showGatewaySections
- ? [
- sortedGroupRows.length ? renderGroupChatSection() : null,
- ...gatewaySections.sections.map(renderGatewaySection)
- ].filter(Boolean)
- : rosterRows.map(row =>
- row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot)
- )),
- showHiddenSection
- ? jsxs(
- 'div',
- {
- ref: hiddenSectionRef,
- className: 'mt-1 border-t border-(--ui-stroke-tertiary) pt-1',
- children: [
- hasRosterConstraint
- ? jsxs('div', {
- className:
- 'flex w-full items-center gap-1 px-2 py-1.5 text-[0.6875rem] font-medium text-(--ui-text-tertiary)',
- children: [
- jsx(Codicon, { name: 'eye-closed' }),
- jsx('span', { children: 'Hidden' }),
- jsx('span', {
- className: 'text-(--ui-text-quaternary)',
- children: matchingHiddenBots.length
- })
- ]
- })
- : jsxs('button', {
- type: 'button',
- 'aria-expanded': hiddenExpanded,
- className:
- 'flex w-full items-center gap-1 rounded-md px-2 py-1.5 text-left text-[0.6875rem] font-medium text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground',
- onClick: () => $showHiddenBots.set(!hiddenExpanded),
- children: [
- jsx(Codicon, { name: hiddenExpanded ? 'chevron-down' : 'chevron-right' }),
- jsx('span', { children: 'Hidden' }),
- jsx('span', {
- className: 'text-(--ui-text-quaternary)',
- children: hiddenBots.length
- })
- ]
- }),
- showHiddenRows
- ? matchingHiddenBots.length
- ? hiddenGatewaySections.sectioned
- ? hiddenGatewaySections.sections.map(renderHiddenGatewaySection)
- : matchingHiddenBots.map(bot => renderBotRow(bot, 'hidden:'))
- : jsx('div', {
- className: 'px-2 py-2 text-xs text-(--ui-text-quaternary)',
- children: 'No hidden bots match these filters.'
- })
- : null
- ]
- },
- 'hidden-section'
- )
- : null
- ]
+ 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')}
+ />
+ <span className="min-w-0 flex-1 truncate">{option.label || option.connectionId}</span>
+ <span className="text-[0.625rem] tabular-nums text-(--ui-text-quaternary)">
+ {option.count}
+ </span>
+ {gatewayFilter === option.connectionId ? <Codicon name="check" /> : null}
+ </DropdownMenuItem>
+ )
})
- }),
- jsx(CreateAgentDialog, {
- open: createOpen,
- onClose: () => {
+ : []}
+ {activeFilterCount ? <DropdownMenuSeparator /> : null}
+ {activeFilterCount ? (
+ <DropdownMenuItem
+ onSelect={() => {
+ setRowKindFilter('all')
+ setActivityFilter('all')
+ setGatewayFilter('all')
+ }}
+ >
+ Clear filters
+ </DropdownMenuItem>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ </div>
+ ) : null}
+ {staleNotice ? (
+ <div className="mx-2.5 mb-1 rounded-md bg-(--chrome-action-hover) px-2 py-1.5 text-[0.6875rem] text-(--ui-text-tertiary)">
+ {staleNotice}
+ </div>
+ ) : null}
+ {(isLoading || initialRosterLoading) && !roster.length ? (
+ <div className="flex flex-1 items-center justify-center">
+ <GlyphSpinner spinner="breathe" className="text-(--ui-text-tertiary)" />
+ </div>
+ ) : error && !roster.length ? (
+ <div className="grid gap-2 px-3 py-4 text-xs text-(--ui-text-tertiary)">
+ <div>
+ {gatewayUp
+ ? `Roster unavailable: ${error instanceof Error ? error.message : 'gateway error'}. If your gateway predates profiles.list, update Hermes and restart the gateway.`
+ : 'Waiting for the gateway connection… (remote gateways can take a few seconds; retries automatically)'}
+ </div>
+ <Button variant="secondary" size="sm" className="justify-self-start" onClick={() => void refetch()}>
+ Retry now
+ </Button>
+ </div>
+ ) : roster.length === 0 ? (
+ <EmptyState icon="hubot" title="No bots yet" description="Create your first bot." />
+ ) : 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)" />
+ All bots are hidden
+ </div>
+ <p className="leading-relaxed">They keep working and retain their history.</p>
+ <Button
+ variant="secondary"
+ size="sm"
+ className="justify-self-start"
+ onClick={() => $showHiddenBots.set(true)}
+ >
+ Show hidden bots
+ </Button>
+ </div>
+ ) : rosterRows.length === 0 && matchingHiddenBots.length === 0 ? (
+ <div
+ aria-live="polite"
+ className="flex flex-1 items-center justify-center px-4 text-center text-xs text-(--ui-text-tertiary)"
+ role="status"
+ >
+ {query.trim()
+ ? `No bots or group chats match “${query.trim()}”${selectedGateway ? ` on ${selectedGateway.label}` : ''}`
+ : selectedGateway
+ ? `No bots or group chats match these filters on ${selectedGateway.label}`
+ : 'No bots or group chats match these filters.'}
+ </div>
+ ) : (
+ <ScrollArea className="hermes-bots-roster min-h-0 flex-1">
+ <div className="grid w-full min-w-0 gap-0.5 px-1.5 pb-2">
+ {showGatewaySections
+ ? [
+ sortedGroupRows.length ? renderGroupChatSection() : null,
+ ...gatewaySections.sections.map(renderGatewaySection)
+ ].filter(Boolean)
+ : rosterRows.map(row => (row.kind === 'group' ? renderGroupRow(row) : renderBotRow(row.bot)))}
+ {showHiddenSection ? (
+ <div
+ 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)">
+ <Codicon name="eye-closed" />
+ <span>Hidden</span>
+ <span className="text-(--ui-text-quaternary)">{matchingHiddenBots.length}</span>
+ </div>
+ ) : (
+ <button
+ type="button"
+ aria-expanded={hiddenExpanded}
+ className="flex w-full items-center gap-1 rounded-md px-2 py-1.5 text-left text-[0.6875rem] font-medium text-(--ui-text-tertiary) transition-colors hover:bg-(--chrome-action-hover) hover:text-foreground"
+ onClick={() => $showHiddenBots.set(!hiddenExpanded)}
+ >
+ <Codicon name={hiddenExpanded ? 'chevron-down' : 'chevron-right'} />
+ <span>Hidden</span>
+ <span className="text-(--ui-text-quaternary)">{hiddenBots.length}</span>
+ </button>
+ )}
+ {showHiddenRows ? (
+ matchingHiddenBots.length ? (
+ hiddenGatewaySections.sectioned ? (
+ hiddenGatewaySections.sections.map(renderHiddenGatewaySection)
+ ) : (
+ matchingHiddenBots.map(bot => renderBotRow(bot, 'hidden:'))
+ )
+ ) : (
+ <div className="px-2 py-2 text-xs text-(--ui-text-quaternary)">
+ No hidden bots match these filters.
+ </div>
+ )
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ </ScrollArea>
+ )}
+ <CreateAgentDialog
+ open={createOpen}
+ onClose={() => {
setCreateOpen(false)
void refetch()
- },
- roster: activeSourceRoster
- }),
- jsx(CreateGroupChatDialog, {
- open: groupCreateOpen,
- // Full multi-source roster: group chats can seat bots from other
+ }}
+ roster={activeSourceRoster}
+ />
+ <CreateGroupChatDialog
+ open={groupCreateOpen} // Full multi-source roster: group chats can seat bots from other
// registered connections — their turns route to their own machines.
- roster,
- onClose: () => setGroupCreateOpen(false),
- onCreated: groupName => openGroupChat(groupName)
- }),
- jsx(EditProfileDialog, {
- bot: editing,
- open: Boolean(editing),
- onClose: () => {
+ roster={roster}
+ onClose={() => setGroupCreateOpen(false)}
+ onCreated={groupName => openGroupChat(groupName)}
+ />
+ <EditProfileDialog
+ bot={editing}
+ open={Boolean(editing)}
+ onClose={() => {
setEditing(null)
void refetch()
+ }}
+ />
+ {grouping ? <GroupDialog bot={grouping} onClose={() => setGrouping(null)} /> : null}
+ <ConfirmDialog
+ open={Boolean(deleting)}
+ title="Delete bot and profile?"
+ description={
+ deleting ? (
+ <span>
+ {'This will permanently delete the bot '}
+ <span className="font-medium text-foreground">{deleting.name}</span>
+ {' and its associated Hermes profile at '}
+ <span className="font-mono text-xs">{deleting.path}</span>. This cannot be undone.
+ </span>
+ ) : null
}
- }),
- grouping ? jsx(GroupDialog, { bot: grouping, onClose: () => setGrouping(null) }) : null,
- jsx(ConfirmDialog, {
- open: Boolean(deleting),
- title: 'Delete bot and profile?',
- description: deleting
- ? jsxs('span', {
- children: [
- 'This will permanently delete the bot ',
- jsx('span', { className: 'font-medium text-foreground', children: deleting.name }),
- ' and its associated Hermes profile at ',
- jsx('span', { className: 'font-mono text-xs', children: deleting.path }),
- '. This cannot be undone.'
- ]
- })
- : null,
- destructive: true,
- confirmLabel: 'Delete',
- busyLabel: 'Deleting…',
- doneLabel: 'Deleted',
- onClose: () => setDeleting(null),
- onConfirm: async () => {
+ destructive
+ confirmLabel="Delete"
+ busyLabel="Deleting…"
+ doneLabel="Deleted"
+ onClose={() => setDeleting(null)}
+ onConfirm={async () => {
if (!deleting) {
return
}
-
const name = deleting.name
await deleteBot(deleting)
await refetch()
- host.notify({ kind: 'success', message: `Deleted profile ${name}` })
+ host.notify({
+ kind: 'success',
+ message: `Deleted profile ${name}`
+ })
+ }}
+ />
+ <ConfirmDialog
+ open={Boolean(deletingGroup)}
+ title="Delete group chat?"
+ description={
+ deletingGroup
+ ? `This removes “${deletingGroup.name}” from its bots and clears the shared room log. The bots and their individual chats are kept.`
+ : null
}
- }),
- jsx(ConfirmDialog, {
- open: Boolean(deletingGroup),
- title: 'Delete group chat?',
- 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: true,
- confirmLabel: 'Delete Group',
- busyLabel: 'Deleting…',
- doneLabel: 'Deleted',
- onClose: () => setDeletingGroup(null),
- onConfirm: async () => {
+ destructive
+ confirmLabel="Delete Group"
+ busyLabel="Deleting…"
+ doneLabel="Deleted"
+ onClose={() => setDeletingGroup(null)}
+ onConfirm={async () => {
if (!deletingGroup) return
await disbandGroupChat(deletingGroup.name, deletingGroup.members)
- host.notify({ kind: 'success', message: `Deleted group “${deletingGroup.name}”` })
- }
- })
- ]
- })
+ host.notify({
+ kind: 'success',
+ message: `Deleted group “${deletingGroup.name}”`
+ })
+ }}
+ />
+ </div>
+ )
}
// ── plugin ───────────────────────────────────────────────────────────────────
@@ -15604,7 +15459,8 @@ function BotsPane() {
export default {
id: ID,
name: 'Bots',
- description: 'Bot Mode — a one-chat-per-agent roster with avatars, routines, group chats, and bot-to-bot messaging. Ships with the app; disable here if unwanted.',
+ description:
+ 'Bot Mode — a one-chat-per-agent roster with avatars, routines, group chats, and bot-to-bot messaging. Ships with the app; disable here if unwanted.',
register(ctx) {
pluginCtx = ctx
groupChatSyncDisposed = false
@@ -15632,11 +15488,9 @@ export default {
provide: query => {
const roster = cachedUnionRoster()
const profiles = Array.isArray(roster?.profiles) ? roster.profiles : []
-
if (!profiles.length) {
return []
}
-
const active = focusedMentionProfile()
const q = (query || '').toLowerCase()
const items = []
@@ -15644,18 +15498,15 @@ export default {
name: active,
connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
}
-
for (const profile of profiles) {
if (!profile?.name || isActiveRosterBot(profile, live)) {
continue
}
-
const handle = botHandle(profile.name, profile)
const display = displayName(profile, $botMeta.get()[profile.name])
// Renamed bots complete on their friendly name — the tag is the
// renamed slug when one exists, the profile handle otherwise.
const tag = botMentionTag(profile)
-
if (
q &&
!tag.toLowerCase().startsWith(q) &&
@@ -15664,16 +15515,13 @@ export default {
) {
continue
}
-
const source = profile.connectionLabel ? ` · ${profile.connectionLabel}` : ''
-
items.push({
insert: `@${tag}`,
display: `@${tag}`,
meta: `Bot · ${display}${source}`
})
}
-
return items.slice(0, 8)
}
}
@@ -15684,7 +15532,8 @@ export default {
if (!document.getElementById('hermes-bots-keyframes')) {
const style = document.createElement('style')
style.id = 'hermes-bots-keyframes'
- style.textContent = '@keyframes hermes-bots-bob { from { transform: translateY(0); } to { transform: translateY(-3px); } }'
+ style.textContent =
+ '@keyframes hermes-bots-bob { from { transform: translateY(0); } to { transform: translateY(-3px); } }'
document.head.appendChild(style)
}
@@ -15736,7 +15585,6 @@ export default {
.then(async value => {
if (value && typeof value === 'object' && !Array.isArray(value)) {
const rooms = {}
-
for (const [name, room] of Object.entries(value)) {
if (room && Array.isArray(room.log)) {
rooms[name] = {
@@ -15760,8 +15608,10 @@ export default {
}
}
}
-
- $groupChats.set({ ...rooms, ...$groupChats.get() })
+ $groupChats.set({
+ ...rooms,
+ ...$groupChats.get()
+ })
// #93492: annotate rows orphaned before this build (their
// connection was deleted while an older Desktop ran, so no
@@ -15777,14 +15627,15 @@ export default {
? new Set(registry.connections.map(connection => String(connection?.id || '').trim()).filter(Boolean))
: null
const annotated = annotateOrphanedGroupChatMembers($groupChats.get(), liveIds)
-
if (annotated.changed) {
// Per-room updateGroupChat keeps the durable record's full
// shape (sessionOwners, holds) in storage; sync:false —
// the scheduleGroupChatServerSync below publishes once.
for (const [roomName, room] of Object.entries(annotated.rooms)) {
if (room !== $groupChats.get()[roomName]) {
- updateGroupChat(roomName, () => room, { sync: false })
+ updateGroupChat(roomName, () => room, {
+ sync: false
+ })
}
}
}
@@ -15836,7 +15687,6 @@ export default {
} catch {
/* registry lifecycle push unavailable — hydrate-time annotate still covers it */
}
-
if (typeof ctx.onDispose === 'function') {
ctx.onDispose(() => {
stopGroupChatServerSync()
@@ -15858,7 +15708,6 @@ export default {
// the meta/room storage hydrates above have landed; idempotent after that.
// (Feature-guarded: bare vm test harnesses have no setTimeout global.)
startHideSweepScheduler(ctx)
-
ctx.register({
id: 'pane',
area: 'panes',
@@ -15885,8 +15734,18 @@ export default {
// sessions pane collapses alone without this flag. The zone then keeps
// a stranded BOTS tab on screen. The narrow edge overlay mirrors the
// zone's tab strip, so the pane stays reachable while collapsed.
- data: { placement: 'left', width: '260px', collapsible: true, hideOnly: true, dock: { pane: 'sessions', pos: 'center', enforce: true } },
- render: () => jsx(BotsPane, {})
+ data: {
+ placement: 'left',
+ width: '260px',
+ collapsible: true,
+ hideOnly: true,
+ dock: {
+ pane: 'sessions',
+ pos: 'center',
+ enforce: true
+ }
+ },
+ render: () => <BotsPane />
})
// Routines — its OWN tiling pane splitting the workspace's right edge
@@ -15909,17 +15768,19 @@ export default {
data: {
placement: 'main',
// Repair persisted layouts that stranded Cronjobs in the Bots tab strip.
- dock: { pane: 'workspace', pos: 'right', enforce: true },
+ dock: {
+ pane: 'workspace',
+ pos: 'right',
+ enforce: true
+ },
width: '250px'
},
- render: () => jsx(RoutinesPane, {})
+ render: () => <RoutinesPane />
})
-
if (typeof host.paneVisibility === 'function') {
// The contribution-scoped pane id (`register` prefixes `${ID}:`).
const $sidebarVisible = host.paneVisibility(`${ID}:pane`)
let unregisterRoutines = null
-
const syncRoutinesPane = () => {
if (botChatOwnsWorkspace()) {
unregisterRoutines ??= registerRoutinesPane()
@@ -15942,7 +15803,6 @@ export default {
syncBotsHomeWorkspace()
syncRoutinesPane()
}
-
const stopSidebarSync = $sidebarVisible.listen(visible => {
$botsPaneVisible.set(Boolean(visible))
if (visible) {
@@ -15999,11 +15859,9 @@ export default {
? focusStore.listen(id => {
$botChatFocused.set(Boolean(id))
releaseStaleOpenBotChat(id)
-
if (id) {
closeBotsHomeWorkspace()
}
-
syncWorkspaceSurfaces()
})
: null
@@ -16023,23 +15881,17 @@ export default {
const payload = event?.payload || {}
const stored = String(payload.stored_session_id || '')
const claim = $openBotChat.get()
-
if (!stored || !claim) {
return
}
-
const owned = [claim.openedSessionId, claim.openedRegistryId].filter(Boolean)
-
if (!owned.includes(stored)) {
return
}
-
const bot = selectedRosterBot($lastRoster.get(), $selectedRosterKey.get())
-
if (!bot) {
return
}
-
const generation = botOpenGeneration
void openBotCanonicalChat(bot)
.then(opened => {
@@ -16047,7 +15899,6 @@ export default {
if (!opened || generation !== botOpenGeneration) {
return
}
-
$openBotChat.set({
key: claim.key,
openedRegistryId: opened.registryId,
@@ -16059,7 +15910,6 @@ export default {
})
})
: null
-
$botsPaneVisible.set(Boolean($sidebarVisible.get()))
$botChatFocused.set(sessionOwnsWorkspace())
$botsHomeFronted.set(Boolean(homeVisibleStore.get()))
@@ -16069,7 +15919,6 @@ export default {
// remains passive, so a real restored chat is never covered.
syncWorkspaceSurfaces()
scheduleSurfaceSync()
-
if (typeof ctx.onDispose === 'function') {
// The registration disposer is already tracked by ctx.register; only
// the listeners need explicit teardown or they survive plugin disable.
@@ -16086,7 +15935,6 @@ export default {
} else {
registerRoutinesPane()
}
-
ctx.register({
id: 'new-agent',
area: PALETTE_AREA,
@@ -16095,7 +15943,10 @@ export default {
label: 'New Bot…',
keywords: ['bot', 'agent', 'profile', 'teammate', 'create'],
run: () => {
- host.notify({ kind: 'info', message: 'Open the Bots pane and hit “New Bot”.' })
+ host.notify({
+ kind: 'info',
+ message: 'Open the Bots pane and hit “New Bot”.'
+ })
}
}
})
@@ -16121,7 +15972,6 @@ export default {
// guards the canonical chat: Sessions-mode scratchpads on the
// same profile keep full /new freedom.
const slashNew = /^\/(new|reset)\s*$/.exec(text.trim())
-
if (slashNew) {
const activeBot = $selectedBot.get()
// Canonical identity is the profile's "Bot Chat" registry row —
@@ -16133,7 +15983,6 @@ export default {
const canonical = row?.canonical_session || null
const currentId = host.activeSessionId?.get?.() ?? null
const canonicalIds = [canonical?.id, canonical?.resolved_id].filter(Boolean).map(String)
-
if (activeBot && currentId && canonicalIds.includes(String(currentId))) {
host.notify({
kind: 'info',
@@ -16142,15 +15991,15 @@ export default {
'Bot chats are one continuous conversation — compacting instead. ' +
'For a throwaway session with this agent, use Sessions mode.'
})
-
- return { ...draft, text: '/compact' }
+ return {
+ ...draft,
+ text: '/compact'
+ }
}
}
-
if (!/(^|\s)@[a-z0-9][a-z0-9_-]*/i.test(text)) {
return draft
}
-
const live = {
name: focusedMentionProfile(),
connectionId: String(host.state.connectionId?.get?.() || host.activeConnectionId?.() || 'local')
@@ -16158,18 +16007,21 @@ export default {
const cached = cachedUnionRoster()
const roster = Array.isArray(cached?.profiles) ? cached.profiles : null
let mentionedBots = roster ? resolveRosterMentions(text, roster, live) : []
-
if (!roster) {
try {
- const res = await host.request('profiles.list', { include_sessions: false })
+ const res = await host.request('profiles.list', {
+ include_sessions: false
+ })
// Same resolver as the cached path — renamed bots (display_name
// / ui_meta title) stay taggable when the roster cache is cold.
- mentionedBots = resolveRosterMentions(text, res?.profiles ?? [], live).map(bot => ({ ...bot, remoteSource: false }))
+ mentionedBots = resolveRosterMentions(text, res?.profiles ?? [], live).map(bot => ({
+ ...bot,
+ remoteSource: false
+ }))
} catch {
return draft
}
}
-
if (!mentionedBots.length) {
return draft
}
@@ -16181,7 +16033,9 @@ export default {
// resolves against the Desktop-synced relay roster.
const lines = mentionedBots.map(bot => {
const handle = botHandle(bot.name, bot)
- const title = String(botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || '').trim()
+ const title = String(
+ botRosterMeta(bot, $botMeta.get())?.title || bot.ui_meta?.['hermes-bots']?.title || bot.title || ''
+ ).trim()
const target = bot.remoteSource && bot.connectionId ? `${handle}@${bot.connectionId}` : handle
const where = bot.remoteSource
? ` — on ${bot.connectionLabel || bot.connectionId} (message_agent target: "${target}")`
@@ -16192,9 +16046,12 @@ export default {
'\n\n[@mentions resolved from the Bot Mode roster — the user is referring to: ' +
lines.join('; ') +
'. If they want one of these agents contacted, compose your own message and send it with your message_agent tool (agents on other connected machines are reachable too — the Desktop relays it); never forward the user\u2019s text verbatim. If this session has no message_agent tool, agent messaging is unavailable here — say so.]'
-
- return { ...draft, text: text + note }
- } }
+ return {
+ ...draft,
+ text: text + note
+ }
+ }
+ }
})
}
}