The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): setup_choose question cards and the start_chat handoff card
alt-glitchb321a7be695d
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.tsindex e09157a6f78..77ec3964a26 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts@@ -12,7 +12,7 @@ import { translateNow } from '@/i18n'import { restorePendingClarifyToolCall } from '@/lib/chat-messages'import type { PreviewActAction } from '@/lib/preview-act/act-in-page'import type { TourAction, TourStep } from '@/lib/tour'-import { normalizeQuestions, setClarifyRequest } from '@/store/clarify'+import { type ClarifyRequest, normalizeQuestions, normalizeSetupChoose, setClarifyRequest } from '@/store/clarify'import type { ScopedServerRequest } from '@/store/gateway'import { dispatchNativeNotification } from '@/store/native-notifications'import {@@ -173,10 +173,7 @@ export function windowReadClaimsSession(sessionId: string, activeSessionId: nullconst sessions = $sessions.get()- const shown = [- $selectedStoredSessionId.get(),- ...$sessionTiles.get().map(tile => tile.storedSessionId)- ]+ const shown = [$selectedStoredSessionId.get(), ...$sessionTiles.get().map(tile => tile.storedSessionId)]return shown.some(stored =>@@ -268,6 +265,43 @@ const notifyInput = (ctx: ServerRequestContext, body: string) => {// user focuses that chat. The Python side blocks on the response frame; without a// handler the channel answers -32601 and the tool fails fast instead of stalling.+const parkClarify = (ctx: ServerRequestContext, clarifyRequest: ClarifyRequest) => {+ const { deps, request, sessionId } = ctx++ rememberServerRequest(request)+ setClarifyRequest(clarifyRequest)++ if (sessionId) {+ // A resumed/hydrated transcript may already contain this provider's clarify+ // call while carrying no live streamId. Re-arm that exact row instead of+ // letting the generic stream mutator append a second card.+ const occurredAt = Date.now() / 1000++ deps.updateSessionState(sessionId, state => {+ const projection = restorePendingClarifyToolCall(+ state.messages,+ pendingClarifyToolPayload(clarifyRequest),+ occurredAt+ )++ return {+ ...state,+ messages: projection.messages,+ streamId: projection.streamId,+ sawAssistantPayload: true,+ awaitingResponse: false,+ needsInput: true+ }+ })++ if (sessionId === deps.activeSessionIdRef.current) {+ requestScrollToBottom(sessionId)+ }+ }++ notifyInput(ctx, clarifyRequest.questions.map(q => q.question).join(' · '))+}+const clarify: Handler = ctx => {const { deps, request, sessionId } = ctxconst p = request.params@@ -297,46 +331,26 @@ const clarify: Handler = ctx => {return}- const clarifyRequest = {+ parkClarify(ctx, {lockedAnswers,questions,receivedAt: Date.now() / 1000,requestId: request.id,sessionId: sessionId || null- }-- rememberServerRequest(request)- setClarifyRequest(clarifyRequest)-- if (sessionId) {- // A resumed/hydrated transcript may already contain this provider's clarify- // call while carrying no live streamId. Re-arm that exact row instead of- // letting the generic stream mutator append a second card.- const occurredAt = Date.now() / 1000+ })+}- deps.updateSessionState(sessionId, state => {- const projection = restorePendingClarifyToolCall(- state.messages,- pendingClarifyToolPayload(clarifyRequest),- occurredAt- )+const setupChoose: Handler = ctx => {+ const { deps, request, sessionId } = ctx+ const setup = normalizeSetupChoose(request.params)- return {- ...state,- messages: projection.messages,- streamId: projection.streamId,- sawAssistantPayload: true,- awaitingResponse: false,- needsInput: true- }- })+ if (!setup || (sessionId && deps.sessionInterrupted(sessionId))) {+ request.respond({})- if (sessionId === deps.activeSessionIdRef.current) {- requestScrollToBottom(sessionId)- }+ return}- notifyInput(ctx, questions.map(q => q.question).join(' · '))+ parkClarify(ctx, { ...setup, receivedAt: Date.now() / 1000, requestId: request.id, sessionId: sessionId || null })}const approval: Handler = ctx => {@@ -609,6 +623,7 @@ export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {'preview.act': previewAct,'preview.read': previewRead,secret,+ setup_choose: setupChoose,sudo,'terminal.read': terminalRead,tour,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.tsindex b96f83e091e..81d5e626011 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@@ -5,7 +5,8 @@ import { invalidateSlashCompletions } from '@/lib/slash-completion-cache'import { refreshBackgroundProcesses } from '@/store/composer-status'import { flashPetActivity, setPetActivity } from '@/store/pet'import { recordPreviewArtifact, reofferPreviewArtifact } from '@/store/preview-status'-import { $sessionStates, storedSessionIdForRuntimeId } from '@/store/session-states'+import { $sessionStates, isSessionInForeground, storedSessionIdForRuntimeId } from '@/store/session-states'+import { markLiveStartChat, readStartChatResult } from '@/store/start-chat'import { pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'import { reportMcpToolResult } from '@/store/suggestion-providers/repair'import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'@@ -100,6 +101,15 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {// (no-op in every other session).reportFirstBuildToolComplete(sessionId)+ if (+ !event.replayed &&+ payload?.name === 'start_chat' &&+ readStartChatResult(payload.result)?.status === 'started' &&+ isSessionInForeground(storedSessionIdForRuntimeId(sessionId) ?? sessionId)+ ) {+ markLiveStartChat(payload.tool_id || payload.tool_call_id || payload.id || '')+ }+if (isActiveEvent) {setPetActivity({ toolRunning: false })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.tsindex 283281427fa..34e20e0b8de 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@@ -22,6 +22,7 @@ import { useI18n } from '@/i18n'import {type ChatMessage,preserveLocalAssistantErrors,+ QUESTION_CARD_TOOLS,restorePendingClarifyToolCall,settlePendingClarifyToolCall,stripPendingClarifyProjectionForCache,@@ -399,7 +400,7 @@ function withoutEarlyClarifyProjection(messages: ChatMessage[], requestId: strinpart =>!(part.type === 'tool-call' &&- part.toolName === 'clarify' &&+ QUESTION_CARD_TOOLS.has(part.toolName) &&part.result === undefined &&part.toolCallId === requestId)diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.tsindex fb49bc33665..21de1ffde7b 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/restore-pending-clarify.ts@@ -1,4 +1,4 @@-import type { GatewayEventPayload } from '@/lib/chat-messages'+import { type GatewayEventPayload, QUESTION_CARD_TOOLS } from '@/lib/chat-messages'import { $clarifyRequests, type ClarifyRequest, clearClarifyRequest } from '@/store/clarify'import type { SessionResumeResult } from '@/types/hermes'@@ -26,7 +26,7 @@ export function restorePendingClarifyFromSnapshot(resumeStartedAt: number,requestIdAtStart?: string): PendingClarifyResumeState {- const pending = (response.open_requests ?? []).find(entry => entry.method === 'clarify')+ const pending = (response.open_requests ?? []).find(entry => QUESTION_CARD_TOOLS.has(entry.method))if (!pending) {const current = $clarifyRequests.get()[sessionId]@@ -53,6 +53,20 @@ export function restorePendingClarifyFromSnapshot(}export function pendingClarifyToolPayload(request: ClarifyRequest): GatewayEventPayload {+ if (request.setup) {+ return {+ args: {+ intent: request.setup.intent,+ kind: request.setup.kind,+ multi_select: request.setup.multiSelect,+ options: request.setup.options ?? undefined,+ question: request.questions[0]?.question+ },+ name: 'setup_choose',+ tool_id: request.requestId+ }+ }+return {args: {questions: request.questions.map(question => ({diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.tsindex 8cf3c898345..ca8467f9856 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts@@ -1,4 +1,4 @@-import type { ChatMessage } from '@/lib/chat-messages'+import { type ChatMessage, QUESTION_CARD_TOOLS } from '@/lib/chat-messages'import type { ClientSessionState, PersistedDisplayTranscriptProvenance } from '../../../types'@@ -87,7 +87,9 @@ export function transcriptRowContentKey(message: ChatMessage): string {function isAnswerableClarifyMessage(message: ChatMessage): boolean {return (message.pending === true &&- message.parts.some(part => part.type === 'tool-call' && part.toolName === 'clarify' && part.result === undefined)+ message.parts.some(+ part => part.type === 'tool-call' && QUESTION_CARD_TOOLS.has(part.toolName) && part.result === undefined+ ))}diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/confirm-bar.tsx b/apps/desktop/src/components/assistant-ui/clarify/core/confirm-bar.tsxnew file mode 100644index 00000000000..8e131bcee07--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/clarify/core/confirm-bar.tsx@@ -0,0 +1,40 @@+'use client'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'+import { Loader2 } from '@/lib/icons'++export function ClarifyConfirmBar({+ canConfirm,+ disabled,+ onSkip,+ submitting+}: {+ canConfirm: boolean+ disabled: boolean+ onSkip: () => void+ submitting: boolean+}) {+ const { t } = useI18n()+ const copy = t.assistant.clarify++ return (+ <div className="flex items-center justify-end gap-1">+ <Button disabled={disabled} onClick={onSkip} size="xs" type="button" variant="text">+ {copy.skip}+ </Button>+ <Button disabled={disabled || !canConfirm} size="xs" type="submit">+ {submitting ? (+ <Loader2 className="animate-spin" />+ ) : (+ <>+ {copy.confirmAndContinueLabel}+ <span aria-hidden className="ml-0.5 text-[0.625rem] opacity-70">+ ⏎+ </span>+ </>+ )}+ </Button>+ </div>+ )+}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.tsindex 97d34bec549..d8740f083e5 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@@ -10,6 +10,7 @@ interface ClarifyKeysOptions {onClear: (question: ClarifyQuestion) => voidonConfirm: () => voidonToggle: (question: ClarifyQuestion, choice: string) => void+ other?: booleanquestions: ClarifyQuestion[]}@@ -20,13 +21,15 @@ export function useClarifyKeys({onClear,onConfirm,onToggle,+ other = true,questions}: ClarifyKeysOptions) {const [cursor, setCursor] = useState({ question: 0, row: 0 })const questionIndex = Math.min(cursor.question, Math.max(questions.length - 1, 0))const active = questions[questionIndex]const choices = active?.choices ?? []- const row = Math.min(cursor.row, choices.length)+ const otherRows = other ? 1 : 0+ const row = Math.min(cursor.row, choices.length - 1 + otherRows)const focusQuestion = useCallback((index: number) => setCursor(current => (current.question === index ? current : { question: index, row: 0 })),@@ -98,11 +101,11 @@ export function useClarifyKeys({onClear(active)}- const itemCount = choices.length + 1+ const itemCount = choices.length + otherRowssetCursor({ question: questionIndex, row: (row + delta + itemCount) % itemCount })},- [active, choices.length, onClear, questionIndex, row]+ [active, choices.length, onClear, otherRows, questionIndex, row])const activate = useCallback(() => {@@ -142,7 +145,7 @@ export function useClarifyKeys({if (index < choices.length) {event.preventDefault()pick(questionIndex, index)- } else if (index === choices.length) {+ } else if (other && index === choices.length) {event.preventDefault()focusOther(questionIndex)}@@ -211,7 +214,7 @@ export function useClarifyKeys({window.addEventListener('keydown', onKeyDown)return () => window.removeEventListener('keydown', onKeyDown)- }, [activate, active, choices.length, enabled, focusOther, formRef, move, pick, questionIndex])+ }, [activate, active, choices.length, enabled, focusOther, formRef, move, other, pick, questionIndex])return { activeQuestion: questionIndex, cursorRow: row, focusQuestion, onOtherFocus, pick }}diff --git a/apps/desktop/src/components/assistant-ui/clarify/index.tsx b/apps/desktop/src/components/assistant-ui/clarify/index.tsxindex cca33b58437..bf668e7666e 100644--- a/apps/desktop/src/components/assistant-ui/clarify/index.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify/index.tsx@@ -6,19 +6,22 @@ import { useMemo, useState } from 'react'import { useSessionView } from '@/app/chat/session-view'import { ToolFallback } from '@/components/assistant-ui/tool/fallback'-import { sessionClarifyRequest } from '@/store/clarify'+import { normalizeSetupChoose, sessionClarifyRequest } from '@/store/clarify'import { selectMessageRunning } from '../tool/fallback-model'+import { parseMaybeObject } from '../tool/fallback-model/format'import { readClarifyArgs } from './parse'import { ClarifyToolPending } from './pending'import { ClarifyToolSettled } from './settled'+import { SetupChoosePending } from './setup-pending'+import { SetupChooseSettled } from './setup-settled'import { useUndeliveredClarify } from './use-undelivered'export const ClarifyTool = (props: ToolCallMessagePartProps) => {// Answered → settled Q&A (ToolFallback collapsed the answer away).if (props.result !== undefined) {- return <ClarifyToolSettled {...props} />+ return props.toolName === 'setup_choose' ? <SetupChooseSettled {...props} /> : <ClarifyToolSettled {...props} />}return <ClarifyToolLive {...props} />@@ -29,8 +32,11 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {// session's clarify (primary or tile), not the globally-active one.const sessionId = useStore(useSessionView().$runtimeId)const $request = useMemo(() => sessionClarifyRequest(sessionId), [sessionId])- const request = useStore($request)+ const setupCard = props.toolName === 'setup_choose'+ const sessionRequest = useStore($request)+ const request = sessionRequest && Boolean(sessionRequest.setup) === setupCard ? sessionRequest : nullconst fromArgs = useMemo(() => readClarifyArgs(props.args), [props.args])+ const setupArgs = useMemo(() => normalizeSetupChoose(parseMaybeObject(props.args)), [props.args])const messageRunning = useAuiState(selectMessageRunning)// Answering clears the request a beat before `tool.complete` swaps in the// settled card. Latch submit so that gap doesn't demote; Stop also clears@@ -46,7 +52,14 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {return <ToolFallback {...props} />}- return (+ return setupCard ? (+ <SetupChoosePending+ fromArgs={setupArgs}+ onAnswered={() => setAnswered(true)}+ request={request}+ undelivered={undelivered}+ />+ ) : (<ClarifyToolPendingfromArgs={fromArgs}onAnswered={() => setAnswered(true)}diff --git a/apps/desktop/src/components/assistant-ui/clarify/pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/pending.tsxindex 5f6d61e1874..50867e7ba45 100644--- a/apps/desktop/src/components/assistant-ui/clarify/pending.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify/pending.tsx@@ -3,11 +3,10 @@import { useStore } from '@nanostores/react'import { type FormEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'-import { Button } from '@/components/ui/button'import { Loader } from '@/components/ui/loader'import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'-import { Loader2, MessageQuestion } from '@/lib/icons'+import { MessageQuestion } from '@/lib/icons'import { bareChoice, type ClarifyQuestion, type ClarifyRequest, clearClarifyRequest } from '@/store/clarify'import { $gateway } from '@/store/gateway'import { reconnectAction } from '@/store/gateway-reconnect'@@ -15,6 +14,7 @@ import { notifyError } from '@/store/notifications'import { forgetServerRequest, respondToServerRequest } from '@/store/server-requests'import { requestForOwnedSession } from '@/store/session-states'+import { ClarifyConfirmBar } from './core/confirm-bar'import { emptyStage, QuestionBlock } from './core/question-block'import { CLARIFY_ICON_CLASS, ClarifyShell } from './core/shell'import { useClarifyKeys } from './core/use-clarify-keys'@@ -306,23 +306,12 @@ export function ClarifyToolPending({</ClarifyShell>{undelivered ? null : (- <div className="flex items-center justify-end gap-1">- <Button disabled={disabled} onClick={() => void cancelAll()} size="xs" type="button" variant="text">- {copy.skip}- </Button>- <Button disabled={disabled || !canConfirm} size="xs" type="submit">- {submitting ? (- <Loader2 className="animate-spin" />- ) : (- <>- {copy.confirmAndContinueLabel}- <span aria-hidden className="ml-0.5 text-[0.625rem] opacity-70">- ⏎- </span>- </>- )}- </Button>- </div>+ <ClarifyConfirmBar+ canConfirm={canConfirm}+ disabled={disabled}+ onSkip={() => void cancelAll()}+ submitting={submitting}+ />)}</form>)diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsxnew file mode 100644index 00000000000..354cd1e6bb8--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx@@ -0,0 +1,269 @@+'use client'++import type { SetupChooseIntent, SetupChooseKind } from '@hermes/shared'+import { useStore } from '@nanostores/react'+import { Puzzle } from 'lucide-react'+import { type ComponentType, type FormEvent, useCallback, useMemo, useRef, useState } from 'react'++import { useSessionView } from '@/app/chat/session-view'+import { useI18n } from '@/i18n'+import { triggerHaptic } from '@/lib/haptics'+import { LayoutDashboard, MessageQuestion, Moon, Palette, Plug } from '@/lib/icons'+import { type ClarifyQuestion, type ClarifyRequest, clearClarifyRequest, SETUP_CHOOSE_QID } from '@/store/clarify'+import { notifyError } from '@/store/notifications'+import { respondToServerRequest } from '@/store/server-requests'+import { useTheme } from '@/themes'++import { ClarifyConfirmBar } from './core/confirm-bar'+import { QuestionBlock } from './core/question-block'+import { CLARIFY_ICON_CLASS, ClarifyShell } from './core/shell'+import { useClarifyKeys } from './core/use-clarify-keys'+import { SETUP_PICKERS, SetupIntentRows } from './setup-pickers'+import { LIVE_APPLY, useSetupRows } from './setup-rows'+import { handleClarifySubmitShortcut } from './submit-shortcut'+import { UndeliveredNotice } from './undelivered-notice'++type SetupSource = Pick<ClarifyRequest, 'questions' | 'setup'>++const KIND_ICONS: Record<SetupChooseKind, ComponentType<{ className?: string }>> = {+ accent: Palette,+ connectors: Plug,+ layout: LayoutDashboard,+ plugins: Puzzle,+ question: MessageQuestion,+ theme: Moon+}++export function SetupChoosePending({+ fromArgs,+ onAnswered,+ request,+ undelivered+}: {+ fromArgs: null | SetupSource+ onAnswered: () => void+ request: ClarifyRequest | null+ undelivered: boolean+}) {+ const { t } = useI18n()+ const copy = t.assistant.clarify+ const setupCopy = t.assistant.setupChoose+ const storedId = useStore(useSessionView().$storedId)+ const { 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 = kind === 'question' ? null : kind+ const freeText = pickerKind === null+ const rows = useSetupRows(setup, storedId)++ const [picked, setPicked] = useState<string[]>([])+ const [draft, setDraft] = useState('')+ const [intents, setIntents] = useState<Record<string, SetupChooseIntent>>({})++ const question: ClarifyQuestion = useMemo(+ () => ({+ choices: rows && rows.length > 0 ? rows.map(row => row.label) : null,+ multiSelect: Boolean(setup?.multiSelect && rows && rows.length > 0),+ qid: SETUP_CHOOSE_QID,+ question: source?.questions[0]?.question ?? ''+ }),+ [rows, setup?.multiSelect, source]+ )++ const answer = useMemo((): null | string | string[] => {+ const text = draft.trim()++ if (question.multiSelect) {+ const all = [...picked, ...(text ? [text] : [])]++ return all.length > 0 ? all : null+ }++ return picked[0] ?? (text || null)+ }, [draft, picked, question.multiSelect])++ const stage = useCallback(+ (id: string) => {+ const removing = question.multiSelect && picked.includes(id)++ setPicked(current =>+ question.multiSelect ? (removing ? current.filter(value => value !== id) : [...current, id]) : [id]+ )++ if (!question.multiSelect) {+ setDraft('')+ }++ if (!removing) {+ LIVE_APPLY[kind]?.(id, setMode)+ }+ },+ [kind, picked, question.multiSelect, setMode]+ )++ const toggle = useCallback(+ (_question: ClarifyQuestion, choice: string) => {+ const row = rows?.[question.choices?.indexOf(choice) ?? -1]++ if (row) {+ stage(row.id)+ }+ },+ [question.choices, rows, stage]+ )++ const onDraft = useCallback(+ (value: string) => {+ setDraft(value)++ if (!question.multiSelect) {+ setPicked([])+ }+ },+ [question.multiSelect]+ )++ const confirm = useCallback(() => {+ if (!request || answer === null) {+ return+ }++ const ids = picked.filter(id => rows?.some(row => row.id === id))+ const intent = setup?.intent ? Object.fromEntries(ids.map(id => [id, intents[id] ?? 'later'])) : undefined++ if (!respondToServerRequest(request.requestId, { intent, picked: answer })) {+ notifyError(new Error(copy.notReady), copy.sendFailed)++ return+ }++ triggerHaptic('submit')+ onAnswered()+ clearClarifyRequest(request.requestId, request.sessionId)+ }, [answer, copy, intents, onAnswered, picked, request, rows, setup?.intent])++ const skip = useCallback(() => {+ if (!request) {+ return+ }++ onAnswered()+ clearClarifyRequest(request.requestId, request.sessionId)+ respondToServerRequest(request.requestId, {})+ }, [onAnswered, request])++ const handleSubmit = useCallback(+ (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault()++ if (ready) {+ confirm()+ }+ },+ [confirm, ready]+ )++ const formRef = useRef<HTMLFormElement | null>(null)+ const questions = useMemo(() => [question], [question])++ const keys = useClarifyKeys({+ enabled: ready,+ formRef,+ isStaged: () => answer !== null,+ onClear: () => setPicked([]),+ onConfirm: confirm,+ onToggle: toggle,+ other: freeText,+ questions+ })++ const cursor = ready ? keys.cursorRow : null+ const Picker = pickerKind === null ? null : SETUP_PICKERS[pickerKind]+ const Icon = KIND_ICONS[kind]+ const intentRows = setup?.intent && rows ? rows.filter(row => picked.includes(row.id)) : []++ return (+ <form+ aria-busy={ready || undelivered ? undefined : 'true'}+ className="my-1.5 grid gap-4"+ data-clarify-batch={1}+ data-clarify-batch-preview={ready ? undefined : ''}+ data-clarify-choices={ready ? question.choices?.length || undefined : undefined}+ data-clarify-other={freeText ? undefined : 'false'}+ data-setup-choose={kind}+ onKeyDownCapture={handleClarifySubmitShortcut}+ onSubmit={handleSubmit}+ ref={formRef}+ >+ {ready || undelivered ? null : (+ <span className="sr-only" role="status">+ {copy.loadingQuestion}+ </span>+ )}+ <ClarifyShell className="grid gap-3">+ <div className="flex items-start gap-2">+ <span className="flex-1 text-[0.6875rem] leading-4 text-(--ui-text-tertiary)">+ {pickerKind === null ? copy.questionProgress(answer === null ? 0 : 1, 1) : setupCopy.kinds[pickerKind]}+ </span>+ <Icon aria-hidden className={CLARIFY_ICON_CLASS} />+ </div>+ {undelivered ? <UndeliveredNotice /> : null}+ {Picker === null ? (+ <QuestionBlock+ cursor={cursor}+ disabled={!ready}+ onActivate={() => keys.focusQuestion(0)}+ onDraft={onDraft}+ onOtherFocus={() => keys.onOtherFocus(0)}+ onPick={index => keys.pick(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}+ />+ )}+ <SetupIntentRows+ intents={intents}+ onIntent={(id, intent) => setIntents(current => ({ ...current, [id]: intent }))}+ rows={intentRows}+ />+ </fieldset>+ )}+ </ClarifyShell>++ {undelivered ? null : (+ <ClarifyConfirmBar canConfirm={answer !== null} disabled={!ready} onSkip={skip} submitting={false} />+ )}+ </form>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsxnew file mode 100644index 00000000000..55ea3d0bc2e--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx@@ -0,0 +1,210 @@+'use client'++import type { SetupChooseIntent, SetupChooseKind } from '@hermes/shared'+import { Puzzle } from 'lucide-react'+import { type FC, type ReactNode, useState } from 'react'++import { Chip } from '@/components/onboarding-chat/chip'+import { AccentSwatch, LayoutPreviewCard, LAYOUTS, NOUS_ACCENT } from '@/components/onboarding-chat/options'+import { ConnectorLogo } from '@/components/ui/connector-logo'+import { SearchField } from '@/components/ui/search-field'+import { SegmentedControl } from '@/components/ui/segmented-control'+import { useI18n } from '@/i18n'+import { connectorIconUrl } from '@/lib/connector-tools'+import { cn } from '@/lib/utils'++import { ChoiceButton, letterFor } from './core/choice-row'+import type { SetupRow } from './setup-rows'++export interface SetupPickerProps {+ cursor: null | number+ onPick: (index: number) => void+ onStage: (id: string) => void+ picked: string[]+ rows: SetupRow[]+}++const SEARCH_THRESHOLD = 12++const INTENTS: readonly SetupChooseIntent[] = ['now', 'later', 'save']++function PickerItem({+ active,+ children,+ className,+ index+}: {+ active: boolean+ children: ReactNode+ className?: string+ index: number+}) {+ return (+ <div+ aria-keyshortcuts={`${letterFor(index)} ${index + 1}`}+ className={cn('min-w-0', active && 'ring-2 ring-primary/40', className)}+ data-highlighted={active || undefined}+ onMouseDown={event => event.preventDefault()}+ >+ {children}+ </div>+ )+}++function ThemePicker({ cursor, onPick, picked, rows }: SetupPickerProps) {+ return (+ <div className="grid gap-px" role="group">+ {rows.map((row, index) => (+ <ChoiceButton+ active={cursor === index}+ char={letterFor(index)}+ choice={row.label}+ key={row.id}+ keyShortcuts={`${letterFor(index)} ${index + 1}`}+ onClick={() => onPick(index)}+ selected={picked.includes(row.id)}+ />+ ))}+ </div>+ )+}++function AccentPicker({ cursor, onPick, onStage, picked, rows }: SetupPickerProps) {+ const { t } = useI18n()+ const current = picked[0] ?? NOUS_ACCENT+ const custom = !rows.some(row => row.id.toLowerCase() === current.toLowerCase())++ return (+ <div className="flex flex-wrap gap-2.5 p-1" role="group">+ {rows.map((row, index) => (+ <PickerItem active={cursor === index} className="rounded-full" index={index} key={row.id}>+ <AccentSwatch active={picked.includes(row.id)} hex={row.id} name={row.label} onPick={() => onPick(index)} />+ </PickerItem>+ ))}+ <AccentSwatch+ active={picked.length > 0 && custom}+ hex={custom ? current : NOUS_ACCENT}+ name={t.assistant.setupChoose.customColor}+ onColorChange={onStage}+ />+ </div>+ )+}++function LayoutPicker({ cursor, onPick, picked, rows }: SetupPickerProps) {+ return (+ <div className="grid grid-cols-2 gap-3 p-1" role="group">+ {rows.map((row, index) => (+ <PickerItem active={cursor === index} className="rounded-[8px]" index={index} key={row.id}>+ <LayoutPreviewCard+ active={picked.includes(row.id)}+ description={row.detail ?? undefined}+ name={row.label}+ onSelect={() => onPick(index)}+ tree={LAYOUTS.find(layout => layout.id === row.id)?.tree ?? 1}+ />+ </PickerItem>+ ))}+ </div>+ )+}++function ChipPicker({+ cursor,+ icon,+ onPick,+ picked,+ rows,+ sub+}: SetupPickerProps & { icon: (row: SetupRow) => ReactNode; sub?: string }) {+ const { t } = useI18n()+ const [query, setQuery] = useState('')+ const search = query.trim().toLowerCase()++ return (+ <div className="grid gap-2">+ {rows.length > SEARCH_THRESHOLD ? (+ <SearchField onChange={setQuery} placeholder={t.assistant.setupChoose.findApp} value={query} />+ ) : null}+ <div className="grid max-h-72 grid-cols-3 gap-2 overflow-y-auto p-1" role="group">+ {rows.map((row, index) =>+ search && !row.label.toLowerCase().includes(search) ? null : (+ <PickerItem active={cursor === index} className="rounded-[6px]" index={index} key={row.id}>+ <Chip+ className="w-full"+ icon={icon(row)}+ label={row.label}+ on={picked.includes(row.id)}+ onToggle={() => onPick(index)}+ sub={row.detail ?? sub}+ />+ </PickerItem>+ )+ )}+ </div>+ </div>+ )+}++const connectorIcon = (row: SetupRow) => (+ <ConnectorLogo+ className="size-7 rounded-full text-sm"+ connector={{ iconUrl: connectorIconUrl(row.id), name: row.id, title: row.label }}+ />+)++const pluginIcon = () => (+ <span className="grid size-7 shrink-0 place-items-center rounded-full bg-background text-muted-foreground">+ <Puzzle className="size-4" />+ </span>+)++function ConnectorPicker(props: SetupPickerProps) {+ return <ChipPicker {...props} icon={connectorIcon} />+}++function PluginPicker(props: SetupPickerProps) {+ const { t } = useI18n()++ return <ChipPicker {...props} icon={pluginIcon} sub={t.assistant.setupChoose.plugin} />+}++export const SETUP_PICKERS: Record<Exclude<SetupChooseKind, 'question'>, FC<SetupPickerProps>> = {+ accent: AccentPicker,+ connectors: ConnectorPicker,+ layout: LayoutPicker,+ plugins: PluginPicker,+ theme: ThemePicker+}++export function SetupIntentRows({+ intents,+ onIntent,+ rows+}: {+ intents: Record<string, SetupChooseIntent>+ onIntent: (id: string, intent: SetupChooseIntent) => void+ rows: SetupRow[]+}) {+ const { t } = useI18n()+ const options = INTENTS.map(id => ({ id, label: t.assistant.setupChoose.intent[id] }))++ if (rows.length === 0) {+ return null+ }++ return (+ <div className="grid gap-1.5 border-t border-(--ui-stroke-tertiary) pt-2.5">+ {rows.map(row => (+ <div className="flex items-center justify-between gap-2" key={row.id}>+ <span className="min-w-0 truncate text-(--ui-text-secondary)">{row.label}</span>+ <SegmentedControl+ onChange={intent => onIntent(row.id, intent)}+ options={options}+ value={intents[row.id] ?? 'later'}+ />+ </div>+ ))}+ </div>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts b/apps/desktop/src/components/assistant-ui/clarify/setup-rows.tsnew file mode 100644index 00000000000..7910ad75ccd--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts@@ -0,0 +1,125 @@+import type { ConnectorRow, SetupChooseKind, SetupChooseOption } from '@hermes/shared'+import { useQuery } from '@tanstack/react-query'++import { listConnectors } from '@/app/capabilities/connectors/data/rpc'+import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'+import { MODE_OPTIONS } from '@/app/settings/constants'+import { $chatLayoutPicked, assembleChatOnboarding } from '@/components/onboarding-chat/assembly'+import { accentsFor, LAYOUTS, NOUS_ACCENT, orderConnectorPicks } from '@/components/onboarding-chat/options'+import type { LayoutNode } from '@/components/pane-shell/tree/model'+import { registry } from '@/contrib/registry'+import { useI18n } from '@/i18n'+import { connectorTitle } from '@/lib/connector-tools'+import type { SetupChooseSpec } from '@/store/clarify'+import { type OnboardingPlugin, useOnboardingPluginList } from '@/store/onboarding-plugins'+import { $activeGatewayProfile } from '@/store/profile'+import { isSessionOwnerRoute } from '@/store/session-request-router'+import { useTheme } from '@/themes'+import { setAccentOverride } from '@/themes/accent-override'+import { normalizeHex } from '@/themes/color'+import type { ThemeMode } from '@/themes/context'++export type SetupRow = SetupChooseOption++type Translations = ReturnType<typeof useI18n>['t']++interface RowSources {+ connectors: ConnectorRow[] | null+ dark: boolean+ plugins: OnboardingPlugin[] | null+ t: Translations+}++const modeLabel = (id: string, t: Translations): string =>+ MODE_OPTIONS.some(option => option.id === id) ? t.settings.modeOptions[id as ThemeMode].label : id++const APP_ROWS: Record<SetupChooseKind, (sources: RowSources) => null | SetupRow[]> = {+ accent: ({ dark }) => accentsFor(dark).map(({ hex, name }) => ({ id: hex, label: name })),+ connectors: ({ connectors }) =>+ connectors &&+ orderConnectorPicks(connectors).map(row => ({ id: row.connector, label: connectorTitle(row.connector) })),+ layout: () => LAYOUTS.map(layout => ({ detail: layout.description, id: layout.id, label: layout.name })),+ plugins: ({ plugins }) =>+ plugins &&+ plugins.map(plugin => ({+ detail: plugin.app_state === 'missing_app' ? plugin.sentence : undefined,+ id: plugin.name,+ label: plugin.title+ })),+ question: () => [],+ theme: ({ t }) => MODE_OPTIONS.map(({ id }) => ({ id, label: modeLabel(id, t) }))+}++const APP_LABELS: Record<SetupChooseKind, (id: string, sources: Pick<RowSources, 'plugins' | 't'>) => string> = {+ accent: id => [...accentsFor(false), ...accentsFor(true)].find(swatch => swatch.hex === normalizeHex(id))?.name ?? id,+ connectors: id => connectorTitle(id),+ layout: id => LAYOUTS.find(layout => layout.id === id)?.name ?? id,+ plugins: (id, { plugins }) => plugins?.find(plugin => plugin.name === id)?.title ?? id,+ question: id => id,+ theme: (id, { t }) => modeLabel(id, t)+}++export const LIVE_APPLY: Partial<Record<SetupChooseKind, (id: string, setMode: (mode: ThemeMode) => void) => void>> = {+ accent: id => {+ const hex = normalizeHex(id)++ if (hex) {+ setAccentOverride(hex === NOUS_ACCENT ? null : hex)+ }+ },+ layout: id => {+ const preset = registry.getArea('layouts').find(contribution => contribution.id === id)++ if (!preset?.data) {+ return+ }++ $chatLayoutPicked.set(true)+ assembleChatOnboarding(preset.id, preset.data as LayoutNode, LAYOUTS.find(layout => layout.id === id)?.mode)+ },+ theme: (id, setMode) => {+ if (MODE_OPTIONS.some(option => option.id === id)) {+ setMode(id as ThemeMode)+ }+ }+}++function useAccountConnectorRows(storedId: null | string): ConnectorRow[] | null {+ const query = useQuery({+ enabled: Boolean(storedId),+ queryFn: async () => {+ const owner = await resolveSessionOwner(storedId)+ const list = await listConnectors(isSessionOwnerRoute(owner) ? owner : owner || $activeGatewayProfile.get())++ return list.available ? list.connectors : []+ },+ queryKey: ['setup-choose', 'connectors.list', storedId],+ staleTime: Infinity+ })++ return query.isError ? [] : (query.data ?? null)+}++export function useSetupRows(setup: null | SetupChooseSpec, storedId: null | string): null | SetupRow[] {+ const { t } = useI18n()+ const { renderedMode } = useTheme()+ const connectors = useAccountConnectorRows(setup?.options === null && setup.kind === 'connectors' ? storedId : null)+ const plugins = useOnboardingPluginList(setup?.options === null && setup.kind === 'plugins' ? storedId : null)++ if (!setup) {+ return []+ }++ return setup.options ?? APP_ROWS[setup.kind]({ connectors, dark: renderedMode === 'dark', plugins, t })+}++export function useSetupLabel(+ kind: SetupChooseKind,+ options: null | SetupRow[],+ storedId: null | string+): (id: string) => string {+ const { t } = useI18n()+ const plugins = useOnboardingPluginList(kind === 'plugins' && !options ? storedId : null)++ return id => options?.find(option => option.id === id)?.label ?? APP_LABELS[kind](id, { plugins, t })+}diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-settled.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-settled.tsxnew file mode 100644index 00000000000..a1d601b96fb--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-settled.tsx@@ -0,0 +1,84 @@+'use client'++import type { ToolCallMessagePartProps } from '@assistant-ui/react'+import type { SetupChooseIntent } from '@hermes/shared'+import { useStore } from '@nanostores/react'++import { useSessionView } from '@/app/chat/session-view'+import { ToolFallback } from '@/components/assistant-ui/tool/fallback'+import { useI18n } from '@/i18n'+import { CircleLetterA, MessageQuestion } from '@/lib/icons'+import { cn } from '@/lib/utils'+import { normalizeSetupChoose } from '@/store/clarify'++import { parseMaybeObject } from '../tool/fallback-model/format'++import { ClarifyLine, ClarifyShell } from './core/shell'+import { useSetupLabel } from './setup-rows'++const OUTCOMES = new Set(['cancelled', 'no_answer', 'submitted'])+const INTENTS = new Set<unknown>(['later', 'now', 'save'])++function readSetupChooseResult(result: unknown) {+ const row = parseMaybeObject(result)++ if (typeof row.outcome !== 'string' || !OUTCOMES.has(row.outcome)) {+ return null+ }++ const picked = Array.isArray(row.picked) ? row.picked.map(String) : typeof row.picked === 'string' ? [row.picked] : []++ const intent = parseMaybeObject(row.intent)++ return {+ intent: Object.fromEntries(+ Object.entries(intent).filter((entry): entry is [string, SetupChooseIntent] => INTENTS.has(entry[1]))+ ),+ outcome: row.outcome,+ picked+ }+}++export function SetupChooseSettled(props: ToolCallMessagePartProps) {+ const { t } = useI18n()+ const copy = t.assistant.clarify+ const storedId = useStore(useSessionView().$storedId)+ const source = normalizeSetupChoose(parseMaybeObject(props.args))+ const result = readSetupChooseResult(props.result)+ const label = useSetupLabel(source?.setup?.kind ?? 'question', source?.setup?.options ?? null, storedId)++ if (!result) {+ return <ToolFallback {...props} />+ }++ const answer = result.picked+ .map(id => {+ const intent = result.intent[id]++ return intent ? `${label(id)} · ${t.assistant.setupChoose.intent[intent]}` : label(id)+ })+ .join(', ')++ const question = source?.questions[0]?.question++ return (+ <ClarifyShell className="my-1.5 grid gap-1" data-clarify-settled="">+ {question ? (+ <ClarifyLine icon={MessageQuestion}>+ <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question}</span>+ </ClarifyLine>+ ) : null}+ <ClarifyLine icon={CircleLetterA}>+ <p+ className={cn(+ 'whitespace-pre-wrap leading-(--conversation-line-height)',+ answer ? 'text-(--ui-text-secondary)' : 'italic text-(--ui-text-tertiary)'+ )}+ data-clarify-answer=""+ >+ {answer || (result.outcome === 'no_answer' ? copy.noAnswer : copy.skipped)}+ </p>+ </ClarifyLine>+ </ClarifyShell>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsxnew file mode 100644index 00000000000..bc30d68f369--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx@@ -0,0 +1,114 @@+'use client'++import type { ToolCallMessagePartProps } from '@assistant-ui/react'+import { useStore } from '@nanostores/react'+import { useEffect, useMemo } from 'react'+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 { Loader2, MessageCircle } from '@/lib/icons'+import { notifyError } from '@/store/notifications'+import { $profiles, profileLabel } from '@/store/profile'+import { setSessionOwnerHint } from '@/store/session'+import { isSessionOwnerRoute } from '@/store/session-request-router'+import { isSessionInForeground } from '@/store/session-states'+import { readStartChatResult, takeLiveStartChat } from '@/store/start-chat'++const TITLE_LIMIT = 40++const CAPTION = 'text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)'++async function openStartedChat(+ chat: { profile: string; sessionId: string },+ callerId: null | string,+ navigate: OpenSessionNavigate,+ stillWanted: () => boolean = () => true+): Promise<void> {+ const owner = await resolveSessionOwner(callerId)++ if (isSessionOwnerRoute(owner)) {+ setSessionOwnerHint(chat.sessionId, { connectionId: owner.connectionId, profile: chat.profile })+ }++ if (stillWanted()) {+ openSessionFromPicker(chat.sessionId, navigate)+ }+}++export function StartChatTool(props: ToolCallMessagePartProps) {+ const { t } = useI18n()+ const copy = t.assistant.startChat+ const callerId = useStore(useSessionView().$storedId)+ const profiles = useStore($profiles)+ const navigate = useNavigate()+ const outcome = useMemo(() => readStartChatResult(props.result), [props.result])+ const started = outcome?.status === 'started' ? outcome : null+ const args = parseMaybeObject(props.args)+ const message = typeof args.message === 'string' ? args.message.trim() : ''++ const title =+ started?.title || (typeof args.title === 'string' && args.title.trim()) || message.slice(0, TITLE_LIMIT) || null++ useEffect(() => {+ if (!started || !takeLiveStartChat(props.toolCallId)) {+ return+ }++ const watching = () => Boolean(callerId) && isSessionInForeground(callerId!)++ void openStartedChat(started, callerId, navigate, watching).catch(error => notifyError(error, copy.openFailed))+ }, [callerId, copy.openFailed, navigate, props.toolCallId, started])++ if (props.result !== undefined && !outcome) {+ return <ToolFallback {...props} />+ }++ if (outcome?.status === 'rejected') {+ return (+ <ClarifyShell className="my-1.5 grid gap-0.5" data-slot="start-chat">+ <span className="font-medium">{copy.notStarted}</span>+ {outcome.reason ? <span className={CAPTION}>{outcome.reason}</span> : null}+ </ClarifyShell>+ )+ }++ 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>+ )+ }++ 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>+ )+}diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex d0741009f17..ddeda674cf8 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -14,6 +14,7 @@ import { ClarifyTool } from '@/components/assistant-ui/clarify'import { ConnectorExecution, ConnectorTool } from '@/components/assistant-ui/connector-tool'import { MarkdownText, MarkdownTextContent } from '@/components/assistant-ui/markdown-text'import { McpSetupTool } from '@/components/assistant-ui/mcp-setup-tool'+import { StartChatTool } from '@/components/assistant-ui/start-chat-tool'import { AgentDeliveryNotice, deliveryTargetFromCommand } from '@/components/assistant-ui/thread/agent-delivery'import { TimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'import { DelegateTool } from '@/components/assistant-ui/tool/delegate'@@ -93,6 +94,19 @@ const ClarifyToolPart: FC<TimelineToolCallProps> = props => {)}+const StartChatToolPart: FC<TimelineToolCallProps> = props => {+ if (props.isError || settledWithoutResult(props)) {+ return <ToolFallback {...props} />+ }++ return (+ <>+ <TimelineTimestamp className="mb-0.5 block" completedAt={props.completedAt} timestamp={props.timestamp} />+ <StartChatTool {...props} />+ </>+ )+}+const ConnectionsToolPart: FC<TimelineToolCallProps> = props =>mcpTargets(props.toolName, props.args).length > 0 ? <McpSetupTool {...props} /> : <ConnectorTool {...props} />@@ -101,7 +115,9 @@ const TOOL_CARDS: Record<CardToolName, FC<TimelineToolCallProps>> = {delegate_task: DelegateToolPart,image_generate: ImageGenerateTool,manage_catalog: CatalogInstallTool,- manage_connections: ConnectionsToolPart+ manage_connections: ConnectionsToolPart,+ setup_choose: ClarifyToolPart,+ start_chat: StartChatToolPart}// A failure the user still has to see. The gateway's tool.complete carries thediff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.tsindex 91f86eefb7b..fa2f94c30db 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model/index.ts@@ -206,6 +206,14 @@ const TOOL_META: Record<ToolTitleKey, ToolMetaSpec> = {icon: 'search',tone: 'agent'},+ setup_choose: {+ icon: 'question',+ tone: 'agent'+ },+ start_chat: {+ icon: 'comment',+ tone: 'agent'+ },terminal: {icon: 'terminal',tone: 'terminal'diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 3102ae85c8c..018b85e002f 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -3366,6 +3366,30 @@ export const ar = defineLocale({confirmAndContinueLabel: 'تأكيد ومتابعة',questionProgress: (answered, total) => `تمت الإجابة على ${answered} من ${total}`},+ setupChoose: {+ kinds: {+ accent: 'لون التمييز',+ connectors: 'التطبيقات',+ layout: 'التخطيط',+ plugins: 'الإضافات',+ theme: 'المظهر'+ },+ loading: 'جار تحميل الخيارات...',+ unavailable: 'هذه القائمة غير متاحة الآن. رد في المحادثة بدلا من ذلك.',+ findApp: 'ابحث عن تطبيق',+ customColor: 'لون مخصص',+ plugin: 'إضافة',+ intent: { now: 'الآن', later: 'عند الحاجة', save: 'دوّنها فقط' }+ },+ startChat: {+ starting: title => `جار بدء "${title}"...`,+ startingUntitled: 'جار بدء محادثة...',+ untitled: 'محادثة جديدة',+ notStarted: 'لم تبدأ المحادثة',+ inProfile: profile => `في ${profile}`,+ open: 'فتح',+ openFailed: 'تعذر فتح المحادثة'+ },tool: {copyCode: 'نسخ الكود',renderingImage: 'جار عرض الصورة...',@@ -3514,6 +3538,8 @@ export const ar = defineLocale({pending: 'جار البحث في سجل الجلسة',pendingAction: 'جار البحث'},+ setup_choose: { done: 'طرح سؤال إعداد', pending: 'يطرح سؤال إعداد', pendingAction: 'يسأل' },+ start_chat: { done: 'بدأ محادثة', pending: 'يبدأ محادثة', pendingAction: 'يبدأ' },terminal: {done: 'تم تشغيل الأمر',pending: 'جار تشغيل الأمر',diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex b2d1131a179..8822b6ae7f3 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -5719,6 +5719,30 @@ export const deOverrides = {notDelivered:'Diese Frage hat die App nicht erreicht und kann hier nicht beantwortet werden. Klicken Sie auf Stopp, um den Durchgang zu beenden, und antworten Sie dann im Chat.'},+ setupChoose: {+ kinds: {+ accent: 'Akzentfarbe',+ connectors: 'Apps',+ layout: 'Layout',+ plugins: 'Plugins',+ theme: 'Erscheinungsbild'+ },+ loading: 'Optionen werden geladen…',+ unavailable: 'Diese Liste ist gerade nicht verfügbar. Antworten Sie stattdessen im Chat.',+ findApp: 'App suchen',+ customColor: 'Eigene Farbe',+ plugin: 'Plugin',+ intent: { now: 'Jetzt', later: 'Bei Bedarf', save: 'Nur merken' }+ },+ startChat: {+ starting: title => `„${title}“ wird gestartet…`,+ startingUntitled: 'Chat wird gestartet…',+ untitled: 'Neuer Chat',+ notStarted: 'Der Chat wurde nicht gestartet',+ inProfile: profile => `In ${profile}`,+ open: 'Öffnen',+ openFailed: 'Der Chat konnte nicht geöffnet werden'+ },catalogInstall: {preparing: 'Installation wird vorbereitet…',install: 'Installieren',@@ -5919,6 +5943,12 @@ export const deOverrides = {pending: 'Durchsucht Session-Verlauf',pendingAction: 'Durchsucht'},+ setup_choose: {+ done: 'Einrichtungsfrage gestellt',+ pending: 'Stellt eine Einrichtungsfrage',+ pendingAction: 'Fragt'+ },+ start_chat: { done: 'Chat gestartet', pending: 'Startet einen Chat', pendingAction: 'Startet' },terminal: {done: 'Befehl ausgeführt',pending: 'Führt Befehl aus',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 11e74c33c4b..cc2a3849e74 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -5324,6 +5324,30 @@ export const en: Translations = {notDelivered:"This question didn't reach the app, so it can't be answered here. Press Stop to end the turn, then reply in chat."},+ setupChoose: {+ kinds: {+ accent: 'Accent color',+ connectors: 'Apps',+ layout: 'Layout',+ plugins: 'Plugins',+ theme: 'Appearance'+ },+ loading: 'Loading options…',+ unavailable: "This list isn't available right now. Reply in chat instead.",+ findApp: 'Find an app',+ customColor: 'Custom color',+ plugin: 'Plugin',+ intent: { now: 'Now', later: 'When needed', save: 'Just note it' }+ },+ startChat: {+ starting: title => `Starting “${title}”…`,+ startingUntitled: 'Starting a chat…',+ untitled: 'New chat',+ notStarted: "The chat didn't start",+ inProfile: profile => `In ${profile}`,+ open: 'Open',+ openFailed: "Couldn't open the chat"+ },catalogInstall: {preparing: 'Preparing the install…',install: 'Install',@@ -5457,6 +5481,8 @@ export const en: Translations = {pending: 'Searching session history',pendingAction: 'Searching'},+ setup_choose: { done: 'Asked a setup question', pending: 'Asking a setup question', pendingAction: 'Asking' },+ start_chat: { done: 'Started a chat', pending: 'Starting a chat', pendingAction: 'Starting' },terminal: { done: 'Ran command', pending: 'Running command', pendingAction: 'Running' },todo: { done: 'Updated todos', pending: 'Updating todos', pendingAction: 'Updating' },vision_analyze: { done: 'Analyzed image', pending: 'Analyzing image', pendingAction: 'Analyzing' },diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 11ba0c0e735..4e2d170746f 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -5712,6 +5712,30 @@ export const esOverrides = {notDelivered:'Esta pregunta no llegó a la app, así que no se puede responder aquí. Pulsa Detener para terminar el turno y luego responde en el chat.'},+ setupChoose: {+ kinds: {+ accent: 'Color de acento',+ connectors: 'Apps',+ layout: 'Diseño',+ plugins: 'Plugins',+ theme: 'Apariencia'+ },+ loading: 'Cargando opciones…',+ unavailable: 'Esta lista no está disponible ahora. Responde en el chat.',+ findApp: 'Buscar una app',+ customColor: 'Color personalizado',+ plugin: 'Plugin',+ intent: { now: 'Ahora', later: 'Cuando haga falta', save: 'Solo anotarlo' }+ },+ startChat: {+ starting: title => `Iniciando «${title}»…`,+ startingUntitled: 'Iniciando un chat…',+ untitled: 'Chat nuevo',+ notStarted: 'El chat no se inició',+ inProfile: profile => `En ${profile}`,+ open: 'Abrir',+ openFailed: 'No se pudo abrir el chat'+ },catalogInstall: {preparing: 'Preparando la instalación…',install: 'Instalar',@@ -5912,6 +5936,12 @@ export const esOverrides = {pending: 'Buscar en el historial de sesiones',pendingAction: 'Buscando'},+ setup_choose: {+ done: 'Hizo una pregunta de configuración',+ pending: 'Haciendo una pregunta de configuración',+ pendingAction: 'Preguntando'+ },+ start_chat: { done: 'Inició un chat', pending: 'Iniciando un chat', pendingAction: 'Iniciando' },terminal: {done: 'Comando ejecutado',pending: 'Ejecutar comando',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex 4ca2f751e96..f5c80a2c0ba 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -5733,6 +5733,30 @@ export const frOverrides = {notDelivered:"Cette question n'a pas atteint l'app, elle ne peut donc pas être répondue ici. Appuyez sur Arrêter pour terminer le tour, puis répondez dans le chat."},+ setupChoose: {+ kinds: {+ accent: 'Couleur d’accent',+ connectors: 'Apps',+ layout: 'Disposition',+ plugins: 'Plugins',+ theme: 'Apparence'+ },+ loading: 'Chargement des options…',+ unavailable: 'Cette liste n’est pas disponible pour le moment. Répondez plutôt dans le chat.',+ findApp: 'Trouver une app',+ customColor: 'Couleur personnalisée',+ plugin: 'Plugin',+ intent: { now: 'Maintenant', later: 'Au besoin', save: 'Juste noter' }+ },+ startChat: {+ starting: title => `Démarrage de « ${title} »…`,+ startingUntitled: 'Démarrage d’un chat…',+ untitled: 'Nouveau chat',+ notStarted: 'Le chat n’a pas démarré',+ inProfile: profile => `Dans ${profile}`,+ open: 'Ouvrir',+ openFailed: 'Impossible d’ouvrir le chat'+ },catalogInstall: {preparing: 'Préparation de l’installation…',install: 'Installer',@@ -5933,6 +5957,12 @@ export const frOverrides = {pending: "Recherche dans l'historique de session en cours",pendingAction: 'Recherche en cours'},+ setup_choose: {+ done: 'Question de configuration posée',+ pending: 'Pose une question de configuration',+ pendingAction: 'Question en cours'+ },+ start_chat: { done: 'Chat démarré', pending: 'Démarrage d’un chat', pendingAction: 'Démarrage' },terminal: {done: 'Commande exécutée',pending: 'Exécution de la commande en cours',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 9d7e830f4e9..443287355ed 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3939,6 +3939,30 @@ export const ja = defineLocale({notDelivered:'この質問はアプリに届かなかったため、ここでは回答できません。停止を押してターンを終了し、チャットで返信してください。'},+ setupChoose: {+ kinds: {+ accent: 'アクセントカラー',+ connectors: 'アプリ',+ layout: 'レイアウト',+ plugins: 'プラグイン',+ theme: '外観'+ },+ loading: 'オプションを読み込み中…',+ unavailable: 'このリストは現在利用できません。代わりにチャットで返信してください。',+ findApp: 'アプリを検索',+ customColor: 'カスタムカラー',+ plugin: 'プラグイン',+ intent: { now: '今すぐ', later: '必要なときに', save: 'メモだけ' }+ },+ startChat: {+ starting: title => `「${title}」を開始中…`,+ startingUntitled: 'チャットを開始中…',+ untitled: '新しいチャット',+ notStarted: 'チャットを開始できませんでした',+ inProfile: profile => `${profile} 内`,+ open: '開く',+ openFailed: 'チャットを開けませんでした'+ },tool: {copyCode: 'コードをコピー',renderingImage: '画像をレンダリング中',@@ -4048,6 +4072,8 @@ export const ja = defineLocale({pending: 'セッション履歴を検索中',pendingAction: '検索中'},+ setup_choose: { done: '設定の質問をしました', pending: '設定の質問をしています', pendingAction: '質問中' },+ start_chat: { done: 'チャットを開始しました', pending: 'チャットを開始中', pendingAction: '開始中' },terminal: { done: 'コマンドを実行しました', pending: 'コマンドを実行中', pendingAction: '実行中' },todo: { done: 'Todo を更新しました', pending: 'Todo を更新中', pendingAction: '更新中' },vision_analyze: { done: '画像を分析しました', pending: '画像を分析中', pendingAction: '分析中' },diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 37204e6bef2..72e523a23bc 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -4061,6 +4061,30 @@ export const ru = defineLocale({notDelivered:'Этот вопрос не дошёл до приложения, поэтому ответить здесь нельзя. Нажмите «Стоп», чтобы завершить ход, и ответьте в чате.'},+ setupChoose: {+ kinds: {+ accent: 'Акцентный цвет',+ connectors: 'Приложения',+ layout: 'Раскладка',+ plugins: 'Плагины',+ theme: 'Оформление'+ },+ loading: 'Загружаю варианты…',+ unavailable: 'Этот список сейчас недоступен. Ответьте в чате.',+ findApp: 'Найти приложение',+ customColor: 'Свой цвет',+ plugin: 'Плагин',+ intent: { now: 'Сейчас', later: 'Когда понадобится', save: 'Просто запомнить' }+ },+ startChat: {+ starting: title => `Запускаю «${title}»…`,+ startingUntitled: 'Запускаю чат…',+ untitled: 'Новый чат',+ notStarted: 'Чат не запустился',+ inProfile: profile => `В ${profile}`,+ open: 'Открыть',+ openFailed: 'Не удалось открыть чат'+ },catalogInstall: {preparing: 'Готовим установку…',install: 'Установить',@@ -4203,6 +4227,12 @@ export const ru = defineLocale({pending: 'Ищу в истории сеансов',pendingAction: 'Ищу'},+ setup_choose: {+ done: 'Задан вопрос о настройке',+ pending: 'Задаю вопрос о настройке',+ pendingAction: 'Спрашиваю'+ },+ start_chat: { done: 'Чат запущен', pending: 'Запускаю чат', pendingAction: 'Запускаю' },terminal: { done: 'Команда выполнена', pending: 'Выполняю команду', pendingAction: 'Выполняю' },todo: { done: 'Todo обновлены', pending: 'Обновляю todo', pendingAction: 'Обновляю' },vision_analyze: {diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex e51603e5f01..5fa7193a7f0 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -42,6 +42,8 @@ export type ToolTitleKey =| 'read_file'| 'search_files'| 'session_search_recall'+ | 'setup_choose'+ | 'start_chat'| 'terminal'| 'todo'| 'vision_analyze'@@ -4430,6 +4432,24 @@ export interface Translations {questionProgress: (answered: number, total: number) => stringnotDelivered: string}+ setupChoose: {+ kinds: Record<'accent' | 'connectors' | 'layout' | 'plugins' | 'theme', string>+ loading: string+ unavailable: string+ findApp: string+ customColor: string+ plugin: string+ intent: Record<'later' | 'now' | 'save', string>+ }+ startChat: {+ starting: (title: string) => string+ startingUntitled: string+ untitled: string+ notStarted: string+ inProfile: (profile: string) => string+ open: string+ openFailed: string+ }catalogInstall: {preparing: stringinstall: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 98373973b64..969cefc6eda 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -4102,6 +4102,30 @@ export const zhHant = defineLocale({questionProgress: (answered, total) => `已回答 ${answered}/${total}`,notDelivered: '此問題未送達應用程式,無法在此回答。請按停止結束本輪,然後在聊天中回覆。'},+ setupChoose: {+ kinds: {+ accent: '強調色',+ connectors: '應用程式',+ layout: '版面配置',+ plugins: '外掛',+ theme: '外觀'+ },+ loading: '正在載入選項…',+ unavailable: '此清單暫時無法使用,請直接在聊天中回覆。',+ findApp: '尋找應用程式',+ customColor: '自訂顏色',+ plugin: '外掛',+ intent: { now: '現在', later: '需要時', save: '僅記下' }+ },+ startChat: {+ starting: title => `正在啟動「${title}」…`,+ startingUntitled: '正在啟動聊天…',+ untitled: '新聊天',+ notStarted: '聊天未能啟動',+ inProfile: profile => `位於 ${profile}`,+ open: '開啟',+ openFailed: '無法開啟聊天'+ },tool: {copyCode: '複製程式碼',renderingImage: '正在渲染圖片',@@ -4187,6 +4211,8 @@ export const zhHant = defineLocale({pending: '正在搜尋工作階段歷史',pendingAction: '正在搜尋'},+ setup_choose: { done: '已提出設定問題', pending: '正在提出設定問題', pendingAction: '正在提問' },+ start_chat: { done: '已啟動聊天', pending: '正在啟動聊天', pendingAction: '正在啟動' },terminal: { done: '已執行指令', pending: '正在執行指令', pendingAction: '正在執行' },todo: { done: '已更新待辦', pending: '正在更新待辦', pendingAction: '正在更新' },vision_analyze: { done: '已分析圖片', pending: '正在分析圖片', pendingAction: '正在分析' },diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 22c0773ac14..e4d48d9695e 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4892,6 +4892,30 @@ export const zh = defineLocale({questionProgress: (answered, total) => `已回答 ${answered}/${total}`,notDelivered: '此问题未送达应用,无法在此回答。请按停止结束本轮,然后在聊天中回复。'},+ setupChoose: {+ kinds: {+ accent: '强调色',+ connectors: '应用',+ layout: '布局',+ plugins: '插件',+ theme: '外观'+ },+ loading: '正在加载选项…',+ unavailable: '此列表暂不可用,请直接在对话中回复。',+ findApp: '查找应用',+ customColor: '自定义颜色',+ plugin: '插件',+ intent: { now: '现在', later: '需要时', save: '仅记下' }+ },+ startChat: {+ starting: title => `正在启动“${title}”…`,+ startingUntitled: '正在启动对话…',+ untitled: '新对话',+ notStarted: '对话未能启动',+ inProfile: profile => `位于 ${profile}`,+ open: '打开',+ openFailed: '无法打开对话'+ },catalogInstall: {preparing: '正在准备安装…',install: '安装',@@ -5013,6 +5037,8 @@ export const zh = defineLocale({read_file: { done: '已读取文件', pending: '正在读取文件', pendingAction: '正在读取' },search_files: { done: '已搜索文件', pending: '正在搜索文件', pendingAction: '正在搜索' },session_search_recall: { done: '已搜索会话历史', pending: '正在搜索会话历史', pendingAction: '正在搜索' },+ setup_choose: { done: '已提出设置问题', pending: '正在提出设置问题', pendingAction: '正在提问' },+ start_chat: { done: '已启动对话', pending: '正在启动对话', pendingAction: '正在启动' },terminal: { done: '已运行命令', pending: '正在运行命令', pendingAction: '正在运行' },todo: { done: '已更新待办', pending: '正在更新待办', pendingAction: '正在更新' },vision_analyze: { done: '已分析图片', pending: '正在分析图片', pendingAction: '正在分析' },diff --git a/apps/desktop/src/lib/chat-messages/index.ts b/apps/desktop/src/lib/chat-messages/index.tsindex 981f0b91b70..9b4e71f7415 100644--- a/apps/desktop/src/lib/chat-messages/index.ts+++ b/apps/desktop/src/lib/chat-messages/index.ts@@ -23,6 +23,7 @@ export {spliceOlderPreservedRows} from './reconciliation'export {+ QUESTION_CARD_TOOLS,restorePendingBlockingToolCall,restorePendingClarifyToolCall,sealOpenToolParts,diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.tsindex 9a1e89357cd..c0f1f130189 100644--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts@@ -12,6 +12,10 @@ function toolId(payload: GatewayEventPayload | undefined): string {return payload?.tool_id || payload?.tool_call_id || payload?.id || ''}+export const QUESTION_CARD_TOOLS = new Set(['clarify', 'setup_choose'])++const REQUEST_BACKED_TOOLS = new Set([...QUESTION_CARD_TOOLS, 'setup_mcp'])+let liveToolCounter = 0function nextLiveToolId(name: string): string {@@ -213,7 +217,7 @@ function findToolPartIndex(part.completedAt === undefined) {// Interactive request IDs differ from provider call IDs and correlate by identifying arguments.- const requestBacked = name === 'clarify' || name === 'setup_mcp'+ const requestBacked = REQUEST_BACKED_TOOLS.has(name)if (!requestBacked &&@@ -526,8 +530,8 @@ export function settlePendingClarifyToolCall(keepMessageRunning: boolean,occurredAt = Date.now() / 1000): SettledClarifyProjection {- const clarifyPayload = { ...payload, name: 'clarify' }- const location = findPendingClarifyLocation(messages, clarifyPayload)+ const clarifyPayload = { name: 'clarify', ...payload }+ const location = findPendingClarifyLocation(messages, clarifyPayload, clarifyPayload.name)if (!location) {return { messages, streamId: null }@@ -563,7 +567,7 @@ export function stripPendingClarifyProjectionForCache(messages: ChatMessage[], rfor (const message of messages) {const hasOpenClarify = message.parts.some(- part => part.type === 'tool-call' && part.toolName === 'clarify' && part.result === undefined+ part => part.type === 'tool-call' && QUESTION_CARD_TOOLS.has(part.toolName) && part.result === undefined)if (!hasOpenClarify) {@@ -577,7 +581,7 @@ export function stripPendingClarifyProjectionForCache(messages: ChatMessage[], r!(requestId &&part.type === 'tool-call' &&- part.toolName === 'clarify' &&+ QUESTION_CARD_TOOLS.has(part.toolName) &&part.result === undefined &&part.toolCallId === requestId)@@ -612,7 +616,7 @@ export function restorePendingClarifyToolCall(payload: GatewayEventPayload,occurredAt = Date.now() / 1000): PendingClarifyProjection {- return restorePendingBlockingToolCall(messages, { ...payload, name: 'clarify' }, occurredAt)+ return restorePendingBlockingToolCall(messages, { name: 'clarify', ...payload }, occurredAt)}/** Restore a blocking tool row (clarify, connection card) from a resume snapshot: mark thediff --git a/apps/desktop/src/lib/keybinds/composer-focus-keys.ts b/apps/desktop/src/lib/keybinds/composer-focus-keys.tsindex 8c009991d8b..7e7e9406d52 100644--- a/apps/desktop/src/lib/keybinds/composer-focus-keys.ts+++ b/apps/desktop/src/lib/keybinds/composer-focus-keys.ts@@ -122,7 +122,8 @@ export function clarifyCardOwnsKey(event: KeyboardEvent): boolean {}// "Other" is the row past the last choice, hence the +1.- const rows = Number(card.getAttribute('data-clarify-choices')) + 1+ const rows =+ Number(card.getAttribute('data-clarify-choices')) + (card.getAttribute('data-clarify-other') === 'false' ? 0 : 1)if (!Number.isFinite(rows)) {return falsediff --git a/apps/desktop/src/lib/tool-render-class.ts b/apps/desktop/src/lib/tool-render-class.tsindex 895265a89ec..ae34c697971 100644--- a/apps/desktop/src/lib/tool-render-class.ts+++ b/apps/desktop/src/lib/tool-render-class.ts@@ -28,7 +28,15 @@ export function isFileEditTool(toolName: string): boolean {//// Everything else is ephemeral activity — reads, searches, commands — which is// what a run summarizes and what the live ticker cycles through.-const CARD_TOOL_NAMES = ['clarify', 'delegate_task', 'image_generate', 'manage_catalog', 'manage_connections'] as const+const CARD_TOOL_NAMES = [+ 'clarify',+ 'delegate_task',+ 'image_generate',+ 'manage_catalog',+ 'manage_connections',+ 'setup_choose',+ 'start_chat'+] as constexport type CardToolName = (typeof CARD_TOOL_NAMES)[number]diff --git a/apps/desktop/src/store/clarify.ts b/apps/desktop/src/store/clarify.tsindex baf8a4688f6..6cd4b9d1e4e 100644--- a/apps/desktop/src/store/clarify.ts+++ b/apps/desktop/src/store/clarify.ts@@ -1,3 +1,4 @@+import type { SetupChooseKind, SetupChooseOption } from '@hermes/shared'import { atom, computed } from 'nanostores'import { hasOpenServerRequest, respondToServerRequest } from './server-requests'@@ -10,6 +11,13 @@ export interface ClarifyQuestion {multiSelect: boolean}+export interface SetupChooseSpec {+ kind: SetupChooseKind+ options: SetupChooseOption[] | null+ multiSelect: boolean+ intent: boolean+}+export interface ClarifyRequest {requestId: string/** Local receipt time (Unix seconds), used to reject stale resume cleanup. */@@ -18,6 +26,7 @@ export interface ClarifyRequest {questions: ClarifyQuestion[]/** Answers already locked server-side (reconnect replay): qid → answer, null = skipped. */lockedAnswers?: Record<string, null | string>+ setup?: SetupChooseSpec}/**@@ -101,6 +110,37 @@ export function normalizeQuestions(questions: unknown): ClarifyQuestion[] {return normalized}+export const SETUP_CHOOSE_QID = 'setup_choose'++const SETUP_CHOOSE_KINDS = new Set<unknown>(['accent', 'connectors', 'layout', 'plugins', 'question', 'theme'])++export function normalizeSetupChoose(+ params: Record<string, unknown>+): Pick<ClarifyRequest, 'questions' | 'setup'> | null {+ const question = typeof params.question === 'string' ? params.question.trim() : ''++ if (!question || !SETUP_CHOOSE_KINDS.has(params.kind)) {+ return null+ }++ const options =+ Array.isArray(params.options) && params.options.length > 0 ? (params.options as SetupChooseOption[]) : null++ const multiSelect = params.multi_select === true++ return {+ questions: [+ {+ choices: options ? options.map(option => option.label) : null,+ multiSelect: multiSelect && options !== null,+ qid: SETUP_CHOOSE_QID,+ question+ }+ ],+ setup: { intent: params.intent === true, kind: params.kind as SetupChooseKind, multiSelect, options }+ }+}+// Pending clarify requests keyed by the runtime session id that raised them.// Storing per-session (instead of one shared slot) lets a *background* session// park its clarify request while the user is looking at a different chat, thendiff --git a/apps/desktop/src/store/onboarding-plugins.ts b/apps/desktop/src/store/onboarding-plugins.tsindex a46edc8d92d..307b2a9341e 100644--- a/apps/desktop/src/store/onboarding-plugins.ts+++ b/apps/desktop/src/store/onboarding-plugins.ts@@ -41,7 +41,7 @@ export function prefetchOnboardingPlugins(storedId: string): void {})}-export function useOnboardingPlugins(storedId: null | string): OnboardingPlugin[] {+export function useOnboardingPluginList(storedId: null | string): null | OnboardingPlugin[] {const query = useQuery({enabled: Boolean(storedId),queryFn: () => readOnboardingPlugins(storedId!),@@ -49,5 +49,9 @@ export function useOnboardingPlugins(storedId: null | string): OnboardingPlugin[staleTime: Infinity})- return query.data ?? []+ return query.data ?? null+}++export function useOnboardingPlugins(storedId: null | string): OnboardingPlugin[] {+ return useOnboardingPluginList(storedId) ?? []}diff --git a/apps/desktop/src/store/start-chat.ts b/apps/desktop/src/store/start-chat.tsnew file mode 100644index 00000000000..5a6c8f9018e--- /dev/null+++ b/apps/desktop/src/store/start-chat.ts@@ -0,0 +1,34 @@+import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'++export type StartChatOutcome =+ | { profile: string; sessionId: string; status: 'started'; title: null | string }+ | { reason: string; status: 'rejected' }++export function readStartChatResult(result: unknown): null | StartChatOutcome {+ const row = parseMaybeObject(result)++ if (row.status === 'started' && typeof row.session_id === 'string' && row.session_id) {+ return {+ profile: typeof row.profile === 'string' ? row.profile : '',+ sessionId: row.session_id,+ status: 'started',+ title: typeof row.title === 'string' && row.title.trim() ? row.title.trim() : null+ }+ }++ if (row.status === 'rejected') {+ return { reason: typeof row.reason === 'string' ? row.reason : '', status: 'rejected' }+ }++ return null+}++const liveStarts = new Set<string>()++export function markLiveStartChat(toolCallId: string): void {+ liveStarts.add(toolCallId)+}++export function takeLiveStartChat(toolCallId: string): boolean {+ return liveStarts.delete(toolCallId)+}diff --git a/locales/_keys.desktop.json b/locales/_keys.desktop.jsonindex 0d92186e54b..074e1731f10 100644--- a/locales/_keys.desktop.json+++ b/locales/_keys.desktop.json@@ -156,6 +156,26 @@"assistant.mcpSetup.reloadFailed","assistant.mcpSetup.sendFailed","assistant.mcpSetup.toolCount",+ "assistant.setupChoose.customColor",+ "assistant.setupChoose.findApp",+ "assistant.setupChoose.intent.later",+ "assistant.setupChoose.intent.now",+ "assistant.setupChoose.intent.save",+ "assistant.setupChoose.kinds.accent",+ "assistant.setupChoose.kinds.connectors",+ "assistant.setupChoose.kinds.layout",+ "assistant.setupChoose.kinds.plugins",+ "assistant.setupChoose.kinds.theme",+ "assistant.setupChoose.loading",+ "assistant.setupChoose.plugin",+ "assistant.setupChoose.unavailable",+ "assistant.startChat.inProfile",+ "assistant.startChat.notStarted",+ "assistant.startChat.open",+ "assistant.startChat.openFailed",+ "assistant.startChat.starting",+ "assistant.startChat.startingUntitled",+ "assistant.startChat.untitled","assistant.thread.attachingFile","assistant.thread.branchNewChat","assistant.thread.copy",@@ -409,6 +429,12 @@"assistant.tool.titles.session_search_recall.done","assistant.tool.titles.session_search_recall.pending","assistant.tool.titles.session_search_recall.pendingAction",+ "assistant.tool.titles.setup_choose.done",+ "assistant.tool.titles.setup_choose.pending",+ "assistant.tool.titles.setup_choose.pendingAction",+ "assistant.tool.titles.start_chat.done",+ "assistant.tool.titles.start_chat.pending",+ "assistant.tool.titles.start_chat.pendingAction","assistant.tool.titles.terminal.done","assistant.tool.titles.terminal.pending","assistant.tool.titles.terminal.pendingAction",@@ -2411,6 +2437,9 @@"rightSidebar.terminalCloseOthers","rightSidebar.terminalHide","rightSidebar.terminalNew",+ "rightSidebar.terminalOpenInteractive",+ "rightSidebar.terminalReadOnly",+ "rightSidebar.terminalReadOnlyHelp","rightSidebar.terminalsAria","rightSidebar.treeErrorBody","rightSidebar.treeErrorTitle",diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 6e5919af015..1f63de2c762 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2093,7 +2093,7 @@ def _tool_progress_enabled(sid: str) -> bool:# set (test_gateway_lifecycle_set_covers_desktop_card_tools pins the direction that matters)._TOOL_LIFECYCLE_UI_TOOLS = frozenset({"clarify", "manage_connections", "setup_mcp",- "image_generate", "manage_catalog", "delegate_task", "setup_choose",+ "image_generate", "manage_catalog", "delegate_task", "setup_choose", "start_chat",# File edits are the turn's deliverable — the diff card the user reviews."edit_file", "patch", "write_file",})diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 52b52e7b042..67286d2a9a4 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -194,7 +194,7 @@ Enabled by the desktop setup profile's own config (`platform_toolsets.cli`). Onl| Tool | Description | Requires environment ||------|-------------|----------------------|-| `setup_choose` | Only through the `setup` toolset, desktop sessions only; never deferred unless a `tools.tool_search.defer` list names it. Shows one card in the setup chat: `kind` is `question`, `accent`, `theme`, `layout`, `connectors` or `plugins`, and `question` is the card's heading. `options` (up to 12 `{id, label, detail?}` rows, unique ids) replaces the app's own list; omitted, the pickers show the app's list and kind `question` asks for free text. A `question` card with options still takes a typed answer. `multi_select` lets the user pick several rows. `intent` (connectors and plugins only) adds a now / later / save choice per row. The result has `outcome` (`submitted`, `cancelled` or `no_answer` with a `notice`), `picked` (an option id or typed text, or a list of ids with `multi_select`) and, with `intent`, a map of picked id to `now`, `later` or `save`. It stores nothing. Anywhere else the call returns an error. | — |+| `setup_choose` | Only through the `setup` toolset, desktop sessions only; never deferred unless a `tools.tool_search.defer` list names it. Shows one card in the setup chat: `kind` is `question`, `accent`, `theme`, `layout`, `connectors` or `plugins`, and `question` is the card's heading. `options` (up to 12 `{id, label, detail?}` rows, unique ids) replaces the app's own list; omitted, the pickers show the app's list and kind `question` asks for free text. A `question` card with options still takes a typed answer. `multi_select` lets the user pick several rows. `intent` (connectors and plugins only) adds a now / later / save choice per row. An accent, theme or layout pick applies in the app as soon as the user picks it. The result has `outcome` (`submitted`, `cancelled` or `no_answer` with a `notice`), `picked` (an option id or typed text, or a list of ids with `multi_select`) and, with `intent`, a map of picked id to `now`, `later` or `save`. It stores nothing. Anywhere else the call returns an error. | — |## `start_chat` toolset@@ -202,7 +202,7 @@ Enabled only when a profile's own config names it (`platform_toolsets.cli`). Onl| Tool | Description | Requires environment ||------|-------------|----------------------|-| `start_chat` | Opens a new chat in the desktop app and sends `message` as its first user message; the calling chat stays where it is. The new chat starts with no history. `profile` must name an existing profile (it is never created); omitted, the chat runs in the caller's own profile. The new chat takes its settings from its own profile, never from the caller's. `title` (at most 40 characters) names the chat in the sidebar; omitted, the chat titles itself. Every call opens another chat: nothing de-duplicates a repeated call. The result is `started` with the new chat's `session_id` and `profile`, or `rejected` with a `reason` (unknown profile, empty message, title too long, not called from a desktop chat). | — |+| `start_chat` | Opens a new chat in the desktop app and sends `message` as its first user message. The calling chat shows a card with the new chat's title, its profile and an Open button; the app moves the user into the new chat only when they are watching the calling chat, otherwise the chat appears in the sidebar. The new chat starts with no history. `profile` must name an existing profile (it is never created); omitted, the chat runs in the caller's own profile. The new chat takes its settings from its own profile, never from the caller's. `title` (at most 40 characters) names the chat in the sidebar; omitted, the chat titles itself. Every call opens another chat: nothing de-duplicates a repeated call. The result is `started` with the new chat's `session_id` and `profile`, or `rejected` with a `reason` (unknown profile, empty message, title too long, not called from a desktop chat). | — |## `session_search` toolset