The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep bot reconciliation off inactive backends
fangliquanflq66186dc58f10
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.jsindex 91f2f5e2abf..3646753d99f 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.js+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js@@ -2233,8 +2233,66 @@ function fallbackSelectionAfterHide(name) {* everything else — canonical Bot Chats are identified by name (the* registry row titled "Bot Chat"), so the title sweep is what hides them;* no stored-id pointer is consulted. Idempotent (the DB setter is a no-op- * on already-hidden rows) and feature-detected: older gateways lack- * session.set_hidden and simply keep the rows visible. */+ * on already-hidden rows) and feature-detected: older Desktop hosts defer+ * reconciliation rather than activating an absent profile backend. */+function startHideSweepScheduler(ctx) {+ let timer = null+ let inflight = null+ let pending = false+ let disposed = false++ const run = () => {+ timer = null+ if (disposed) {+ return+ }+ if (inflight) {+ pending = true+ return+ }++ inflight = Promise.resolve()+ .then(() => hideOwnedBotSessions())+ .catch(() => undefined)+ .finally(() => {+ inflight = null+ if (pending && !disposed) {+ pending = false+ schedule()+ }+ })+ }+ const schedule = () => {+ if (disposed) {+ return+ }++ try {+ if (timer !== null) {+ clearTimeout(timer)+ }+ timer = setTimeout(run, 0)+ } catch {+ run()+ }+ }+ const stopGatewayListener = host.state.gateway.listen(state => {+ if (state === 'open') {+ schedule()+ }+ })++ ctx.onDispose(() => {+ disposed = true+ stopGatewayListener()+ if (timer !== null) {+ clearTimeout(timer)+ timer = null+ }+ })+ schedule()+}+function hideOwnedBotSessions() {const roomEntries = Object.values($groupChats.get()).flatMap(room =>Object.entries(room?.sessions || {})@@ -2272,15 +2330,28 @@ function hideOwnedBotSessions() {const known = Promise.all(rooms.map(({ owner, id }) =>- Promise.resolve(requestForBot(owner, 'session.set_hidden', { session_id: id, hidden: true })).catch(- () => undefined- )+ hidePersistedBotSession(owner, id).catch(() => undefined)))return Promise.all([known, sweepBotProfileSessions().catch(() => undefined)])}+/** Reconcile durable visibility through the source's primary REST backend.+ * Never fall back to requestForBot: that compatibility path activates an+ * absent profile backend, which is worse than deferring this best-effort sweep. */+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 }))+}+// Titles Bot Mode itself mints for its plumbing sessions. Bot-to-bot CLI// handoffs (`hermes -p <bot> chat --in ~ -c "Bot Chat" --create-if-missing`)// create sessions with EXACTLY these titles; the "Group: " prefix is the@@ -2322,10 +2393,14 @@ function isBotModeSweepCandidate(row, nowSeconds = Date.now() / 1000) {* millisecond, or future timestamps fail closed and stay visible. session.list* without include_hidden returns only visible rows, which keeps the sweep* naturally idempotent.- * Remote-source bots route to their own connection via requestForBot.- * Feature-detected + fire-and-forget: older gateways without per-profile- * session.list / session.set_hidden simply reject and the sweep no-ops. */+ * Reads and writes go through the owning source's primary REST backend, which+ * opens persisted state directly and never starts an inactive profile backend.+ * Feature-detected + fire-and-forget: older Desktop hosts defer the sweep. */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@@ -2351,7 +2426,9 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {}try {- const res = await requestForBot(bot, 'session.list', { profile: name, limit: PROFILE_SESSION_LIST_LIMIT })+ const route = botConnectionRoute(bot)+ const profile = backendTargetProfile(route, name)+ const res = await host.listPersistedSessions(route, { profile, limit: PROFILE_SESSION_LIST_LIMIT })const rows = Array.isArray(res?.sessions) ? res.sessions : []await Promise.all(@@ -2359,7 +2436,7 @@ async function sweepBotProfileSessions(nowSeconds = Date.now() / 1000) {.filter(row => isBotModeSweepCandidate(row, nowSeconds)).map(row =>Promise.resolve(- requestForBot(bot, 'session.set_hidden', { session_id: row.id, hidden: true, profile: name })+ hidePersistedBotSession(bot, row.id, profile)).catch(() => undefined)))@@ -15125,19 +15202,7 @@ export default {// rows were created before the always-hidden policy). Deferred a tick so// the meta/room storage hydrates above have landed; idempotent after that.// (Feature-guarded: bare vm test harnesses have no setTimeout global.)- const scheduleHideSweep = () => {- try {- setTimeout(() => void hideOwnedBotSessions(), 0)- } catch {- void hideOwnedBotSessions()- }- }- host.state.gateway.listen(state => {- if (state === 'open') {- scheduleHideSweep()- }- })- scheduleHideSweep()+ startHideSweepScheduler(ctx)ctx.register({id: 'pane',diff --git a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjsindex 9e9dcb48aee..a845550f2af 100644--- a/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs+++ b/apps/desktop/src/plugins/hermes-bots/tests/hide-bot-chats.test.mjs@@ -60,6 +60,9 @@ test('hideOwnedBotSessions sweeps room member sessions by id', async () => {const calls = []const context = {host: {+ setPersistedSessionHidden: async (_route, options) => {+ calls.push({ method: 'session.set_hidden', params: { session_id: options.sessionId, hidden: options.hidden } })+ },request: async (method, params) => {calls.push({ method, params })return {}@@ -117,7 +120,10 @@ test('remote group member sessions derive their immutable owner from persisted r}}const context = {- host: { request: async (method, params) => ambient.push({ method, params }) },+ host: {+ request: async (method, params) => ambient.push({ method, params }),+ setPersistedSessionHidden: async (route, options) => routed.push({ route, options })+ },$botMeta: { get: () => ({}) },$lastRoster: { get: () => [] },$groupChats: {@@ -129,7 +135,11 @@ test('remote group member sessions derive their immutable owner from persisted r})},groupMemberKey: member => `${member.route.connectionId}::${member.name}`,- requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),+ botConnectionRoute: bot => bot.route || null,+ backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,+ requestForBot: async () => {+ throw new Error('gateway RPC must not be used')+ },sweepBotProfileSessions: async () => undefined}const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')@@ -139,9 +149,9 @@ test('remote group member sessions derive their immutable owner from persisted rassert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)assert.equal(routed.length, 1)- assert.equal(routed[0].bot.route.connectionId, 'source-a')- assert.equal(routed[0].bot.route.targetProfile, 'backend-worker')- assert.equal(routed[0].params.session_id, 'remote-room-1')+ assert.equal(routed[0].route.connectionId, 'source-a')+ assert.equal(routed[0].route.targetProfile, 'backend-worker')+ assert.equal(routed[0].options.sessionId, 'remote-room-1')})test('same session id on two remote group owners never hides an ambient collision', async () => {@@ -157,7 +167,10 @@ test('same session id on two remote group owners never hides an ambient collisioconst ownerA = owner('source-a')const ownerB = owner('source-b')const context = {- host: { request: async (method, params) => ambient.push({ method, params }) },+ host: {+ request: async (method, params) => ambient.push({ method, params }),+ setPersistedSessionHidden: async (route, options) => routed.push({ route, options })+ },$botMeta: { get: () => ({}) },$lastRoster: { get: () => [] },$groupChats: {@@ -167,7 +180,11 @@ test('same session id on two remote group owners never hides an ambient collisio})},groupMemberKey: member => `${member.route.connectionId}::${member.name}`,- requestForBot: async (bot, method, params) => routed.push({ bot, method, params }),+ botConnectionRoute: bot => bot.route || null,+ backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,+ requestForBot: async () => {+ throw new Error('gateway RPC must not be used')+ },sweepBotProfileSessions: async () => undefined}const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions };\n')@@ -176,8 +193,8 @@ test('same session id on two remote group owners never hides an ambient collisioawait context.__h.hideOwnedBotSessions()assert.equal(ambient.some(call => call.method === 'session.set_hidden'), false)- assert.deepEqual(routed.map(call => call.bot.route.connectionId).sort(), ['source-a', 'source-b'])- assert.ok(routed.every(call => call.params.session_id === 'same-id'))+ assert.deepEqual(routed.map(call => call.route.connectionId).sort(), ['source-a', 'source-b'])+ assert.ok(routed.every(call => call.options.sessionId === 'same-id'))})test('malformed persisted owner for a source-qualified group session fails closed', async () => {@@ -234,11 +251,25 @@ test('sweepBotProfileSessions hides Bot-Mode-titled rows per roster bot, and onlremy: [{ id: 'r-1', title: 'Agent Inbox', started_at: 1 }]}const context = {- host: { request: async () => ({}) },+ host: {+ request: async () => ({}),+ listPersistedSessions: async (route, options) => {+ calls.push({ bot: options.profile, method: 'persisted.list', params: options, route })+ return { sessions: rowsByProfile[options.profile] || [] }+ },+ setPersistedSessionHidden: async (route, options) => {+ calls.push({ bot: options.profile, method: 'persisted.set_hidden', params: options, route })+ }+ },$botMeta: { get: () => ({}) },$groupChats: { get: () => ({}) },$lastRoster: { get: () => [{ name: 'alpha' }, { name: 'remy', remoteSource: true, connectionId: 'mini' }] },PROFILE_SESSION_LIST_LIMIT: 200,+ botConnectionRoute: bot =>+ bot.remoteSource+ ? { connectionId: bot.connectionId, mode: 'remote', profile: bot.name, targetProfile: bot.name }+ : null,+ backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,requestForBot: async (bot, method, params) => {calls.push({ bot: bot.name, method, params })if (method === 'session.list') {@@ -251,20 +282,137 @@ test('sweepBotProfileSessions hides Bot-Mode-titled rows per roster bot, and onlvm.runInNewContext(section, context, { filename: 's.js' })await context.__h.sweepBotProfileSessions(nowSeconds)- const lists = calls.filter(c => c.method === 'session.list')+ const lists = calls.filter(c => c.method === 'persisted.list')assert.deepEqual(lists.map(c => c.params.profile).sort(), ['alpha', 'remy'])// Visible-rows-only listing keeps the sweep idempotent.assert.ok(lists.every(c => !c.params.include_hidden))- const hidden = calls.filter(c => c.method === 'session.set_hidden')+ const hidden = calls.filter(c => c.method === 'persisted.set_hidden')assert.deepEqual(- hidden.map(c => c.params.session_id).sort(),+ hidden.map(c => c.params.sessionId).sort(),['a-1', 'a-2', 'a-3', 'a-8', 'r-1'],'exact plumbing titles only — user-titled and brand-new rows stay visible')assert.ok(hidden.every(c => c.params.hidden === true))- // Remote-source bots route through requestForBot with their own bot row.- assert.equal(hidden.find(c => c.params.session_id === 'r-1').bot, 'remy')+ // Remote-source rows keep their immutable source owner on the REST route.+ assert.equal(hidden.find(c => c.params.sessionId === 'r-1').route.connectionId, 'mini')+})++test('load reconciliation uses persisted REST doors and never wakes profile gateways', async () => {+ const start = source.indexOf('function hideOwnedBotSessions()')+ const end = source.indexOf('/** Fetch server-side avatars', start)+ const reads = []+ const writes = []+ const context = {+ host: {+ request: async () => ({}),+ listPersistedSessions: async (route, options) => {+ reads.push({ route, options })+ return { sessions: [{ id: `${options.profile}-bot`, profile: options.profile, title: 'Bot Chat', started_at: 1 }] }+ },+ setPersistedSessionHidden: async (route, options) => writes.push({ route, options })+ },+ $groupChats: { get: () => ({}) },+ $lastRoster: {+ get: () => [+ {+ name: 'alpha',+ sourceScoped: true,+ route: { connectionId: 'local', mode: 'local', profile: 'alpha', targetProfile: 'alpha' }+ },+ {+ name: 'remy',+ sourceScoped: true,+ route: { connectionId: 'mini', mode: 'remote', profile: 'remy', targetProfile: 'worker' }+ }+ ]+ },+ PROFILE_SESSION_LIST_LIMIT: 200,+ backendTargetProfile: (route, fallback) => route?.targetProfile || fallback,+ botConnectionRoute: bot => bot.route || null,+ groupMemberKey: member => member.name,+ requestForBot: async () => {+ throw new Error('reconciliation must not use gateway RPC')+ }+ }+ const section = source.slice(start, end).concat('\nglobalThis.__h = { hideOwnedBotSessions, sweepBotProfileSessions };\n')+ vm.runInNewContext(section, context, { filename: 'persisted-sweep.js' })++ await context.__h.hideOwnedBotSessions()++ assert.deepEqual(reads.map(call => call.options.profile).sort(), ['alpha', 'worker'])+ assert.deepEqual(writes.map(call => call.options.sessionId).sort(), ['alpha-bot', 'worker-bot'])+ assert.ok(writes.every(call => call.options.hidden === true))+})++test('hide-sweep scheduling coalesces reconnects, queues one trailing run, and cancels on dispose', async () => {+ const start = source.indexOf('function startHideSweepScheduler(')+ const end = source.indexOf('function hideOwnedBotSessions()', start)+ const timers = new Map()+ let nextTimer = 1+ let gatewayListener = null+ let dispose = null+ let stopped = 0+ let resolveFirst+ let sweeps = 0+ const context = {+ host: {+ state: {+ gateway: {+ listen: listener => {+ gatewayListener = listener+ return () => {+ stopped += 1+ }+ }+ }+ }+ },+ hideOwnedBotSessions: () => {+ sweeps += 1+ return sweeps === 1 ? new Promise(resolve => (resolveFirst = resolve)) : Promise.resolve()+ },+ setTimeout: callback => {+ const id = nextTimer+++ timers.set(id, callback)+ return id+ },+ clearTimeout: id => timers.delete(id)+ }+ const ctx = { onDispose: callback => (dispose = callback) }+ const runNextTimer = () => {+ const [id, callback] = timers.entries().next().value+ timers.delete(id)+ callback()+ }+ const section = source.slice(start, end).concat('\nglobalThis.__scheduler = startHideSweepScheduler;\n')+ vm.runInNewContext(section, context, { filename: 'hide-scheduler.js' })++ context.__scheduler(ctx)+ gatewayListener('open')+ gatewayListener('open')+ assert.equal(timers.size, 1, 'load plus duplicate open events coalesce before execution')++ runNextTimer()+ await Promise.resolve()+ assert.equal(sweeps, 1)++ gatewayListener('open')+ runNextTimer()+ assert.equal(sweeps, 1, 'an inflight sweep is not overlapped')++ resolveFirst()+ await new Promise(resolve => setImmediate(resolve))+ assert.equal(timers.size, 1, 'one trailing sweep preserves the reconnect signal')+ runNextTimer()+ await Promise.resolve()+ assert.equal(sweeps, 2)++ gatewayListener('open')+ assert.equal(timers.size, 1)+ dispose()+ assert.equal(timers.size, 0)+ assert.equal(stopped, 1)})test('hideOwnedBotSessions chains the ownership sweep and survives its absence of context', async () => {diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex ed4cf6cf09a..a0e7349de47 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -41,7 +41,7 @@ import {import { onGatewayEvent } from '@/contrib/events'import { registry } from '@/contrib/registry'import type { WorkspaceMode } from '@/contrib/types'-import { deleteProfile, getLogs, getStatus, type HermesGateway } from '@/hermes'+import { deleteProfile, getLogs, getStatus, hermesApi, type HermesGateway } from '@/hermes'import {$gateway,activeGatewayConnectionId,@@ -92,7 +92,7 @@ import {$sessionTiles} from '@/store/session-states'import { runGatewayRestart } from '@/store/system-actions'-import type { UsageStats } from '@/types/hermes'+import type { PaginatedSessions, UsageStats } from '@/types/hermes'import { planPluginOpenSession } from './plugin-open-session-plan'@@ -1184,6 +1184,65 @@ export const host = {return retainGatewayForAgent(null, route.trim() || 'default')},+ /** Read persisted sessions from a profile's owning source without dialing+ * that profile's gateway. The source primary opens state.db directly. */+ listPersistedSessions: async (+ route: PluginProfileRoute | null,+ options: { profile: string; limit?: number }+ ): Promise<PaginatedSessions> => {+ if (route && (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim())) {+ throw new Error('Profile route must include connectionId, profile, and targetProfile')+ }++ const profile = options.profile.trim()++ if (!profile) {+ throw new Error('Persisted session reads require a profile')+ }++ const limit = Math.min(500, Math.max(0, options.limit ?? 200))++ const query = new URLSearchParams({+ limit: String(limit),+ offset: '0',+ min_messages: '0',+ archived: 'exclude',+ order: 'created',+ profile+ })++ return hermesApi<PaginatedSessions>({+ ...(route ? { connectionId: route.connectionId } : {}),+ path: `/api/profiles/sessions?${query.toString()}`,+ timeoutMs: 60_000+ })+ },++ /** Mutate the durable hidden flag through the source primary. Keeping the+ * owner profile in the body (not request.profile) prevents Electron from+ * starting a profile backend merely to reconcile persisted visibility. */+ setPersistedSessionHidden: async (+ route: PluginProfileRoute | null,+ options: { sessionId: string; profile: string; hidden: boolean }+ ): Promise<{ ok: boolean; hidden: boolean }> => {+ if (route && (!route.connectionId.trim() || !route.profile.trim() || !route.targetProfile.trim())) {+ throw new Error('Profile route must include connectionId, profile, and targetProfile')+ }++ const profile = options.profile.trim()++ if (!profile || !options.sessionId.trim()) {+ throw new Error('Persisted session updates require a profile and session id')+ }++ return hermesApi<{ ok: boolean; hidden: boolean }>({+ ...(route ? { connectionId: route.connectionId } : {}),+ path: `/api/sessions/${encodeURIComponent(options.sessionId)}`,+ method: 'PATCH',+ body: { hidden: options.hidden, profile }+ })+ },+/** Gateway JSON-RPC — sessions, config, skills, cron, kanban, everything* the app itself uses. Lazy: resolves the LIVE socket per call. */request: async <T>(method: string, params: Record<string, unknown> = {}): Promise<T> => {diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.tsindex 71237762d0f..cc8d4c0e362 100644--- a/apps/desktop/src/sdk/profile-routing.test.ts+++ b/apps/desktop/src/sdk/profile-routing.test.ts@@ -14,7 +14,7 @@ vi.mock('@/components/pane-shell/tree/store', async () => {return { $narrowViewport: atom(false) }})vi.mock('@/contrib/events', () => ({ onGatewayEvent: vi.fn() }))-vi.mock('@/hermes', () => ({ deleteProfile: vi.fn(), getLogs: vi.fn(), getStatus: vi.fn() }))+vi.mock('@/hermes', () => ({ deleteProfile: vi.fn(), getLogs: vi.fn(), getStatus: vi.fn(), hermesApi: vi.fn() }))vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))vi.mock('@/store/system-actions', () => ({ runGatewayRestart: vi.fn() }))vi.mock('@/store/session', async () => {@@ -105,7 +105,7 @@ vi.mock('@/store/gateway', async () => {const { host } = await import('./index')const { openSession: openSessionCore } = await import('@/app/open-session')-const { deleteProfile } = await import('@/hermes')+const { deleteProfile, hermesApi } = await import('@/hermes')const {activeGatewayConnectionId,@@ -269,6 +269,43 @@ describe('connection-aware plugin host APIs', () => {expect(requestGatewayForProfile).not.toHaveBeenCalled()})+ it('reads and hides persisted sessions through the source primary without activating the profile', async () => {+ const route = {+ connectionId: 'source-a',+ mode: 'remote' as const,+ profile: 'remote-worker',+ targetProfile: 'backend-worker'+ }++ vi.mocked(hermesApi)+ .mockResolvedValueOnce({ sessions: [{ id: 'bot-chat', profile: 'backend-worker', title: 'Bot Chat' }] })+ .mockResolvedValueOnce({ ok: true, hidden: true })++ await expect(host.listPersistedSessions(route, { profile: 'backend-worker', limit: 200 })).resolves.toMatchObject({+ sessions: [{ id: 'bot-chat' }]+ })+ await expect(+ host.setPersistedSessionHidden(route, { sessionId: 'bot-chat', profile: 'backend-worker', hidden: true })+ ).resolves.toMatchObject({ ok: true, hidden: true })++ expect(hermesApi).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ connectionId: 'source-a',+ path: expect.stringContaining('/api/profiles/sessions?')+ })+ )+ expect(hermesApi).toHaveBeenNthCalledWith(2, {+ connectionId: 'source-a',+ path: '/api/sessions/bot-chat',+ method: 'PATCH',+ body: { hidden: true, profile: 'backend-worker' }+ })+ expect(vi.mocked(hermesApi).mock.calls.every(([request]) => !('profile' in request))).toBe(true)+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ expect(requestGatewayForProfile).not.toHaveBeenCalled()+ })+it('fails closed when a descriptor omits connection or target profile identity', async () => {await expect(host.requestProfile(diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex 2a44cfef083..86f766ff20e 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -330,6 +330,9 @@ class SessionImport(BaseModel):class SessionRename(BaseModel):title: Optional[str] = Nonearchived: Optional[bool] = None+ # Generic visibility flag. This is also used by process-light cross-profile+ # reconciliation, where the primary backend opens the owner's state.db.+ hidden: Optional[bool] = None# Durable "keep" flag mirrored from the Desktop sidebar's pins; pinned# sessions are exempt from the sessions.auto_archive stale sweep.pinned: Optional[bool] = Nonediff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex 933db5ed5db..32ab0ee8cba 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -704,10 +704,11 @@ async def delete_session_endpoint(session_id: str, profile: Optional[str] = None@manage_router.patch("/api/sessions/{session_id}")async def rename_session_endpoint(session_id: str, body: SessionRename):- """Update a session: rename, archive, pin, and/or mark read/unread.+ """Update a session: rename, archive, hide, pin, and/or mark read/unread.``title`` renames (empty/null clears the title); ``archived`` soft-hides or- restores the session; ``pinned`` sets the durable keep flag (exempts the+ restores the session; ``hidden`` controls generic list visibility;+ ``pinned`` sets the durable keep flag (exempts thesession from the auto-archive sweep); ``unread`` toggles the read-statewatermark (True = explicitly unread, False = read up to now — see``SessionDB.set_session_read``). Any field may be omitted. ``profile``@@ -721,12 +722,13 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):if (body.title is Noneand body.archived is None+ and body.hidden is Noneand body.pinned is Noneand body.unread is None):raise HTTPException(status_code=400,- detail="Nothing to update; provide 'title', 'archived', 'pinned', and/or 'unread'.",+ detail="Nothing to update; provide 'title', 'archived', 'hidden', 'pinned', and/or 'unread'.",)if body.title is not None:try:@@ -736,6 +738,8 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):raise HTTPException(status_code=400, detail=str(e))if body.archived is not None:db.set_session_archived(sid, body.archived)+ if body.hidden is not None:+ db.set_session_hidden(sid, body.hidden)if body.pinned is not None:db.set_session_pinned(sid, body.pinned)if body.unread is not None:@@ -743,6 +747,8 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):result = {"ok": True, "title": db.get_session_title(sid) or ""}if body.archived is not None:result["archived"] = bool(body.archived)+ if body.hidden is not None:+ result["hidden"] = bool(body.hidden)if body.pinned is not None:result["pinned"] = bool(body.pinned)if body.unread is not None:diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 796719a6eb7..cab3efb9024 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -5053,3 +5053,22 @@ class TestSessionPatchUnread:# a string outside the accepted set to prove validation rejects it.resp = self.auth_client.patch("/api/sessions/s1", json={"unread": "maybe"})assert resp.status_code == 422 # pydantic validation++ def test_patch_hidden_updates_persisted_session_without_live_runtime(self):+ resp = self.auth_client.patch("/api/sessions/s1", json={"hidden": True})+ assert resp.status_code == 200+ assert resp.json()["hidden"] is True++ rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]+ assert all(s["id"] != "s1" for s in rows)++ restored = self.auth_client.patch(+ "/api/sessions/s1", json={"hidden": False}+ )+ assert restored.status_code == 200+ rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]+ assert bool(next(s for s in rows if s["id"] == "s1")["hidden"]) is False++ def test_patch_hidden_alone_is_accepted(self):+ resp = self.auth_client.patch("/api/sessions/s1", json={"hidden": True})+ assert resp.status_code == 200