The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): delete the setup_choose and start_chat cards
alt-glitch9846c2399ceb
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.tsindex 16a8d9fba33..8291ddc5201 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@@ -313,8 +313,6 @@ export function useComposerSubmit({if (routable && hasConnectionRequest(sessionId)) {void skipConnectionRequest(sessionId)}-- return false}const submitDraft = () => {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 e437909ab0d..2ebc11c9794 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@@ -18,7 +18,7 @@ import { restorePendingClarifyToolCall } from '@/lib/chat-messages'import type { PreviewActAction } from '@/lib/preview-act/act-in-page'import type { TourAction, TourStep } from '@/lib/tour'import { type AppearanceValues, applyAppearance, THEME_MODES } from '@/store/appearance-apply'-import { type ClarifyRequest, normalizeQuestions, normalizeSetupChoose, setClarifyRequest } from '@/store/clarify'+import { type ClarifyRequest, normalizeQuestions, setClarifyRequest } from '@/store/clarify'import type { ScopedServerRequest } from '@/store/gateway'import { dispatchNativeNotification } from '@/store/native-notifications'import type { PreviewOwner } from '@/store/preview-ownership'@@ -370,19 +370,6 @@ const clarify: Handler = ctx => {})}-const setupChoose: Handler = ctx => {- const { deps, request, sessionId } = ctx- const setup = normalizeSetupChoose(request.params)-- if (!setup || (sessionId && deps.sessionInterrupted(sessionId))) {- request.respond({})-- return- }-- parkClarify(ctx, { ...setup, receivedAt: Date.now() / 1000, requestId: request.id, sessionId: sessionId || null })-}-const approval: Handler = ctx => {const { request, sessionId } = ctxconst p = request.params@@ -746,7 +733,6 @@ export const SERVER_REQUEST_HANDLERS: Record<string, Handler> = {'preview.act': previewAct,'preview.read': previewRead,secret,- setup_choose: setupChoose,sudo,'terminal.read': terminalRead,'theme.apply': themeApply,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 e3ee6ae85a1..81a696d292b 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,12 +1,10 @@import { isPreviewableTarget, toolPreviewOutcome } from '@/components/assistant-ui/tool/fallback-model'-import { finishGuidedOnboarding } from '@/components/onboarding-chat/intro'-import { type GatewayEventPayload, toolCallOwnerMessageId } from '@/lib/chat-messages'+import { toolCallOwnerMessageId } from '@/lib/chat-messages'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 { isStartChatCallerWatched, markLiveStartChat, readStartChatResult } from '@/store/start-chat'import { isTerminalSubagentCompletion, pruneDelegateFallbackSubagents, upsertSubagent } from '@/store/subagents'import { reportMcpToolResult } from '@/store/suggestion-providers/repair'import { invalidateSkillSuggestionIndex } from '@/store/suggestion-providers/skill'@@ -40,23 +38,6 @@ function recordToolPreview(ctx: GatewayEventContext, sessionId: string, cwd: str}}-function reportStartChatHandoff(payload: GatewayEventPayload | undefined, sessionId: string): void {- const outcome = readStartChatResult(payload?.result)-- if (payload?.name !== 'start_chat' || outcome?.status !== 'started') {- return- }-- const callerId = storedSessionIdForRuntimeId(sessionId) ?? sessionId-- if (isStartChatCallerWatched(callerId)) {- markLiveStartChat(callerId, 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, outcome.sessionId)-}-/** tool.generating / tool.start / tool.complete / subagent.*. */export function handleToolEvent(ctx: GatewayEventContext): boolean {const { deps, event, payload, sessionId, isActiveEvent, occurredAt } = ctx@@ -124,10 +105,6 @@ export function handleToolEvent(ctx: GatewayEventContext): boolean {recordToolPreview(ctx, sessionId, state?.cwd ?? '', pendingProduction)}- if (!event.replayed) {- reportStartChatHandoff(payload, sessionId)- }-if (isActiveEvent) {setPetActivity({ toolRunning: false })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 120d399b721..feac3b91428 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@@ -53,19 +53,6 @@ export function restorePendingClarifyFromSnapshot(}export function pendingClarifyToolPayload(request: ClarifyRequest): GatewayEventPayload {- if (request.setup) {- return {- args: {- 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/components/assistant-ui/clarify/index.tsx b/apps/desktop/src/components/assistant-ui/clarify/index.tsxindex b49c2e575be..dd12005f82a 100644--- a/apps/desktop/src/components/assistant-ui/clarify/index.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify/index.tsx@@ -6,22 +6,19 @@ import { useMemo, useState } from 'react'import { useSessionView } from '@/app/chat/session-view'import { ToolFallback } from '@/components/assistant-ui/tool/fallback'-import { $settledClarifyResults, normalizeSetupChoose, sessionClarifyRequest } from '@/store/clarify'+import { $settledClarifyResults, 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 props.toolName === 'setup_choose' ? <SetupChooseSettled {...props} /> : <ClarifyToolSettled {...props} />+ return <ClarifyToolSettled {...props} />}return <ClarifyToolLive {...props} />@@ -39,11 +36,8 @@ 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 setupCard = props.toolName === 'setup_choose'- const sessionRequest = useStore($request)- const request = sessionRequest && Boolean(sessionRequest.setup) === setupCard ? sessionRequest : null+ const request = useStore($request)const fromArgs = useMemo(() => readClarifyArgs(props.args), [props.args])- const setupArgs = useMemo(() => normalizeSetupChoose(parseMaybeObject(props.args)), [props.args])const messageRunning = useAuiState(selectMessageRunning)const messageId = useAuiState(s => s.message.id)const rowKey = `${sessionId ?? ''}:${messageId}:${props.toolCallId}`@@ -62,11 +56,7 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {const undelivered = useUndeliveredClarify(sessionId, messageRunning && !request && !answered && !settledResult)if (settledResult) {- return setupCard ? (- <SetupChooseSettled {...props} result={settledResult} />- ) : (- <ClarifyToolSettled {...props} result={settledResult} />- )+ return <ClarifyToolSettled {...props} result={settledResult} />}// Stopped mid-prompt with no result — don't leave a dead interactive panel.@@ -77,14 +67,7 @@ function ClarifyToolLive(props: ToolCallMessagePartProps) {return <ToolFallback {...props} />}- return setupCard ? (- <SetupChoosePending- fromArgs={setupArgs}- onAnswered={() => setAnswered(true)}- request={request}- undelivered={undelivered}- />- ) : (+ return (<ClarifyToolPendingfromArgs={fromArgs}onAnswered={() => setAnswered(true)}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.tsxdeleted file mode 100644index 64a11ddfa09..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pending-parts.tsx+++ /dev/null@@ -1,124 +0,0 @@-'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.test.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.test.tsxdeleted file mode 100644index 6dfac90674a..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.test.tsx+++ /dev/null@@ -1,199 +0,0 @@-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'-import { atom } from 'nanostores'-import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest'--import { PRIMARY_SESSION_VIEW, type SessionView, SessionViewProvider } from '@/app/chat/session-view'-import type { HermesConnection } from '@/global'-import { I18nProvider } from '@/i18n'-import {- answerSetupCard,- type ClarifyRequest,- clearClarifyRequest,- setClarifyRequest,- type SetupChooseSpec-} from '@/store/clarify'-import { $activeGatewayProfile } from '@/store/profile'-import { rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'-import { $connection } from '@/store/session'-import { $accentOverride } from '@/themes/accent-override'-import { accentsFor, NOUS_ACCENT } from '@/themes/accents'-import { modePref, skinPref, ThemeProvider, useTheme } from '@/themes/context'-import { DEFAULT_SKIN_NAME } from '@/themes/presets'-import { $userThemes } from '@/themes/user-themes'--import { SetupChoosePending } from './setup-pending'--const SESSION = 'setup-session'--const CONNECTION: HermesConnection = {- baseUrl: 'http://localhost:1',- isFullscreen: false,- nativeOverlayWidth: 0,- windowButtonPosition: null,- token: '',- wsUrl: 'ws://localhost:1',- logs: []-}--const view: SessionView = { ...PRIMARY_SESSION_VIEW, $runtimeId: atom(SESSION), $storedId: atom('stored-setup') }--let theme: ReturnType<typeof useTheme>--function ThemeProbe() {- theme = useTheme()-- return null-}--const primary = () => window.document.documentElement.style.getPropertyValue('--theme-primary')--function renderCard(requestId: string, question: string, kind: SetupChooseSpec['kind'], preselected: string[] = []) {- const request: ClarifyRequest = {- questions: [{ choices: null, multiSelect: false, qid: 'q0', question }],- requestId,- sessionId: SESSION,- setup: { kind, multiSelect: false, options: null, preselected }- }-- rememberServerRequest({ fail: vi.fn(), id: requestId, method: 'setup_choose', params: {}, respond: vi.fn() })- setClarifyRequest(request)-- return render(- <QueryClientProvider client={new QueryClient()}>- <I18nProvider configClient={null} initialLocale="en">- <ThemeProvider>- <ThemeProbe />- <SessionViewProvider value={view}>- <SetupChoosePending fromArgs={null} onAnswered={vi.fn()} request={request} undelivered={false} />- </SessionViewProvider>- </ThemeProvider>- </I18nProvider>- </QueryClientProvider>- )-}--let consoleError: MockInstance<typeof console.error>--beforeEach(() => {- window.localStorage.clear()- $userThemes.set({})- $activeGatewayProfile.set('default')- $connection.set(CONNECTION)- resetServerRequestsForTests()- consoleError = vi.spyOn(console, 'error')-})--afterEach(() => {- cleanup()- clearClarifyRequest()- resetServerRequestsForTests()- $accentOverride.set(null)- consoleError.mockRestore()-})--const loopErrors = () => consoleError.mock.calls.filter(([first]) => /Maximum update depth/.test(String(first)))--describe('setup cards render without redrawing themselves', () => {- it('shows the name card and waits for an answer', async () => {- renderCard('name-1', 'What should I call you?', 'question')-- expect(await screen.findByText('What should I call you?')).toBeTruthy()- expect(loopErrors()).toEqual([])- })-- it('keeps a confirmed accent through cold startup, profile switches, and later theme changes', async () => {- skinPref.assign('other', 'ember')- skinPref.assign('default', DEFAULT_SKIN_NAME)- $activeGatewayProfile.set('setup')- modePref.assign('setup', 'light')- renderCard('accent-1', 'Pick an accent', 'accent')- await screen.findByText('Pick an accent')-- const swatch = accentsFor(false).find(({ name }) => name === 'GitHub green')-- expect(swatch).toBeTruthy()- act(() => expect(answerSetupCard(SESSION, swatch!.name)).toBe(true))- const selected = theme.themeName- const light = primary()-- expect(selected).not.toBe(DEFAULT_SKIN_NAME)- expect(skinPref.resolve('setup')).toBe(selected)- expect($accentOverride.get()).toBeNull()- act(() => theme.setMode('dark'))- const dark = primary()-- // Drop every module-level atom, preserving only localStorage as a new renderer does.- cleanup()- vi.resetModules()- const fresh = await import('@/themes/context')- expect(primary()).toBe(dark)- const { $activeGatewayProfile: profile } = await import('@/store/profile')- const { $connection: connection } = await import('@/store/session')- let restored: ReturnType<typeof useTheme>-- function RestoredProbe() {- restored = fresh.useTheme()-- return null- }-- profile.set('setup')- connection.set(CONNECTION)- render(- <fresh.ThemeProvider>- <RestoredProbe />- </fresh.ThemeProvider>- )- expect(restored!.themeName).toBe(selected)- expect(primary()).toBe(dark)- act(() => restored!.setMode('light'))- expect(primary()).toBe(light)- act(() => profile.set('other'))- expect(restored!.themeName).toBe('ember')- act(() => profile.set('setup'))- expect(restored!.themeName).toBe(selected)- expect(primary()).toBe(light)- act(() => restored!.setTheme('midnight'))- const replacement = primary()- cleanup()- render(- <fresh.ThemeProvider>- <RestoredProbe />- </fresh.ThemeProvider>- )- expect(restored!.themeName).toBe('midnight')- expect(primary()).toBe(replacement)- expect(loopErrors()).toEqual([])- })-- it('only saves the clicked accent when confirmed and restores skipped previews', async () => {- modePref.assign('default', 'light')- renderCard('accent-click', 'Pick an accent', 'accent')- const original = primary()- const swatch = accentsFor(false).find(({ hex }) => hex !== NOUS_ACCENT)!-- fireEvent.click(await screen.findByRole('button', { name: swatch.name }))- expect(primary()).not.toBe(original)- expect(skinPref.resolve('default')).toBe(DEFAULT_SKIN_NAME)- expect(Object.keys($userThemes.get())).toHaveLength(0)- act(() => clearClarifyRequest())- expect(primary()).toBe(original)- cleanup()-- renderCard('accent-confirm', 'Pick an accent', 'accent')- fireEvent.click(await screen.findByRole('button', { name: swatch.name }))- fireEvent.click(screen.getByRole('button', { name: /confirm/i }))- expect(skinPref.resolve('default')).toBe(theme.themeName)- expect(theme.themeName).not.toBe(DEFAULT_SKIN_NAME)- expect(Object.keys($userThemes.get())).toHaveLength(1)- expect($accentOverride.get()).toBeNull()- cleanup()-- renderCard('accent-blue', 'Pick an accent', 'accent', [NOUS_ACCENT])- fireEvent.click(await screen.findByRole('button', { name: /confirm/i }))- expect(theme.themeName).toBe(DEFAULT_SKIN_NAME)- expect(primary()).toBe(original)- expect(Object.keys($userThemes.get())).toHaveLength(1)- })-})diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsxdeleted file mode 100644index e5ba732889d..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx+++ /dev/null@@ -1,293 +0,0 @@-'use client'--import type { SetupChooseKind } from '@hermes/shared'-import { useStore } from '@nanostores/react'-import { Puzzle } from 'lucide-react'-import { type ComponentType, type FormEvent, useCallback, useEffect, useMemo, useRef } 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 {- $setupChooseStages,- type ClarifyQuestion,- type ClarifyRequest,- clearClarifyRequest,- commitSetupChoose,- EMPTY_SETUP_STAGE,- SETUP_CHOOSE_QID,- setupChooseAnswer,- setupChooseStage,- skipClarify,- stageSetupChoose-} 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 { CLARIFY_ICON_CLASS, ClarifyShell } from './core/shell'-import { useClarifyKeys } from './core/use-clarify-keys'-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'--type SetupSource = Pick<ClarifyRequest, 'questions' | 'setup'>--function sameLabels(a: Record<string, string>, b: Record<string, string>): boolean {- const ids = Object.keys(a)-- return ids.length === Object.keys(b).length && ids.every(id => a[id] === b[id])-}--const KIND_ICONS: Record<SetupChooseKind, ComponentType<{ className?: string }>> = {- accent: Palette,- connectors: Plug,- fork: MessageQuestion,- layout: LayoutDashboard,- machine_use: MessageQuestion,- plugins: Puzzle,- question: MessageQuestion,- theme: Moon,- tour: MessageQuestion-}--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 { mode, setMode } = useTheme()-- const { kind, pickerKind, ready, requestId, setup, source } = setupChooseSource(request, fromArgs)- const freeText = pickerKind === null- const rows = useSetupRows(setup, storedId)-- const stages = useStore($setupChooseStages)- const { draft, picked } = (requestId && stages[requestId]) || EMPTY_SETUP_STAGE- const preselected = setup?.preselected- const rowLabels = useMemo(() => Object.fromEntries((rows ?? []).map(row => [row.id, row.label])), [rows])-- // Once the list is known, record its names (composer text is matched against them) and start the card with- // the rows the scan saw in use; the card may not list them all.- useEffect(() => {- if (!requestId || !rows) {- return- }-- const current = $setupChooseStages.get()[requestId]-- if (current && sameLabels(current.labels, rowLabels)) {- return- }-- const ids = new Set(rows.map(row => row.id))- const scanned = !current && preselected?.length ? { picked: preselected.filter(id => ids.has(id)) } : {}-- stageSetupChoose(requestId, { labels: rowLabels, ...scanned })- }, [preselected, requestId, rowLabels, rows])-- 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) => {- if (!requestId) {- return- }-- const current = setupChooseStage(requestId)- const removing = question.multiSelect && current.picked.includes(id)- const live = removing ? undefined : LIVE_LOOK[kind]-- stageSetupChoose(requestId, {- picked: question.multiSelect- ? removing- ? current.picked.filter(value => value !== id)- : [...current.picked, id]- : [id],- revert: current.revert ?? live?.snapshot(mode, setMode) ?? null,- ...(question.multiSelect ? {} : { draft: '' })- })- live?.apply(id, setMode)- },- // Value-stable deps only: the effect below writes this into the store the card reads, so a dep that- // changes identity every render redraws the card forever (React #185). The labels effect stages the row names.- [kind, mode, question.multiSelect, requestId, setMode]- )-- const commitLook = useCallback(- (ids: string[]) => {- if (ids[0]) {- LIVE_LOOK[kind]?.commit?.(ids[0])- }- },- [kind]- )-- // Composer text that names a row picks it through this card, so the typed pick applies its look too.- const liveRequestId = request?.requestId-- useEffect(() => {- if (liveRequestId) {- stageSetupChoose(liveRequestId, { commit: commitLook, preview: stage })- }- }, [commitLook, liveRequestId, stage])-- 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) => {- if (requestId) {- stageSetupChoose(requestId, { draft: value, ...(question.multiSelect ? {} : { picked: [] }) })- }- },- [question.multiSelect, requestId]- )-- const confirm = useCallback(() => {- if (!request || answer === null) {- return- }-- if (!respondToServerRequest(request.requestId, setupChooseAnswer(answer, rowLabels))) {- notifyError(new Error(copy.notReady), copy.sendFailed)-- return- }-- triggerHaptic('submit')- onAnswered()- commitSetupChoose(request.requestId)- clearClarifyRequest(request.requestId, request.sessionId)- }, [answer, copy, onAnswered, request, rowLabels])-- const skip = useCallback(() => {- if (!request) {- return- }-- onAnswered()- skipClarify(request)- }, [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({- columns: pickerKind === null ? undefined : PICKER_COLUMNS[pickerKind](rows ?? []),- enabled: ready,- formRef,- initialRow: Math.max(0, rows?.findIndex(row => row.id === picked[0]) ?? 0),- isStaged: (_question, row) =>- answer !== null &&- (pickerKind === null || question.multiSelect || row === undefined || picked.includes(rows?.[row]?.id ?? '')),- onClear: pickerKind === null && requestId ? () => stageSetupChoose(requestId, { picked: [] }) : undefined,- onConfirm: confirm,- onToggle: toggle,- other: freeText,- questions,- shortcuts: false- })-- const cursor = ready ? keys.cursorRow : null- const Icon = KIND_ICONS[kind]-- 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 ? 0 : undefined}- data-clarify-other="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.oneQuestion : setupCopy.kinds[pickerKind]}- </span>- <Icon aria-hidden className={CLARIFY_ICON_CLASS} />- </div>- {undelivered ? <UndeliveredNotice /> : null}- <SetupChooseBody- cursor={cursor}- draft={draft}- keys={keys}- onDraft={onDraft}- onStage={stage}- picked={picked}- pickerKind={pickerKind}- question={question}- ready={ready}- rows={rows}- />- </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.tsxdeleted file mode 100644index 3ba2c92fba1..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx+++ /dev/null@@ -1,332 +0,0 @@-'use client'--import type { SetupChooseKind } from '@hermes/shared'-import { useStore } from '@nanostores/react'-import { Puzzle } from 'lucide-react'-import { type CSSProperties, type FC, type ReactNode, useId, useState } from 'react'--import { useSessionView } from '@/app/chat/session-view'-import { Chip } from '@/components/onboarding-chat/chip'-import { LayoutPreviewCard, LAYOUTS } from '@/components/onboarding-chat/options'-import { AccentSwatch } from '@/components/ui/accent-swatch'-import { ConnectorLogo } from '@/components/ui/connector-logo'-import { FadeScroll } from '@/components/ui/fade-scroll'-import { SearchField } from '@/components/ui/search-field'-import { useI18n } from '@/i18n'-import { connectorIconUrl } from '@/lib/connector-tools'-import { cn } from '@/lib/utils'-import type { ClarifyQuestion } from '@/store/clarify'-import { pluginNeedsApp, useOnboardingPluginList } from '@/store/onboarding-plugins'-import { useTheme } from '@/themes'-import { NOUS_ACCENT } from '@/themes/accents'-import { getBaseColors } from '@/themes/context'--import { ChoiceLabel } from './core/choice-row'-import type { SetupRow } from './setup-rows'--interface SetupPickerProps {- cursor: null | number- onPick: (index: number) => void- onStage: (id: string) => void- picked: string[]- rows: SetupRow[]-}--/** Kinds drawn as a picker; question, tour, fork and machine_use are drawn as question pills. */-export type SetupPickerKind = Exclude<SetupChooseKind, 'fork' | 'machine_use' | 'question' | 'tour'>--export const isSetupPickerKind = (kind: SetupChooseKind): kind is SetupPickerKind =>- kind !== 'question' && kind !== 'tour' && kind !== 'fork' && kind !== 'machine_use'--const SEARCH_THRESHOLD = 12--export const PICKER_COLUMNS: Record<SetupPickerKind, (rows: SetupRow[]) => number> = {- accent: rows => rows.length,- connectors: () => 3,- layout: () => 2,- plugins: () => 3,- theme: rows => rows.length-}--function PickerItem({ active, children, className }: { active: boolean; children: ReactNode; className?: string }) {- return (- <div- className={cn('grid 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) {- const { themeName } = useTheme()- const light = getBaseColors(themeName, 'light')- const dark = getBaseColors(themeName, 'dark')-- const palettes: Record<string, CSSProperties> = {- dark: {- background: dark.background,- borderColor: dark.border,- '--color-foreground': dark.foreground- } as CSSProperties,- light: {- background: light.background,- borderColor: light.border,- '--color-foreground': light.foreground- } as CSSProperties- }-- return (- <div className="grid grid-cols-2 gap-3 p-1" role="group">- {rows.map((row, index) => {- const active = picked.includes(row.id)- const palette = palettes[row.id]-- return (- <PickerItem active={cursor === index} className="rounded-[8px]" key={row.id}>- <LayoutPreviewCard- active={active}- name={row.label}- onSelect={() => onPick(index)}- previewStyle={active && palette ? { ...palette, borderColor: undefined } : palette}- tree={LAYOUTS[0].tree}- />- </PickerItem>- )- })}- </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" 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]" 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,- dim,- icon,- onPick,- picked,- rows,- sub-}: SetupPickerProps & {- dim?: (row: SetupRow) => boolean- 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 role="group">- <FadeScroll className="grid grid-cols-3 gap-2 p-1" fade="1.5rem" maxHeight="18rem" pad="1.5rem">- {rows.map((row, index) =>- search && !row.label.toLowerCase().includes(search) ? null : (- <PickerItem active={cursor === index} className="rounded-[6px]" key={row.id}>- <Chip- className={cn('w-full', dim?.(row) && 'opacity-60')}- icon={icon(row)}- label={row.label}- on={picked.includes(row.id)}- onToggle={() => onPick(index)}- sub={row.detail ?? sub}- />- </PickerItem>- )- )}- </FadeScroll>- </div>- <p className="text-xs text-muted-foreground">{t.assistant.setupChoose.startsLater}</p>- </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()- const plugins = useOnboardingPluginList(useStore(useSessionView().$storedId))-- const needsApp = (row: SetupRow) => Boolean(plugins?.some(plugin => plugin.name === row.id && pluginNeedsApp(plugin)))-- return <ChipPicker {...props} dim={needsApp} icon={pluginIcon} sub={t.assistant.setupChoose.plugin} />-}--export const SETUP_PICKERS: Record<SetupPickerKind, FC<SetupPickerProps>> = {- accent: AccentPicker,- connectors: ConnectorPicker,- layout: LayoutPicker,- plugins: PluginPicker,- theme: ThemePicker-}--const PILL_CLASS =- 'flex max-w-full shrink-0 items-center gap-1.5 rounded-full border px-3 py-1 text-left text-[12px] whitespace-normal wrap-anywhere transition-colors disabled:cursor-not-allowed disabled:opacity-50'--const PILL_CURSOR_CLASS = 'ring-2 ring-ring/60 ring-offset-2 ring-offset-(--dt-background)'--export function QuestionPills({- cursor,- details,- disabled,- onActivate,- onDraft,- onOtherFocus,- onPick,- onRowFocus,- question,- staged-}: {- cursor: null | number- details: (null | string | undefined)[]- disabled: boolean- onActivate: () => void- onDraft: (value: string) => void- onOtherFocus: () => void- onPick: (index: number) => void- onRowFocus: (index: number) => void- question: ClarifyQuestion- staged: { choices: string[]; draft: string }-}) {- const { t } = useI18n()- const detailId = useId()- const choices = question.choices ?? []- const otherActive = cursor === choices.length- const drafted = Boolean(staged.draft.trim())- const detail = cursor === null ? undefined : details[cursor]-- return (- <div- className="grid gap-2"- data-clarify-batch-question={question.qid}- onFocus={onActivate}- onPointerDown={onActivate}- >- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question.question}</span>- <div className="flex min-w-0 flex-wrap gap-2 p-1" role="group">- {choices.map((choice, index) => {- const selected = staged.choices.includes(choice)-- return (- <button- aria-current={cursor === index || undefined}- aria-describedby={cursor === index && detail ? detailId : undefined}- aria-pressed={selected}- className={cn(- PILL_CLASS,- selected- ? 'border-primary bg-primary text-primary-foreground'- : 'border-border bg-card hover:border-primary/50 hover:bg-primary/10',- cursor === index && PILL_CURSOR_CLASS- )}- data-choice- data-highlighted={cursor === index || undefined}- disabled={disabled}- key={`${index}-${choice}`}- onClick={() => onPick(index)}- onFocus={() => onRowFocus(index)}- onPointerEnter={() => onRowFocus(index)}- type="button"- >- <span>- <ChoiceLabel choice={choice} />- </span>- {details[index] ? (- <span aria-hidden className="size-1 shrink-0 rounded-full bg-current opacity-60" />- ) : null}- </button>- )- })}- <label- className={cn(- PILL_CLASS,- 'cursor-text',- drafted ? 'border-primary bg-primary/10' : 'border-border bg-card',- otherActive && PILL_CURSOR_CLASS,- disabled && 'cursor-not-allowed opacity-50'- )}- data-highlighted={otherActive || undefined}- >- <textarea- aria-current={otherActive || undefined}- className="field-sizing-content max-h-40 min-w-8 resize-none bg-transparent leading-5 outline-none placeholder:text-muted-foreground focus:min-w-48"- disabled={disabled}- onChange={event => onDraft(event.target.value)}- onFocus={onOtherFocus}- placeholder={choices.length > 0 ? t.assistant.clarify.other : t.assistant.clarify.placeholder}- rows={1}- value={staged.draft}- />- </label>- </div>- {details.some(Boolean) ? (- <p- className="h-4 truncate px-1 text-xs leading-4 text-(--ui-text-tertiary)"- id={detailId}- title={detail ?? undefined}- >- {detail}- </p>- ) : null}- </div>- )-}diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts b/apps/desktop/src/components/assistant-ui/clarify/setup-rows.tsdeleted file mode 100644index 76a390bf9c0..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts+++ /dev/null@@ -1,170 +0,0 @@-import type { ConnectorRow, SetupChooseKind, SetupChooseOption } from '@hermes/shared'-import { useMemo } from 'react'--import { MODE_OPTIONS } from '@/app/settings/constants'-import { $chatLayoutPicked, assembleChatOnboarding, snapshotChatLayout } from '@/components/onboarding-chat/assembly'-import { LAYOUTS, 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 { useConnectorCatalog } from '@/store/connector-catalog'-import { $onboardingAnswers, setOnboardingAnswers } from '@/store/onboarding-answers'-import { type OnboardingPlugin, useOnboardingPluginList } from '@/store/onboarding-plugins'-import { useTheme } from '@/themes'-import { $accentOverride, setAccentOverride } from '@/themes/accent-override'-import { accentsFor, NOUS_ACCENT } from '@/themes/accents'-import { normalizeHex } from '@/themes/color'-import type { ThemeMode } from '@/themes/context'-import { persistAccent } from '@/themes/persist-accent'--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--// The theme card offers light and dark only, whoever supplies its options; System stays in Settings.-const THEME_TILES: readonly string[] = MODE_OPTIONS.filter(({ id }) => id !== 'system').map(({ id }) => 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) })),- // The backend fills the fork, machine_use and tour rows, so they are known only once the request arrives.- fork: () => null,- layout: () => LAYOUTS.map(layout => ({ detail: layout.description, id: layout.id, label: layout.name })),- machine_use: () => null,- plugins: ({ plugins }) =>- plugins &&- plugins.map(plugin => ({- detail: plugin.app_state === 'missing_app' ? plugin.sentence : undefined,- id: plugin.name,- label: plugin.title- })),- question: () => [],- theme: ({ t }) => THEME_TILES.map(id => ({ id, label: modeLabel(id, t) })),- tour: () => null-}--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),- fork: id => id,- layout: id => LAYOUTS.find(layout => layout.id === id)?.name ?? id,- machine_use: id => id,- plugins: (id, { plugins }) => plugins?.find(plugin => plugin.name === id)?.title ?? id,- question: id => id,- theme: (id, { t }) => modeLabel(id, t),- tour: id => id-}--interface LiveLook {- apply: (id: string, setMode: (mode: ThemeMode) => void) => void- commit?: (id: string) => void- snapshot: (mode: ThemeMode, setMode: (mode: ThemeMode) => void) => () => void-}--export const LIVE_LOOK: Partial<Record<SetupChooseKind, LiveLook>> = {- accent: {- commit: id => {- const hex = normalizeHex(id)-- if (hex) {- setOnboardingAnswers({ accent: hex === NOUS_ACCENT ? null : hex })- persistAccent(hex)- }- },- apply: id => {- const hex = normalizeHex(id)-- if (hex) {- const accent = hex === NOUS_ACCENT ? null : hex-- setOnboardingAnswers({ accent })- setAccentOverride(accent)- }- },- snapshot: () => {- const { accent } = $onboardingAnswers.get()- const override = $accentOverride.get()-- return () => {- setOnboardingAnswers({ accent })- setAccentOverride(override)- }- }- },- layout: {- apply: 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)- },- snapshot: snapshotChatLayout- },- theme: {- apply: (id, setMode) => {- if (MODE_OPTIONS.some(option => option.id === id)) {- setMode(id as ThemeMode)- }- },- snapshot: (mode, setMode) => () => setMode(mode)- }-}--function useConnectorRows(storedId: null | string): ConnectorRow[] | null {- const catalog = useConnectorCatalog(storedId)-- if (!storedId || catalog.status === 'loading') {- return null- }-- return catalog.status === 'ready' ? catalog.rows : []-}--export function useSetupRows(setup: null | SetupChooseSpec, storedId: null | string): null | SetupRow[] {- const { t } = useI18n()- const { renderedMode } = useTheme()- const connectors = useConnectorRows(setup?.options === null && setup.kind === 'connectors' ? storedId : null)- const plugins = useOnboardingPluginList(setup?.options === null && setup.kind === 'plugins' ? storedId : null)-- // Same inputs must return the same array: the pending card's stage callback and store write key off it.- return useMemo(() => {- if (!setup) {- return NO_ROWS- }-- const rows = setup.options ?? APP_ROWS[setup.kind]({ connectors, dark: renderedMode === 'dark', plugins, t })-- return setup.kind === 'theme' && rows ? rows.filter(row => THEME_TILES.includes(row.id)) : rows- }, [connectors, plugins, renderedMode, setup, t])-}--const NO_ROWS: SetupRow[] = []--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.tsxdeleted file mode 100644index 190c09e2234..00000000000--- a/apps/desktop/src/components/assistant-ui/clarify/setup-settled.tsx+++ /dev/null@@ -1,68 +0,0 @@-'use client'--import type { ToolCallMessagePartProps } from '@assistant-ui/react'-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 { cn } from '@/lib/utils'-import { normalizeSetupChoose } from '@/store/clarify'--import { parseMaybeObject } from '../tool/fallback-model/format'--import { ClarifyShell } from './core/shell'-import { useSetupLabel } from './setup-rows'--const OUTCOMES = new Set(['cancelled', 'no_answer', 'submitted', 'typed'])--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] : []- // Rows the backend filled (tour, fork) are not in the call's args; the result names the pick.- const labels = Array.isArray(row.label) ? row.label.map(String) : typeof row.label === 'string' ? [row.label] : null-- // Composer words that named no row: shown as written, never as a pick.- const said = row.outcome === 'typed' && typeof row.said === 'string' ? row.said : null-- return { labels, outcome: row.outcome, picked, said }-}--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.said ?? (result.labels ?? result.picked.map(label)).join(', ')-- const question = source?.questions[0]?.question-- return (- <ClarifyShell className="my-1.5 grid gap-1" data-clarify-settled="">- {question ? (- <span className="whitespace-pre-wrap font-medium leading-(--conversation-line-height)">{question}</span>- ) : null}- <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>- </ClarifyShell>- )-}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.tsxdeleted file mode 100644index 705388359d1..00000000000--- a/apps/desktop/src/components/assistant-ui/start-chat-tool-parts.tsx+++ /dev/null@@ -1,95 +0,0 @@-'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.tsxdeleted file mode 100644index cc777b73eee..00000000000--- a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx+++ /dev/null@@ -1,141 +0,0 @@-'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 { ToolFallback } from '@/components/assistant-ui/tool/fallback'-import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'-import { useI18n } from '@/i18n'-import type { TimelinePartMetadata } from '@/lib/chat-messages/types'-import { sessionTitle } from '@/lib/chat-runtime'-import { useStoresSelector } from '@/lib/use-session-slice'-import { notifyError } from '@/store/notifications'-import { $profiles } from '@/store/profile'-import { $sessions, sessionMatchesStoredId, setSessionOwnerHint } from '@/store/session'-import { isSessionOwnerRoute } from '@/store/session-request-router'-import {- $startChatRetries,- isStartChatCallerWatched,- retryStartChat,- startChatOutcome,- startChatRetry,- startChatSuperseded,- takeLiveStartChat-} from '@/store/start-chat'--import {- requestedTitle,- retryRequest,- StartChatRejected,- StartChatStarted,- StartChatStarting-} from './start-chat-tool-parts'--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 & Pick<TimelinePartMetadata, 'toolResultMetadata'>) {- const { t } = useI18n()- const copy = t.assistant.startChat- const view = useSessionView()- const callerId = useStore(view.$storedId)- const callerRuntimeId = useStore(view.$runtimeId)- const callerBusy = useStore(view.$busy)- const profiles = useStore($profiles)- const sessions = useStore($sessions)- // Same fallback as the live-start mark in gateway-event/tools.ts, so both sides build the same key.- const callerKey = callerId ?? callerRuntimeId ?? ''- const retry = startChatRetry(useStore($startChatRetries), callerKey, props.toolCallId)- const navigate = useNavigate()- const { result, toolResultMetadata } = props-- const outcome = useMemo(- () => startChatOutcome({ result, toolResultMetadata }, retry),- [result, retry, toolResultMetadata]- )-- const superseded = useStoresSelector(- [view.$messages, $startChatRetries],- () => outcome?.status === 'rejected' && startChatSuperseded(view.$messages.get(), callerKey, props.toolCallId)- )-- const started = outcome?.status === 'started' ? outcome : null- const args = parseMaybeObject(props.args)- const row = started ? sessions.find(session => sessionMatchesStoredId(session, started.sessionId)) : undefined- const title = row ? sessionTitle(row) : requestedTitle(started, args)-- const retryChat = () => {- if (!callerRuntimeId) {- return- }-- void retryStartChat(callerKey, props.toolCallId, callerRuntimeId, retryRequest(args)).then(- next => {- if (next?.status === 'started') {- void openStartedChat(next, callerId, navigate).catch(error => notifyError(error, copy.openFailed))- }- },- error => notifyError(error, copy.notStarted)- )- }-- useEffect(() => {- if (!started || !takeLiveStartChat(callerKey, props.toolCallId)) {- return- }-- const watching = () => Boolean(callerId) && isStartChatCallerWatched(callerId!)-- void openStartedChat(started, callerId, navigate, watching).catch(error => notifyError(error, copy.openFailed))- }, [callerId, callerKey, copy.openFailed, navigate, props.toolCallId, started])-- if (props.result !== undefined && !outcome) {- return <ToolFallback {...props} />- }-- if (outcome?.status === 'rejected') {- return (- <StartChatRejected- disabled={retry === 'pending' || callerBusy || !callerRuntimeId}- onRetry={retryChat}- pending={retry === 'pending'}- reason={outcome.reason}- showRetry={outcome.retryable && !superseded}- />- )- }-- if (!started) {- return <StartChatStarting title={title} />- }-- return (- <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/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex 689baa30d60..ec91def6abe 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -14,7 +14,6 @@ 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 { setThemeCall } from '@/components/assistant-ui/theme-picker/args'import { ThemeTool } from '@/components/assistant-ui/theme-picker/theme-tool'import { AgentDeliveryNotice, deliveryTargetFromCommand } from '@/components/assistant-ui/thread/agent-delivery'@@ -26,7 +25,6 @@ import { formatElapsed, useElapsedSeconds, useMeasuredDuration } from '@/componeimport { ActivityTimerText } from '@/components/chat/activity-timer-text'import { GeneratedImage } from '@/components/chat/generated-image-result'import { SCAFFOLD_LABEL_CLASS, SCAFFOLD_META_CLASS, ScaffoldRow } from '@/components/chat/scaffold-row'-import { useOnboardingChatActive } from '@/components/onboarding-chat/assembly'import { useI18n } from '@/i18n'import { mcpTargets, toolLabels } from '@/lib/connector-tools'import { generatedImageFromResult } from '@/lib/generated-images'@@ -96,19 +94,6 @@ 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 ThemeToolPart: FC<TimelineToolCallProps> = props => {if (settledWithoutResult(props)) {return <ToolFallback {...props} />@@ -131,9 +116,7 @@ const TOOL_CARDS: Record<CardToolName, FC<TimelineToolCallProps>> = {image_generate: ImageGenerateTool,manage_catalog: CatalogInstallTool,manage_connections: ConnectionsToolPart,- set_theme: ThemeToolPart,- setup_choose: ClarifyToolPart,- start_chat: StartChatToolPart+ set_theme: ThemeToolPart}// A failure the user still has to see. The gateway's tool.complete carries the@@ -374,10 +357,6 @@ const ReasoningAccordionGroup: FC<{ children?: ReactNode; endIndex: number; starconst showReasoning = useStore($showReasoning)const messageId = useAuiState(s => s.message.id)const messageRunning = useAuiState(s => s.message.status?.type === 'running')- // The guide's reasoning is it reading its own runbook ("Now step 4: offer- // the layout picker"), and a first-time user reading that alongside the- // greeting breaks the one conversation the guide is trying to have.- const guidedChat = useOnboardingChatActive()const pending = useAuiState(s =>@@ -416,7 +395,7 @@ const ReasoningAccordionGroup: FC<{ children?: ReactNode; endIndex: number; star}, undefined))- if (!hasContent || guidedChat || !showReasoning) {+ if (!hasContent || !showReasoning) {return null}diff --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 fa2f94c30db..91f86eefb7b 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,14 +206,6 @@ 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/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.tsindex 16fdfd8d250..e216e07686a 100644--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts@@ -12,7 +12,7 @@ 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'])+export const QUESTION_CARD_TOOLS = new Set(['clarify'])const REQUEST_BACKED_TOOLS = new Set([...QUESTION_CARD_TOOLS, 'setup_mcp'])@@ -825,16 +825,8 @@ export function toolPartFromStoredCall(function storedToolResultMetadata(toolMessage: SessionMessage): ToolResultMetadata | undefined {const display = parseMaybeJsonObject(toolMessage.display_metadata)const metadata = parseMaybeJsonObject(display.tool_result_metadata)- const retried = parseMaybeJsonObject(display.retried).result- if (typeof metadata.inline_diff !== 'string' && retried === undefined) {- return undefined- }-- return {- ...(typeof metadata.inline_diff === 'string' ? { inline_diff: metadata.inline_diff } : {}),- ...(retried === undefined ? {} : { retried })- }+ return typeof metadata.inline_diff === 'string' ? { inline_diff: metadata.inline_diff } : undefined}export function applyStoredToolResult(messages: ChatMessage[], toolMessage: SessionMessage): boolean {diff --git a/apps/desktop/src/lib/tool-render-class.ts b/apps/desktop/src/lib/tool-render-class.tsindex fcb545c8803..e2c87f04daf 100644--- a/apps/desktop/src/lib/tool-render-class.ts+++ b/apps/desktop/src/lib/tool-render-class.ts@@ -35,9 +35,7 @@ const CARD_TOOL_NAMES = ['image_generate','manage_catalog','manage_connections',- 'set_theme',- 'setup_choose',- 'start_chat'+ 'set_theme'] as constexport type CardToolName = (typeof CARD_TOOL_NAMES)[number]diff --git a/apps/desktop/src/lib/tool-result-metadata.ts b/apps/desktop/src/lib/tool-result-metadata.tsindex c511e2ccb22..ec3dce76393 100644--- a/apps/desktop/src/lib/tool-result-metadata.ts+++ b/apps/desktop/src/lib/tool-result-metadata.ts@@ -8,8 +8,6 @@ export interface ToolResultMetadata {preview?: stringsummary?: stringtodos?: unknown- /** A card's Retry of this call, recorded on the saved tool row (start_chat's handoff card). */- retried?: unknown}export interface ToolResultSource {diff --git a/apps/desktop/src/store/clarify.test.ts b/apps/desktop/src/store/clarify.test.tsindex 1b259d89177..9dccd7dfd0b 100644--- a/apps/desktop/src/store/clarify.test.ts+++ b/apps/desktop/src/store/clarify.test.ts@@ -3,17 +3,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {$clarifyRequest,$clarifyRequests,- $setupChooseStages,- answerSetupCard,type ClarifyRequest,clearClarifyRequest,hasClarifyRequest,normalizeChoices,normalizeQuestions,setClarifyRequest,- setupChooseStage,- skipClarifyRequest,- stageSetupChoose+ skipClarifyRequest} from './clarify'import { $gateway } from './gateway'import { rememberServerRequest, resetServerRequestsForTests } from './server-requests'@@ -133,71 +129,6 @@ describe('skipClarifyRequest', () => {})})-describe('answerSetupCard', () => {- const ACCENTS = { '#0000ff': 'Blue', '#ff0000': 'Red' }- let look: string-- // The card's pick: snapshot the look once, then apply the row (as setup-pending's `stage` does).- function mountAccentCard(requestId: string) {- stageSetupChoose(requestId, {- labels: ACCENTS,- preview: id => {- const before = look- stageSetupChoose(requestId, {- picked: [id],- revert: setupChooseStage(requestId).revert ?? (() => (look = before))- })- look = id- }- })- }-- beforeEach(() => {- look = 'original'- $clarifyRequests.set({})- $setupChooseStages.set({})- resetServerRequestsForTests()- })-- afterEach(() => {- $clarifyRequests.set({})- $setupChooseStages.set({})- })-- it('applies a typed row over the row previewed on the card, and keeps it after the card clears', () => {- const respond = vi.fn()-- rememberServerRequest({ fail: vi.fn(), id: 'req-a', method: 'setup_choose', params: {}, respond })- setClarifyRequest({- ...clarify('session-a', 'req-a'),- setup: { kind: 'accent', multiSelect: false, options: null, preselected: [] }- })- mountAccentCard('req-a')- setupChooseStage('req-a').preview?.('#ff0000')-- expect(answerSetupCard('session-a', 'blue')).toBe(true)-- expect(respond).toHaveBeenCalledWith({ label: 'Blue', picked: '#0000ff' })- expect(hasClarifyRequest('session-a')).toBe(false)- expect(look).toBe('#0000ff')- })-- it('does not notify subscribers when a staged patch changes nothing', () => {- const preview = () => undefined- const listener = vi.fn()-- stageSetupChoose('req-a', { labels: ACCENTS, preview })- const before = $setupChooseStages.get()- const unlisten = $setupChooseStages.listen(listener)-- stageSetupChoose('req-a', { labels: ACCENTS, preview })- unlisten()-- expect($setupChooseStages.get()).toBe(before)- expect(listener).not.toHaveBeenCalled()- })-})-describe('normalizeChoices', () => {it('returns empty array for null/undefined', () => {expect(normalizeChoices(null)).toEqual([])diff --git a/apps/desktop/src/store/clarify.ts b/apps/desktop/src/store/clarify.tsindex 4457e84cec5..6197959cb5e 100644--- a/apps/desktop/src/store/clarify.ts+++ b/apps/desktop/src/store/clarify.ts@@ -1,4 +1,3 @@-import type { SetupChooseKind, SetupChooseOption } from '@hermes/shared'import { atom, computed } from 'nanostores'import { translateNow } from '@/i18n'@@ -17,14 +16,6 @@ export interface ClarifyQuestion {multiSelect: boolean}-export interface SetupChooseSpec {- kind: SetupChooseKind- options: SetupChooseOption[] | null- multiSelect: boolean- /** Row ids the card starts with picked (the backend fills them from the setup facts). */- preselected: string[]-}-export interface ClarifyRequest {requestId: string/** Local receipt time (Unix seconds), used to reject stale resume cleanup. */@@ -33,7 +24,6 @@ export interface ClarifyRequest {questions: ClarifyQuestion[]/** Answers already locked server-side (reconnect replay): qid → answer, null = skipped. */lockedAnswers?: Record<string, null | string>- setup?: SetupChooseSpec}/**@@ -117,51 +107,6 @@ export function normalizeQuestions(questions: unknown): ClarifyQuestion[] {return normalized}-export const SETUP_CHOOSE_QID = 'setup_choose'--const SETUP_CHOOSE_KINDS = new Set<unknown>([- 'accent',- 'connectors',- 'fork',- 'layout',- 'machine_use',- 'plugins',- 'question',- 'theme',- 'tour'-])--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-- const preselected = Array.isArray(params.preselected)- ? params.preselected.filter((id): id is string => typeof id === 'string')- : []-- return {- questions: [- {- choices: options ? options.map(option => option.label) : null,- multiSelect: multiSelect && options !== null,- qid: SETUP_CHOOSE_QID,- question- }- ],- setup: { kind: params.kind as SetupChooseKind, multiSelect, options, preselected }- }-}-// 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, then@@ -249,86 +194,6 @@ export function clearClarifyRequest(requestId?: string, sessionId?: string | nul}}-interface SetupChooseStage {- /** Persist a confirmed look; clearing or skipping the card only reverts its preview. */- commit?: (picked: string[]) => void- draft: string- /**- * The name each row of the card shows, by id: a typed answer still names the rows staged with it, and- * composer text is matched against the rows of a card whose list the app owns.- */- labels: Record<string, string>- picked: string[]- /** The card's own pick of a row: it applies the row's look the same way a click does. */- preview: ((id: string) => void) | null- revert: (() => void) | null-}--export const EMPTY_SETUP_STAGE: SetupChooseStage = { draft: '', labels: {}, picked: [], preview: null, revert: null }--/**- * A card's answer: the picked ids, and the names the user saw for them when any id is a row. The backend- * hands both to the model, which would otherwise guess a name from an id such as `#8a2be2`.- */-export function setupChooseAnswer(- picked: string | string[],- labels: Record<string, string>-): { label?: string | string[]; picked: string | string[] } {- const ids = Array.isArray(picked) ? picked : [picked]-- if (!ids.some(id => Object.hasOwn(labels, id))) {- return { picked }- }-- const named = ids.map(id => (Object.hasOwn(labels, id) ? labels[id] : id))-- return { label: Array.isArray(picked) ? named : named[0], picked }-}--export const $setupChooseStages = atom<Record<string, SetupChooseStage>>({})--export const setupChooseStage = (requestId: string): SetupChooseStage =>- $setupChooseStages.get()[requestId] ?? EMPTY_SETUP_STAGE--export function stageSetupChoose(requestId: string, patch: Partial<SetupChooseStage>): void {- const current = setupChooseStage(requestId)-- // A no-op patch keeps the atom reference so subscribers do not rerender.- const unchanged = Object.entries(patch).every(([key, value]) =>- // SAFETY: the entries of a Partial<SetupChooseStage> carry only SetupChooseStage keys.- Object.is(current[key as keyof SetupChooseStage], value)- )-- if (unchanged && requestId in $setupChooseStages.get()) {- return- }-- $setupChooseStages.set({ ...$setupChooseStages.get(), [requestId]: { ...current, ...patch } })-}--function clearSetupChoose(requestId: string): void {- const next = { ...$setupChooseStages.get() }- delete next[requestId]- $setupChooseStages.set(next)-}--export function commitSetupChoose(requestId: string): void {- const stage = setupChooseStage(requestId)- clearSetupChoose(requestId)- stage.commit?.(stage.picked)-}--$clarifyRequests.listen(requests => {- const live = new Set(Object.values(requests).map(request => request.requestId))-- for (const [requestId, stage] of Object.entries($setupChooseStages.get())) {- if (!live.has(requestId)) {- clearSetupChoose(requestId)- stage.revert?.()- }- }-})-/** Whether `sessionId` has a clarify parked on it right now (imperative read —* the composer checks this on Enter, not on every render). */export const hasClarifyRequest = (sessionId: string | null | undefined): boolean =>@@ -370,22 +235,17 @@ export function skipClarify(request: ClarifyRequest): void {respondToServerRequest(request.requestId, {})- settleClarify(- request,- request.setup- ? { outcome: 'cancelled', picked: null }- : {- outcome: 'cancelled',- // Answers locked server-side before a reconnect stand: the server merges them into its result too.- responses: request.questions.map(question => {- const locked = request.lockedAnswers?.[question.qid]-- return locked- ? { question: question.question, status: 'answered', user_response: lockedAnswer(question, locked) }- : { question: question.question, status: 'unanswered', user_response: null }- })- }- )+ settleClarify(request, {+ outcome: 'cancelled',+ // Answers locked server-side before a reconnect stand: the server merges them into its result too.+ responses: request.questions.map(question => {+ const locked = request.lockedAnswers?.[question.qid]++ return locked+ ? { question: question.question, status: 'answered', user_response: lockedAnswer(question, locked) }+ : { question: question.question, status: 'unanswered', user_response: null }+ })+ })}export async function skipClarifyRequest(sessionId: string | null | undefined): Promise<boolean> {@@ -400,22 +260,7 @@ export async function skipClarifyRequest(sessionId: string | null | undefined):return true}-/**- * Answer the setup card parked on `sessionId` with text the user typed in the- * composer: the setup turn reads typed words as the card's answer. False when- * no setup card is parked (an ordinary clarify card included) or its request is- * gone; the caller then skips any card and sends the words as a message.- */-export function answerSetupCard(sessionId: string | null | undefined, text: string): boolean {- const request = $clarifyRequests.get()[keyFor(sessionId)]-- return request?.setup ? answerSetupChoose(request, request.setup, text) : false-}--/**- * Answer the card parked on `sessionId` with composer text. A setup card reads the words as its- * pick; a clarify card takes them as the answer to its first question not yet locked.- */+/** Answer the clarify parked on `sessionId` with composer text: the answer to its first question not yet locked. */function answerClarifyText(sessionId: string, text: string): boolean {const request = $clarifyRequests.get()[keyFor(sessionId)]@@ -423,7 +268,7 @@ function answerClarifyText(sessionId: string, text: string): boolean {return false}- return request.setup ? answerSetupCard(sessionId, text) : lockTypedAnswer(request, text)+ return lockTypedAnswer(request, text)}registerParkedCardAnswer('clarify', answerClarifyText)@@ -539,57 +384,3 @@ function rollBackTypedAnswer(delete kept[qid]setClarifyRequest({ ...live, lockedAnswers: kept })}--/** The row typed text names, by id or label (any case). */-function matchSetupRow(labels: Record<string, string>, text: string): string | undefined {- const typed = text.trim().toLowerCase()-- return Object.keys(labels).find(id => id.toLowerCase() === typed || labels[id].trim().toLowerCase() === typed)-}--function answerSetupChoose(request: ClarifyRequest, setup: SetupChooseSpec, text: string): boolean {- const stage = setupChooseStage(request.requestId)- // The backend fills its own rows into the request; the app's lists are known to the card that drew them.- const labels = setup.options ? Object.fromEntries(setup.options.map(row => [row.id, row.label])) : stage.labels- const freeText = setup.kind === 'question' && !setup.options- const id = freeText ? text : matchSetupRow(labels, text)-- if (id === undefined) {- // Words that name no row are not a pick: the model reads them and asks again.- if (!respondToServerRequest(request.requestId, { said: text })) {- return false- }-- clearClarifyRequest(request.requestId, request.sessionId)- settleClarify(request, { outcome: 'typed', picked: null, said: text })-- return true- }-- // A multi-select picker keeps the rows already staged on the card, the- // same as its own Confirm: the typed row is one more pick.- const answer = setupChooseAnswer(- setup.multiSelect ? [...new Set([...stage.picked, id])] : id,- freeText ? stage.labels : { ...stage.labels, ...labels }- )-- if (!respondToServerRequest(request.requestId, answer)) {- return false- }-- // A typed row is picked as if clicked, so its look stays once the request clears.- const staged = setup.multiSelect || stage.picked.includes(id)-- if (!staged) {- stage.preview?.(id)- }-- if (staged || stage.preview) {- commitSetupChoose(request.requestId)- }-- clearClarifyRequest(request.requestId, request.sessionId)- settleClarify(request, { outcome: 'submitted', ...answer })-- return true-}diff --git a/apps/desktop/src/store/start-chat.test.ts b/apps/desktop/src/store/start-chat.test.tsdeleted file mode 100644index 8ab70416f23..00000000000--- a/apps/desktop/src/store/start-chat.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, expect, it } from 'vitest'--import { $gateway } from '@/store/gateway'--import { $startChatRetries, markLiveStartChat, retryStartChat, startChatRetry, takeLiveStartChat } from './start-chat'--describe('start_chat per-call state', () => {- it("keeps one chat's retry off another chat's call with the same tool call id", async () => {- const started = { profile: 'default', session_id: 'child-a', status: 'started', title: 'Task A' }-- // SAFETY: retryStartChat only calls gateway.request, which this stub provides.- $gateway.set({ request: async () => started } as never)-- await retryStartChat('chat-a', 'call_0', 'runtime-a', { message: 'do A' })-- expect(startChatRetry($startChatRetries.get(), 'chat-a', 'call_0')).toMatchObject({ sessionId: 'child-a' })- expect(startChatRetry($startChatRetries.get(), 'chat-b', 'call_0')).toBeUndefined()- })-- it("does not auto-open another chat's call that reused the same tool call id", () => {- markLiveStartChat('chat-a', 'call_0')-- expect(takeLiveStartChat('chat-b', 'call_0')).toBe(false)- expect(takeLiveStartChat('chat-a', 'call_0')).toBe(true)- })-})diff --git a/apps/desktop/src/store/start-chat.ts b/apps/desktop/src/store/start-chat.tsdeleted file mode 100644index f342f56f1e6..00000000000--- a/apps/desktop/src/store/start-chat.ts+++ /dev/null@@ -1,146 +0,0 @@-import type { SessionStartChatResult, StartChatArgs } from '@hermes/shared'-import { atom } from 'nanostores'--import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'-import type { ChatMessage, ChatMessagePart } from '@/lib/chat-messages/types'-import { $gateway } from '@/store/gateway'-import { $focusedStoredSessionId } from '@/store/session-focus'-import { isSessionInForeground, requestForOwnedSession } from '@/store/session-states'--type StartChatOutcome =- | { profile: string; sessionId: string; status: 'started'; title: null | string }- | { reason: string; retryable: boolean; 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 : '',- retryable: row.retryable === true,- status: 'rejected'- }- }-- return null-}--// Tool call ids are unique only within one session (providers reuse ids like `call_0`), so per-call state is keyed by the calling session too.-function callKey(callerId: string, toolCallId: string): string {- return `${callerId}\u0000${toolCallId}`-}--const liveStarts = new Set<string>()--export function markLiveStartChat(callerId: string, toolCallId: string): void {- liveStarts.add(callKey(callerId, toolCallId))-}--export function takeLiveStartChat(callerId: string, toolCallId: string): boolean {- return liveStarts.delete(callKey(callerId, toolCallId))-}--export function isStartChatCallerWatched(storedId: string): boolean {- return $focusedStoredSessionId.get() !== null && isSessionInForeground(storedId)-}--export const $startChatRetries = atom<Record<string, 'pending' | StartChatOutcome>>({})--type StartChatRetry = 'pending' | StartChatOutcome | undefined--export function startChatRetry(- retries: Record<string, 'pending' | StartChatOutcome>,- callerId: string,- toolCallId: string-): StartChatRetry {- return retries[callKey(callerId, toolCallId)]-}--function setRetry(key: string, value: 'pending' | null | StartChatOutcome): void {- const { [key]: _previous, ...rest } = $startChatRetries.get()-- $startChatRetries.set(value ? { ...rest, [key]: value } : rest)-}--/** The card's Retry (live in this window, else recorded on the saved tool row) wins over the call's own result. */-export function startChatOutcome(- part: Pick<ChatMessagePart, 'toolResultMetadata'> & { result?: unknown },- retry: StartChatRetry-): null | StartChatOutcome {- return (- (retry && retry !== 'pending' ? retry : null) ??- readStartChatResult(part.toolResultMetadata?.retried) ??- readStartChatResult(part.result)- )-}--/** A later start_chat in this chat already started: a Retry here could only start the task twice. */-export function startChatSuperseded(messages: ChatMessage[], callerId: string, toolCallId: string): boolean {- const retries = $startChatRetries.get()- let after = false-- for (const message of messages) {- for (const part of message.parts) {- if (part.type !== 'tool-call' || part.toolName !== 'start_chat') {- continue- }-- if (- after &&- startChatOutcome(part, part.toolCallId ? startChatRetry(retries, callerId, part.toolCallId) : undefined)- ?.status === 'started'- ) {- return true- }-- after ||= part.toolCallId === toolCallId- }- }-- return false-}--export async function retryStartChat(- callerId: string,- toolCallId: string,- callerRuntimeId: string,- args: StartChatArgs-): Promise<null | StartChatOutcome> {- const gateway = $gateway.get()-- if (!gateway) {- throw new Error('Gateway not connected')- }-- const key = callKey(callerId, toolCallId)-- setRetry(key, 'pending')-- try {- const outcome = readStartChatResult(- await requestForOwnedSession<SessionStartChatResult>(- callerRuntimeId,- gateway.request.bind(gateway) as typeof gateway.request,- 'session.start_chat',- { args, session_id: callerRuntimeId, tool_call_id: toolCallId }- )- )-- setRetry(key, outcome)-- return outcome- } catch (error) {- setRetry(key, null)-- throw error- }-}