Skip to content

The agent that grows with you

desktop: split the components the onboarding work pushed over the ratchets

alt-glitcha687738e9ced
diff --git a/apps/desktop/src/app/chat/chat-surface-state.ts b/apps/desktop/src/app/chat/chat-surface-state.ts
new file mode 100644
index 00000000000..328c32f6265
--- /dev/null
+++ b/apps/desktop/src/app/chat/chat-surface-state.ts
@@ -0,0 +1,50 @@
+import { useRef } from 'react'
+
+import { isWatchWindow } from '@/store/windows'
+
+import type { DragKind } from './hooks/use-file-drop-zone'
+import { composerStaysMounted } from './thread-loading'
+
+interface ShowChatBarOptions {
+ guideOpening: boolean
+ loadingSession: boolean
+ resumeExhausted: boolean
+ routedSessionId: null | string
+ routedSessionView: boolean
+}
+
+// Hide the composer in the exhausted error state too: there's no live runtime
+// to send to until a retry rebinds one. Watch windows are pure spectators of a
+// subagent run driven elsewhere — no composer, transcript is read-only.
+//
+// Once this route has rendered with its composer, a later transient loader
+// (periodic list/status refresh, hydrate through an empty frame) must not
+// unmount it again — see composerStaysMounted (#117375).
+export function useShowChatBar({
+ guideOpening,
+ loadingSession,
+ resumeExhausted,
+ routedSessionId,
+ routedSessionView
+}: ShowChatBarOptions): boolean {
+ const settledRoutedSessionRef = useRef<null | string>(null)
+
+ if (!guideOpening && !loadingSession && routedSessionView) {
+ settledRoutedSessionRef.current = routedSessionId
+ } else if (!routedSessionView) {
+ settledRoutedSessionRef.current = null
+ }
+
+ return composerStaysMounted({
+ hideComposer: resumeExhausted || isWatchWindow(),
+ loadingSession,
+ routedSessionId,
+ settledRoutedSessionId: settledRoutedSessionRef.current
+ })
+}
+
+// While a session drag targets one of the surface's EDGES or a tab strip, the
+// zone overlay/caret owns the visual — the link overlay stands down.
+export function dropOverlayKind(dragKind: DragKind, sessionDragging: boolean, sessionEdgeHover: boolean): DragKind {
+ return dragKind === 'files' ? 'files' : sessionDragging && !sessionEdgeHover ? 'session' : null
+}
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index e0411f868b0..a15c82f93f7 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@ -221,36 +221,57 @@ export function useComposerSubmit({
[activeQueueSessionKeyRef, inputDisabled, paneVisible, scope.target, sessionId, surfaceId]
)
- const submitDraft = () => {
- if (disabled) {
- return
- }
-
- // Source the text from the DOM editor, not React state. The AUI composer
- // state (`draft`) and the derived `hasComposerPayload` lag the DOM by a
- // render, so on fast typing or IME composition the final keystroke(s) may
- // not have synced yet — reading state here drops the message (Enter looks
- // like it does nothing; typing a trailing space only "fixes" it because the
- // extra input event forces a state sync). draftRef is updated on every
- // input event; refresh it from the editor once more to also cover an
- // in-flight keystroke that hasn't fired its input event yet.
- const editor = editorRef.current
-
- if (editor) {
- const domText = composerPlainText(editor)
+ // Returns false when the submit was refused and must not refocus the input.
+ const submitWhileBusy = (text: string, payloadPresent: boolean, blockingPrompt: boolean) => {
+ // Slash commands should execute immediately even while the agent is
+ // busy — they're client-side operations (/yolo, /skin, /new, /help,
+ // etc.) or self-contained gateway RPCs (/status, /compress). onSubmit
+ // routes them to executeSlashCommand, which has its own per-command
+ // busy guard for commands that genuinely need an idle session (skill
+ // /send directives). Queuing them would make every slash command wait
+ // for the current turn to finish, which is how the TUI never behaves.
+ if (isSlashCommandText(text)) {
+ if (attachments.length) {
+ // Slash commands cannot ride alongside attachments — warn the user
+ // instead of silently queuing the payload (which would then reach the
+ // idle path and be submitted as plain text with no command execution).
+ notify({
+ kind: 'warning',
+ title: copy.slashCommandIgnoredTitle,
+ message: copy.slashCommandIgnoredBody
+ })
- if (domText !== draftRef.current) {
- draftRef.current = domText
- setComposerText(domText)
+ return false
}
+
+ triggerHaptic('submit')
+ clearDraft()
+ dispatchSubmit(text)
+ } else if (!blockingPrompt && !attachments.length && text.trim()) {
+ // Cursor-style stop-and-correct: interrupt the live turn and redirect
+ // it with this text. redirect() preserves the shown reasoning/work; if
+ // the turn already ended, steerDraft re-queues so nothing is lost.
+ // Compaction is the gateway's call: it answers `queued` under the
+ // compression lock. The client flag can outlive an aborted compaction.
+ steerDraft()
+ } else if (payloadPresent) {
+ // Attachments can't ride a redirect (no tool-result image carriage) —
+ // queue the whole payload for the next turn. Same for a turn parked on
+ // an approval/sudo/secret prompt: a steer can't reach the model while
+ // the tool batch is blocked, so the message runs as the next turn.
+ queueCurrentDraft()
+ } else {
+ // Stop button (the only way to reach here while busy with an empty
+ // composer — empty Enter is short-circuited in the keydown handler).
+ triggerHaptic('cancel')
+ void Promise.resolve(onCancel())
}
- // A path that never got its committing space (`@apps/desktop/` left by a Tab
- // descend, then Enter) is still the reference the user picked — promote it
- // on the way out so it attaches instead of submitting as inert text.
- const text = pathifyRefs(draftRef.current)
- const payloadPresent = text.trim().length > 0 || attachments.length > 0
+ return true
+ }
+ // True when the draft was consumed as a parked clarify card's answer.
+ const answerParkedCard = (text: string, payloadPresent: boolean) => {
// A clarify or setup card parked on this session owns the turn: the agent
// is blocked inside its tool batch waiting on the card's answer, so a
// follow-up routed through steer/queue sits undelivered until the card's
@@ -282,7 +303,7 @@ export function useComposerSubmit({
clearDraft()
focusInput()
- return
+ return true
}
if (cardParked) {
@@ -294,6 +315,43 @@ export function useComposerSubmit({
void skipConnectionRequest(sessionId)
}
+ return false
+ }
+
+ const submitDraft = () => {
+ if (disabled) {
+ return
+ }
+
+ // Source the text from the DOM editor, not React state. The AUI composer
+ // state (`draft`) and the derived `hasComposerPayload` lag the DOM by a
+ // render, so on fast typing or IME composition the final keystroke(s) may
+ // not have synced yet — reading state here drops the message (Enter looks
+ // like it does nothing; typing a trailing space only "fixes" it because the
+ // extra input event forces a state sync). draftRef is updated on every
+ // input event; refresh it from the editor once more to also cover an
+ // in-flight keystroke that hasn't fired its input event yet.
+ const editor = editorRef.current
+
+ if (editor) {
+ const domText = composerPlainText(editor)
+
+ if (domText !== draftRef.current) {
+ draftRef.current = domText
+ setComposerText(domText)
+ }
+ }
+
+ // A path that never got its committing space (`@apps/desktop/` left by a Tab
+ // descend, then Enter) is still the reference the user picked — promote it
+ // on the way out so it attaches instead of submitting as inert text.
+ const text = pathifyRefs(draftRef.current)
+ const payloadPresent = text.trim().length > 0 || attachments.length > 0
+
+ if (answerParkedCard(text, payloadPresent)) {
+ return
+ }
+
// Approval / sudo / secret prompts also park the turn inside a tool batch,
// but typing CANNOT answer them (no message text approves a command or
// supplies a password), so there is no skip-and-steer path: a steer would
@@ -306,48 +364,8 @@ export function useComposerSubmit({
if (queueEdit) {
exitQueuedEdit('save')
} else if (busy) {
- // Slash commands should execute immediately even while the agent is
- // busy — they're client-side operations (/yolo, /skin, /new, /help,
- // etc.) or self-contained gateway RPCs (/status, /compress). onSubmit
- // routes them to executeSlashCommand, which has its own per-command
- // busy guard for commands that genuinely need an idle session (skill
- // /send directives). Queuing them would make every slash command wait
- // for the current turn to finish, which is how the TUI never behaves.
- if (isSlashCommandText(text)) {
- if (attachments.length) {
- // Slash commands cannot ride alongside attachments — warn the user
- // instead of silently queuing the payload (which would then reach the
- // idle path and be submitted as plain text with no command execution).
- notify({
- kind: 'warning',
- title: copy.slashCommandIgnoredTitle,
- message: copy.slashCommandIgnoredBody
- })
-
- return
- }
-
- triggerHaptic('submit')
- clearDraft()
- dispatchSubmit(text)
- } else if (!blockingPrompt && !attachments.length && text.trim()) {
- // Cursor-style stop-and-correct: interrupt the live turn and redirect
- // it with this text. redirect() preserves the shown reasoning/work; if
- // the turn already ended, steerDraft re-queues so nothing is lost.
- // Compaction is the gateway's call: it answers `queued` under the
- // compression lock. The client flag can outlive an aborted compaction.
- steerDraft()
- } else if (payloadPresent) {
- // Attachments can't ride a redirect (no tool-result image carriage) —
- // queue the whole payload for the next turn. Same for a turn parked on
- // an approval/sudo/secret prompt: a steer can't reach the model while
- // the tool batch is blocked, so the message runs as the next turn.
- queueCurrentDraft()
- } else {
- // Stop button (the only way to reach here while busy with an empty
- // composer — empty Enter is short-circuited in the keydown handler).
- triggerHaptic('cancel')
- void Promise.resolve(onCancel())
+ if (!submitWhileBusy(text, payloadPresent, blockingPrompt)) {
+ return
}
} else if (!payloadPresent && queuedPrompts.length > 0) {
void drainNextQueued()
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-middleware-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-middleware-submit.ts
new file mode 100644
index 00000000000..de13c1cf35e
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/hooks/use-middleware-submit.ts
@@ -0,0 +1,52 @@
+import { useCallback, useRef } from 'react'
+
+import { interceptsTypedVoiceStop } from '@/lib/voice-stop-word'
+
+import { runComposerMiddleware } from '../contrib'
+import type { ChatBarProps } from '../types'
+
+export interface VoiceStopHandle {
+ active: boolean
+ end: () => void
+}
+
+export function useMiddlewareSubmit(onSubmitProp: ChatBarProps['onSubmit']) {
+ // Typed stop phrase during an active voice conversation ends it — same
+ // semantics as SAYING "stop" (voice-stop-word.ts) or clicking the pill's
+ // end control. The caller populates it after useComposerVoice (the submit
+ // wrapper is created first); render-time assignment keeps the ref current.
+ const voiceStopRef = useRef<VoiceStopHandle>({ active: false, end: () => {} })
+
+ // Every send (typed, queued, voice) passes through the contributed
+ // middleware chain first — rewrite / pass-through / cancel. Empty chain =
+ // exact pass-through, so surfaces without contributions are byte-identical.
+ const onSubmit = useCallback<ChatBarProps['onSubmit']>(
+ async (value, options) => {
+ // Bare stop phrase typed while the voice conversation is live: end the
+ // conversation (mic off, pill dismissed) instead of sending "stop" to
+ // the agent. Spoken transcripts are already stop-checked inside
+ // use-voice-conversation, so this only catches typed/queued sends.
+ // Outside a voice conversation, typed "stop" is a normal message.
+ const voiceStop = voiceStopRef.current
+
+ if (interceptsTypedVoiceStop(voiceStop.active, value, options?.attachments?.length ?? 0)) {
+ voiceStop.end()
+
+ // Consumed (not rejected): report accepted so the submit engine
+ // clears the draft instead of restoring "stop" into the composer.
+ return true
+ }
+
+ const draft = await runComposerMiddleware({ text: value, attachments: options?.attachments })
+
+ if (!draft) {
+ return false
+ }
+
+ return onSubmitProp(draft.text, { ...options, attachments: draft.attachments })
+ },
+ [onSubmitProp]
+ )
+
+ return { onSubmit, voiceStopRef }
+}
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index 8ae9fac8a09..8d213fc9008 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -26,7 +26,6 @@ import { triggerHaptic } from '@/lib/haptics'
import { isMacPlatform } from '@/lib/platform'
import { useStoreSelector, useStoresSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
-import { interceptsTypedVoiceStop } from '@/lib/voice-stop-word'
import { sessionCompacting } from '@/store/compaction'
import { browseBackward, browseForward, deriveUserHistory, isBrowsingHistory } from '@/store/composer-input-history'
import { POPOUT_WIDTH_REM } from '@/store/composer-popout'
@@ -55,7 +54,7 @@ import {
slashArgStage
} from './composer-utils'
import { ContextMenu } from './context-menu'
-import { COMPOSER_AREAS, runComposerMiddleware } from './contrib'
+import { COMPOSER_AREAS } from './contrib'
import { ComposerControls } from './controls'
import { ComposerDirectiveActions } from './directive-actions'
import { COMPOSER_DROP_ACTIVE_CLASS, COMPOSER_DROP_FADE_CLASS } from './drop-affordance'
@@ -78,6 +77,7 @@ import { useComposerUrlDialog } from './hooks/use-composer-url-dialog'
import { useComposerVoice } from './hooks/use-composer-voice'
import { useEmojiCompletions } from './hooks/use-emoji-completions'
import { useComposerMicroActions } from './hooks/use-micro-actions'
+import { useMiddlewareSubmit } from './hooks/use-middleware-submit'
import { useSlashCompletions } from './hooks/use-slash-completions'
import { useStatusDrawer } from './hooks/use-status-drawer'
import { useSessionStatusPresence } from './hooks/use-status-presence'
@@ -151,42 +151,8 @@ export function ChatBar({
workspaceTransfer: hudWindowing?.workspaceTransfer === true
})
- // Typed stop phrase during an active voice conversation ends it — same
- // semantics as SAYING "stop" (voice-stop-word.ts) or clicking the pill's
- // end control. Populated after useComposerVoice below (the submit wrapper
- // is created first); render-time assignment keeps the ref current.
- const voiceStopRef = useRef<{ active: boolean; end: () => void }>({ active: false, end: () => {} })
-
- // Every send (typed, queued, voice) passes through the contributed
- // middleware chain first — rewrite / pass-through / cancel. Empty chain =
- // exact pass-through, so surfaces without contributions are byte-identical.
- const onSubmit = useCallback<ChatBarProps['onSubmit']>(
- async (value, options) => {
- // Bare stop phrase typed while the voice conversation is live: end the
- // conversation (mic off, pill dismissed) instead of sending "stop" to
- // the agent. Spoken transcripts are already stop-checked inside
- // use-voice-conversation, so this only catches typed/queued sends.
- // Outside a voice conversation, typed "stop" is a normal message.
- const voiceStop = voiceStopRef.current
-
- if (interceptsTypedVoiceStop(voiceStop.active, value, options?.attachments?.length ?? 0)) {
- voiceStop.end()
-
- // Consumed (not rejected): report accepted so the submit engine
- // clears the draft instead of restoring "stop" into the composer.
- return true
- }
-
- const draft = await runComposerMiddleware({ text: value, attachments: options?.attachments })
-
- if (!draft) {
- return false
- }
-
- return onSubmitProp(draft.text, { ...options, attachments: draft.attachments })
- },
- [onSubmitProp]
- )
+ // Voice-stop interception + contributed middleware wrap every send.
+ const { onSubmit, voiceStopRef } = useMiddlewareSubmit(onSubmitProp)
// Which live composer this instance IS (main | tile) — its attachment set,
// focus-bus key, and awaiting-input edge. Main scope = the legacy globals.
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 362680f9199..5c019a23c97 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -1,7 +1,5 @@
import { type AppendMessage, AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react'
-import type { ModelOptionsResult } from '@hermes/shared'
import { useStore } from '@nanostores/react'
-import { useQuery } from '@tanstack/react-query'
import type { ReadableAtom } from 'nanostores'
import type * as React from 'react'
import { memo, Suspense, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
@@ -23,9 +21,8 @@ import { TitleMenuTrigger } from '@/components/ui/title-menu-trigger'
import { type HermesGateway, type ResolvedOwner } from '@/hermes'
import { useI18n } from '@/i18n'
import type { ChatMessage } from '@/lib/chat-messages'
-import { NEW_SESSION_TITLE, quickModelOptions, sessionTitle } from '@/lib/chat-runtime'
+import { NEW_SESSION_TITLE, sessionTitle } from '@/lib/chat-runtime'
import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'
-import { currentModelCapabilities, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { migrateSessionDraft } from '@/store/composer'
@@ -55,12 +52,13 @@ import {
import { $focusedStoredSessionId } from '@/store/session-focus'
import { $sessionStates, sessionTileDelegate } from '@/store/session-states'
import { $transcriptTailBySessionId, transcriptTailState } from '@/store/transcript-tail'
-import { isAuxiliaryWindow, isMainWindow, isWatchWindow } from '@/store/windows'
+import { isAuxiliaryWindow, isMainWindow } from '@/store/windows'
import { primaryRouteSelectedSessionId, routeSessionId } from '../routes'
import { titlebarHeaderBaseClass, titlebarHeaderShadowClass, titlebarHeaderTitleClass } from '../shell/titlebar'
import { ChatDropOverlay } from './chat-drop-overlay'
+import { dropOverlayKind, useShowChatBar } from './chat-surface-state'
import { ChatSwapOverlay, ChatSyncBadge } from './chat-swap-overlay'
import { ChatBar, ChatBarFallback } from './composer'
import { FloatingComposerSurface } from './composer/floating-surface'
@@ -72,10 +70,9 @@ import {
useComposerScope,
useComposerSurfaceId
} from './composer/scope'
-import type { ChatBarState } from './composer/types'
import { useHistoryWindow } from './history-window'
import { type DroppedFile, partitionDroppedFiles } from './hooks/use-composer-actions'
-import { type DragKind, useFileDropZone } from './hooks/use-file-drop-zone'
+import { useFileDropZone } from './hooks/use-file-drop-zone'
import { shouldShowIntro } from './intro-visibility'
import { ProfileTag } from './profile-tag'
import { ResumeExhaustedOverlay } from './resume-exhausted-overlay'
@@ -84,13 +81,14 @@ import { useRuntimeMessageRepository } from './runtime-repository'
import { ScrollToBottomButton } from './scroll-to-bottom-button'
import { useSessionView } from './session-view'
import { SessionActionsMenu } from './sidebar/session-actions-menu'
-import { composerStaysMounted, routedSessionIsLoading, threadLoadingState } from './thread-loading'
+import { routedSessionIsLoading, threadLoadingState } from './thread-loading'
import {
backfillOlderTranscriptPage,
mergeOlderTranscriptPage,
transcriptBackfillAvailable
} from './transcript-backfill'
import { advanceSessionTranscriptWindow, type SessionWindowMemo } from './transcript-window'
+import { useChatBarState } from './use-chat-bar-state'
import { useTranscriptRetention } from './use-transcript-retention'
interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
@@ -681,87 +679,32 @@ const ChatViewContent = memo(function ChatViewContent({
})
const threadLoading = threadLoadingState(loadingSession, busy, awaitingResponse, lastVisibleIsUser)
- // Hide the composer in the exhausted error state too: there's no live runtime
- // to send to until a retry rebinds one. Watch windows are pure spectators of a
- // subagent run driven elsewhere — no composer, transcript is read-only.
- //
- // Once this route has rendered with its composer, a later transient loader
- // (periodic list/status refresh, hydrate through an empty frame) must not
- // unmount it again — see composerStaysMounted (#117375).
- const settledRoutedSessionRef = useRef<null | string>(null)
-
- if (!guideOpening && !loadingSession && isRoutedSessionView) {
- settledRoutedSessionRef.current = routedSessionId
- } else if (!isRoutedSessionView) {
- settledRoutedSessionRef.current = null
- }
- const showChatBar = composerStaysMounted({
- hideComposer: resumeExhausted || isWatchWindow(),
+ const showChatBar = useShowChatBar({
+ guideOpening,
loadingSession,
+ resumeExhausted,
routedSessionId,
- settledRoutedSessionId: settledRoutedSessionRef.current
+ routedSessionView: isRoutedSessionView
})
const threadKey = selectedSessionId || activeSessionId || (isRoutedSessionView ? location.pathname : 'new')
- const modelOptionsQuery = useQuery<ModelOptionsResult>({
- queryKey: modelOptionsQueryKey(
- modelOptionsProfile || activeGatewayProfile,
- activeSessionId,
- modelOptionsOwnerConnectionId
- ),
- queryFn: () =>
- requestModelOptions({
- gateway: gateway || undefined,
- profile: modelOptionsProfile || activeGatewayProfile,
- request: requestModelOptionsForOwner,
- sessionId: activeSessionId
- }),
- enabled: gatewayOpen
+ const chatBarState = useChatBarState({
+ activeGatewayProfile,
+ activeSessionId,
+ contextSuggestions,
+ currentModel,
+ currentProvider,
+ gateway,
+ gatewayOpen,
+ modelMenuContent,
+ modelOptionsOwnerConnectionId,
+ modelOptionsProfile,
+ reasoningMenuContent,
+ requestModelOptionsForOwner
})
- const quickModels = useMemo(
- () => quickModelOptions(modelOptionsQuery.data, currentProvider, currentModel),
- [currentModel, currentProvider, modelOptionsQuery.data]
- )
-
- const supportsReasoning = currentModelCapabilities(modelOptionsQuery.data, currentProvider, currentModel)?.reasoning
-
- const chatBarState = useMemo<ChatBarState>(
- () => ({
- model: {
- model: currentModel,
- provider: currentProvider,
- canSwitch: gatewayOpen,
- loading: !gatewayOpen || (!currentModel && !currentProvider),
- modelMenuContent,
- quickModels,
- reasoningMenuContent,
- supportsReasoning
- },
- tools: {
- enabled: true,
- label: 'Add context',
- suggestions: contextSuggestions
- },
- voice: {
- enabled: true,
- active: false
- }
- }),
- [
- contextSuggestions,
- currentModel,
- currentProvider,
- gatewayOpen,
- modelMenuContent,
- quickModels,
- reasoningMenuContent,
- supportsReasoning
- ]
- )
-
// Drop files anywhere in the conversation area, not just on the composer
// input. In-app drags (project tree / gutter) carry workspace-relative paths
// the gateway resolves directly, so they stay inline `@file:` refs. OS/Finder
@@ -800,7 +743,7 @@ const ChatViewContent = memo(function ChatViewContent({
const sessionDragging = useStore($sessionTileDragging)
const sessionEdgeHover = useStore($sessionTileEdgeHover)
- const overlayKind: DragKind = dragKind === 'files' ? 'files' : sessionDragging && !sessionEdgeHover ? 'session' : null
+ const overlayKind = dropOverlayKind(dragKind, sessionDragging, sessionEdgeHover)
return (
<div
diff --git a/apps/desktop/src/app/chat/use-chat-bar-state.ts b/apps/desktop/src/app/chat/use-chat-bar-state.ts
new file mode 100644
index 00000000000..6e10b278281
--- /dev/null
+++ b/apps/desktop/src/app/chat/use-chat-bar-state.ts
@@ -0,0 +1,99 @@
+import type { ModelOptionsResult } from '@hermes/shared'
+import { useQuery } from '@tanstack/react-query'
+import type * as React from 'react'
+import { useMemo } from 'react'
+
+import type { HermesGateway } from '@/hermes'
+import { quickModelOptions } from '@/lib/chat-runtime'
+import { currentModelCapabilities, modelOptionsQueryKey, requestModelOptions } from '@/lib/model-options'
+
+import type { ChatBarState } from './composer/types'
+
+interface ChatBarStateOptions {
+ activeGatewayProfile: string
+ activeSessionId: null | string
+ contextSuggestions: ChatBarState['tools']['suggestions']
+ currentModel: string
+ currentProvider: string
+ gateway: HermesGateway | null
+ gatewayOpen: boolean
+ modelMenuContent?: React.ReactNode
+ modelOptionsOwnerConnectionId?: string
+ modelOptionsProfile?: string
+ reasoningMenuContent?: React.ReactNode
+ requestModelOptionsForOwner?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>
+}
+
+// The composer's model / tools / voice state, backed by the model-options query
+// for the active session's profile.
+export function useChatBarState({
+ activeGatewayProfile,
+ activeSessionId,
+ contextSuggestions,
+ currentModel,
+ currentProvider,
+ gateway,
+ gatewayOpen,
+ modelMenuContent,
+ modelOptionsOwnerConnectionId,
+ modelOptionsProfile,
+ reasoningMenuContent,
+ requestModelOptionsForOwner
+}: ChatBarStateOptions): ChatBarState {
+ const modelOptionsQuery = useQuery<ModelOptionsResult>({
+ queryKey: modelOptionsQueryKey(
+ modelOptionsProfile || activeGatewayProfile,
+ activeSessionId,
+ modelOptionsOwnerConnectionId
+ ),
+ queryFn: () =>
+ requestModelOptions({
+ gateway: gateway || undefined,
+ profile: modelOptionsProfile || activeGatewayProfile,
+ request: requestModelOptionsForOwner,
+ sessionId: activeSessionId
+ }),
+ enabled: gatewayOpen
+ })
+
+ const quickModels = useMemo(
+ () => quickModelOptions(modelOptionsQuery.data, currentProvider, currentModel),
+ [currentModel, currentProvider, modelOptionsQuery.data]
+ )
+
+ const supportsReasoning = currentModelCapabilities(modelOptionsQuery.data, currentProvider, currentModel)?.reasoning
+
+ return useMemo<ChatBarState>(
+ () => ({
+ model: {
+ model: currentModel,
+ provider: currentProvider,
+ canSwitch: gatewayOpen,
+ loading: !gatewayOpen || (!currentModel && !currentProvider),
+ modelMenuContent,
+ quickModels,
+ reasoningMenuContent,
+ supportsReasoning
+ },
+ tools: {
+ enabled: true,
+ label: 'Add context',
+ suggestions: contextSuggestions
+ },
+ voice: {
+ enabled: true,
+ active: false
+ }
+ }),
+ [
+ contextSuggestions,
+ currentModel,
+ currentProvider,
+ gatewayOpen,
+ modelMenuContent,
+ quickModels,
+ reasoningMenuContent,
+ supportsReasoning
+ ]
+ )
+}
diff --git a/apps/desktop/src/app/contrib/wiring-effects.ts b/apps/desktop/src/app/contrib/wiring-effects.ts
new file mode 100644
index 00000000000..45ffc6018a8
--- /dev/null
+++ b/apps/desktop/src/app/contrib/wiring-effects.ts
@@ -0,0 +1,99 @@
+import { useStore } from '@nanostores/react'
+import { useEffect, useRef } from 'react'
+import type { NavigateFunction } from 'react-router'
+
+import { $freshSessionRequest, refreshActiveProfile } from '@/store/profile'
+
+import { resetProjectTreeState } from '../right-sidebar/files/use-project-tree'
+import { SETTINGS_ROUTE } from '../routes'
+
+import { $restartPreviewServer } from './panes'
+
+type RestartPreviewServer = NonNullable<ReturnType<typeof $restartPreviewServer.get>>
+
+// Palette "Keyboard shortcuts" entry dispatches a custom event (contributions
+// don't have router access); listen and navigate to the settings keybinds tab.
+export function useOpenKeybindsListener(navigate: NavigateFunction) {
+ useEffect(() => {
+ const onOpenKeybinds = () => navigate(`${SETTINGS_ROUTE}?tab=keybinds`)
+ window.addEventListener('hermes:open-keybinds', onOpenKeybinds)
+
+ return () => window.removeEventListener('hermes:open-keybinds', onOpenKeybinds)
+ }, [navigate])
+}
+
+// Dev-only: install the credit-notice demo trigger (Ctrl+Shift+C / ⌘K palette
+// / window.__creditsDemo). Dynamic import inside the DEV guard so the module
+// is dropped from production builds.
+export function useCreditsNoticeDemo() {
+ useEffect(() => {
+ if (!import.meta.env.DEV) {
+ return
+ }
+
+ let dispose: (() => void) | undefined
+
+ void import('./dev/credits-notice-demo').then(m => {
+ dispose = m.installCreditsNoticeDemo()
+ })
+
+ return () => dispose?.()
+ }, [])
+}
+
+// Expose the restart handler to the preview pane contribution (module
+// boundary crossed via atom — contrib-panes can't import wiring.tsx).
+export function usePublishRestartPreviewServer(restartPreviewServer: RestartPreviewServer) {
+ useEffect(() => {
+ $restartPreviewServer.set(restartPreviewServer)
+
+ return () => $restartPreviewServer.set(null)
+ }, [restartPreviewServer])
+}
+
+// A profile switch/create drops to a fresh new-session draft so the
+// previously open session doesn't bleed across contexts. Skip initial value.
+export function useFreshSessionRequest(startFreshSessionDraft: () => void) {
+ const freshSessionRequest = useStore($freshSessionRequest)
+ const lastFreshRef = useRef(freshSessionRequest)
+
+ // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
+ useEffect(() => {
+ if (freshSessionRequest === lastFreshRef.current) {
+ return
+ }
+
+ lastFreshRef.current = freshSessionRequest
+ startFreshSessionDraft()
+ }, [freshSessionRequest, startFreshSessionDraft])
+}
+
+// Swapping the live gateway to another source or profile must re-pull that
+// source's model/config/profile state. Two sources commonly both expose a
+// `default` profile, so profile alone is not a sufficient identity.
+export function useGatewayScopeRefresh(
+ activeConnectionId: null | string,
+ activeGatewayProfile: string,
+ refreshCurrentModel: (force: boolean) => Promise<unknown>,
+ refreshHermesConfig: (force: boolean) => Promise<unknown>
+) {
+ const gatewayScope = `${activeConnectionId ?? ''}\0${activeGatewayProfile}`
+ const lastGatewayScopeRef = useRef(gatewayScope)
+
+ // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
+ useEffect(() => {
+ if (gatewayScope === lastGatewayScopeRef.current) {
+ return
+ }
+
+ lastGatewayScopeRef.current = gatewayScope
+ // Force: the new source/profile pair has its own defaults, so reseed the
+ // selector even if the composer already shows values from the previous
+ // backend. These refreshes carry intent tokens so an in-flight picker
+ // click still wins.
+ void refreshCurrentModel(true)
+ void refreshHermesConfig(true)
+ void refreshActiveProfile()
+ resetProjectTreeState()
+ }, [gatewayScope, refreshCurrentModel, refreshHermesConfig])
+}
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 4f18001a5c7..d66d6fe63b3 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -57,13 +57,11 @@ import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
import { $previewTarget } from '@/store/preview'
import {
$activeGatewayProfile,
- $freshSessionRequest,
$profileScope,
ALL_PROFILES,
ensureGatewayProfile,
newSessionInProfile,
- normalizeProfileKey,
- refreshActiveProfile
+ normalizeProfileKey
} from '@/store/profile'
import { $newProjectSessionRequest, $startWorkSessionRequest, followActiveSessionCwd } from '@/store/projects'
import { $backendRestartRequest, $routeRequest } from '@/store/recovery-requests'
@@ -171,10 +169,17 @@ import { useSessionTileDelegate } from './hooks/use-session-tile-delegate'
import { McpInstallDeepLinkDialog } from './mcp-install-deeplink-dialog'
import { useOnboardingHandoff } from './onboarding-handoff'
import { type KickoffSlashCommand, useOnboardingKickoff } from './onboarding-kickoff'
-import { $restartPreviewServer, useTitlebarToolContributions } from './panes'
+import { useTitlebarToolContributions } from './panes'
import { type AmbientGatewayRequest, createSessionRpcDispatcher } from './session-rpc-dispatcher'
import { ChatRoutesSurface, SidebarSurface, StatusbarSurface, TerminalSurface } from './surfaces'
import type { WiringActions, WiringApi } from './types'
+import {
+ useCreditsNoticeDemo,
+ useFreshSessionRequest,
+ useGatewayScopeRefresh,
+ useOpenKeybindsListener,
+ usePublishRestartPreviewServer
+} from './wiring-effects'
import { POOL_LIMITS_SETTINGS_ROUTE } from './wiring-routing'
// Overlay views the controller mounts over the shell — lazy, load on demand.
@@ -462,31 +467,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {
const openProviderSettings = useCallback(() => navigate(`${SETTINGS_ROUTE}?tab=providers`), [navigate])
- // Palette "Keyboard shortcuts" entry dispatches a custom event (contributions
- // don't have router access); listen and navigate to the settings keybinds tab.
- useEffect(() => {
- const onOpenKeybinds = () => navigate(`${SETTINGS_ROUTE}?tab=keybinds`)
- window.addEventListener('hermes:open-keybinds', onOpenKeybinds)
-
- return () => window.removeEventListener('hermes:open-keybinds', onOpenKeybinds)
- }, [navigate])
-
- // Dev-only: install the credit-notice demo trigger (Ctrl+Shift+C / ⌘K palette
- // / window.__creditsDemo). Dynamic import inside the DEV guard so the module
- // is dropped from production builds.
- useEffect(() => {
- if (!import.meta.env.DEV) {
- return
- }
-
- let dispose: (() => void) | undefined
-
- void import('./dev/credits-notice-demo').then(m => {
- dispose = m.installCreditsNoticeDemo()
- })
-
- return () => dispose?.()
- }, [])
+ useOpenKeybindsListener(navigate)
+ useCreditsNoticeDemo()
// Post-turn rehydrate from stored history (same behavior as DesktopController,
// including finished-todos restoration).
@@ -560,13 +542,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
requestGateway
})
- // Expose the restart handler to the preview pane contribution (module
- // boundary crossed via atom — contrib-panes can't import this file).
- useEffect(() => {
- $restartPreviewServer.set(restartPreviewServer)
-
- return () => $restartPreviewServer.set(null)
- }, [restartPreviewServer])
+ usePublishRestartPreviewServer(restartPreviewServer)
const {
archiveSession,
@@ -603,43 +579,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {
updateSessionState
})
- // A profile switch/create drops to a fresh new-session draft so the
- // previously open session doesn't bleed across contexts. Skip initial value.
- const freshSessionRequest = useStore($freshSessionRequest)
- const lastFreshRef = useRef(freshSessionRequest)
-
- // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
- useEffect(() => {
- if (freshSessionRequest === lastFreshRef.current) {
- return
- }
-
- lastFreshRef.current = freshSessionRequest
- startFreshSessionDraft()
- }, [freshSessionRequest, startFreshSessionDraft])
-
- // Swapping the live gateway to another source or profile must re-pull that
- // source's model/config/profile state. Two sources commonly both expose a
- // `default` profile, so profile alone is not a sufficient identity.
- const gatewayScope = `${activeConnectionId ?? ''}\0${activeGatewayProfile}`
- const lastGatewayScopeRef = useRef(gatewayScope)
-
- // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
- useEffect(() => {
- if (gatewayScope === lastGatewayScopeRef.current) {
- return
- }
-
- lastGatewayScopeRef.current = gatewayScope
- // Force: the new source/profile pair has its own defaults, so reseed the
- // selector even if the composer already shows values from the previous
- // backend. These refreshes carry intent tokens so an in-flight picker
- // click still wins.
- void refreshCurrentModel(true)
- void refreshHermesConfig(true)
- void refreshActiveProfile()
- resetProjectTreeState()
- }, [gatewayScope, refreshCurrentModel, refreshHermesConfig])
+ useFreshSessionRequest(startFreshSessionDraft)
+ useGatewayScopeRefresh(activeConnectionId, activeGatewayProfile, refreshCurrentModel, refreshHermesConfig)
// New session anchored to a workspace. Seeds cwd + branch from the clicked
// workspace; an explicit worktree path also drills the sidebar into that
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index 19109178268..cfd80d57fa5 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -4,6 +4,7 @@ import { burstVibeHearts } from '@/components/chat/vibe-hearts'
import { $chatOnboardingThreadIds } from '@/components/onboarding-chat/assembly'
import { reportFirstBuildTurnComplete } from '@/components/onboarding-chat/first-build'
import { translateNow } from '@/i18n'
+import type { GatewayEventPayload } from '@/lib/chat-messages'
import { coerceGatewayText, coerceThinkingText } from '@/lib/chat-runtime'
import { playCompletionSound } from '@/lib/completion-sound'
import { parseErrorSurface } from '@/lib/error-surface'
@@ -68,6 +69,74 @@ function surfaceBillingBlock(sessionId: string, raw: unknown): void {
})
}
+/** Terminal error frames (status "error") carry the failure in structured
+ * fields: `error` is the message, `partial` marks `text` as streamed output to
+ * keep rather than the error string, and `error_surface` (newer gateways)
+ * names the failing layer for the card. */
+function turnFailure(payload: GatewayEventPayload | undefined, finalText: string) {
+ if (payload?.status !== 'error') {
+ return undefined
+ }
+
+ return {
+ error: coerceGatewayText(payload.error).trim() || finalText || 'Hermes reported an error',
+ partial: Boolean(payload.partial),
+ surface: parseErrorSurface(payload.error_surface)
+ }
+}
+
+function reportOnboardingTurnComplete(ctx: GatewayEventContext, sessionId: string, finalText: string): void {
+ // Onboarding's first build: between turns is the only moment Setup may
+ // put a check-in into that session (no-op everywhere else).
+ reportFirstBuildTurnComplete(sessionId, finalText)
+
+ // The whole agent loop has returned: the end of a task, not a step in one.
+ // Only the session on screen counts, which drops subagent mirrors (child ids).
+ if (!ctx.isActiveEvent) {
+ return
+ }
+
+ const setupThreads = $chatOnboardingThreadIds.get()
+ const storedId = storedSessionIdForRuntimeId(sessionId)
+
+ reportLocalSetupTurnComplete({
+ failed: ctx.payload?.status !== 'complete',
+ sessionId,
+ setupChat: setupThreads.includes(sessionId) || (storedId !== null && setupThreads.includes(storedId))
+ })
+}
+
+function appendMoaReference(ctx: GatewayEventContext, sessionId: string): void {
+ const { deps, payload, occurredAt } = ctx
+ const label = coerceGatewayText(payload?.label) || 'reference'
+ const idx = typeof payload?.index === 'number' ? payload.index : undefined
+ const cnt = typeof payload?.count === 'number' ? payload.count : undefined
+ const header = idx && cnt ? `◇ Reference ${idx}/${cnt} — ${label}` : `◇ Reference — ${label}`
+ const body = coerceThinkingText(payload?.text)
+ const text = `${header}\n${body}\n\n`
+
+ if (idx === undefined || idx <= 1) {
+ // First reference: clear any stale reasoning left over from
+ // before this turn's references start, same as before.
+ deps.appendReasoningDelta(sessionId, text, true, occurredAt)
+
+ return
+ }
+
+ // Later references must accumulate, not replace — otherwise
+ // each new reference wipes out the ones already shown (#64658).
+ // Queue-then-flush (rather than the streamed/batched queue path)
+ // applies it immediately, since each reference arrives as one
+ // complete block rather than incremental tokens. reasoning.delta
+ // cannot be mid-flight here: MoAChatCompletions.reference_callback
+ // (agent/moa_loop.py) fires "moa.reference" once per reference's
+ // already-complete text, with no concurrent token stream for the
+ // reference-gathering phase, so there is no in-flight delta to
+ // collide with in the shared queue bucket.
+ deps.appendReasoningDelta(sessionId, text, false, occurredAt)
+ deps.flushQueuedDeltas(sessionId)
+}
+
/** The message/reasoning/MoA streaming family: message.start → deltas →
* interim → complete, thinking/reasoning deltas, moa.* progress, reaction. */
export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
@@ -247,31 +316,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
// the mixture-of-agents process is visible. Reuses the reasoning
// disclosure rather than introducing a parallel surface.
if (sessionId) {
- const label = coerceGatewayText(payload?.label) || 'reference'
- const idx = typeof payload?.index === 'number' ? payload.index : undefined
- const cnt = typeof payload?.count === 'number' ? payload.count : undefined
- const header = idx && cnt ? `◇ Reference ${idx}/${cnt} — ${label}` : `◇ Reference — ${label}`
- const body = coerceThinkingText(payload?.text)
- const text = `${header}\n${body}\n\n`
-
- if (idx === undefined || idx <= 1) {
- // First reference: clear any stale reasoning left over from
- // before this turn's references start, same as before.
- appendReasoningDelta(sessionId, text, true, occurredAt)
- } else {
- // Later references must accumulate, not replace — otherwise
- // each new reference wipes out the ones already shown (#64658).
- // Queue-then-flush (rather than the streamed/batched queue path)
- // applies it immediately, since each reference arrives as one
- // complete block rather than incremental tokens. reasoning.delta
- // cannot be mid-flight here: MoAChatCompletions.reference_callback
- // (agent/moa_loop.py) fires "moa.reference" once per reference's
- // already-complete text, with no concurrent token stream for the
- // reference-gathering phase, so there is no in-flight delta to
- // collide with in the shared queue bucket.
- appendReasoningDelta(sessionId, text, false, occurredAt)
- flushQueuedDeltas(sessionId)
- }
+ appendMoaReference(ctx, sessionId)
}
if (isActiveEvent) {
@@ -355,24 +400,11 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
const finalText = coerceGatewayText(payload?.text) || coerceGatewayText(payload?.rendered)
- // Terminal error frames (status "error") carry the failure in
- // structured fields: `error` is the message, `partial` marks
- // `text` as streamed output to keep rather than the error string, and
- // `error_surface` (newer gateways) names the failing layer for the card.
- const failure =
- payload?.status === 'error'
- ? {
- error: coerceGatewayText(payload.error).trim() || finalText || 'Hermes reported an error',
- partial: Boolean(payload.partial),
- surface: parseErrorSurface(payload.error_surface)
- }
- : undefined
-
completeAssistantMessage(
sessionId,
finalText,
payload?.response_previewed,
- failure,
+ turnFailure(payload, finalText),
occurredAt,
payload?.persisted_turn,
Boolean(payload?.response_transformed),
@@ -380,22 +412,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
payload?.response_reused === true
)
- // Onboarding's first build: between turns is the only moment Setup may
- // put a check-in into that session (no-op everywhere else).
- reportFirstBuildTurnComplete(sessionId, finalText)
-
- // The whole agent loop has returned: the end of a task, not a step in one.
- // Only the session on screen counts, which drops subagent mirrors (child ids).
- if (isActiveEvent) {
- const setupThreads = $chatOnboardingThreadIds.get()
- const storedId = storedSessionIdForRuntimeId(sessionId)
-
- reportLocalSetupTurnComplete({
- failed: payload?.status !== 'complete',
- sessionId,
- setupChat: setupThreads.includes(sessionId) || (storedId !== null && setupThreads.includes(storedId))
- })
- }
+ reportOnboardingTurnComplete(ctx, sessionId, finalText)
// Structured billing wall forwarded by the gateway (out of credits /
// payment required) — cache it + raise a billing-specific toast.
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
index cbeb4b7d9ea..63294ad9848 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/tools.ts
@@ -1,7 +1,7 @@
import { isPreviewableTarget, toolPreviewOutcome } from '@/components/assistant-ui/tool/fallback-model'
import { reportFirstBuildToolComplete } from '@/components/onboarding-chat/first-build'
import { finishGuidedOnboarding } from '@/components/onboarding-chat/intro'
-import { toolCallOwnerMessageId } from '@/lib/chat-messages'
+import { type GatewayEventPayload, toolCallOwnerMessageId } from '@/lib/chat-messages'
import { invalidateSlashCompletions } from '@/lib/slash-completion-cache'
import { refreshBackgroundProcesses } from '@/store/composer-status'
import { flashPetActivity, setPetActivity } from '@/store/pet'
@@ -19,6 +19,41 @@ import { SUBAGENT_EVENT_TYPES, toTodoPayload } from '../utils'
import type { GatewayEventContext } from './types'
+function recordToolPreview(ctx: GatewayEventContext, sessionId: string, cwd: string, pendingProduction: boolean): void {
+ const { event, payload, occurredAt } = ctx
+
+ if (!payload?.name || payload.result === undefined || event.seq === undefined) {
+ return
+ }
+
+ const { previewTarget, status } = toolPreviewOutcome({
+ type: 'tool-call',
+ toolName: payload.name,
+ args: payload.args ?? {},
+ result: payload.result,
+ toolResultMetadata: payload,
+ completedAt: occurredAt
+ })
+
+ if (status === 'success' && previewTarget && isPreviewableTarget(previewTarget)) {
+ const record = pendingProduction ? reofferPreviewArtifact : recordPreviewArtifact
+ record(sessionId, previewTarget, cwd, storedSessionIdForRuntimeId(sessionId) ?? sessionId)
+ }
+}
+
+function reportStartChatHandoff(payload: GatewayEventPayload | undefined, sessionId: string): void {
+ if (payload?.name !== 'start_chat' || readStartChatResult(payload.result)?.status !== 'started') {
+ return
+ }
+
+ if (isStartChatCallerWatched(storedSessionIdForRuntimeId(sessionId) ?? sessionId)) {
+ markLiveStartChat(payload.tool_id || payload.tool_call_id || payload.id || '')
+ }
+
+ // From the setup chat, the handoff completes the guided first run (no-op elsewhere).
+ finishGuidedOnboarding(sessionId)
+}
+
/** tool.generating / tool.start / tool.complete / subagent.*. */
export function handleToolEvent(ctx: GatewayEventContext): boolean {
const { deps, event, payload, sessionId, isActiveEvent, occurredAt } = ctx
@@ -82,37 +117,16 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {
upsertToolCall(sessionId, toTodoPayload(payload) ?? payload, 'complete', event.type, occurredAt)
- if (!sessionInterrupted(sessionId) && payload?.name && payload.result !== undefined && event.seq !== undefined) {
- const { previewTarget, status } = toolPreviewOutcome({
- type: 'tool-call',
- toolName: payload.name,
- args: payload.args ?? {},
- result: payload.result,
- toolResultMetadata: payload,
- completedAt: occurredAt
- })
-
- if (status === 'success' && previewTarget && isPreviewableTarget(previewTarget)) {
- const record = pendingProduction ? reofferPreviewArtifact : recordPreviewArtifact
- record(sessionId, previewTarget, state?.cwd ?? '', storedSessionIdForRuntimeId(sessionId) ?? sessionId)
- }
+ if (!sessionInterrupted(sessionId)) {
+ recordToolPreview(ctx, sessionId, state?.cwd ?? '', pendingProduction)
}
// Onboarding's first build paces its check-ins off real work done
// (no-op in every other session).
reportFirstBuildToolComplete(sessionId)
- if (
- !event.replayed &&
- payload?.name === 'start_chat' &&
- readStartChatResult(payload.result)?.status === 'started'
- ) {
- if (isStartChatCallerWatched(storedSessionIdForRuntimeId(sessionId) ?? sessionId)) {
- markLiveStartChat(payload.tool_id || payload.tool_call_id || payload.id || '')
- }
-
- // From the setup chat, the handoff completes the guided first run (no-op elsewhere).
- finishGuidedOnboarding(sessionId)
+ if (!event.replayed) {
+ reportStartChatHandoff(payload, sessionId)
}
if (isActiveEvent) {
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index 79b13415fec..8a926751f36 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@ -168,6 +168,19 @@ interface SlashCommandDeps {
}
/** The /slash command dispatcher, extracted from usePromptActions. */
+type CommandDispatch = NonNullable<ReturnType<typeof parseCommandDispatch>>
+
+function dispatchDisplayText(dispatch: CommandDispatch, message: string): string | undefined {
+ const projected = 'display' in dispatch ? dispatch.display?.trim() : ''
+
+ return projected || skillInvocationText(message) || undefined
+}
+
+const BUSY_KICKOFF_TEXT = {
+ queued: 'session busy — message queued to send when the current turn finishes',
+ busy: 'session busy — stop the current reply first (Stop button or Esc), then send this command'
+} as const
+
export function useSlashCommand(deps: SlashCommandDeps) {
const {
activeSessionIdRef,
@@ -361,8 +374,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {
// model-facing scaffolding. Never render it; the bubble shows the
// invocation the gateway projected, or one read from the payload
// when the backend is older than this app.
- const projected = 'display' in dispatch ? dispatch.display?.trim() : ''
- const displayText = projected || skillInvocationText(message) || undefined
+ const displayText = dispatchDisplayText(dispatch, message)
// Gate on the TARGET session's own busy state, not the foreground
// view's — see isTargetSessionBusy. `busyRef` mirrors whatever chat
@@ -382,11 +394,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {
})
if (queued !== 'idle') {
- renderSlashOutput(
- queued === 'queued'
- ? 'session busy — message queued to send when the current turn finishes'
- : 'session busy — stop the current reply first (Stop button or Esc), then send this command'
- )
+ renderSlashOutput(BUSY_KICKOFF_TEXT[queued])
return
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/branch-create-key.ts b/apps/desktop/src/app/session/hooks/use-session-actions/branch-create-key.ts
new file mode 100644
index 00000000000..7d0086691a9
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/branch-create-key.ts
@@ -0,0 +1,41 @@
+import type { SessionOwnerRoute } from '@/store/session-request-router'
+
+import type { BranchMessage } from './utils'
+
+interface BranchCreateKeyInput {
+ branchCount?: number
+ branchMessages: BranchMessage[]
+ cwd?: string
+ ownerRoute?: SessionOwnerRoute
+ parentStoredId: null | string
+ profile?: null | string
+ sourceSessionId: null | string
+}
+
+const branchMessagesFingerprint = (messages: BranchMessage[]): string =>
+ JSON.stringify(messages.map(({ content, role }) => [role, content]))
+
+// Identity of one branch create, so a re-entered branch action (a retried
+// renderer transition, a double right-click) rides the create already in
+// flight instead of minting a second child. The OWNER is part of the identity:
+// the same parent id served by two connections is two different sessions.
+export function branchCreateKey({
+ branchCount,
+ branchMessages,
+ cwd,
+ ownerRoute,
+ parentStoredId,
+ profile,
+ sourceSessionId
+}: BranchCreateKeyInput): string {
+ return JSON.stringify({
+ branchCount: branchCount ?? null,
+ connectionId: ownerRoute?.connectionId || null,
+ cwd: cwd?.trim() || null,
+ messages: sourceSessionId ? null : branchMessagesFingerprint(branchMessages),
+ ownerProfile: ownerRoute?.profile || null,
+ parentStoredId,
+ profile: profile?.trim() || null,
+ sourceSessionId
+ })
+}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index e6b9e249fd8..716a3237e71 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -163,6 +163,7 @@ import type { ClientSessionState, SidebarNavItem } from '../../../types'
import { pinStoredSessionForOwner, releaseStoredSessionPins, sessionContextDrift } from '../session-context-drift'
import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
+import { branchCreateKey } from './branch-create-key'
import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'
import { markSessionCreatedThisRun, sessionCreatedThisRun } from './created-this-run'
import { captureDisplayHydration } from './display-hydration'
@@ -246,42 +247,6 @@ export interface BranchLoadedSessionOptions {
storedSessionId: null | string
}
-const branchMessagesFingerprint = (messages: BranchMessage[]): string =>
- JSON.stringify(messages.map(({ content, role }) => [role, content]))
-
-// Identity of one branch create, so a re-entered branch action (a retried
-// renderer transition, a double right-click) rides the create already in
-// flight instead of minting a second child. The OWNER is part of the identity:
-// the same parent id served by two connections is two different sessions.
-function branchCreateKey({
- branchCount,
- branchMessages,
- cwd,
- ownerRoute,
- parentStoredId,
- profile,
- sourceSessionId
-}: {
- branchCount?: number
- branchMessages: BranchMessage[]
- cwd?: string
- ownerRoute?: SessionOwnerRoute
- parentStoredId: null | string
- profile?: null | string
- sourceSessionId: null | string
-}): string {
- return JSON.stringify({
- branchCount: branchCount ?? null,
- connectionId: ownerRoute?.connectionId || null,
- cwd: cwd?.trim() || null,
- messages: sourceSessionId ? null : branchMessagesFingerprint(branchMessages),
- ownerProfile: ownerRoute?.profile || null,
- parentStoredId,
- profile: profile?.trim() || null,
- sourceSessionId
- })
-}
-
// How long we keep creatingSessionRef after create/fork navigate before giving up
// if the router never lands on the pending stored id (stuck navigate / lost race).
const CREATE_GUARD_RELEASE_MS = 3_000
diff --git a/apps/desktop/src/app/shell/model-catalog-menu.tsx b/apps/desktop/src/app/shell/model-catalog-menu.tsx
index 6967dbdb4c4..138dbcc0fa4 100644
--- a/apps/desktop/src/app/shell/model-catalog-menu.tsx
+++ b/apps/desktop/src/app/shell/model-catalog-menu.tsx
@@ -196,6 +196,35 @@ interface ProviderGroup {
provider: ModelOptionProvider
}
+function queryErrorMessage(error: unknown): null | string {
+ return error ? (error instanceof Error ? error.message : String(error)) : null
+}
+
+function useDownloadRows(owner: LocalModelsOwner, localModelsEnabled: boolean) {
+ const downloadsKey: string = useLocalRuntimeJobs(
+ owner,
+ (jobs: readonly LocalRuntimeJob[]): string =>
+ localModelsEnabled
+ ? runningModelDownloads(jobs)
+ .map(job => `${job.job_id}\u0000${job.target}`)
+ .join('\u0001')
+ : '',
+ localModelsEnabled
+ )
+
+ return useMemo(
+ () =>
+ downloadsKey === ''
+ ? []
+ : downloadsKey.split('\u0001').map(pair => {
+ const [jobId, target] = pair.split('\u0000')
+
+ return { jobId, target }
+ }),
+ [downloadsKey]
+ )
+}
+
/**
* THE model catalog menu: searchable, provider-grouped, `-fast` families
* collapsed to one row, per-row hover submenu for thinking/effort/fast, full
@@ -270,34 +299,9 @@ export function ModelCatalogMenu({
// (breaking open submenus and focus — the #72163 class). Subscribe to a
// STABLE identity projection instead: it changes only when a download
// starts or ends. Each row selects its own percent scalar.
- const downloadsKey: string = useLocalRuntimeJobs(
- owner,
- (jobs: readonly LocalRuntimeJob[]): string =>
- localModelsEnabled
- ? runningModelDownloads(jobs)
- .map(job => `${job.job_id}\u0000${job.target}`)
- .join('\u0001')
- : '',
- localModelsEnabled
- )
-
- const downloads = useMemo(
- () =>
- downloadsKey === ''
- ? []
- : downloadsKey.split('\u0001').map(pair => {
- const [jobId, target] = pair.split('\u0000')
-
- return { jobId, target }
- }),
- [downloadsKey]
- )
+ const downloads = useDownloadRows(owner, localModelsEnabled)
- const error = modelOptions.error
- ? modelOptions.error instanceof Error
- ? modelOptions.error.message
- : String(modelOptions.error)
- : null
+ const error = queryErrorMessage(modelOptions.error)
const providers = modelOptions.data?.providers
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys-handlers.ts b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys-handlers.ts
new file mode 100644
index 00000000000..e473294959b
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys-handlers.ts
@@ -0,0 +1,61 @@
+import { visibleClarifyCard } from '@/lib/keybinds/composer-focus-keys'
+
+interface ArrowMove {
+ delta: number
+ wrap: boolean
+}
+
+const INTERACTIVE = 'a[href], button, input, select, textarea, [role="button"]'
+
+function focusOwnsKeys(focused: HTMLElement | null): boolean {
+ return Boolean(
+ focused && (focused.isContentEditable || (focused.matches(INTERACTIVE) && !focused.matches('button[data-choice]')))
+ )
+}
+
+/** True when this card must leave the keystroke alone. */
+export function isForeignKeystroke(event: globalThis.KeyboardEvent, form: HTMLFormElement | null): boolean {
+ if (event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) {
+ return true
+ }
+
+ // Not the visible card ⇒ not our keystroke. Inactive tabs stay MOUNTED,
+ // so every parked clarify keeps a live `window` listener; without this the
+ // card that acts is whichever mounted first, and answering the question in
+ // front of you silently answers a background session's question instead —
+ // resuming an agent turn the user never saw. Same resolver the composer's
+ // `clarifyCardOwnsKey` yields to, so the two cannot disagree about which
+ // card is live.
+ if (visibleClarifyCard() !== form) {
+ return true
+ }
+
+ return focusOwnsKeys(document.activeElement as HTMLElement | null)
+}
+
+const ARROWS = new Map<string, (columns: number | undefined) => ArrowMove | null>([
+ ['ArrowDown', columns => ({ delta: columns ?? 1, wrap: columns === undefined })],
+ ['ArrowLeft', columns => (columns === undefined ? null : { delta: -1, wrap: true })],
+ ['ArrowRight', columns => (columns === undefined ? null : { delta: 1, wrap: true })],
+ ['ArrowUp', columns => ({ delta: -(columns ?? 1), wrap: columns === undefined })]
+])
+
+/** Cursor move for an arrow key; left/right only move in a grid. */
+export function arrowMove(key: string, columns: number | undefined): ArrowMove | null {
+ return ARROWS.get(key)?.(columns) ?? null
+}
+
+/** Row index for a 1-9 / a-z shortcut key, or null. */
+export function shortcutIndex(key: string): null | number {
+ if (/^[1-9]$/.test(key)) {
+ return Number(key) - 1
+ }
+
+ const lower = key.toLowerCase()
+
+ // Only the letters this card actually renders a row for (the caller checks
+ // the bound). Anything past the last row belongs to the composer — the user
+ // is typing a message instead of picking an option, and swallowing the
+ // keystroke here would make the first letter of it vanish.
+ return lower.length === 1 && lower >= 'a' && lower <= 'z' ? lower.charCodeAt(0) - 97 : null
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
index 1aa1775cd59..6c3a906bec7 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
+++ b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
@@ -1,8 +1,9 @@
import { type RefObject, useCallback, useEffect, useState } from 'react'
-import { visibleClarifyCard } from '@/lib/keybinds/composer-focus-keys'
import type { ClarifyQuestion } from '@/store/clarify'
+import { arrowMove, isForeignKeystroke, shortcutIndex } from './use-clarify-keys-handlers'
+
interface ClarifyKeysOptions {
columns?: number
enabled: boolean
@@ -166,64 +167,25 @@ export function useClarifyKeys({
}
const onKeyDown = (event: globalThis.KeyboardEvent) => {
- if (event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented) {
+ if (isForeignKeystroke(event, formRef.current)) {
return
}
- // Not the visible card ⇒ not our keystroke. Inactive tabs stay MOUNTED,
- // so every parked clarify keeps a live `window` listener; without this the
- // card that acts is whichever mounted first, and answering the question in
- // front of you silently answers a background session's question instead —
- // resuming an agent turn the user never saw. Same resolver the composer's
- // `clarifyCardOwnsKey` yields to, so the two cannot disagree about which
- // card is live.
- if (visibleClarifyCard() !== formRef.current) {
- return
- }
-
- const focused = document.activeElement as HTMLElement | null
-
- if (
- focused &&
- (focused.isContentEditable ||
- (focused.matches('a[href], button, input, select, textarea, [role="button"]') &&
- !focused.matches('button[data-choice]')))
- ) {
- return
- }
-
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- if (choices.length > 0) {
- event.preventDefault()
- move((event.key === 'ArrowDown' ? 1 : -1) * (columns ?? 1), columns === undefined)
- }
-
- return
- }
+ const arrow = arrowMove(event.key, columns)
- if ((event.key === 'ArrowRight' || event.key === 'ArrowLeft') && columns !== undefined) {
+ if (arrow) {
if (choices.length > 0) {
event.preventDefault()
- move(event.key === 'ArrowRight' ? 1 : -1)
+ move(arrow.delta, arrow.wrap)
}
return
}
- if (shortcuts && /^[1-9]$/.test(event.key)) {
- pickByIndex(event, Number(event.key) - 1)
-
- return
- }
-
- const key = event.key.toLowerCase()
+ const index = shortcuts ? shortcutIndex(event.key) : null
- // Only the letters this card actually renders a row for. Anything past
- // the last row belongs to the composer — the user is typing a message
- // instead of picking an option, and swallowing the keystroke here would
- // make the first letter of it vanish.
- if (shortcuts && key.length === 1 && key >= 'a' && key <= 'z') {
- pickByIndex(event, key.charCodeAt(0) - 97)
+ if (index !== null) {
+ pickByIndex(event, index)
return
}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pending-parts.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending-parts.tsx
new file mode 100644
index 00000000000..64a11ddfa09
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pending-parts.tsx
@@ -0,0 +1,124 @@
+'use client'
+
+import { useI18n } from '@/i18n'
+import { type ClarifyQuestion, type ClarifyRequest, SETUP_CHOOSE_QID } from '@/store/clarify'
+
+import type { useClarifyKeys } from './core/use-clarify-keys'
+import { isSetupPickerKind, QuestionPills, SETUP_PICKERS, type SetupPickerKind } from './setup-pickers'
+import type { SetupRow } from './setup-rows'
+
+type SetupSource = Pick<ClarifyRequest, 'questions' | 'setup'>
+
+/** What the card draws from: the live request once it can be answered, else the tool-call args preview. */
+export function setupChooseSource(request: ClarifyRequest | null, fromArgs: null | SetupSource) {
+ const ready = Boolean(request?.requestId && request.setup)
+ const source = request ?? fromArgs
+ const setup = source?.setup ?? null
+ const kind = setup?.kind ?? 'question'
+
+ return {
+ kind,
+ pickerKind: isSetupPickerKind(kind) ? kind : null,
+ ready,
+ requestId: ready ? (request?.requestId ?? null) : null,
+ setup,
+ source
+ }
+}
+
+interface SetupChooseBodyProps {
+ cursor: null | number
+ draft: string
+ keys: ReturnType<typeof useClarifyKeys>
+ onDraft: (value: string) => void
+ onStage: (id: string) => void
+ picked: string[]
+ pickerKind: null | SetupPickerKind
+ question: ClarifyQuestion
+ ready: boolean
+ rows: null | SetupRow[]
+}
+
+function PillsLoading({ question }: { question: string }) {
+ const setupCopy = useI18n().t.assistant.setupChoose
+
+ return (
+ <div className="grid gap-2">
+ <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question}</span>
+ <div className="flex flex-wrap gap-2 p-1" role="status">
+ <span className="sr-only">{setupCopy.loading}</span>
+ {Array.from({ length: 3 }, (_, index) => (
+ <div className="h-7 w-28 animate-pulse rounded-full bg-muted/40" key={index} />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+function PickerRows({
+ cursor,
+ keys,
+ onStage,
+ picked,
+ pickerKind,
+ rows
+}: Pick<SetupChooseBodyProps, 'cursor' | 'keys' | 'onStage' | 'picked' | 'rows'> & { pickerKind: SetupPickerKind }) {
+ const setupCopy = useI18n().t.assistant.setupChoose
+ const Picker = SETUP_PICKERS[pickerKind]
+
+ if (rows === null) {
+ return (
+ <div className="grid grid-cols-3 gap-2" role="status">
+ <span className="sr-only">{setupCopy.loading}</span>
+ {Array.from({ length: 6 }, (_, index) => (
+ <div className="h-10 animate-pulse rounded-lg bg-muted/40" key={index} />
+ ))}
+ </div>
+ )
+ }
+
+ if (rows.length === 0) {
+ return <p className="text-(--ui-text-tertiary)">{setupCopy.unavailable}</p>
+ }
+
+ return <Picker cursor={cursor} onPick={index => keys.pick(0, index)} onStage={onStage} picked={picked} rows={rows} />
+}
+
+export function SetupChooseBody(props: SetupChooseBodyProps) {
+ const { cursor, draft, keys, onDraft, picked, pickerKind, question, ready, rows } = props
+
+ if (pickerKind === null && rows === null) {
+ return <PillsLoading question={question.question} />
+ }
+
+ if (pickerKind === null) {
+ return (
+ <QuestionPills
+ cursor={cursor}
+ details={(rows ?? []).map(row => row.detail)}
+ disabled={!ready}
+ onActivate={() => keys.focusQuestion(0)}
+ onDraft={onDraft}
+ onOtherFocus={() => keys.onOtherFocus(0)}
+ onPick={index => keys.pick(0, index)}
+ onRowFocus={index => keys.focusRow(0, index)}
+ question={question}
+ staged={{
+ choices: (rows ?? []).filter(row => picked.includes(row.id)).map(row => row.label),
+ draft
+ }}
+ />
+ )
+ }
+
+ return (
+ <fieldset
+ className="m-0 grid min-w-0 gap-2 border-0 p-0"
+ data-clarify-batch-question={SETUP_CHOOSE_QID}
+ disabled={!ready}
+ >
+ <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question.question}</span>
+ <PickerRows {...props} pickerKind={pickerKind} />
+ </fieldset>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
index 1cb7efbd5f2..7d519e940b3 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
@@ -29,7 +29,8 @@ import { useTheme } from '@/themes'
import { ClarifyConfirmBar } from './core/confirm-bar'
import { CLARIFY_ICON_CLASS, ClarifyShell } from './core/shell'
import { useClarifyKeys } from './core/use-clarify-keys'
-import { isSetupPickerKind, PICKER_COLUMNS, QuestionPills, SETUP_PICKERS } from './setup-pickers'
+import { SetupChooseBody, setupChooseSource } from './setup-pending-parts'
+import { PICKER_COLUMNS } from './setup-pickers'
import { LIVE_LOOK, useSetupRows } from './setup-rows'
import { handleClarifySubmitShortcut } from './submit-shortcut'
import { UndeliveredNotice } from './undelivered-notice'
@@ -71,15 +72,10 @@ export function SetupChoosePending({
const storedId = useStore(useSessionView().$storedId)
const { mode, setMode } = useTheme()
- const ready = Boolean(request?.requestId && request.setup)
- const source = request ?? fromArgs
- const setup = source?.setup ?? null
- const kind = setup?.kind ?? 'question'
- const pickerKind = isSetupPickerKind(kind) ? kind : null
+ const { kind, pickerKind, ready, requestId, setup, source } = setupChooseSource(request, fromArgs)
const freeText = pickerKind === null
const rows = useSetupRows(setup, storedId)
- const requestId = ready ? (request?.requestId ?? null) : null
const stages = useStore($setupChooseStages)
const { draft, picked } = (requestId && stages[requestId]) || EMPTY_SETUP_STAGE
const preselected = setup?.preselected
@@ -228,7 +224,6 @@ export function SetupChoosePending({
})
const cursor = ready ? keys.cursorRow : null
- const Picker = pickerKind === null ? null : SETUP_PICKERS[pickerKind]
const Icon = KIND_ICONS[kind]
return (
@@ -257,63 +252,18 @@ export function SetupChoosePending({
<Icon aria-hidden className={CLARIFY_ICON_CLASS} />
</div>
{undelivered ? <UndeliveredNotice /> : null}
- {Picker === null && rows === null ? (
- <div className="grid gap-2">
- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
- {question.question}
- </span>
- <div className="flex flex-wrap gap-2 p-1" role="status">
- <span className="sr-only">{setupCopy.loading}</span>
- {Array.from({ length: 3 }, (_, index) => (
- <div className="h-7 w-28 animate-pulse rounded-full bg-muted/40" key={index} />
- ))}
- </div>
- </div>
- ) : Picker === null ? (
- <QuestionPills
- cursor={cursor}
- details={(rows ?? []).map(row => row.detail)}
- disabled={!ready}
- onActivate={() => keys.focusQuestion(0)}
- onDraft={onDraft}
- onOtherFocus={() => keys.onOtherFocus(0)}
- onPick={index => keys.pick(0, index)}
- onRowFocus={index => keys.focusRow(0, index)}
- question={question}
- staged={{
- choices: (rows ?? []).filter(row => picked.includes(row.id)).map(row => row.label),
- draft
- }}
- />
- ) : (
- <fieldset
- className="m-0 grid min-w-0 gap-2 border-0 p-0"
- data-clarify-batch-question={SETUP_CHOOSE_QID}
- disabled={!ready}
- >
- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">
- {question.question}
- </span>
- {rows === null ? (
- <div className="grid grid-cols-3 gap-2" role="status">
- <span className="sr-only">{setupCopy.loading}</span>
- {Array.from({ length: 6 }, (_, index) => (
- <div className="h-10 animate-pulse rounded-lg bg-muted/40" key={index} />
- ))}
- </div>
- ) : rows.length === 0 ? (
- <p className="text-(--ui-text-tertiary)">{setupCopy.unavailable}</p>
- ) : (
- <Picker
- cursor={cursor}
- onPick={index => keys.pick(0, index)}
- onStage={stage}
- picked={picked}
- rows={rows}
- />
- )}
- </fieldset>
- )}
+ <SetupChooseBody
+ cursor={cursor}
+ draft={draft}
+ keys={keys}
+ onDraft={onDraft}
+ onStage={stage}
+ picked={picked}
+ pickerKind={pickerKind}
+ question={question}
+ ready={ready}
+ rows={rows}
+ />
</ClarifyShell>
{undelivered ? null : (
diff --git a/apps/desktop/src/components/assistant-ui/start-chat-tool-parts.tsx b/apps/desktop/src/components/assistant-ui/start-chat-tool-parts.tsx
new file mode 100644
index 00000000000..7cc84cc96f9
--- /dev/null
+++ b/apps/desktop/src/components/assistant-ui/start-chat-tool-parts.tsx
@@ -0,0 +1,92 @@
+'use client'
+
+import { CLARIFY_ICON_CLASS, ClarifyShell } from '@/components/assistant-ui/clarify/core/shell'
+import { Button } from '@/components/ui/button'
+import { useI18n } from '@/i18n'
+import { Loader2, MessageCircle } from '@/lib/icons'
+import { profileLabel } from '@/store/profile'
+import type { ProfileInfo } from '@/types/hermes'
+
+const TITLE_LIMIT = 40
+
+const CAPTION = 'text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)'
+
+const stringArg = (value: unknown): null | string => (typeof value === 'string' ? value : null)
+
+/** Card title before the session row exists: outcome title, then the requested title, then the message head. */
+export function requestedTitle(started: null | { title?: null | string }, args: Record<string, unknown>): null | string {
+ const message = stringArg(args.message)?.trim() ?? ''
+
+ return started?.title || stringArg(args.title)?.trim() || message.slice(0, TITLE_LIMIT) || null
+}
+
+export function retryRequest(args: Record<string, unknown>) {
+ return {
+ message: stringArg(args.message) ?? '',
+ profile: stringArg(args.profile),
+ title: stringArg(args.title)
+ }
+}
+
+interface StartChatRejectedProps {
+ disabled: boolean
+ onRetry: () => void
+ pending: boolean
+ reason?: null | string
+ showRetry: boolean
+}
+
+export function StartChatRejected({ disabled, onRetry, pending, reason, showRetry }: StartChatRejectedProps) {
+ const copy = useI18n().t.assistant.startChat
+
+ return (
+ <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat">
+ <div className="grid min-w-0 flex-1 gap-0.5">
+ <span className="font-medium">{copy.notStarted}</span>
+ {reason ? <span className={CAPTION}>{reason}</span> : null}
+ </div>
+ {showRetry ? (
+ <Button disabled={disabled} onClick={onRetry} size="xs" type="button" variant="outline">
+ {pending ? <Loader2 aria-hidden className="size-3.5 animate-spin motion-reduce:animate-none" /> : null}
+ {copy.retry}
+ </Button>
+ ) : null}
+ </ClarifyShell>
+ )
+}
+
+export function StartChatStarting({ title }: { title: null | string }) {
+ const copy = useI18n().t.assistant.startChat
+
+ return (
+ <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat" role="status">
+ <Loader2 aria-hidden className="size-4 animate-spin text-(--ui-text-tertiary) motion-reduce:animate-none" />
+ <span className="text-(--ui-text-tertiary)">{title ? copy.starting(title) : copy.startingUntitled}</span>
+ </ClarifyShell>
+ )
+}
+
+interface StartChatStartedProps {
+ onOpen: () => void
+ profile: string
+ profiles: ProfileInfo[]
+ title: null | string
+}
+
+export function StartChatStarted({ onOpen, profile, profiles, title }: StartChatStartedProps) {
+ const copy = useI18n().t.assistant.startChat
+ const entry = profiles.find(candidate => candidate.name === profile)
+
+ return (
+ <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat">
+ <MessageCircle aria-hidden className={CLARIFY_ICON_CLASS} />
+ <div className="grid min-w-0 flex-1">
+ <span className="truncate font-medium">{title ?? copy.untitled}</span>
+ {profile ? <span className={CAPTION}>{copy.inProfile(entry ? profileLabel(entry) : profile)}</span> : null}
+ </div>
+ <Button onClick={onOpen} size="xs" type="button" variant="outline">
+ {copy.open}
+ </Button>
+ </ClarifyShell>
+ )
+}
diff --git a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
index 7272562ad99..bbcfaea1a79 100644
--- a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
@@ -8,17 +8,14 @@ import { useNavigate } from 'react-router'
import { useSessionView } from '@/app/chat/session-view'
import { openSessionFromPicker, type OpenSessionNavigate } from '@/app/open-session'
import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
-import { CLARIFY_ICON_CLASS, ClarifyShell } from '@/components/assistant-ui/clarify/core/shell'
import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'
-import { Button } from '@/components/ui/button'
import { useI18n } from '@/i18n'
import type { TimelinePartMetadata } from '@/lib/chat-messages/types'
import { sessionTitle } from '@/lib/chat-runtime'
-import { Loader2, MessageCircle } from '@/lib/icons'
import { useStoresSelector } from '@/lib/use-session-slice'
import { notifyError } from '@/store/notifications'
-import { $profiles, profileLabel } from '@/store/profile'
+import { $profiles } from '@/store/profile'
import { $sessions, sessionMatchesStoredId, setSessionOwnerHint } from '@/store/session'
import { isSessionOwnerRoute } from '@/store/session-request-router'
import {
@@ -30,9 +27,7 @@ import {
takeLiveStartChat
} from '@/store/start-chat'
-const TITLE_LIMIT = 40
-
-const CAPTION = 'text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)'
+import { requestedTitle, retryRequest, StartChatRejected, StartChatStarted, StartChatStarting } from './start-chat-tool-parts'
async function openStartedChat(
chat: { profile: string; sessionId: string },
@@ -63,6 +58,7 @@ export function StartChatTool(props: ToolCallMessagePartProps & Pick<TimelinePar
const retry = useStore($startChatRetries)[props.toolCallId]
const navigate = useNavigate()
const { result, toolResultMetadata } = props
+
const outcome = useMemo(
() => startChatOutcome({ result, toolResultMetadata }, retry),
[result, retry, toolResultMetadata]
@@ -75,23 +71,15 @@ export function StartChatTool(props: ToolCallMessagePartProps & Pick<TimelinePar
const started = outcome?.status === 'started' ? outcome : null
const args = parseMaybeObject(props.args)
- const message = typeof args.message === 'string' ? args.message.trim() : ''
const row = started ? sessions.find(session => sessionMatchesStoredId(session, started.sessionId)) : undefined
-
- const title = row
- ? sessionTitle(row)
- : started?.title || (typeof args.title === 'string' && args.title.trim()) || message.slice(0, TITLE_LIMIT) || null
+ const title = row ? sessionTitle(row) : requestedTitle(started, args)
const retryChat = () => {
if (!callerRuntimeId) {
return
}
- void retryStartChat(props.toolCallId, callerRuntimeId, {
- message: typeof args.message === 'string' ? args.message : '',
- profile: typeof args.profile === 'string' ? args.profile : null,
- title: typeof args.title === 'string' ? args.title : null
- }).then(
+ void retryStartChat(props.toolCallId, callerRuntimeId, retryRequest(args)).then(
next => {
if (next?.status === 'started') {
void openStartedChat(next, callerId, navigate).catch(error => notifyError(error, copy.openFailed))
@@ -117,59 +105,28 @@ export function StartChatTool(props: ToolCallMessagePartProps & Pick<TimelinePar
if (outcome?.status === 'rejected') {
return (
- <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat">
- <div className="grid min-w-0 flex-1 gap-0.5">
- <span className="font-medium">{copy.notStarted}</span>
- {outcome.reason ? <span className={CAPTION}>{outcome.reason}</span> : null}
- </div>
- {outcome.retryable && !superseded ? (
- <Button
- disabled={retry === 'pending' || callerBusy || !callerRuntimeId}
- onClick={retryChat}
- size="xs"
- type="button"
- variant="outline"
- >
- {retry === 'pending' ? (
- <Loader2 aria-hidden className="size-3.5 animate-spin motion-reduce:animate-none" />
- ) : null}
- {copy.retry}
- </Button>
- ) : null}
- </ClarifyShell>
+ <StartChatRejected
+ disabled={retry === 'pending' || callerBusy || !callerRuntimeId}
+ onRetry={retryChat}
+ pending={retry === 'pending'}
+ reason={outcome.reason}
+ showRetry={outcome.retryable && !superseded}
+ />
)
}
if (!started) {
- return (
- <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat" role="status">
- <Loader2 aria-hidden className="size-4 animate-spin text-(--ui-text-tertiary) motion-reduce:animate-none" />
- <span className="text-(--ui-text-tertiary)">{title ? copy.starting(title) : copy.startingUntitled}</span>
- </ClarifyShell>
- )
+ return <StartChatStarting title={title} />
}
- const profile = profiles.find(entry => entry.name === started.profile)
-
return (
- <ClarifyShell className="my-1.5 flex items-center gap-2" data-slot="start-chat">
- <MessageCircle aria-hidden className={CLARIFY_ICON_CLASS} />
- <div className="grid min-w-0 flex-1">
- <span className="truncate font-medium">{title ?? copy.untitled}</span>
- {started.profile ? (
- <span className={CAPTION}>{copy.inProfile(profile ? profileLabel(profile) : started.profile)}</span>
- ) : null}
- </div>
- <Button
- onClick={() =>
- void openStartedChat(started, callerId, navigate).catch(error => notifyError(error, copy.openFailed))
- }
- size="xs"
- type="button"
- variant="outline"
- >
- {copy.open}
- </Button>
- </ClarifyShell>
+ <StartChatStarted
+ onOpen={() =>
+ void openStartedChat(started, callerId, navigate).catch(error => notifyError(error, copy.openFailed))
+ }
+ profile={started.profile}
+ profiles={profiles}
+ title={title}
+ />
)
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/status.tsx b/apps/desktop/src/components/assistant-ui/thread/status.tsx
index cc84c744aa0..46297cc61ff 100644
--- a/apps/desktop/src/components/assistant-ui/thread/status.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/status.tsx
@@ -297,6 +297,61 @@ export const BackgroundResumeNotice: FC = () => {
)
}
+// Hands a turn back from the user, re-arming the quiet mark: see the call site.
+function useHandBackQuiet(
+ awaitingInput: boolean,
+ turnStartedAt: number | undefined,
+ setQuietSince: (since: number) => void
+) {
+ const [handBack, setHandBack] = useState({ awaitingInput, turnStartedAt })
+
+ if (handBack.awaitingInput !== awaitingInput || handBack.turnStartedAt !== turnStartedAt) {
+ setHandBack({ awaitingInput, turnStartedAt })
+
+ if (turnStartedAt !== undefined && turnStartedAt !== handBack.turnStartedAt) {
+ setQuietSince(turnStartedAt)
+ } else if (handBack.awaitingInput && !awaitingInput) {
+ setQuietSince(Date.now())
+ }
+ }
+}
+
+interface TurnActivityRowProps {
+ active: boolean
+ elapsed: number
+ hint: string
+ localLoad: ReturnType<typeof useLocalModelLoad>
+}
+
+const TurnActivityRow: FC<TurnActivityRowProps> = ({ active, elapsed, hint, localLoad }) => {
+ const { t } = useI18n()
+
+ return (
+ <StatusRow
+ className={cn(!active && 'sr-only')}
+ data-slot="aui_turn-activity"
+ data-state={active ? 'active' : 'idle'}
+ label={active ? hint || 'Hermes is working' : ''}
+ >
+ {active && (
+ <>
+ <StatusPulse
+ aria-hidden="true"
+ className="dither inline-block size-3 rounded-[2px] text-midground/80"
+ kind="opacity"
+ />
+ {hint ? (
+ <WaitHint hint={hint} />
+ ) : localLoad ? (
+ <ProgressHint label={t.assistant.thread.loadingLocalModel(localLoad.model)} percent={localLoad.percent} />
+ ) : null}
+ <ActivityTimerText aria-hidden={true} seconds={elapsed} />
+ </>
+ )}
+ </StatusRow>
+ )
+}
+
// Tail activity row. The pre-first-token spinner goes away once content flows,
// but a turn keeps working through gaps it produces nothing during — between
// one tool result landing and the next call arriving, while the provider
@@ -313,7 +368,6 @@ export const BackgroundResumeNotice: FC = () => {
// so that per-token updates re-render only this leaf, not the whole
// AssistantMessage subtree.
export const TurnActivityIndicator: FC<{ thinking?: boolean }> = ({ thinking = false }) => {
- const { t } = useI18n()
// Same rule the reasoning disclosure renders by (message-parts.tsx).
const showReasoning = useStore($showReasoning)
const guidedChat = useOnboardingChatActive()
@@ -357,17 +411,7 @@ export const TurnActivityIndicator: FC<{ thinking?: boolean }> = ({ thinking = f
// card resumes the turn it paused. Neither is a gap between two quick calls,
// so the wait after it shows at once, timed from that moment, the way a
// normal send's row does.
- const [handBack, setHandBack] = useState({ awaitingInput, turnStartedAt })
-
- if (handBack.awaitingInput !== awaitingInput || handBack.turnStartedAt !== turnStartedAt) {
- setHandBack({ awaitingInput, turnStartedAt })
-
- if (turnStartedAt !== undefined && turnStartedAt !== handBack.turnStartedAt) {
- setQuietSince(turnStartedAt)
- } else if (handBack.awaitingInput && !awaitingInput) {
- setQuietSince(Date.now())
- }
- }
+ useHandBackQuiet(awaitingInput, turnStartedAt, setQuietSince)
// Every second the app claims to be working belongs to something. A named
// wait says what it is straight away; an unnamed gap has to go quiet for
@@ -410,28 +454,5 @@ export const TurnActivityIndicator: FC<{ thinking?: boolean }> = ({ thinking = f
return null
}
- return (
- <StatusRow
- className={cn(!active && 'sr-only')}
- data-slot="aui_turn-activity"
- data-state={active ? 'active' : 'idle'}
- label={active ? hint || 'Hermes is working' : ''}
- >
- {active && (
- <>
- <StatusPulse
- aria-hidden="true"
- className="dither inline-block size-3 rounded-[2px] text-midground/80"
- kind="opacity"
- />
- {hint ? (
- <WaitHint hint={hint} />
- ) : localLoad ? (
- <ProgressHint label={t.assistant.thread.loadingLocalModel(localLoad.model)} percent={localLoad.percent} />
- ) : null}
- <ActivityTimerText aria-hidden={true} seconds={elapsed} />
- </>
- )}
- </StatusRow>
- )
+ return <TurnActivityRow active={active} elapsed={elapsed} hint={hint} localLoad={localLoad} />
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
index 28326a32c52..99413ee0c37 100644
--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx
@@ -243,6 +243,75 @@ const ProcessNotificationNote: FC<{ text: string }> = ({ text }) => {
return <BackgroundResult process report={detail} text={headline} />
}
+function isChipOnlyTurn(hasBody: boolean, attachmentRefs: readonly string[]): boolean {
+ return !hasBody && attachmentRefs.length > 0 && attachmentRefs.every(isAttachmentRef)
+}
+
+interface UserBubbleActionsProps {
+ fullText: string
+ messageId: string
+ onCancel?: () => Promise<void> | void
+ onRequestRestoreConfirm?: (messageId: string, target: RestoreMessageTarget) => void
+ runtimeUserOrdinal: RestoreMessageTarget['userOrdinal']
+ showRestore: boolean
+ showStop: boolean
+}
+
+const UserBubbleActions: FC<UserBubbleActionsProps> = ({
+ fullText,
+ messageId,
+ onCancel,
+ onRequestRestoreConfirm,
+ runtimeUserOrdinal,
+ showRestore,
+ showStop
+}) => {
+ const copy = useI18n().t.assistant.thread
+
+ return (
+ <>
+ <MessageHoverTime className={cn(!showStop && !showRestore && 'pr-0.5')} />
+ {showStop ? (
+ <button
+ aria-label={copy.stop}
+ className={cn('pointer-events-auto size-5', USER_ACTION_ICON_BUTTON_CLASS)}
+ onClick={event => {
+ event.preventDefault()
+ event.stopPropagation()
+ void onCancel?.()
+ }}
+ type="button"
+ >
+ {StopGlyph}
+ </button>
+ ) : showRestore ? (
+ <Tip label={copy.restoreFromHere}>
+ <button
+ aria-label={copy.restoreCheckpoint}
+ className={cn('pointer-events-auto size-6', USER_ACTION_ICON_BUTTON_CLASS)}
+ onClick={event => {
+ event.preventDefault()
+ event.stopPropagation()
+ triggerHaptic('selection')
+ onRequestRestoreConfirm?.(messageId, {
+ text: fullText,
+ userOrdinal: runtimeUserOrdinal
+ })
+ }}
+ onPointerDown={event => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ type="button"
+ >
+ <Codicon name="discard" size="0.875rem" />
+ </button>
+ </Tip>
+ ) : null}
+ </>
+ )
+}
+
export const UserMessage: FC<{
onCancel?: () => Promise<void> | void
onRequestRestoreConfirm?: (messageId: string, target: RestoreMessageTarget) => void
@@ -365,7 +434,7 @@ export const UserMessage: FC<{
}
const hasBody = messageText.trim().length > 0
- const chipOnlyTurn = !hasBody && attachmentRefs.length > 0 && attachmentRefs.every(isAttachmentRef)
+ const chipOnlyTurn = isChipOnlyTurn(hasBody, attachmentRefs)
const isLatestUser = messageId === latestUserId
const showStop = !readOnly && isLatestUser && threadRunning && Boolean(onCancel)
// Restore (re-run this exact prompt) is available everywhere the Stop button
@@ -511,44 +580,15 @@ export const UserMessage: FC<{
{/* Hover cluster, bottom-right: when it was sent, then Stop or
Restore. Its fill masks the last line's tail while shown. */}
<div className="pointer-events-none absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-md bg-(--dt-user-bubble) pl-1 opacity-0 transition-opacity group-hover/user-message:opacity-100 group-hover/user-message:transition-none group-focus-within/user-message:opacity-100">
- <MessageHoverTime className={cn(!showStop && !showRestore && 'pr-0.5')} />
- {showStop ? (
- <button
- aria-label={copy.stop}
- className={cn('pointer-events-auto size-5', USER_ACTION_ICON_BUTTON_CLASS)}
- onClick={event => {
- event.preventDefault()
- event.stopPropagation()
- void onCancel?.()
- }}
- type="button"
- >
- {StopGlyph}
- </button>
- ) : showRestore ? (
- <Tip label={copy.restoreFromHere}>
- <button
- aria-label={copy.restoreCheckpoint}
- className={cn('pointer-events-auto size-6', USER_ACTION_ICON_BUTTON_CLASS)}
- onClick={event => {
- event.preventDefault()
- event.stopPropagation()
- triggerHaptic('selection')
- onRequestRestoreConfirm?.(messageId, {
- text: fullText,
- userOrdinal: runtimeUserOrdinal
- })
- }}
- onPointerDown={event => {
- event.preventDefault()
- event.stopPropagation()
- }}
- type="button"
- >
- <Codicon name="discard" size="0.875rem" />
- </button>
- </Tip>
- ) : null}
+ <UserBubbleActions
+ fullText={fullText}
+ messageId={messageId}
+ onCancel={onCancel}
+ onRequestRestoreConfirm={onRequestRestoreConfirm}
+ runtimeUserOrdinal={runtimeUserOrdinal}
+ showRestore={showRestore}
+ showStop={showStop}
+ />
</div>
</div>
</ReactionPicker>
diff --git a/apps/desktop/src/components/gateway-connecting-overlay.tsx b/apps/desktop/src/components/gateway-connecting-overlay.tsx
index ccee6c4d695..b2bab64b3ad 100644
--- a/apps/desktop/src/components/gateway-connecting-overlay.tsx
+++ b/apps/desktop/src/components/gateway-connecting-overlay.tsx
@@ -1,3 +1,4 @@
+import type { ConnectionState } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { useEffect, useRef, useState } from 'react'
@@ -5,7 +6,7 @@ import { DecodeText } from '@/components/ui/decode-text'
import { prefersReducedMotion } from '@/hooks/use-media-query'
import { isOnboardingEnabled } from '@/lib/onboarding-enabled'
import { cn } from '@/lib/utils'
-import { $desktopBoot } from '@/store/boot'
+import { $desktopBoot, type DesktopBootState } from '@/store/boot'
import { $gatewaySwitching } from '@/store/gateway-switch'
import { $onboardingStateRead } from '@/store/onboarding-gate'
import { $introView } from '@/store/onboarding-intro'
@@ -40,6 +41,57 @@ function forcedPreview(): boolean {
}
}
+// The full-screen connecting overlay is for initial boot only. After a
+// healthy boot, flaky networks / sleep-wake can drop the socket and flip the
+// gateway state back to closed/error while the app reconnects. Do not cover
+// the chat then — users should still be able to type drafts, open settings,
+// and recover instead of staring at a modal CONNECTING screen.
+function isInitialConnect(
+ boot: DesktopBootState,
+ gatewaySwitching: boolean,
+ gatewayState: ConnectionState,
+ coldBootDone: boolean
+): boolean {
+ const initialBootActive = boot.visible || boot.running || boot.progress < 100
+
+ return !coldBootDone && !gatewaySwitching && gatewayState !== 'open' && !boot.error && initialBootActive
+}
+
+interface ConnectingOverlayViewProps {
+ decoding: boolean
+ phase: Phase
+}
+
+function ConnectingOverlayView({ decoding, phase }: ConnectingOverlayViewProps) {
+ const leaving = phase !== 'live'
+ const overlayHidden = phase === 'overlay-out' || phase === 'gone'
+
+ return (
+ <div
+ className={cn(
+ 'fixed inset-0 z-(--z-connecting) grid place-items-center bg-(--ui-chat-surface-background) transition-opacity duration-500 ease-out',
+ overlayHidden ? 'pointer-events-none opacity-0' : 'opacity-100'
+ )}
+ // Masks the whole app while booting — must stay filled under window
+ // glass or the shell shows through. Contract: `[data-glass-opaque]`
+ // in styles.css.
+ data-glass-opaque=""
+ >
+ <DecodeText
+ active={decoding}
+ className={cn(
+ 'pl-[0.4em] text-(--theme-primary) transition duration-300 ease-out',
+ leaving ? 'translate-y-2 opacity-0 saturate-0' : 'translate-y-0 opacity-100 saturate-100'
+ )}
+ cursor
+ loop
+ prefix={4}
+ text={TEXT}
+ />
+ </div>
+ )
+}
+
export function GatewayConnectingOverlay() {
const gatewayState = useStore($gatewayState)
const boot = useStore($desktopBoot)
@@ -61,15 +113,7 @@ export function GatewayConnectingOverlay() {
coldBootDoneRef.current = true
}
- // The full-screen connecting overlay is for initial boot only. After a
- // healthy boot, flaky networks / sleep-wake can drop the socket and flip the
- // gateway state back to closed/error while the app reconnects. Do not cover
- // the chat then — users should still be able to type drafts, open settings,
- // and recover instead of staring at a modal CONNECTING screen.
- const initialBootActive = boot.visible || boot.running || boot.progress < 100
-
- const connecting =
- !coldBootDoneRef.current && !gatewaySwitching && gatewayState !== 'open' && !boot.error && initialBootActive
+ const connecting = isInitialConnect(boot, gatewaySwitching, gatewayState, coldBootDoneRef.current)
// Latches once we've actually shown the overlay, so the brief frame where
// gatewayState flips to "open" (connecting -> false) before the exit phase
@@ -143,31 +187,5 @@ export function GatewayConnectingOverlay() {
return null
}
- const leaving = phase !== 'live'
- const overlayHidden = phase === 'overlay-out' || phase === 'gone'
-
- return (
- <div
- className={cn(
- 'fixed inset-0 z-(--z-connecting) grid place-items-center bg-(--ui-chat-surface-background) transition-opacity duration-500 ease-out',
- overlayHidden ? 'pointer-events-none opacity-0' : 'opacity-100'
- )}
- // Masks the whole app while booting — must stay filled under window
- // glass or the shell shows through. Contract: `[data-glass-opaque]`
- // in styles.css.
- data-glass-opaque=""
- >
- <DecodeText
- active={phase === 'live' && (previewing || connecting)}
- className={cn(
- 'pl-[0.4em] text-(--theme-primary) transition duration-300 ease-out',
- leaving ? 'translate-y-2 opacity-0 saturate-0' : 'translate-y-0 opacity-100 saturate-100'
- )}
- cursor
- loop
- prefix={4}
- text={TEXT}
- />
- </div>
- )
+ return <ConnectingOverlayView decoding={phase === 'live' && (previewing || connecting)} phase={phase} />
}