The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(wake-word): enforce single-owner lifecycle
Omid Saadat5839aad13dbf
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.tsindex 1223f1bbd57..0709b3d02ee 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts@@ -147,30 +147,32 @@ export function useComposerVoice({)useEffect(() => {- if (- target === 'main' &&- !disabled &&- takeVoiceConversationStart(voiceStartRequest) &&- !voiceConversationActive- ) {+ if (target === 'main' && !disabled && takeVoiceConversationStart(voiceStartRequest) && !voiceConversationActive) {setVoiceConversationActive(true)}}, [disabled, target, voiceConversationActive, voiceStartRequest])const wakePausedRef = useRef(false)+const resumeWakeIfPaused = useCallback(() => {if (!wakePausedRef.current) {return}wakePausedRef.current = false- void $gateway.get()?.request('wake.resume', {}).catch(() => undefined)+ void $gateway+ .get()+ ?.request('wake.resume', {})+ .catch(() => undefined)}, [])useEffect(() => {if (voiceConversationActive) {wakePausedRef.current = true- void $gateway.get()?.request('wake.pause', {}).catch(() => undefined)+ void $gateway+ .get()+ ?.request('wake.pause', {})+ .catch(() => undefined)} else {resumeWakeIfPaused()}diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 9bd6db5d80b..a8359290af2 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -30,6 +30,7 @@ import { sessionMessagesSignature } from '@/lib/session-signatures'import { isMessagingSource } from '@/lib/session-source'import { latestSessionTodos } from '@/lib/todos'import { $billingSettingsRequest } from '@/store/billing-block'+import { requestVoiceConversationStart } from '@/store/composer'import { setCronFocusJobId } from '@/store/cron'import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'import { $previewTarget } from '@/store/preview'@@ -662,9 +663,22 @@ export function ContribWiring({ children }: { children: ReactNode }) {const handleGatewayEventWithPlugins = useCallback((event: Parameters<typeof handleDesktopGatewayEvent>[0]) => {emitGatewayEvent(event)++ if (event.type === 'wake.detected') {+ const payload = event.payload as { start_new_session?: boolean } | undefined++ if (payload?.start_new_session !== false) {+ startFreshSessionDraft()+ }++ requestVoiceConversationStart()++ return+ }+handleDesktopGatewayEvent(event)},- [handleDesktopGatewayEvent]+ [handleDesktopGatewayEvent, startFreshSessionDraft])useGatewayBoot({@@ -685,6 +699,12 @@ export function ContribWiring({ children }: { children: ReactNode }) {refreshSessions})+ useEffect(() => {+ if (gatewayState === 'open') {+ void requestGateway('wake.start', { surface: 'gui' }).catch(() => undefined)+ }+ }, [gatewayState, requestGateway])+// Only the open messaging transcript needs its own poll — local chats are// live over the websocket already.const activeIsMessaging =diff --git a/apps/desktop/src/app/desktop-controller.tsx b/apps/desktop/src/app/desktop-controller.tsxdeleted file mode 100644index fb4589bdadb..00000000000--- a/apps/desktop/src/app/desktop-controller.tsx+++ /dev/null@@ -1,1449 +0,0 @@-import { useStore } from '@nanostores/react'-import { useQueryClient } from '@tanstack/react-query'-import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from 'react'-import { Navigate, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom'--import { BootFailureOverlay } from '@/components/boot-failure-overlay'-import { DesktopInstallOverlay } from '@/components/desktop-install-overlay'-import { DesktopOnboardingOverlay } from '@/components/desktop-onboarding-overlay'-import { GatewayConnectingOverlay } from '@/components/gateway-connecting-overlay'-import { Pane, PaneMain } from '@/components/pane-shell'-import { RemoteDisplayBanner } from '@/components/remote-display-banner'-import { useMediaQuery } from '@/hooks/use-media-query'-import { cn } from '@/lib/utils'-import { useSkinCommand } from '@/themes/use-skin-command'--import { formatRefValue } from '../components/assistant-ui/directive-text'-import { getCronJobs, getSessionMessages, listAllProfileSessions, type SessionInfo, triggerCronJob } from '../hermes'-import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '../lib/chat-messages'-import { storedSessionIdForNotification } from '../lib/session-ids'-import {- isMessagingSource,- LOCAL_SESSION_SOURCE_IDS,- MESSAGING_SESSION_SOURCE_IDS,- normalizeSessionSource-} from '../lib/session-source'-import { latestSessionTodos } from '../lib/todos'-import { setCronFocusJobId, setCronJobs } from '../store/cron'-import {- $fileBrowserOpen,- $panesFlipped,- $pinnedSessionIds,- $sessionsLimit,- bumpSessionsLimit,- FILE_BROWSER_DEFAULT_WIDTH,- FILE_BROWSER_MAX_WIDTH,- FILE_BROWSER_MIN_WIDTH,- pinSession,- PREVIEW_PANE_ID,- restoreWorktree,- setSidebarOverlayMounted,- SIDEBAR_DEFAULT_WIDTH,- SIDEBAR_MAX_WIDTH,- SIDEBAR_SESSIONS_PAGE_SIZE,- unpinSession-} from '../store/layout'-import { respondToApprovalAction } from '../store/native-notifications'-import { $paneOpen } from '../store/panes'-import { setPetActivity } from '../store/pet'-import { setPetScale } from '../store/pet-gallery'-import {- setPetOverlayOpenAppHandler,- setPetOverlayScaleHandler,- setPetOverlaySubmitHandler-} from '../store/pet-overlay'-import { requestVoiceConversationStart } from '../store/composer'-import { $filePreviewTarget, $previewTarget, closeActiveRightRailTab } from '../store/preview'-import {- $activeGatewayProfile,- $freshSessionRequest,- $profileScope,- ALL_PROFILES,- normalizeProfileKey,- refreshActiveProfile-} from '../store/profile'-import { $startWorkSessionRequest, followActiveSessionCwd, resolveNewSessionCwd } from '../store/projects'-import { $reviewOpen, REVIEW_PANE_ID } from '../store/review'-import {- $activeSessionId,- $attentionSessionIds,- $currentCwd,- $freshDraftReady,- $gatewayState,- $messages,- $messagingSessions,- $resumeExhaustedSessionId,- $resumeFailedSessionId,- $selectedStoredSessionId,- $sessions,- $workingSessionIds,- CRON_SECTION_LIMIT,- getRecentlySettledSessionIds,- getRememberedSessionId,- mergeSessionPage,- MESSAGING_SECTION_LIMIT,- sessionPinId,- setAwaitingResponse,- setBusy,- setCronSessions,- setCurrentBranch,- setCurrentCwd,- setCurrentModel,- setCurrentProvider,- setMessages,- setMessagingPlatformTotals,- setMessagingSessions,- setMessagingTruncated,- setRememberedSessionId,- setSessionProfileTotals,- setSessions,- setSessionsLoading,- setSessionsTotal-} from '../store/session'-import { onSessionsChanged } from '../store/session-sync'-import { clearSessionTodos, setSessionTodos, todoListActive } from '../store/todos'-import { openUpdatesWindow, startUpdatePoller, stopUpdatePoller } from '../store/updates'-import { isSecondaryWindow } from '../store/windows'--import { ChatView } from './chat'-import { requestComposerFocus, requestComposerInsert } from './chat/composer/focus'-import { useComposerActions } from './chat/hooks/use-composer-actions'-import {- ChatPreviewRail,- PREVIEW_RAIL_MAX_WIDTH,- PREVIEW_RAIL_MIN_WIDTH,- PREVIEW_RAIL_PANE_WIDTH-} from './chat/right-rail'-import { ChatSidebar } from './chat/sidebar'-import { CommandPalette } from './command-palette'-import { useGatewayBoot } from './gateway/hooks/use-gateway-boot'-import { useGatewayRequest } from './gateway/hooks/use-gateway-request'-import { useKeybinds } from './hooks/use-keybinds'-import { SIDEBAR_COLLAPSE_MEDIA_QUERY } from './layout-constants'-import { ModelPickerOverlay } from './model-picker-overlay'-import { ModelVisibilityOverlay } from './model-visibility-overlay'-import { PetGenerateOverlay } from './pet-generate/pet-generate-overlay'-import { RightSidebarPane } from './right-sidebar'-import { FileActionDialogs } from './right-sidebar/file-actions'-import { ReviewPane } from './right-sidebar/review'-import { $terminalTakeover } from './right-sidebar/store'-import { PersistentTerminal, TerminalSlot } from './right-sidebar/terminal/persistent'-import { CRON_ROUTE, NEW_CHAT_ROUTE, routeSessionId, sessionRoute, SETTINGS_ROUTE } from './routes'-import { SessionPickerOverlay } from './session-picker-overlay'-import { SessionSwitcher } from './session-switcher'-import { useContextSuggestions } from './session/hooks/use-context-suggestions'-import { useCwdActions } from './session/hooks/use-cwd-actions'-import { useHermesConfig } from './session/hooks/use-hermes-config'-import { useMessageStream } from './session/hooks/use-message-stream'-import { useModelControls } from './session/hooks/use-model-controls'-import { usePreviewRouting } from './session/hooks/use-preview-routing'-import { usePromptActions } from './session/hooks/use-prompt-actions'-import { useRouteResume } from './session/hooks/use-route-resume'-import { useSessionActions } from './session/hooks/use-session-actions'-import { useSessionStateCache } from './session/hooks/use-session-state-cache'-import { AppShell } from './shell/app-shell'-import { useOverlayRouting } from './shell/hooks/use-overlay-routing'-import { useStatusSnapshot } from './shell/hooks/use-status-snapshot'-import { useStatusbarItems } from './shell/hooks/use-statusbar-items'-import { ModelMenuPanel } from './shell/model-menu-panel'-import type { StatusbarItem } from './shell/statusbar-controls'-import type { TitlebarTool } from './shell/titlebar-controls'-import { useGroupRegistry } from './shell/use-group-registry'-import { UpdatesOverlay } from './updates-overlay'--const AgentsView = lazy(async () => ({ default: (await import('./agents')).AgentsView }))-const ArtifactsView = lazy(async () => ({ default: (await import('./artifacts')).ArtifactsView }))-const CommandCenterView = lazy(async () => ({ default: (await import('./command-center')).CommandCenterView }))-const CronView = lazy(async () => ({ default: (await import('./cron')).CronView }))-const MessagingView = lazy(async () => ({ default: (await import('./messaging')).MessagingView }))-const ProfilesView = lazy(async () => ({ default: (await import('./profiles')).ProfilesView }))-const SettingsView = lazy(async () => ({ default: (await import('./settings')).SettingsView }))-const SkillsView = lazy(async () => ({ default: (await import('./skills')).SkillsView }))--// Latest cron-job sessions surfaced in the collapsed "Cron jobs" section. The-// Cron sessions are written by a background scheduler tick (the desktop-// backend), so no user action signals the UI. Poll the bounded cron list on-// this cadence while the app is open + visible so new runs surface promptly-// instead of waiting for the next user-triggered refreshSessions().-const CRON_POLL_INTERVAL_MS = 30_000-// The recents list is local-only: cron rows have their own section, and each-// messaging platform (telegram, discord, …) is fetched separately into its own-// self-managed sidebar section (refreshMessagingSessions). Excluding both here-// keeps "Load more" paging through interactive local chats instead of-// interleaving gateway threads that bury them.-const SIDEBAR_EXCLUDED_SOURCES = ['cron', 'subagent', 'tool', ...MESSAGING_SESSION_SOURCE_IDS]-// The messaging slice is the inverse: drop cron + every local source so only-// external-platform conversations remain, then split per platform in the UI.-const MESSAGING_EXCLUDED_SOURCES = ['cron', ...LOCAL_SESSION_SOURCE_IDS]--// Cheap signature compare so the poll only swaps the atom (and re-renders the-// sidebar) when the visible cron rows actually changed.-function sameCronSignature(a: SessionInfo[], b: SessionInfo[]): boolean {- if (a.length !== b.length) {- return false- }-- return a.every((session, i) => session.id === b[i]?.id && session.title === b[i]?.title)-}--// Rows a session refresh must preserve even if the aggregator omits them:-// in-flight first turns (message_count 0), pinned rows aged off the page, the-// actively-viewed chat (its "working" flag clears a beat before the aggregator-// sees the persisted row), and sessions whose turn just settled (same race, but-// for a chat the user has already navigated away from). Pass `scope` to only-// keep the active row when it belongs to the profile being paged.-function sessionsToKeep(scope?: string): Set<string> {- const keep = new Set<string>([- ...$workingSessionIds.get(),- ...$pinnedSessionIds.get(),- ...getRecentlySettledSessionIds()- ])-- const active = $selectedStoredSessionId.get()-- if (active) {- const session = scope ? $sessions.get().find(s => s.id === active) : null-- if (!scope || !session || normalizeProfileKey(session.profile) === scope) {- keep.add(active)- }- }-- return keep-}--export function DesktopController() {- const queryClient = useQueryClient()- const location = useLocation()- const navigate = useNavigate()-- const busyRef = useRef(false)- const creatingSessionRef = useRef(false)- const refreshSessionsRequestRef = useRef(0)-- const gatewayState = useStore($gatewayState)- const activeSessionId = useStore($activeSessionId)- const currentCwd = useStore($currentCwd)- const freshDraftReady = useStore($freshDraftReady)- const resumeFailedSessionId = useStore($resumeFailedSessionId)- const resumeExhaustedSessionId = useStore($resumeExhaustedSessionId)- const filePreviewTarget = useStore($filePreviewTarget)- const previewTarget = useStore($previewTarget)- const selectedStoredSessionId = useStore($selectedStoredSessionId)- const terminalTakeover = useStore($terminalTakeover)- const reviewOpen = useStore($reviewOpen)- const fileBrowserOpen = useStore($fileBrowserOpen)- const previewPaneOpen = useStore($paneOpen(PREVIEW_PANE_ID))- const panesFlipped = useStore($panesFlipped)- const profileScope = useStore($profileScope)- // Below SIDEBAR_COLLAPSE_BREAKPOINT_PX there's no room for a docked rail —- // collapse both sidebars (without touching their stored open state) so the- // hover-reveal overlay becomes the way in. Restores once it's wide again.- const narrowViewport = useMediaQuery(SIDEBAR_COLLAPSE_MEDIA_QUERY)-- const routedSessionId = routeSessionId(location.pathname)- const routeToken = `${location.pathname}:${location.search}:${location.hash}`- const routeTokenRef = useRef(routeToken)- routeTokenRef.current = routeToken- const getRouteToken = useCallback(() => routeTokenRef.current, [])-- const {- agentsOpen,- chatOpen,- closeOverlayToPreviousRoute,- commandCenterInitialSection,- commandCenterOpen,- cronOpen,- currentView,- openAgents,- openCommandCenterSection,- profilesOpen,- settingsOpen,- toggleCommandCenter- } = useOverlayRouting()-- const terminalSidebarOpen = chatOpen && terminalTakeover-- const titlebarToolGroups = useGroupRegistry<TitlebarTool>()- const statusbarItemGroups = useGroupRegistry<StatusbarItem>()- const setTitlebarToolGroup = titlebarToolGroups.set- const setStatusbarItemGroup = statusbarItemGroups.set-- const {- activeSessionIdRef,- ensureSessionState,- runtimeIdByStoredSessionIdRef,- selectedStoredSessionIdRef,- sessionStateByRuntimeIdRef,- syncSessionStateToView,- updateSessionState- } = useSessionStateCache({- activeSessionId,- busyRef,- selectedStoredSessionId,- setAwaitingResponse,- setBusy,- setMessages- })-- const { connectionRef, gatewayRef, requestGateway } = useGatewayRequest()-- useEffect(() => {- window.hermesDesktop?.setPreviewShortcutActive?.(Boolean(chatOpen && (filePreviewTarget || previewTarget)))- }, [chatOpen, filePreviewTarget, previewTarget])-- useEffect(() => {- startUpdatePoller()- const unsubscribe = window.hermesDesktop?.onOpenUpdatesRequested?.(() => openUpdatesWindow())-- return () => {- unsubscribe?.()- stopUpdatePoller()- }- }, [])-- // Remember the open chat so a relaunch reopens it instead of an empty new-chat.- useEffect(() => {- if (routedSessionId) {- setRememberedSessionId(routedSessionId)- }- }, [routedSessionId])-- // Restore that chat once, on cold start only (we're at the new-chat route and- // haven't navigated yet). A dead/deleted id self-clears via the exhausted latch- // below, so we never boot-loop into an error screen.- const restoredLastSessionRef = useRef(false)- useEffect(() => {- if (restoredLastSessionRef.current) {- return- }-- restoredLastSessionRef.current = true- const last = getRememberedSessionId()-- if (last && location.pathname === NEW_CHAT_ROUTE) {- navigate(sessionRoute(last), { replace: true })- }- }, [location.pathname, navigate])-- useEffect(() => {- if (resumeExhaustedSessionId && getRememberedSessionId() === resumeExhaustedSessionId) {- setRememberedSessionId(null)- }- }, [resumeExhaustedSessionId])-- // Notification click: the main process already focused the window; jump to its- // session. Notifications are tagged with the gateway *runtime* session id, but- // the chat route is keyed by the *stored* id — navigating with the runtime id- // resumes a non-existent stored session ("session not found") and strands the- // user. Translate runtime -> stored before navigating.- useEffect(() => {- const unsubscribe = window.hermesDesktop?.onFocusSession?.(sessionId => {- if (sessionId) {- navigate(sessionRoute(storedSessionIdForNotification(sessionId, runtimeIdByStoredSessionIdRef.current)))- }- })-- return () => unsubscribe?.()- }, [navigate, runtimeIdByStoredSessionIdRef])-- // Notification action button (Approve/Reject) — resolve in place, no navigation.- useEffect(() => {- const unsubscribe = window.hermesDesktop?.onNotificationAction?.(({ actionId, sessionId }) => {- void respondToApprovalAction(sessionId ?? null, actionId)- })-- return () => unsubscribe?.()- }, [])-- // hermes:// deep links (e.g. a docs "Send to App" button for an automation blueprint).- // Build the equivalent /blueprint slash command from the payload and drop- // it into the composer — the user reviews/edits, then sends; the agent (or- // the shared command handler) creates the job. Signal readiness so a link- // that arrived during boot is flushed exactly once.- useEffect(() => {- const unsubscribe = window.hermesDesktop?.onDeepLink?.(payload => {- if (!payload || payload.kind !== 'blueprint' || !payload.name) {- return- }-- const slots = Object.entries(payload.params || {})- .map(([k, v]) => {- const sval = /\s/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v-- return `${k}=${sval}`- })- .join(' ')-- const command = `/blueprint ${payload.name}${slots ? ' ' + slots : ''}`- requestComposerInsert(command, { mode: 'block', target: 'main' })- requestComposerFocus('main')- })-- // Tell the main process the renderer is ready to receive deep links.- void window.hermesDesktop?.signalDeepLinkReady?.()-- return () => unsubscribe?.()- }, [])-- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- if (!$filePreviewTarget.get() && !$previewTarget.get()) {- return- }-- if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'w') {- event.preventDefault()- event.stopPropagation()- closeActiveRightRailTab()- }- }-- const unsubscribe = window.hermesDesktop?.onClosePreviewRequested?.(closeActiveRightRailTab)-- window.addEventListener('keydown', onKeyDown, { capture: true })-- return () => {- unsubscribe?.()- window.removeEventListener('keydown', onKeyDown, { capture: true })- }- }, [])-- // Cron-job sessions as their own list (latest N). Independent of the recents- // page so the two never compete for slots. Cheap + bounded. Kept (even though- // the sidebar now lists cron *jobs*, not run sessions) so a pinned cron run- // still resolves into the Pinned section via sessionByAnyId.- const refreshCronSessions = useCallback(async () => {- try {- const { sessions } = await listAllProfileSessions(CRON_SECTION_LIMIT, 1, 'exclude', 'recent', 'all', {- source: 'cron'- })-- setCronSessions(prev => (sameCronSignature(prev, sessions) ? prev : sessions))- } catch {- // Non-fatal: the cron section just stays empty/stale.- }- }, [])-- // Messaging-platform sessions as their own slice, fetched separately from- // local recents so each platform renders a self-managed section and never- // competes with local chats for the recents page budget. One combined fetch- // seeds every platform; the sidebar splits the rows per source.- const refreshMessagingSessions = useCallback(async () => {- try {- const result = await listAllProfileSessions(MESSAGING_SECTION_LIMIT, 1, 'exclude', 'recent', 'all', {- excludeSources: MESSAGING_EXCLUDED_SOURCES- })-- // Drop any non-messaging source the broad exclude didn't catch (custom- // sources) — those stay in local recents, not a platform section.- const rows = result.sessions.filter(s => isMessagingSource(s.source))-- setMessagingSessions(prev => (sameCronSignature(prev, rows) ? prev : rows))- // Hit the cap → at least one platform may have more on disk than loaded,- // so platform sections offer their own per-platform "load more".- setMessagingTruncated(result.sessions.length >= MESSAGING_SECTION_LIMIT)- } catch {- // Non-fatal: the messaging sections just stay empty/stale.- }- }, [])-- // Page a single platform's section independently (mirrors the per-profile- // pager): fetch that source's next window and merge it back in place, leaving- // every other platform's rows untouched. Resolves the platform's exact total.- const loadMoreMessagingForPlatform = useCallback(async (platform: string) => {- const inPlatform = (s: SessionInfo) => normalizeSessionSource(s.source) === platform- const loaded = $messagingSessions.get().filter(inPlatform).length-- const result = await listAllProfileSessions(loaded + SIDEBAR_SESSIONS_PAGE_SIZE, 1, 'exclude', 'recent', 'all', {- source: platform- })-- const incoming = result.sessions.filter(s => normalizeSessionSource(s.source) === platform)-- setMessagingSessions(prev => [- ...prev.filter(s => !inPlatform(s)),- ...mergeSessionPage(prev.filter(inPlatform), incoming, sessionsToKeep())- ])-- const total = result.total ?? incoming.length- setMessagingPlatformTotals(prev => ({ ...prev, [platform]: Math.max(total, incoming.length) }))- }, [])-- // Cron *jobs* drive the sidebar "Cron jobs" section. Jobs are created- // synchronously (agent tool call or the cron UI), so refreshing here right- // after an agent turn surfaces a new job immediately; the interval poll keeps- // next-run/state fresh as the scheduler advances them.- const refreshCronJobs = useCallback(async () => {- try {- const jobs = await getCronJobs()-- setCronJobs(jobs)- } catch {- // Non-fatal: the cron section just keeps its last-known jobs.- }- }, [])-- const refreshSessions = useCallback(async () => {- const requestId = refreshSessionsRequestRef.current + 1- refreshSessionsRequestRef.current = requestId- setSessionsLoading(true)-- try {- const limit = $sessionsLimit.get()-- // Require at least one message so abandoned/empty "Untitled" drafts (one- // was created per TUI/desktop launch before the lazy-create fix) don't- // clutter the sidebar.- // Unified cross-profile list (served read-only off each profile's- // state.db; no per-profile backend is spawned). Single-profile users get- // the same rows tagged profile="default". Cron sessions are excluded here- // and fetched separately (refreshCronSessions) so the scheduler's- // always-newest rows can't consume the recents page budget.- // Scope the fetch to the active profile (not always 'all') so a profile- // with few recent sessions isn't windowed out of the cross-profile- // recency page — the empty-history-on-profile-switch bug.- const sessionProfile = profileScope === ALL_PROFILES ? 'all' : profileScope-- const result = await listAllProfileSessions(limit, 1, 'exclude', 'recent', sessionProfile, {- excludeSources: SIDEBAR_EXCLUDED_SOURCES- })-- if (refreshSessionsRequestRef.current === requestId) {- setSessions(prev => mergeSessionPage(prev, result.sessions, sessionsToKeep()))- setSessionsTotal(typeof result.total === 'number' ? result.total : result.sessions.length)- setSessionProfileTotals(result.profile_totals ?? {})- }- } finally {- if (refreshSessionsRequestRef.current === requestId) {- setSessionsLoading(false)- }- }-- void refreshCronSessions()- void refreshCronJobs()- void refreshMessagingSessions()- }, [profileScope, refreshCronSessions, refreshCronJobs, refreshMessagingSessions])-- const loadMoreSessions = useCallback(async () => {- bumpSessionsLimit()- await refreshSessions()- }, [refreshSessions])-- // Another window mutated the shared session list (e.g. a chat started in the- // pop-out). Re-pull so the sidebar reflects it. Pop-outs have no sidebar, so- // only real windows bother.- useEffect(() => {- if (isSecondaryWindow()) {- return- }-- return onSessionsChanged(() => void refreshSessions().catch(() => undefined))- }, [refreshSessions])-- // ALL-profiles view pages one profile at a time: fetch that profile's next- // page and merge it in place, leaving every other profile's rows untouched.- const loadMoreSessionsForProfile = useCallback(async (profile: string) => {- const key = normalizeProfileKey(profile)- const inKey = (s: SessionInfo) => normalizeProfileKey(s.profile) === key- const loaded = $sessions.get().filter(inKey).length-- const result = await listAllProfileSessions(loaded + SIDEBAR_SESSIONS_PAGE_SIZE, 1, 'exclude', 'recent', key, {- excludeSources: SIDEBAR_EXCLUDED_SOURCES- })-- const keep = sessionsToKeep(key)-- setSessions(prev => [- ...prev.filter(s => !inKey(s)),- ...mergeSessionPage(prev.filter(inKey), result.sessions, keep)- ])-- const total = result.profile_totals?.[key] ?? result.total ?? result.sessions.length- setSessionProfileTotals(prev => ({ ...prev, [key]: Math.max(total, result.sessions.length) }))- }, [])-- const toggleSelectedPin = useCallback(() => {- const sessionId = $selectedStoredSessionId.get()-- if (!sessionId) {- return- }-- // Pin on the durable lineage-root id so the pin survives auto-compression.- const session = $sessions.get().find(s => s.id === sessionId || s._lineage_root_id === sessionId)- const pinId = session ? sessionPinId(session) : sessionId-- if ($pinnedSessionIds.get().includes(pinId)) {- unpinSession(pinId)- } else {- pinSession(pinId)- }- }, [])-- const { gatewayLogLines, inferenceStatus, statusSnapshot } = useStatusSnapshot(gatewayState, requestGateway)-- const updateActiveSessionRuntimeInfo = useCallback(- (info: { branch?: string; cwd?: string }) => {- const sessionId = activeSessionIdRef.current-- if (!sessionId) {- return- }-- updateSessionState(sessionId, state => ({- ...state,- branch: info.branch ?? state.branch,- cwd: info.cwd ?? state.cwd- }))- },- [activeSessionIdRef, updateSessionState]- )-- const { refreshProjectBranch } = useCwdActions({- activeSessionId,- activeSessionIdRef,- onSessionRuntimeInfo: updateActiveSessionRuntimeInfo,- requestGateway- })-- const { refreshHermesConfig, sttEnabled, voiceMaxRecordingSeconds } = useHermesConfig({- activeSessionIdRef,- refreshProjectBranch- })-- const { refreshCurrentModel, selectModel, updateModelOptionsCache } = useModelControls({- activeSessionId,- queryClient,- requestGateway- })-- const openProviderSettings = useCallback(() => {- navigate(`${SETTINGS_ROUTE}?tab=providers`)- }, [navigate])-- const modelMenuContent = useMemo(- () =>- gatewayState === 'open' ? (- <ModelMenuPanel- gateway={gatewayRef.current || undefined}- onSelectModel={selectModel}- requestGateway={requestGateway}- />- ) : null,- [gatewayRef, gatewayState, requestGateway, selectModel]- )-- useContextSuggestions({- activeSessionId,- activeSessionIdRef,- currentCwd,- gatewayState,- requestGateway- })-- const hydrateFromStoredSession = useCallback(- async (- attempts = 1,- storedSessionId = selectedStoredSessionIdRef.current,- runtimeSessionId = activeSessionIdRef.current- ) => {- if (!storedSessionId || !runtimeSessionId) {- return- }-- const storedProfile = $sessions- .get()- .find(session => session.id === storedSessionId || session._lineage_root_id === storedSessionId)?.profile-- for (let index = 0; index < Math.max(1, attempts); index += 1) {- try {- const latest = await getSessionMessages(storedSessionId, storedProfile)- const messages = toChatMessages(latest.messages)- updateSessionState(- runtimeSessionId,- state => ({- ...state,- messages: preserveLocalAssistantErrors(messages, state.messages)- }),- storedSessionId- )-- // Seed the status stack's todo group from history — but only while- // the plan is still in flight, so reopening an old chat doesn't pin- // its finished todo list above the composer forever.- const todos = latestSessionTodos(messages)-- if (todos && todoListActive(todos)) {- setSessionTodos(runtimeSessionId, todos)- } else {- clearSessionTodos(runtimeSessionId)- }-- return- } catch {- // Best-effort fallback when live stream payloads are empty.- }-- if (index < attempts - 1) {- await new Promise(resolve => window.setTimeout(resolve, 250))- }- }- },- [activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState]- )-- const { handleGatewayEvent } = useMessageStream({- activeSessionIdRef,- hydrateFromStoredSession,- queryClient,- refreshHermesConfig,- refreshSessions,- sessionStateByRuntimeIdRef,- updateSessionState- })-- const { handleDesktopGatewayEvent, restartPreviewServer } = usePreviewRouting({- activeSessionIdRef,- baseHandleGatewayEvent: handleGatewayEvent,- currentCwd,- currentView,- requestGateway,- routedSessionId,- selectedStoredSessionId- })-- const {- archiveSession,- branchCurrentSession,- branchStoredSession,- createBackendSessionForSend,- openSettings,- removeSession,- resumeSession,- selectSidebarItem,- startFreshSessionDraft- } = useSessionActions({- activeSessionId,- activeSessionIdRef,- busyRef,- creatingSessionRef,- ensureSessionState,- getRouteToken,- navigate,- requestGateway,- runtimeIdByStoredSessionIdRef,- selectedStoredSessionId,- selectedStoredSessionIdRef,- sessionStateByRuntimeIdRef,- syncSessionStateToView,- updateSessionState- })-- // "Hey Hermes": handle the wake event on the canonical onEvent pipeline (the- // path every gateway socket already feeds), not a side-registered listener —- // open a fresh session and begin back-and-forth voice.- const handleGatewayEventWithWake = useCallback(- (event: Parameters<typeof handleDesktopGatewayEvent>[0]) => {- if (event.type === 'wake.detected') {- const payload = event.payload as { start_new_session?: boolean } | undefined- if (payload?.start_new_session !== false) {- startFreshSessionDraft()- }- requestVoiceConversationStart()- return- }- handleDesktopGatewayEvent(event)- },- [handleDesktopGatewayEvent, startFreshSessionDraft]- )-- // Single global listener for every rebindable hotkey (incl. profile switching)- // plus the on-screen keybind editor's capture mode.- useKeybinds({- startFreshSession: startFreshSessionDraft,- toggleCommandCenter,- toggleSelectedPin- })-- // A profile switch/create drops to a fresh new-session draft so the previously- // open session doesn't bleed across contexts. Skip the initial value.- const freshSessionRequest = useStore($freshSessionRequest)- const lastFreshRef = useRef(freshSessionRequest)-- useEffect(() => {- if (freshSessionRequest === lastFreshRef.current) {- return- }-- lastFreshRef.current = freshSessionRequest- startFreshSessionDraft()- }, [freshSessionRequest, startFreshSessionDraft])-- // Swapping the live gateway to another profile must re-pull that profile's- // global model + active-profile pill. Both are nanostores, so the blanket- // invalidateQueries() the profile store fires on swap doesn't touch them —- // without this the statusbar keeps showing the previous profile's model- // (the "forgets the LLM setting" report). gatewayState stays 'open' across a- // swap (background sockets persist), so the open→open effect won't re-run.- const activeGatewayProfile = useStore($activeGatewayProfile)- const lastGatewayProfileRef = useRef(activeGatewayProfile)-- useEffect(() => {- if (activeGatewayProfile === lastGatewayProfileRef.current) {- return- }-- lastGatewayProfileRef.current = activeGatewayProfile- // Force: the new profile has its own default, so reseed even if the composer- // already shows the previous profile's model.- void refreshCurrentModel(true)- void refreshActiveProfile()- }, [activeGatewayProfile, refreshCurrentModel])-- const composer = useComposerActions({- activeSessionId,- currentCwd,- requestGateway- })-- const branchInNewChat = useCallback(- async (messageId?: string) => {- const branched = await branchCurrentSession(messageId)-- if (branched) {- await refreshSessions().catch(() => undefined)- }-- return branched- },- [branchCurrentSession, refreshSessions]- )-- // Clear a failed turn's red error banner from the transcript. Errors are- // renderer-local state (never persisted), so dismissing is purely a view +- // session-cache edit. A message that errored before emitting any visible- // text is a bare error placeholder → drop it entirely; one that streamed- // partial output then failed keeps its content and just sheds the error.- // Both the per-runtime cache AND the live $messages view must be updated:- // `preserveLocalAssistantErrors` re-grafts any still-errored message it- // finds in the view onto the next session.info flush, so clearing only the- // cache would let the heartbeat resurrect the banner.- const dismissError = useCallback(- (messageId: string) => {- const runtimeSessionId = activeSessionIdRef.current-- if (!runtimeSessionId) {- return- }-- const clearErrorIn = (messages: ChatMessage[]): ChatMessage[] =>- messages.flatMap(message => {- if (message.id !== messageId || !message.error) {- return [message]- }-- if (!chatMessageText(message).trim() && !message.parts.some(part => part.type !== 'text')) {- return []- }-- return [{ ...message, error: undefined, pending: false }]- })-- // View first: the flush below reads $messages as the "current" baseline- // for error preservation, so the banner must be gone from it before the- // cache update triggers a re-sync.- setMessages(clearErrorIn($messages.get()))-- updateSessionState(runtimeSessionId, state => ({- ...state,- messages: clearErrorIn(state.messages)- }))- },- [activeSessionIdRef, updateSessionState]- )-- const startSessionInWorkspace = useCallback(- (path: null | string) => {- startFreshSessionDraft()-- // A worktree lane carries its own path; the trunk "+" can be path-less (the- // main checkout is implicit), so fall back to the active project's root- // instead of no-op'ing on null — that was "+ on main does nothing".- const target = path?.trim() || resolveNewSessionCwd()-- if (!target) {- return- }-- // The next message creates the backend session in $currentCwd, so seed- // it (and the branch) from the workspace the user clicked the + on.- setCurrentCwd(target)- void requestGateway<{ branch?: string; cwd?: string }>('config.get', { key: 'project', cwd: target })- .then(info => {- const resolved = info.cwd || target-- setCurrentCwd(resolved)- setCurrentBranch(info.branch || '')-- // An EXPLICIT target (a worktree/lane path — e.g. just-created via- // "convert a branch" / "new worktree") drills the sidebar into that- // project so the new lane is visible at once. Without this, a brand-new- // worktree session is invisible from the all-projects overview (the- // live overlay skips `.worktrees` rows, and the session.info cwd-follow- // only fires on a same-session move, not a fresh session). The- // path-less trunk "+" keeps the current scope untouched.- if (path?.trim()) {- restoreWorktree(resolved)- void followActiveSessionCwd(resolved)- }- })- .catch(() => undefined)- },- [requestGateway, startFreshSessionDraft]- )-- // Composer "branch off into a new worktree": the composer already created the- // worktree and cleared its draft; open a fresh session anchored to that tree,- // then prefill the task that kicked it off. startSessionInWorkspace owns the- // reset+cwd seed (it runs startFreshSessionDraft, which would otherwise stomp- // the cwd back to the default), so the prefill is dispatched right after — its- // deferred event lands once the fresh composer has remounted and rebound.- const startWorkSessionRequest = useStore($startWorkSessionRequest)- const lastStartWorkTokenRef = useRef(startWorkSessionRequest?.token ?? 0)-- useEffect(() => {- if (!startWorkSessionRequest || startWorkSessionRequest.token === lastStartWorkTokenRef.current) {- return- }-- lastStartWorkTokenRef.current = startWorkSessionRequest.token- startSessionInWorkspace(startWorkSessionRequest.path)-- if (startWorkSessionRequest.draft) {- requestComposerInsert(startWorkSessionRequest.draft, { target: 'main' })- }- }, [startSessionInWorkspace, startWorkSessionRequest])-- const handleSkinCommand = useSkinCommand()-- const {- cancelRun,- editMessage,- handleThreadMessagesChange,- reloadFromMessage,- restoreToMessage,- steerPrompt,- submitText,- transcribeVoiceAudio- } = usePromptActions({- activeSessionId,- activeSessionIdRef,- branchCurrentSession: branchInNewChat,- busyRef,- createBackendSessionForSend,- handleSkinCommand,- refreshSessions,- requestGateway,- resumeStoredSession: resumeSession,- selectedStoredSessionIdRef,- startFreshSessionDraft,- sttEnabled,- updateSessionState- })-- // The popped-out pet drives two actions back into the app: send a prompt, and- // open the most recent thread. Both are registered ONCE through refs that track- // the latest callbacks — re-registering on every `submitText`/`resumeSession`- // identity change left a brief window where the handler was nulled (cleanup- // before re-register), which could drop a submit fired from the overlay (e.g.- // creating a session from the new-session screen). The ref form keeps a stable,- // always-current handler. Primary window only — it owns the overlay.- const submitTextRef = useRef(submitText)- submitTextRef.current = submitText- const resumeSessionRef = useRef(resumeSession)- resumeSessionRef.current = resumeSession- const requestGatewayRef = useRef(requestGateway)- requestGatewayRef.current = requestGateway-- useEffect(() => {- if (isSecondaryWindow()) {- return- }-- setPetOverlaySubmitHandler(text => void submitTextRef.current(text))- // Alt+wheel resize from the popped-out pet — persist it through this- // window's gateway (the overlay has none) so it survives restart.- setPetOverlayScaleHandler(scale => setPetScale(requestGatewayRef.current, scale))- // Mail icon: $sessions is ordered most-recent-first; the pet is global (not- // per session) so "most recent" is the right target. main.cjs already raised- // the window before forwarding this.- setPetOverlayOpenAppHandler(() => {- const recent = $sessions.get()[0]-- if (recent?.id) {- void resumeSessionRef.current(recent.id)- }- })-- return () => {- setPetOverlaySubmitHandler(null)- setPetOverlayOpenAppHandler(null)- setPetOverlayScaleHandler(null)- }- }, [])-- // Mirror "a session is blocked on the user" (clarify/approval) into the pet's- // awaitingInput flag so it shows the `waiting` pose. Lives on $petActivity so- // it rides the same atom the pop-out overlay mirrors — no session list needed- // there. Every window keeps its own in-window pet in sync.- useEffect(() => {- const sync = () => setPetActivity({ awaitingInput: $attentionSessionIds.get().length > 0 })-- sync()-- return $attentionSessionIds.listen(sync)- }, [])-- useGatewayBoot({- handleGatewayEvent: handleGatewayEventWithWake,- onConnectionReady: c => {- connectionRef.current = c- },- onGatewayReady: g => {- gatewayRef.current = g- },- refreshHermesConfig,- refreshSessions- })-- useEffect(() => {- if (gatewayState === 'open') {- void refreshCurrentModel()- void refreshActiveProfile()- void refreshSessions().catch(() => undefined)- }- }, [gatewayState, refreshCurrentModel, refreshSessions])-- // "Hey Hermes" wake word: arm the server-side detector for this surface- // (gated on config). Detection arrives as a wake.detected event handled in- // handleGatewayEventWithWake. Idempotent server-side, so reconnects are safe.- useEffect(() => {- if (gatewayState !== 'open') {- return- }- void requestGateway('wake.start', { surface: 'gui' }).catch(() => undefined)- }, [gatewayState, requestGateway])-- // Keep the cron jobs section live without a user action: the scheduler ticks- // in the background (advancing next-run/state and creating runs), so poll the- // job list on an interval (and on tab re-focus) while connected.- useEffect(() => {- if (gatewayState !== 'open') {- return- }-- const tick = () => {- if (document.visibilityState === 'visible') {- void refreshCronJobs()- }- }-- const intervalId = window.setInterval(tick, CRON_POLL_INTERVAL_MS)- document.addEventListener('visibilitychange', tick)-- return () => {- window.clearInterval(intervalId)- document.removeEventListener('visibilitychange', tick)- }- }, [gatewayState, refreshCronJobs])-- useEffect(() => {- if (gatewayState === 'open' && !activeSessionId && freshDraftReady) {- void refreshCurrentModel()- void refreshHermesConfig()- }- }, [activeSessionId, freshDraftReady, gatewayState, refreshCurrentModel, refreshHermesConfig])-- useRouteResume({- activeSessionId,- activeSessionIdRef,- creatingSessionRef,- currentView,- freshDraftReady,- gatewayState,- locationPathname: location.pathname,- resumeSession,- resumeFailedSessionId,- resumeExhaustedSessionId,- routedSessionId,- runtimeIdByStoredSessionIdRef,- selectedStoredSessionId,- selectedStoredSessionIdRef,- startFreshSessionDraft- })-- const { leftStatusbarItems, statusbarItems } = useStatusbarItems({- agentsOpen,- chatOpen,- commandCenterOpen,- extraLeftItems: statusbarItemGroups.flat.left,- extraRightItems: statusbarItemGroups.flat.right,- gatewayLogLines,- gatewayState,- inferenceStatus,- openAgents,- freshDraftReady,- openCommandCenterSection,- requestGateway,- statusSnapshot,- toggleCommandCenter- })-- const sidebar = (- <ChatSidebar- currentView={currentView}- onArchiveSession={sessionId => void archiveSession(sessionId)}- onBranchSession={sessionId => void branchStoredSession(sessionId)}- onDeleteSession={sessionId => void removeSession(sessionId)}- onLoadMoreMessaging={loadMoreMessagingForPlatform}- onLoadMoreProfileSessions={loadMoreSessionsForProfile}- onLoadMoreSessions={loadMoreSessions}- onManageCronJob={jobId => {- setCronFocusJobId(jobId)- navigate(CRON_ROUTE)- }}- onNavigate={selectSidebarItem}- onNewSessionInWorkspace={startSessionInWorkspace}- onResumeSession={sessionId => navigate(sessionRoute(sessionId))}- onTriggerCronJob={jobId => {- void triggerCronJob(jobId)- .then(() => refreshCronJobs())- .catch(() => undefined)- }}- />- )-- // One PTY-backed terminal mounted forever; <TerminalSlot /> placeholders decide- // where it shows. Lives in main's stacking context (not the root overlay layer)- // so pane resize handles still paint above it. Toggling never rebuilds the shell.- const mainOverlays = (- <PersistentTerminal cwd={currentCwd} onAddSelectionToChat={composer.addTerminalSelectionAttachment} />- )-- const overlays = (- <>- <RemoteDisplayBanner />- {!isSecondaryWindow() && <DesktopInstallOverlay />}- {!isSecondaryWindow() && (- <DesktopOnboardingOverlay- enabled={gatewayState === 'open'}- onCompleted={() => {- void refreshHermesConfig()- void refreshCurrentModel()- void queryClient.invalidateQueries({ queryKey: ['model-options'] })- }}- requestGateway={requestGateway}- />- )}- <ModelPickerOverlay gateway={gatewayRef.current || undefined} onSelect={selectModel} />- <SessionPickerOverlay onResume={resumeSession} />- <ModelVisibilityOverlay gateway={gatewayRef.current || undefined} onOpenProviders={openProviderSettings} />- <UpdatesOverlay />- <GatewayConnectingOverlay />- <BootFailureOverlay />- <CommandPalette />- <PetGenerateOverlay />- <SessionSwitcher />- <FileActionDialogs />-- {settingsOpen && (- <Suspense fallback={null}>- <SettingsView- gateway={gatewayRef.current}- onClose={closeOverlayToPreviousRoute}- onConfigSaved={() => {- void refreshHermesConfig()- void refreshCurrentModel()- void queryClient.invalidateQueries({ queryKey: ['model-options'] })- }}- onMainModelChanged={(provider, model) => {- setCurrentProvider(provider)- setCurrentModel(model)- updateModelOptionsCache(provider, model, true)- void refreshCurrentModel()- void queryClient.invalidateQueries({ queryKey: ['model-options'] })- }}- />- </Suspense>- )}-- {commandCenterOpen && (- <Suspense fallback={null}>- <CommandCenterView- initialSection={commandCenterInitialSection}- onClose={closeOverlayToPreviousRoute}- onDeleteSession={removeSession}- onNavigateRoute={path => navigate(path)}- onOpenSession={sessionId => navigate(sessionRoute(sessionId))}- />- </Suspense>- )}-- {agentsOpen && (- <Suspense fallback={null}>- <AgentsView onClose={closeOverlayToPreviousRoute} />- </Suspense>- )}-- {cronOpen && (- <Suspense fallback={null}>- <CronView- onClose={closeOverlayToPreviousRoute}- onOpenSession={sessionId => navigate(sessionRoute(sessionId))}- />- </Suspense>- )}-- {profilesOpen && (- <Suspense fallback={null}>- <ProfilesView onClose={closeOverlayToPreviousRoute} />- </Suspense>- )}- </>- )-- const chatView = (- <ChatView- gateway={gatewayRef.current}- maxVoiceRecordingSeconds={voiceMaxRecordingSeconds}- modelMenuContent={modelMenuContent}- onAddContextRef={composer.addContextRefAttachment}- onAddUrl={url => composer.addContextRefAttachment(`@url:${formatRefValue(url)}`, url)}- onAttachDroppedItems={composer.attachDroppedItems}- onAttachImageBlob={composer.attachImageBlob}- onBranchInNewChat={branchInNewChat}- onCancel={cancelRun}- onDeleteSelectedSession={() => {- if (selectedStoredSessionId) {- void removeSession(selectedStoredSessionId)- }- }}- onDismissError={dismissError}- onEdit={editMessage}- onPasteClipboardImage={opts => composer.pasteClipboardImage(opts)}- onPickFiles={() => void composer.pickContextPaths('file')}- onPickFolders={() => void composer.pickContextPaths('folder')}- onPickImages={() => void composer.pickImages()}- onReload={reloadFromMessage}- onRemoveAttachment={id => void composer.removeAttachment(id)}- onRestoreToMessage={restoreToMessage}- onRetryResume={sessionId => void resumeSession(sessionId, true)}- onSteer={steerPrompt}- onSubmit={submitText}- onThreadMessagesChange={handleThreadMessagesChange}- onToggleSelectedPin={toggleSelectedPin}- onTranscribeAudio={transcribeVoiceAudio}- />- )-- // Flipped layout mirrors the default: sessions sidebar → right, file- // browser + preview rail → left. Same panes, swapped sides.- const sidebarSide = panesFlipped ? 'right' : 'left'- const railSide = panesFlipped ? 'left' : 'right'-- // Other sidebars docked as real columns on the terminal's rail. Force-collapsed- // hover-reveal overlays (narrow window) don't take a column, so they don't count.- const railColumnOpen =- (chatOpen && Boolean(previewTarget || filePreviewTarget) && previewPaneOpen) ||- (chatOpen && !narrowViewport && fileBrowserOpen) ||- (chatOpen && Boolean(currentCwd.trim()) && !narrowViewport && reviewOpen)-- // Once the terminal would share its rail with another sidebar, drop it to a- // full-width row beneath them rather than cramming in one more skinny column.- const terminalAsRow = terminalSidebarOpen && railColumnOpen-- const previewPane = (- <Pane- disabled={!chatOpen || (!previewTarget && !filePreviewTarget)}- id={PREVIEW_PANE_ID}- key="preview"- maxWidth={PREVIEW_RAIL_MAX_WIDTH}- minWidth={PREVIEW_RAIL_MIN_WIDTH}- resizable- side={railSide}- width={PREVIEW_RAIL_PANE_WIDTH}- >- {chatOpen ? (- <ChatPreviewRail onRestartServer={restartPreviewServer} setTitlebarToolGroup={setTitlebarToolGroup} />- ) : null}- </Pane>- )-- const fileBrowserPane = (- <Pane- defaultOpen={false}- disabled={!chatOpen}- forceCollapsed={narrowViewport}- hoverReveal- id="file-browser"- key="file-browser"- maxWidth={FILE_BROWSER_MAX_WIDTH}- minWidth={FILE_BROWSER_MIN_WIDTH}- resizable- side={railSide}- width={FILE_BROWSER_DEFAULT_WIDTH}- >- {/* Key on the project (cwd) so switching projects unmounts the old tree and- mounts a fresh one straight into its skeleton — no stale-then-blip. */}- <RightSidebarPane- key={currentCwd || 'no-cwd'}- onActivateFile={path => composer.insertContextPathInlineRef(path)}- onActivateFolder={path => composer.insertContextPathInlineRef(path, true)}- />- </Pane>- )-- const reviewPane = (- <Pane- defaultOpen- // The diff pane only makes sense in a workspace, so force it shut when the- // session is detached — "No diffs" then only ever shows inside a project,- // never as a second empty panel next to the file browser.- // Docked (wide): `reviewOpen` gates it. Narrow: drop `reviewOpen` from the- // gate so the pane stays mounted as a collapsed overlay — `toggleReview`- // then slides it in/out via the forced-reveal pin, exactly like ⌘B for the- // sidebar. Still requires a repo (no diffs to show otherwise).- disabled={!chatOpen || !currentCwd.trim() || (!narrowViewport && !reviewOpen)}- forceCollapsed={narrowViewport}- hoverReveal- id={REVIEW_PANE_ID}- key="review"- maxWidth={FILE_BROWSER_MAX_WIDTH}- minWidth={FILE_BROWSER_MIN_WIDTH}- // Mobile overlay sits at its min width — compact, doesn't bury the chat.- overlayWidth={FILE_BROWSER_MIN_WIDTH}- resizable- side={railSide}- width={FILE_BROWSER_DEFAULT_WIDTH}- >- <ReviewPane key={currentCwd || 'no-cwd'} />- </Pane>- )-- const terminalPane = (- <Pane- bottomRow={terminalAsRow}- defaultOpen- disabled={!terminalSidebarOpen}- divider- height="38vh"- id="terminal-sidebar"- key="terminal-sidebar"- maxHeight="80vh"- maxWidth="80vw"- minHeight="8rem"- minWidth="22vw"- resizable- side={railSide}- width="42vw"- >- {/* As a column the terminal clears the titlebar; as a bottom row it sits- below the rail's panes (so it fills its row edge-to-edge) and gets a- left border separating it from the chat — the column-mode separator- lives on the resize sash, which moves to the top edge as a row. */}- <div- className={cn(- 'relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-(--ui-editor-surface-background)',- terminalAsRow ? 'border-l border-(--ui-stroke-secondary) pt-0' : 'pt-(--titlebar-height)'- )}- >- <TerminalSlot />- </div>- </Pane>- )-- return (- <AppShell- leftStatusbarItems={leftStatusbarItems}- leftTitlebarTools={titlebarToolGroups.flat.left}- mainOverlays={mainOverlays}- onOpenSettings={openSettings}- overlays={overlays}- previewPaneOpen={chatOpen && Boolean(previewTarget || filePreviewTarget)}- statusbarItems={statusbarItems}- terminalPaneOpen={terminalSidebarOpen}- titlebarTools={titlebarToolGroups.flat.right}- >- {!isSecondaryWindow() && (- <Pane- forceCollapsed={narrowViewport}- hoverReveal- id="chat-sidebar"- maxWidth={SIDEBAR_MAX_WIDTH}- minWidth={SIDEBAR_DEFAULT_WIDTH}- onOverlayActiveChange={setSidebarOverlayMounted}- resizable- side={sidebarSide}- width={`${SIDEBAR_DEFAULT_WIDTH}px`}- >- {sidebar}- </Pane>- )}- <PaneMain>- <Routes>- <Route element={chatView} index />- <Route element={chatView} path=":sessionId" />- <Route- element={- <Suspense fallback={null}>- <SkillsView setStatusbarItemGroup={setStatusbarItemGroup} />- </Suspense>- }- path="skills"- />- <Route- element={- <Suspense fallback={null}>- <MessagingView setStatusbarItemGroup={setStatusbarItemGroup} />- </Suspense>- }- path="messaging"- />- <Route- element={- <Suspense fallback={null}>- <ArtifactsView setStatusbarItemGroup={setStatusbarItemGroup} />- </Suspense>- }- path="artifacts"- />- <Route element={null} path="cron" />- <Route element={null} path="profiles" />- <Route element={null} path="settings" />- <Route element={null} path="command-center" />- <Route element={null} path="agents" />- <Route element={<Navigate replace to={NEW_CHAT_ROUTE} />} path="new" />- <Route element={<LegacySessionRedirect />} path="sessions/:sessionId" />- <Route element={<Navigate replace to={NEW_CHAT_ROUTE} />} path="*" />- </Routes>- </PaneMain>- {/*- Order within a side maps to column order. Default (rail on the right):- main | terminal | preview | file-browser. Flipped (rail on the left):- mirror to file-browser | preview | terminal | main so terminal stays- adjacent to the chat.- */}- {panesFlipped ? fileBrowserPane : terminalPane}- {previewPane}- {reviewPane}- {panesFlipped ? terminalPane : fileBrowserPane}- </AppShell>- )-}--function LegacySessionRedirect() {- const { sessionId } = useParams()-- return <Navigate replace to={sessionId ? sessionRoute(sessionId) : NEW_CHAT_ROUTE} />-}diff --git a/apps/desktop/src/store/composer.test.ts b/apps/desktop/src/store/composer.test.tsindex 1b3a174ba9f..d5445ea64c1 100644--- a/apps/desktop/src/store/composer.test.ts+++ b/apps/desktop/src/store/composer.test.ts@@ -2,17 +2,33 @@ import { afterEach, describe, expect, it } from 'vitest'import {$composerAttachments,+ $voiceConversationStartRequest,addComposerAttachment,clearSessionDraft,type ComposerAttachment,migrateSessionDraft,removeComposerAttachment,+ requestVoiceConversationStart,SESSION_DRAFTS_STORAGE_KEY,stashSessionDraft,takeSessionDraft,+ takeVoiceConversationStart,updateComposerAttachment} from './composer'+describe('voice conversation start requests', () => {+ it('latches each request until the main composer consumes it once', () => {+ requestVoiceConversationStart()+ const first = $voiceConversationStartRequest.get()++ expect(takeVoiceConversationStart(first)).toBe(true)+ expect(takeVoiceConversationStart(first)).toBe(false)++ requestVoiceConversationStart()+ expect(takeVoiceConversationStart($voiceConversationStartRequest.get())).toBe(true)+ })+})+function attachment(overrides: Partial<ComposerAttachment> & Pick<ComposerAttachment, 'id'>): ComposerAttachment {return { kind: 'file', label: 'doc.pdf', ...overrides }}diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex a9df29b6df7..7f32348cd36 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -27,8 +27,7 @@ export const $voiceConversationStartRequest = atom(0)let nextVoiceStartRequest = 0let handledVoiceStartRequest = 0-export const requestVoiceConversationStart = (): void =>- $voiceConversationStartRequest.set(++nextVoiceStartRequest)+export const requestVoiceConversationStart = (): void => $voiceConversationStartRequest.set(++nextVoiceStartRequest)export const takeVoiceConversationStart = (current: number): boolean => {if (current <= handledVoiceStartRequest) {diff --git a/cli.py b/cli.pyindex 042b888e271..472e20df902 100644--- a/cli.py+++ b/cli.py@@ -984,6 +984,7 @@ def _cleanup_all_browsers(*args, **kwargs):# Guard to prevent cleanup from running multiple times on exit_cleanup_done = False+_cli_wake_owner = None# One-shot CLI finalization runs before process cleanup so plugins can observe# the session boundary while the agent is still attached. If a signal lands in# that narrow window, atexit cleanup must not emit that session finalize again.@@ -1179,7 +1180,8 @@ def _run_cleanup(*, notify_session_finalize: bool = True):try:from tools.wake_word import stop_listening as _stop_wake_word- _stop_wake_word()+ if _cli_wake_owner is not None:+ _stop_wake_word(owner=_cli_wake_owner)except Exception:passtry:@@ -12182,7 +12184,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):# threading resume logic through the voice machinery.def _maybe_start_wake_word(self):- """Start the wake-word listener at CLI startup if this surface owns it."""+ """Start the wake-word listener at CLI startup if this surface is eligible."""try:from tools.wake_word import wake_surface_enabledif not wake_surface_enabled("cli"):@@ -12193,14 +12195,11 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):def _start_wake_word_listener(self, announce: bool = False) -> bool:"""Build + start the hotword detector. Returns True on success."""- if getattr(self, "_wake_word_active", False):- if announce:- _cprint(f"{_DIM}Wake word is already listening.{_RST}")- return Truetry:from tools.wake_word import (check_wake_word_requirements,load_wake_word_config,+ owns_listener,start_listening,)except Exception as e:@@ -12208,6 +12207,12 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):_cprint(f"{_DIM}Wake word unavailable: {e}{_RST}")return False+ if getattr(self, "_wake_word_active", False) and owns_listener(self):+ if announce:+ _cprint(f"{_DIM}Wake word is already listening.{_RST}")+ return True+ self._wake_word_active = False+cfg = load_wake_word_config()reqs = check_wake_word_requirements(cfg)if not reqs["available"]:@@ -12219,7 +12224,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):self._wake_start_new_session = bool(cfg.get("start_new_session", True))try:- start_listening(self._on_wake_word, config=cfg)+ start_listening(self._on_wake_word, owner=self, config=cfg)except Exception as e:if announce:_cprint(f"\n{_DIM}Failed to start wake word: {e}{_RST}")@@ -12227,6 +12232,8 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):self._wake_word_active = Trueself._wake_suspended = False+ global _cli_wake_owner+ _cli_wake_owner = selfself._start_wake_watchdog()if announce:_cprint(f"\n{_ACCENT}Wake word listening{_RST} "@@ -12235,14 +12242,17 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):def _stop_wake_word_listener(self, announce: bool = False):"""Stop and tear down the hotword detector."""+ global _cli_wake_ownerwas_active = getattr(self, "_wake_word_active", False)self._wake_word_active = Falseself._wake_suspended = Falsetry:from tools.wake_word import stop_listening- stop_listening()+ stop_listening(owner=self)except Exception:pass+ if _cli_wake_owner is self:+ _cli_wake_owner = Noneif announce:if was_active:_cprint(f"{_DIM}Wake word stopped.{_RST}")@@ -12250,7 +12260,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):_cprint(f"{_DIM}Wake word is not running.{_RST}")def _on_wake_word(self):- """Fired (on the detector thread) when the wake phrase is heard."""+ """Fired after the detector hears the wake phrase."""if getattr(self, "_should_exit", False):return# Ignore wake while a turn is in flight or the mic is already in use.@@ -12260,9 +12270,12 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):# Release the mic so STT can capture the command utterance.try:from tools.wake_word import pause_listening- pause_listening()- except Exception:- pass+ if not pause_listening(owner=self):+ self._wake_word_active = False+ return+ except Exception as e:+ logger.debug("wake word pause failed: %s", e)+ returnself._wake_suspended = True_cprint(f"\n{_ACCENT}✦ Wake word detected — listening...{_RST}")@@ -12319,8 +12332,10 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):idle_polls = 0try:from tools.wake_word import resume_listening- resume_listening()- self._wake_suspended = False+ if resume_listening(owner=self):+ self._wake_suspended = False+ else:+ self._wake_word_active = Falseexcept Exception as e:logger.debug("wake word resume failed: %s", e)finally:@@ -12330,21 +12345,27 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):def _show_wake_word_status(self):"""Show current wake-word listener status."""- from tools.wake_word import check_wake_word_requirements, load_wake_word_config+ from tools.wake_word import (+ check_wake_word_requirements,+ is_listening,+ load_wake_word_config,+ owns_listener,+ )cfg = load_wake_word_config()reqs = check_wake_word_requirements(cfg)- active = getattr(self, "_wake_word_active", False)+ owned = owns_listener(self)+ state = "LISTENING" if owned and is_listening() else "PAUSED" if owned else "OFF"_cprint(f"\n{_BOLD}Wake Word Status{_RST}")- _cprint(f" State: {'LISTENING' if active else 'OFF'}")+ _cprint(f" State: {state}")_cprint(f" Phrase: \"{reqs['phrase']}\"")_cprint(f" Provider: {reqs['provider']}")_cprint(f" Surface: {cfg.get('surface', 'auto')}")_cprint(f" New session: {'yes' if cfg.get('start_new_session', True) else 'no'}")if not reqs["available"] and reqs.get("hint"):_cprint(f" {_DIM}{reqs['hint']}{_RST}")- if not active:+ if not owned:_cprint(f" {_DIM}Enable with /wake on{_RST}")def _toggle_voice_tts(self):diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 4881ddd2900..15acd118536 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2374,12 +2374,12 @@ DEFAULT_CONFIG = {"stop_phrases": ["stop"],},- # "Hey Hermes" hands-free wake word (CLI). Always-on, on-device hotword+ # "Hey Hermes" hands-free wake word. Always-on, on-device hotword# detection that starts a fresh voice session — the "Hey Siri" pattern.# Off by default; toggle with /wake or `wake_word.enabled: true`."wake_word": {"enabled": False,- "surface": "auto", # which surface owns the listener / opens the new session: "auto" (the running one) | "cli" | "tui" | "gui"+ "surface": "auto", # eligible surface: "auto" (first claimant) | "cli" | "tui" | "gui""provider": "openwakeword", # "openwakeword" (free, local) | "porcupine" (premium; needs PORCUPINE_ACCESS_KEY)"phrase": "hey jarvis", # cosmetic label only; detection is keyed by the engine model/keyword below"sensitivity": 0.5, # 0.0-1.0 detection threshold (higher = stricter)diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex fdb146f08c3..caf22da054e 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -1276,6 +1276,7 @@ def test_voice_record_start_handles_non_dict_voice_cfg(monkeypatch):assert captured["silence_duration"] == 3.0assert captured["auto_restart"] is False+# Round-12 Copilot review regression on #19835: ``bool`` is a subclass# of ``int``, so the naive ``isinstance(threshold, (int, float))``# guard would forward ``silence_threshold: true`` as ``1`` instead@@ -1306,6 +1307,173 @@ def test_voice_record_start_handles_non_dict_voice_cfg(monkeypatch):assert captured["auto_restart"] is False+def test_wake_owner_is_sticky_and_routes_detection_to_first_transport(monkeypatch):+ from tools import wake_word++ state = {"owner": None, "callback": None, "paused": False}+ voice_callbacks = {}++ def start_listening(callback, *, owner, config):+ if state["owner"] is not None and state["owner"] is not owner:+ raise wake_word.WakeWordInUse+ state.update(owner=owner, callback=callback, paused=False)++ def pause_listening(*, owner):+ if state["owner"] is not owner:+ return False+ state["paused"] = True+ return True++ def stop_listening(*, owner):+ if state["owner"] is not owner:+ return False+ state.update(owner=None, callback=None, paused=False)+ return True++ def resume_listening(*, owner):+ if state["owner"] is not owner:+ return False+ state["paused"] = False+ return True++ def start_continuous(**callbacks):+ voice_callbacks.update(callbacks)+ return True++ monkeypatch.setattr(wake_word, "load_wake_word_config", lambda: {+ "enabled": True,+ "phrase": "hey hermes",+ "surface": "auto",+ "start_new_session": True,+ })+ monkeypatch.setattr(wake_word, "check_wake_word_requirements", lambda _cfg: {+ "available": True,+ "phrase": "hey hermes",+ "provider": "test",+ "hint": "",+ })+ monkeypatch.setattr(wake_word, "start_listening", start_listening)+ monkeypatch.setattr(wake_word, "pause_listening", pause_listening)+ monkeypatch.setattr(wake_word, "stop_listening", stop_listening)+ monkeypatch.setattr(wake_word, "owns_listener", lambda owner: state["owner"] is owner)+ monkeypatch.setattr(+ wake_word,+ "is_listening",+ lambda: state["owner"] is not None and not state["paused"],+ )+ monkeypatch.setattr(+ wake_word,+ "resume_listening",+ resume_listening,+ )+ monkeypatch.setitem(+ sys.modules,+ "hermes_cli.voice",+ types.SimpleNamespace(+ start_continuous=start_continuous,+ stop_continuous=lambda **_kwargs: None,+ ),+ )+ monkeypatch.setenv("HERMES_VOICE", "1")++ first = types.SimpleNamespace(_closed=False)+ second = types.SimpleNamespace(_closed=False)+ emitted = []+ monkeypatch.setattr(+ server,+ "_emit",+ lambda event, sid, payload: emitted.append(+ (event, sid, payload, server.current_transport())+ ),+ )+ server._wake_owner_transport = None+ server._wake_owner_surface = ""+ try:+ started = server.dispatch({+ "id": "wake-1",+ "method": "wake.start",+ "params": {"surface": "gui", "session_id": "first-session"},+ }, transport=first)+ denied = server.dispatch({+ "id": "wake-2",+ "method": "wake.start",+ "params": {"surface": "tui", "session_id": "second-session"},+ }, transport=second)+ denied_stop = server.dispatch({+ "id": "wake-stop-2",+ "method": "wake.stop",+ "params": {},+ }, transport=second)+ denied_voice_stop = server.dispatch({+ "id": "voice-stop-2",+ "method": "voice.record",+ "params": {"action": "stop"},+ }, transport=second)++ assert started["result"]["started"] is True+ assert denied["result"] == {+ "started": False,+ "reason": "owned",+ "owner_surface": "gui",+ }+ assert denied_stop["result"] == {"stopped": False, "reason": "not_owner"}+ assert denied_voice_stop["result"] == {+ "status": "busy",+ "reason": "wake_owned",+ }++ state["callback"]()+ assert emitted == [(+ "wake.detected",+ "first-session",+ {"phrase": "hey hermes", "start_new_session": True},+ first,+ )]+ assert state["paused"] is True++ voice_started = server.dispatch({+ "id": "voice-start-1",+ "method": "voice.record",+ "params": {"action": "start", "session_id": "first-session"},+ }, transport=first)+ assert voice_started["result"]["status"] == "recording"+ voice_callbacks["on_status"]("idle")+ assert state["paused"] is False++ stopped = server.dispatch({+ "id": "wake-stop-1",+ "method": "wake.stop",+ "params": {},+ }, transport=first)+ assert stopped["result"] == {"stopped": True, "reason": None}++ reclaimed = server.dispatch({+ "id": "wake-reclaim-2",+ "method": "wake.start",+ "params": {"surface": "tui", "session_id": "second-session"},+ }, transport=second)+ assert reclaimed["result"]["started"] is True+ assert state["owner"] is second++ state["callback"]()+ assert emitted[-1] == (+ "wake.detected",+ "second-session",+ {"phrase": "hey hermes", "start_new_session": True},+ second,+ )++ stopped_again = server.dispatch({+ "id": "wake-stop-2-after-reclaim",+ "method": "wake.stop",+ "params": {},+ }, transport=second)+ assert stopped_again["result"] == {"stopped": True, "reason": None}+ finally:+ server._wake_owner_transport = None+ server._wake_owner_surface = ""++def test_voice_record_stop_forces_transcription(monkeypatch):captured: dict = {}diff --git a/tests/test_tui_gateway_ws.py b/tests/test_tui_gateway_ws.pyindex ad41ba9dade..8c32f9798ed 100644--- a/tests/test_tui_gateway_ws.py+++ b/tests/test_tui_gateway_ws.py@@ -152,6 +152,20 @@ def test_ws_connection_registers_then_disconnect_unregisters_live_transport(monkserver._live_transports.clear()+def test_ws_disconnect_releases_wake_word_owner(monkeypatch):+ released = []+ created = []+ monkeypatch.setattr(+ server,+ "_release_wake_for_transport",+ lambda transport: released.append(transport) or True,+ )++ _run_disconnect(monkeypatch, lambda transport: created.append(transport))++ assert released == created++def test_ws_write_loop_stall_does_not_latch_transport(monkeypatch):"""A write that times out because the event loop is stalled (GIL-heavyagent turn) must NOT latch the transport closed — the frame is alreadydiff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.pyindex e765e4ac5ee..7c65eedadd4 100644--- a/tests/tools/test_wake_word.py+++ b/tests/tools/test_wake_word.py@@ -6,8 +6,11 @@ dispatch, the requirements probe, the detector fire/cooldown loop, and theprocess-wide singleton lifecycle."""+import multiprocessing+import threadingimport timeimport types+from pathlib import Pathimport pytest@@ -30,7 +33,7 @@ def test_config_defaults_and_clamping():def test_wake_surface_enabled_gate():# Disabled → never, regardless of surface.assert ww.wake_surface_enabled("cli", {"enabled": False, "surface": "cli"}) is False- # auto → every surface.+ # auto → every surface is eligible; ownership still admits only one.for s in ("cli", "tui", "gui"):assert ww.wake_surface_enabled(s, {"enabled": True, "surface": "auto"}) is True# Pinned surface → only that one.@@ -219,24 +222,151 @@ def test_detector_pause_resume(monkeypatch):# ── Singleton lifecycle ──────────────────────────────────────────────────-def test_singleton_lifecycle(monkeypatch):+def test_singleton_lifecycle(monkeypatch, tmp_path):_fake_audio(monkeypatch)monkeypatch.setattr(ww, "_build_engine", lambda cfg: _FakeEngine(fire=False))+ monkeypatch.setattr(ww, "_lock_path", lambda: tmp_path / "wake.lock")+ owner = object()assert ww.is_listening() is False- det = ww.start_listening(lambda: None, config={})+ det = ww.start_listening(lambda: None, owner=owner, config={})time.sleep(0.05)assert ww.is_listening() is True+ assert ww.owns_listener(owner) is True# Re-entrant start returns the same detector and re-arms it.- det2 = ww.start_listening(lambda: None, config={})+ det2 = ww.start_listening(lambda: None, owner=owner, config={})assert det2 is det- ww.pause_listening()+ assert ww.pause_listening(owner=owner) is Trueassert ww.is_listening() is False- ww.resume_listening()+ assert ww.resume_listening(owner=owner) is Truetime.sleep(0.05)assert ww.is_listening() is True- ww.stop_listening()+ assert ww.stop_listening(owner=owner) is Trueassert ww.is_listening() is False+++def test_second_owner_cannot_mutate_listener(monkeypatch, tmp_path):+ _fake_audio(monkeypatch)+ monkeypatch.setattr(ww, "_build_engine", lambda cfg: _FakeEngine(fire=False))+ monkeypatch.setattr(ww, "_lock_path", lambda: tmp_path / "wake.lock")+ owner, intruder = object(), object()+ first_callback = lambda: None++ detector = ww.start_listening(first_callback, owner=owner, config={})+ with pytest.raises(ww.WakeWordInUse):+ ww.start_listening(lambda: None, owner=intruder, config={})++ assert detector.on_wake is first_callback+ assert ww.pause_listening(owner=intruder) is False+ assert ww.resume_listening(owner=intruder) is False+ assert ww.stop_listening(owner=intruder) is False+ assert ww.owns_listener(owner) is True+ assert ww.stop_listening(owner=owner) is True+++def test_detection_callback_can_pause_and_close_stream(monkeypatch, tmp_path):+ streams = []++ def _stream(**kw):+ stream = _FakeStream(**kw)+ streams.append(stream)+ return stream++ fake_sd = types.SimpleNamespace(InputStream=_stream)+ monkeypatch.setattr(ww, "_import_audio", lambda: (fake_sd, None))+ monkeypatch.setattr(ww, "_build_engine", lambda cfg: _FakeEngine(fire=True))+ monkeypatch.setattr(ww, "_lock_path", lambda: tmp_path / "wake.lock")+ owner = object()+ paused = threading.Event()++ def _on_wake():+ if ww.pause_listening(owner=owner):+ paused.set()++ ww.start_listening(_on_wake, owner=owner, config={})+ assert paused.wait(2)+ assert ww.is_listening() is False+ assert streams[0].closed is True+ assert ww.stop_listening(owner=owner) is True+++def test_startup_failure_releases_owner_and_machine_lock(monkeypatch, tmp_path):+ class _BrokenSoundDevice:+ @staticmethod+ def InputStream(**_kw):+ raise OSError("no microphone")++ lock_path = tmp_path / "wake.lock"+ monkeypatch.setattr(ww, "_import_audio", lambda: (_BrokenSoundDevice, None))+ monkeypatch.setattr(ww, "_build_engine", lambda cfg: _FakeEngine(fire=False))+ monkeypatch.setattr(ww, "_lock_path", lambda: lock_path)+ owner = object()++ with pytest.raises(RuntimeError, match="Failed to open"):+ ww.start_listening(lambda: None, owner=owner, config={})++ assert ww.owns_listener(owner) is False+ handle = ww._acquire_machine_lock(lock_path)+ ww._release_machine_lock(handle)+++def test_stream_failure_releases_owner_and_machine_lock(monkeypatch, tmp_path):+ class _FailingStream(_FakeStream):+ def read(self, _n):+ raise OSError("device disconnected")++ fake_sd = types.SimpleNamespace(InputStream=lambda **kw: _FailingStream(**kw))+ engine = _FakeEngine(fire=False)+ lock_path = tmp_path / "wake.lock"+ monkeypatch.setattr(ww, "_import_audio", lambda: (fake_sd, None))+ monkeypatch.setattr(ww, "_build_engine", lambda cfg: engine)+ monkeypatch.setattr(ww, "_lock_path", lambda: lock_path)+ owner = object()++ ww.start_listening(lambda: None, owner=owner, config={})+ deadline = time.time() + 2+ while ww.owns_listener(owner) and time.time() < deadline:+ time.sleep(0.01)++ assert ww.owns_listener(owner) is False+ assert engine.closed is True+ handle = ww._acquire_machine_lock(lock_path)+ ww._release_machine_lock(handle)+++def _hold_machine_lock(path: str, ready, release) -> None:+ from tools import wake_word++ handle = wake_word._acquire_machine_lock(Path(path))+ ready.set()+ release.wait(10)+ assert handle is not None+++def test_machine_lock_is_released_when_owner_process_exits(tmp_path):+ lock_path = tmp_path / "wake.lock"+ ctx = multiprocessing.get_context("spawn")+ ready = ctx.Event()+ release = ctx.Event()+ process = ctx.Process(+ target=_hold_machine_lock,+ args=(str(lock_path), ready, release),+ )+ process.start()+ try:+ assert ready.wait(10)+ with pytest.raises(ww.WakeWordInUse):+ ww._acquire_machine_lock(lock_path)+ release.set()+ process.join(10)+ assert process.exitcode == 0+ handle = ww._acquire_machine_lock(lock_path)+ ww._release_machine_lock(handle)+ finally:+ release.set()+ if process.is_alive():+ process.terminate()+ process.join(10)diff --git a/tools/wake_word.py b/tools/wake_word.pyindex 641a20bda81..fb13e0a597a 100644--- a/tools/wake_word.py+++ b/tools/wake_word.py@@ -31,6 +31,7 @@ import loggingimport osimport threadingimport time+from pathlib import Pathfrom typing import Any, Callable, Dict, Optionallogger = logging.getLogger(__name__)@@ -41,6 +42,11 @@ SAMPLE_RATE = 16000# Minimum gap between two consecutive wake fires, so one "hey hermes" can't# retrigger across several frames while the caller is still reacting._FIRE_COOLDOWN_SECONDS = 2.0+_START_TIMEOUT_SECONDS = 5.0+++class WakeWordInUse(RuntimeError):+ """Raised when another surface or process owns the wake-word listener."""# ---------------------------------------------------------------------------@@ -96,8 +102,8 @@ def wake_surface_enabled(surface: str, cfg: Optional[Dict[str, Any]] = None) ->"""Should ``surface`` (``cli`` / ``tui`` / ``gui``) host the listener?True when the wake word is enabled and the configured ``surface`` is either- ``auto`` or this exact surface — the single gate every surface consults so- only one place owns the wake word and the new session it opens.+ ``auto`` or this exact surface. ``auto`` makes a surface eligible; the+ process/machine ownership lock still permits only the first claimant."""cfg = cfg if cfg is not None else load_wake_word_config()if not cfg.get("enabled"):@@ -299,12 +305,15 @@ class WakeWordDetector:"""def __init__(self, engine: _Engine, on_wake: Callable[[], None],- cooldown: float = _FIRE_COOLDOWN_SECONDS):+ cooldown: float = _FIRE_COOLDOWN_SECONDS,+ on_failure: Optional[Callable[["WakeWordDetector"], None]] = None):self.engine = engineself.on_wake = on_wakeself.cooldown = cooldown+ self.on_failure = on_failureself._thread: Optional[threading.Thread] = Noneself._stop = threading.Event()+ self._callback_inflight = threading.Event()self._last_fire = 0.0self._lock = threading.Lock()@@ -319,10 +328,21 @@ class WakeWordDetector:if self._thread is not None and self._thread.is_alive():returnself._stop.clear()+ ready = threading.Event()+ startup_errors: list[BaseException] = []self._thread = threading.Thread(- target=self._run, daemon=True, name="wake-word"+ target=self._run,+ args=(ready, startup_errors),+ daemon=True,+ name="wake-word",)self._thread.start()+ if not ready.wait(_START_TIMEOUT_SECONDS):+ self._halt_thread()+ raise TimeoutError("Timed out while opening the wake-word microphone.")+ if startup_errors:+ self._halt_thread()+ raise RuntimeError("Failed to open the wake-word microphone.") from startup_errors[0]# pause/resume keep the engine; stop tears it down.def pause(self) -> None:@@ -337,16 +357,29 @@ class WakeWordDetector:def _halt_thread(self) -> None:with self._lock:- t, self._thread = self._thread, None- if t is not None and t is not threading.current_thread():self._stop.set()- t.join(timeout=2.0)+ t = self._thread+ if t is not None and t is not threading.current_thread():+ t.join(timeout=2.0)+ if self._thread is t:+ self._thread = None++ def _dispatch_wake(self) -> None:+ try:+ self.on_wake()+ except Exception as e:+ logger.warning("wake word callback failed: %s", e)+ finally:+ self._callback_inflight.clear()- def _run(self) -> None:+ def _run(self, ready: threading.Event,+ startup_errors: list[BaseException]) -> None:try:sd, _ = _import_audio()except (ImportError, OSError) as e:logger.error("wake word: audio libraries unavailable: %s", e)+ startup_errors.append(e)+ ready.set()returnframe_length = self.engine.frame_length@@ -360,6 +393,8 @@ class WakeWordDetector:stream.start()except Exception as e:logger.error("wake word: failed to open microphone: %s", e)+ startup_errors.append(e)+ ready.set()return# Drop any buffered audio/feature state so a resume right after a voice@@ -371,12 +406,15 @@ class WakeWordDetector:passlogger.info("wake word: listening (frame=%d, rate=%d)", frame_length, SAMPLE_RATE)+ ready.set()+ failed = Falsetry:while not self._stop.is_set():try:data, _overflow = stream.read(frame_length)except Exception as e:logger.warning("wake word: stream read error: %s", e)+ failed = not self._stop.is_set()breakframe = data[:, 0] if getattr(data, "ndim", 1) == 2 else datatry:@@ -389,10 +427,13 @@ class WakeWordDetector:if now - self._last_fire >= self.cooldown:self._last_fire = nowlogger.info("wake word: phrase detected — firing callback")- try:- self.on_wake()- except Exception as e:- logger.warning("wake word callback failed: %s", e)+ if not self._callback_inflight.is_set():+ self._callback_inflight.set()+ threading.Thread(+ target=self._dispatch_wake,+ daemon=True,+ name="wake-word-callback",+ ).start()else:logger.debug("wake word: detection within cooldown — ignored")finally:@@ -402,6 +443,8 @@ class WakeWordDetector:except Exception:passlogger.info("wake word: stream closed")+ if failed and self.on_failure is not None:+ self.on_failure(self)# ---------------------------------------------------------------------------@@ -409,55 +452,162 @@ class WakeWordDetector:# ---------------------------------------------------------------------------_detector: Optional[WakeWordDetector] = None+_detector_owner: object | None = None+_detector_file_lock = None_detector_lock = threading.Lock()+def _lock_path() -> Path:+ from hermes_constants import get_default_hermes_root++ return get_default_hermes_root() / "runtime" / "wake-word.lock"+++def _acquire_machine_lock(path: Optional[Path] = None):+ """Acquire the cross-process microphone lease, or raise WakeWordInUse."""+ lock_path = path or _lock_path()+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ handle = open(lock_path, "a+b")+ try:+ if os.name == "nt":+ import msvcrt++ handle.seek(0, os.SEEK_END)+ if handle.tell() == 0:+ handle.write(b"\0")+ handle.flush()+ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl++ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except (OSError, BlockingIOError) as e:+ handle.close()+ raise WakeWordInUse("Wake-word microphone is already owned.") from e+ return handle+++def _release_machine_lock(handle) -> None:+ if handle is None:+ return+ try:+ if os.name == "nt":+ import msvcrt++ handle.seek(0)+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ except OSError:+ pass+ finally:+ handle.close()+++def _detector_failed(detector: WakeWordDetector) -> None:+ """Release ownership if the active microphone stream dies unexpectedly."""+ global _detector, _detector_owner, _detector_file_lock+ with _detector_lock:+ if _detector is not detector:+ return+ lock_handle = _detector_file_lock+ _detector = None+ _detector_owner = None+ _detector_file_lock = None+ try:+ detector.engine.close()+ finally:+ _release_machine_lock(lock_handle)++def start_listening(on_wake: Callable[[], None],*,+ owner: object,config: Optional[Dict[str, Any]] = None,) -> WakeWordDetector:- """Build (once) and start the wake-word detector. Idempotent.+ """Claim, build, and start the detector. Idempotent for the same owner.Raises if engine construction fails (missing deps / access key / model);- callers should probe :func:`check_wake_word_requirements` first.+ callers should probe :func:`check_wake_word_requirements` first. A different+ owner, including another process, receives :class:`WakeWordInUse`."""- global _detector+ if owner is None:+ raise ValueError("wake-word owner must not be None")++ global _detector, _detector_owner, _detector_file_lockwith _detector_lock:if _detector is not None:+ if _detector_owner is not owner:+ raise WakeWordInUse("Wake-word microphone is already owned.")_detector.on_wake = on_wake_detector.resume()return _detector- cfg = config if config is not None else load_wake_word_config()- engine = _build_engine(cfg)- _detector = WakeWordDetector(engine, on_wake)- _detector.start()- return _detector+ lock_handle = _acquire_machine_lock()+ try:+ cfg = config if config is not None else load_wake_word_config()+ engine = _build_engine(cfg)+ detector = WakeWordDetector(engine, on_wake, on_failure=_detector_failed)+ _detector = detector+ _detector_owner = owner+ _detector_file_lock = lock_handle+ detector.start()+ return detector+ except Exception:+ if _detector is not None:+ try:+ _detector.stop()+ except Exception:+ pass+ _detector = None+ _detector_owner = None+ _detector_file_lock = None+ _release_machine_lock(lock_handle)+ raise-def pause_listening() -> None:- """Release the microphone without tearing down the engine."""+def owns_listener(owner: object) -> bool:with _detector_lock:- det = _detector- if det is not None:- det.pause()+ return _detector is not None and _detector_owner is owner-def resume_listening() -> None:- """Re-open the microphone after a pause. No-op if not initialised."""+def pause_listening(*, owner: object) -> bool:+ """Release the microphone only when ``owner`` holds the lease."""with _detector_lock:- det = _detector- if det is not None:- det.resume()+ if _detector is None or _detector_owner is not owner:+ return False+ _detector.pause()+ return True+++def resume_listening(*, owner: object) -> bool:+ """Re-open the microphone only when ``owner`` holds the lease."""+ with _detector_lock:+ if _detector is None or _detector_owner is not owner:+ return False+ _detector.resume()+ return True-def stop_listening() -> None:- """Fully stop and discard the detector (closes the engine)."""- global _detector+def stop_listening(*, owner: object) -> bool:+ """Fully stop the detector only when ``owner`` holds the lease."""+ global _detector, _detector_owner, _detector_file_lockwith _detector_lock:- det, _detector = _detector, None- if det is not None:- det.stop()+ if _detector is None or _detector_owner is not owner:+ return False+ det = _detector+ lock_handle = _detector_file_lock+ _detector = None+ _detector_owner = None+ _detector_file_lock = None+ try:+ det.stop()+ finally:+ _release_machine_lock(lock_handle)+ return Truedef is_listening() -> bool:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 399c2d7068d..e29fcae05c4 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -926,8 +926,7 @@ def _close_sessions_for_transport(def _shutdown_sessions() -> None:try:- from tools.wake_word import stop_listening as _stop_wake- _stop_wake()+ _release_gateway_wake_owner()except Exception:passwith _sessions_lock:@@ -17426,6 +17425,7 @@ def _(rid, params: dict) -> dict:_voice_sid_lock = threading.Lock()_voice_event_sid: str = ""+_voice_wake_owner: "Optional[Transport]" = Nonedef _voice_emit(event: str, payload: dict | None = None) -> None:@@ -17439,6 +17439,14 @@ def _voice_emit(event: str, payload: dict | None = None) -> None:_emit(event, sid, payload)+def _resume_voice_wake() -> None:+ global _voice_wake_owner+ with _voice_sid_lock:+ owner, _voice_wake_owner = _voice_wake_owner, None+ if owner is not None:+ _wake_resume_if_owner(owner)++def _voice_mode_enabled() -> bool:"""Current voice-mode flag (runtime-only, CLI parity).@@ -17593,62 +17601,51 @@ def _voice_record_key() -> str:# ── Wake word ("Hey Hermes") ──────────────────────────────────────────────-# The detector is process-global (one mic), like voice. It runs server-side so-# both the TUI and desktop GUI share it; clients pass their surface identity to-# wake.start and the shared gate (wake_surface_enabled) decides whether to arm.+# The detector is process-global (one mic), like voice. The first eligible+# transport to call wake.start owns it until stop, disconnect, or stream failure.# On detection we emit wake.detected; the client opens a new session and starts# its own voice capture. The detector yields the mic to gateway voice.record# (pause/resume below) and to the desktop's browser mic (wake.pause/resume RPCs)._wake_lock = threading.Lock()-_wake_active = False-_wake_event_sid = ""-# Transport captured at wake.start time. The detector callback fires on a-# background thread where the request-scoped transport ContextVar is unset, so-# write_json would fall back to stdio and the event would never cross the-# desktop's websocket (#wake-detected-not-delivered). We pin the arming-# request's transport here and bind it for the emit.-_wake_transport: "Optional[Transport]" = None+_wake_owner_transport: "Optional[Transport]" = None+_wake_owner_surface = ""-def _wake_is_active() -> bool:+def _wake_owner_snapshot():with _wake_lock:- return _wake_active+ return _wake_owner_transport, _wake_owner_surface-def _wake_resume_if_active() -> None:- if not _wake_is_active():- return+def _release_wake_for_transport(transport: "Transport") -> bool:+ """Release the wake lease iff ``transport`` is the current gateway owner."""+ global _wake_owner_transport, _wake_owner_surface+ with _wake_lock:+ if _wake_owner_transport is not transport:+ return False+ _wake_owner_transport = None+ _wake_owner_surface = ""try:- from tools.wake_word import resume_listening- resume_listening()+ from tools.wake_word import stop_listening++ stop_listening(owner=transport)except Exception as e:- logger.debug("wake resume failed: %s", e)+ logger.debug("wake stop failed: %s", e)+ return True-def _wake_on_detect() -> None:- """Detector-thread callback: tell the client to open a fresh voice session."""- with _wake_lock:- sid = _wake_event_sid- transport = _wake_transport- phrase, new_session = "", True- try:- from tools.wake_word import load_wake_word_config, wake_phrase- cfg = load_wake_word_config()- phrase = wake_phrase(cfg)- new_session = bool(cfg.get("start_new_session", True))- except Exception:- pass- logger.info("wake.detected: emitting to sid=%r (transport=%s)",- sid, type(transport).__name__ if transport else None)- # Bind the arming request's transport so write_json reaches the right peer- # (WS for desktop/dashboard) instead of falling back to stdio on this- # background thread. Carry start_new_session so every surface honors it.- token = bind_transport(transport) if transport is not None else None+def _release_gateway_wake_owner() -> bool:+ owner, _surface = _wake_owner_snapshot()+ return owner is not None and _release_wake_for_transport(owner)+++def _wake_resume_if_owner(owner: "Transport") -> bool:try:- _emit("wake.detected", sid, {"phrase": phrase, "start_new_session": new_session})- finally:- if token is not None:- reset_transport(token)+ from tools.wake_word import resume_listening++ return resume_listening(owner=owner)+ except Exception as e:+ logger.debug("wake resume failed: %s", e)+ return False@method("wake.start")@@ -17658,13 +17655,16 @@ def _(rid, params: dict) -> dict:Idempotent and gated: returns ``{started: False, reason}`` when the wakeword is disabled, scoped to another surface, or its deps/mic aren't ready."""- global _wake_active, _wake_event_sid, _wake_transportsurface = str(params.get("surface") or "auto").strip().lower()+ transport = current_transport() or _stdio_transporttry:from tools.wake_word import (+ WakeWordInUse,check_wake_word_requirements,load_wake_word_config,+ owns_listener,start_listening,+ wake_phrase,wake_surface_enabled,)except Exception as e:@@ -17678,59 +17678,113 @@ def _(rid, params: dict) -> dict:reqs = check_wake_word_requirements(cfg)if not reqs["available"]:logger.warning("wake.start(%s): not available — %s", surface, reqs.get("hint"))- return _ok(rid, {"started": False, "reason": reqs.get("hint") or "unavailable"})+ return _ok(rid, {+ "started": False,+ "reason": "unavailable",+ "hint": reqs.get("hint") or "",+ })++ existing_owner, existing_surface = _wake_owner_snapshot()+ if existing_owner is not None and (+ _transport_is_dead(existing_owner) or not owns_listener(existing_owner)+ ):+ _release_wake_for_transport(existing_owner)+ existing_owner = None+ existing_surface = ""+ if existing_owner is not None and existing_owner is not transport:+ return _ok(rid, {+ "started": False,+ "reason": "owned",+ "owner_surface": existing_surface,+ })++ sid = str(params.get("session_id") or "")+ phrase = wake_phrase(cfg)+ new_session = bool(cfg.get("start_new_session", True))++ def _on_detect() -> None:+ from tools.wake_word import owns_listener, pause_listening++ if not pause_listening(owner=transport):+ return+ if not owns_listener(transport):+ return+ if _transport_is_dead(transport):+ _release_wake_for_transport(transport)+ return+ logger.info("wake.detected: emitting to sid=%r (transport=%s)",+ sid, type(transport).__name__)+ token = bind_transport(transport)+ try:+ _emit("wake.detected", sid, {+ "phrase": phrase,+ "start_new_session": new_session,+ })+ finally:+ reset_transport(token)- with _wake_lock:- _wake_event_sid = params.get("session_id") or _wake_event_sid- # Capture the live transport (WS for desktop) so the background detector- # thread can route wake.detected back to this client, not stdio.- _wake_transport = current_transport() or _wake_transporttry:- start_listening(_wake_on_detect, config=cfg)+ start_listening(_on_detect, owner=transport, config=cfg)+ except WakeWordInUse:+ return _ok(rid, {+ "started": False,+ "reason": "owned",+ "owner_surface": existing_surface or None,+ })except Exception as e:logger.warning("wake.start(%s): failed to start listener: %s", surface, e)return _err(rid, 5026, str(e))+ global _wake_owner_transport, _wake_owner_surfacewith _wake_lock:- _wake_active = True+ _wake_owner_transport = transport+ _wake_owner_surface = surfacelogger.info("wake.start(%s): listening for %r (%s)", surface, reqs["phrase"], reqs["provider"])- return _ok(rid, {"started": True, "phrase": reqs["phrase"], "provider": reqs["provider"]})+ return _ok(rid, {+ "started": True,+ "phrase": reqs["phrase"],+ "provider": reqs["provider"],+ "owner_surface": surface,+ })@method("wake.stop")def _(rid, params: dict) -> dict:- global _wake_active- with _wake_lock:- _wake_active = False- try:- from tools.wake_word import stop_listening- stop_listening()- except Exception:- pass- return _ok(rid, {"stopped": True})+ transport = current_transport() or _stdio_transport+ stopped = _release_wake_for_transport(transport)+ return _ok(rid, {+ "stopped": stopped,+ "reason": None if stopped else "not_owner",+ })@method("wake.pause")def _(rid, params: dict) -> dict:"""Release the mic (e.g. while the desktop's browser captures audio)."""+ transport = current_transport() or _stdio_transporttry:from tools.wake_word import pause_listening- pause_listening()- logger.info("wake.pause: detector paused")++ paused = pause_listening(owner=transport)+ logger.info("wake.pause: detector paused=%s", paused)except Exception as e:logger.debug("wake.pause failed: %s", e)- return _ok(rid, {"paused": True})+ paused = False+ return _ok(rid, {+ "paused": paused,+ "reason": None if paused else "not_owner",+ })@method("wake.resume")def _(rid, params: dict) -> dict:"""Reclaim the mic after a pause; no-op if the listener isn't armed."""- active = _wake_is_active()- if active:- _wake_resume_if_active()- logger.info("wake.resume: detector resumed")- else:- logger.info("wake.resume: ignored (listener not armed)")- return _ok(rid, {"resumed": active})+ transport = current_transport() or _stdio_transport+ resumed = _wake_resume_if_owner(transport)+ logger.info("wake.resume: detector resumed=%s", resumed)+ return _ok(rid, {+ "resumed": resumed,+ "reason": None if resumed else "not_owner",+ })@method("wake.status")@@ -17740,11 +17794,17 @@ def _(rid, params: dict) -> dict:check_wake_word_requirements,is_listening,load_wake_word_config,+ owns_listener,)cfg = load_wake_word_config()reqs = check_wake_word_requirements(cfg)+ transport = current_transport() or _stdio_transport+ owner, owner_surface = _wake_owner_snapshot()+ owned_by_caller = owns_listener(transport)return _ok(rid, {- "listening": _wake_is_active() and is_listening(),+ "listening": owned_by_caller and is_listening(),+ "owned_by_caller": owned_by_caller,+ "owner_surface": owner_surface if owner is not None else None,"phrase": reqs["phrase"],"provider": reqs["provider"],"available": reqs["available"],@@ -17866,17 +17926,23 @@ def _(rid, params: dict) -> dict:captures emit ``voice.transcript`` with ``no_speech_limit=True``."""action = params.get("action", "start")+ wake_paused = Falseif action not in {"start", "stop"}:return _err(rid, 4019, f"unknown voice action: {action}")+ transport = current_transport() or _stdio_transport+ wake_owner, _surface = _wake_owner_snapshot()+ if wake_owner is not None and wake_owner is not transport:+ return _ok(rid, {"status": "busy", "reason": "wake_owned"})+try:if action == "start":if not _voice_mode_enabled():return _err(rid, 4015, "voice mode is off — enable with /voice on")with _voice_sid_lock:- global _voice_event_sid+ global _voice_event_sid, _voice_wake_owner_voice_event_sid = params.get("session_id") or _voice_event_sidfrom hermes_cli.voice import start_continuous@@ -17905,30 +17971,39 @@ def _(rid, params: dict) -> dict:# Hand the mic to STT if the wake-word detector holds it; resume# once a terminal capture event fires (one-shot transcript / silence# limit), so wake-triggered and manual captures both coexist.- if _wake_is_active():- try:- from tools.wake_word import pause_listening- pause_listening()- except Exception:- pass+ try:+ from tools.wake_word import pause_listening++ wake_paused = pause_listening(owner=transport)+ except Exception:+ wake_paused = False+ if wake_paused:+ with _voice_sid_lock:+ _voice_wake_owner = transportdef _on_transcript(t):_voice_emit("voice.transcript", {"text": t})- _wake_resume_if_active()+ _resume_voice_wake()def _on_silent():_voice_emit("voice.transcript", {"no_speech_limit": True})- _wake_resume_if_active()+ _resume_voice_wake()++ def _on_status(state):+ _voice_emit("voice.status", {"state": state})+ if state == "idle":+ _resume_voice_wake()started = start_continuous(on_transcript=_on_transcript,- on_status=lambda s: _voice_emit("voice.status", {"state": s}),+ on_status=_on_status,on_silent_limit=_on_silent,silence_threshold=safe_threshold,silence_duration=safe_duration,auto_restart=False,)if started is False:+ _resume_voice_wake()return _ok(rid, {"status": "busy"})return _ok(rid, {"status": "recording"})@@ -17939,13 +18014,17 @@ def _(rid, params: dict) -> dict:from hermes_cli.voice import stop_continuousstop_continuous(force_transcribe=True)- _wake_resume_if_active()+ _resume_voice_wake()return _ok(rid, {"status": "stopped"})except ImportError:+ if wake_paused or action == "stop":+ _resume_voice_wake()return _err(rid, 5025, "voice module not available — install audio dependencies")except Exception as e:+ if wake_paused or action == "stop":+ _resume_voice_wake()return _err(rid, 5025, str(e))diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 795f85c13e7..c6057efd685 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -422,6 +422,11 @@ async def handle_ws(ws: Any) -> None:server.unregister_live_transport(transport)transport.close()+ try:+ await asyncio.to_thread(server._release_wake_for_transport, transport)+ except Exception:+ _log.exception("ws wake-word teardown failed peer=%s", peer)+# Reap sessions this transport owned (close_on_disconnect sidecar# sessions) or detach the rest to the drop sentinel so later emits# don't crash into a closed socket or fall through to desktop stdoutdiff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.tsindex 42bf75e74d2..87647079529 100644--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts@@ -779,6 +779,7 @@ describe('createGatewayEventHandler', () => {expect(ctx.gateway.rpc).not.toHaveBeenCalled()})+<<<<<<< HEADit('picks the polarity-matching paired palette from gateway.ready skins', async () => {const appended: Msg[] = []@@ -851,6 +852,65 @@ describe('createGatewayEventHandler', () => {expect(polarityBackgroundFromForeground('not-a-color')).toBeUndefined()})+ it('claims wake-word ownership when the gateway becomes ready', () => {+ const ctx = buildCtx([])++ createGatewayEventHandler(ctx)({ payload: {}, type: 'gateway.ready' } as any)++ expect(ctx.gateway.rpc).toHaveBeenCalledWith('wake.start', { surface: 'tui' })+ })++ it('opens a fresh session before starting voice after wake detection', async () => {+ const ctx = buildCtx([])+ ctx.session.newSession = vi.fn(async () => patchUiState({ sid: 'wake-session' }))+ patchUiState({ sid: 'old-session' })++ createGatewayEventHandler(ctx)({+ payload: { phrase: 'hey hermes', start_new_session: true },+ type: 'wake.detected'+ } as any)++ await vi.waitFor(() =>+ expect(ctx.gateway.rpc).toHaveBeenCalledWith('voice.record', {+ action: 'start',+ session_id: 'wake-session'+ })+ )+ expect(ctx.session.newSession).toHaveBeenCalledOnce()+ expect(ctx.voice.setVoiceEnabled).toHaveBeenCalledWith(true)+ })++ it('keeps the current session when wake detection disables session creation', async () => {+ const ctx = buildCtx([])+ patchUiState({ sid: 'current-session' })++ createGatewayEventHandler(ctx)({+ payload: { phrase: 'hey hermes', start_new_session: false },+ type: 'wake.detected'+ } as any)++ await vi.waitFor(() =>+ expect(ctx.gateway.rpc).toHaveBeenCalledWith('voice.record', {+ action: 'start',+ session_id: 'current-session'+ })+ )+ expect(ctx.session.newSession).not.toHaveBeenCalled()+ })++ it('rearms wake detection when no session is available', async () => {+ const ctx = buildCtx([])+ patchUiState({ sid: '' })++ createGatewayEventHandler(ctx)({+ payload: { start_new_session: false },+ type: 'wake.detected'+ } as any)++ await vi.waitFor(() => expect(ctx.gateway.rpc).toHaveBeenCalledWith('wake.resume', {}))+ expect(ctx.gateway.rpc).not.toHaveBeenCalledWith('voice.record', expect.anything())+ })+it('on gateway.ready with no STARTUP_RESUME_ID and auto_resume off, forges a new session', async () => {const appended: Msg[] = []const newSession = vi.fn()diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 9d4132e93a9..49c55fc358f 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -623,7 +623,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:// Arm "Hey Hermes" if this surface owns it (server gates on config).// Fire-and-forget + idempotent server-side, so reconnects are harmless.- void rpc('wake.start', { surface: 'tui' })+ void rpc('wake.start', { surface: 'tui' }).catch(() => undefined)rpc<CommandsCatalogResponse>('commands.catalog', {}).then(r => {@@ -947,14 +947,23 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:if (ev.payload?.start_new_session !== false) {await newSession()}+const sid = getUiState().sid+if (!sid) {+ await rpc('wake.resume', {}).catch(() => undefined)+return}+setVoiceEnabled(true)await rpc('voice.toggle', { action: 'on' })await rpc('voice.record', { action: 'start', session_id: sid })- })()+ })().catch((e: unknown) => {+ sys(`wake: ${rpcErrorMessage(e)}`)++ void rpc('wake.resume', {}).catch(() => undefined)+ })return}diff --git a/website/docs/user-guide/features/overview.md b/website/docs/user-guide/features/overview.mdindex cb3eef22109..094b2962260 100644--- a/website/docs/user-guide/features/overview.md+++ b/website/docs/user-guide/features/overview.md@@ -32,7 +32,7 @@ Hermes Agent includes a rich set of capabilities that extend far beyond basic ch## Media & Web- **[Voice Mode](voice-mode.md)** — Full voice interaction across CLI and messaging platforms. Talk to the agent using your microphone, hear spoken replies, and have live voice conversations in Discord voice channels.-- **[Wake Word](wake-word.md)** — Hands-free "Hey Hermes" trigger for the CLI. An on-device hotword listener starts a fresh voice session when you speak the wake phrase, the "Hey Siri" way.+- **[Wake Word](wake-word.md)** — Hands-free "Hey Hermes" trigger for the CLI, TUI, and desktop app. An on-device hotword listener starts a voice session when you speak the wake phrase.- **[Browser Automation](browser.md)** — Full browser automation with multiple backends: Browserbase cloud, Browser Use cloud, local Chrome/Brave/Chromium/Edge via CDP, or local Chromium. Navigate websites, fill forms, and extract information.- **[Vision & Image Paste](vision.md)** — Multimodal vision support. Paste images from your clipboard into the CLI and ask the agent to analyze, describe, or work with them using any vision-capable model.- **[Image Generation](image-generation.md)** — Generate images from text prompts using FAL.ai. Eleven models supported (FLUX 2 Klein/Pro, GPT-Image 1.5/2, Nano Banana Pro, Ideogram V3, Recraft V4 Pro, Qwen, Z-Image Turbo, Krea V2 Medium/Large); pick one via `hermes tools`.diff --git a/website/docs/user-guide/features/wake-word.md b/website/docs/user-guide/features/wake-word.mdindex 57c5b5457d8..e9e87c87260 100644--- a/website/docs/user-guide/features/wake-word.md+++ b/website/docs/user-guide/features/wake-word.md@@ -63,7 +63,7 @@ wake_word:```yamlwake_word:enabled: false- surface: auto # which surface owns the listener: "auto" | "cli" | "tui" | "gui"+ surface: auto # eligible surface: "auto" | "cli" | "tui" | "gui"provider: openwakeword # "openwakeword" (free, local) | "porcupine"phrase: "hey jarvis" # cosmetic label only — detection is keyed by the model/keyword belowsensitivity: 0.5 # 0.0-1.0 — raise to reduce false triggers@@ -85,15 +85,19 @@ owns the listener and opens the new session when it fires:| `surface` | Behavior ||-----------|----------|-| `auto` (default) | Whichever surface you launch arms the listener. |+| `auto` (default) | All local surfaces are eligible; the first one to arm owns the listener. || `cli` | Only the classic `hermes` CLI. || `tui` | Only `hermes --tui`. || `gui` | Only the desktop app. |-The detector is on-device and single-mic, so only one surface listens at a time-— `surface` is how you pin it. The TUI and desktop GUI share the same Python-backend (`tui_gateway`), which runs the detector server-side and yields the mic-to voice capture while a command records.+The detector is on-device and single-mic, so only one surface listens at a time,+including when Hermes surfaces run in separate processes. Ownership is sticky:+the first eligible claimant keeps the listener until it stops, disconnects, or+its process exits. Hermes does not silently fail over to another open surface.+Set `surface` when you want to pin ownership instead of using first-claim wins.+The TUI and desktop GUI share the same Python backend (`tui_gateway`), which+runs the detector server-side and yields the mic to voice capture while a+command records.## Using a real "Hey Hermes"