Skip to content

The agent that grows with you

Setup cards: pills only, no key letters, no System tile; handoff card title + Retry (#129243)

Siddharth Balyanf7b0a2f61374
diff --git a/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts b/apps/desktop/src/components/assistant-ui/clarify/core/use-clarify-keys.ts
index a17017d5e8a..1aa1775cd59 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
@@ -14,7 +14,7 @@ interface ClarifyKeysOptions {
onToggle: (question: ClarifyQuestion, choice: string) => void
other?: boolean
questions: ClarifyQuestion[]
- shortcuts?: number
+ shortcuts?: boolean
}
export function useClarifyKeys({
@@ -28,14 +28,13 @@ export function useClarifyKeys({
onToggle,
other = true,
questions,
- shortcuts
+ shortcuts = true
}: ClarifyKeysOptions) {
const [cursor, setCursor] = useState({ question: 0, row: initialRow })
const questionIndex = Math.min(cursor.question, Math.max(questions.length - 1, 0))
const active = questions[questionIndex]
const choices = active?.choices ?? []
const otherRows = other ? 1 : 0
- const shortcutRows = shortcuts ?? choices.length
const row = Math.min(cursor.row, choices.length - 1 + otherRows)
const focusQuestion = useCallback(
@@ -43,6 +42,14 @@ export function useClarifyKeys({
[]
)
+ const focusRow = useCallback(
+ (index: number, choiceIndex: number) =>
+ setCursor(current =>
+ current.question === index && current.row === choiceIndex ? current : { question: index, row: choiceIndex }
+ ),
+ []
+ )
+
const onOtherFocus = useCallback(
(index: number) => setCursor({ question: index, row: questions[index]?.choices?.length ?? 0 }),
[questions]
@@ -149,7 +156,7 @@ export function useClarifyKeys({
}
const pickByIndex = (event: globalThis.KeyboardEvent, index: number) => {
- if (index < shortcutRows) {
+ if (index < choices.length) {
event.preventDefault()
pick(questionIndex, index)
} else if (other && index === choices.length) {
@@ -203,7 +210,7 @@ export function useClarifyKeys({
return
}
- if (/^[1-9]$/.test(event.key)) {
+ if (shortcuts && /^[1-9]$/.test(event.key)) {
pickByIndex(event, Number(event.key) - 1)
return
@@ -215,7 +222,7 @@ export function useClarifyKeys({
// the last row belongs to the composer — the user is typing a message
// instead of picking an option, and swallowing the keystroke here would
// make the first letter of it vanish.
- if (key.length === 1 && key >= 'a' && key <= 'z') {
+ if (shortcuts && key.length === 1 && key >= 'a' && key <= 'z') {
pickByIndex(event, key.charCodeAt(0) - 97)
return
@@ -242,8 +249,8 @@ export function useClarifyKeys({
other,
pick,
questionIndex,
- shortcutRows
+ shortcuts
])
- return { activeQuestion: questionIndex, cursorRow: row, focusQuestion, onOtherFocus, pick }
+ return { activeQuestion: questionIndex, cursorRow: row, focusQuestion, focusRow, onOtherFocus, pick }
}
diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
index ccce4f28163..621473e08f5 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pending.tsx
@@ -25,10 +25,9 @@ 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 { PICKER_COLUMNS, pickerShortcutCount, pillQuestion, QuestionPills, SETUP_PICKERS } from './setup-pickers'
+import { PICKER_COLUMNS, QuestionPills, SETUP_PICKERS } from './setup-pickers'
import { LIVE_LOOK, useSetupRows } from './setup-rows'
import { handleClarifySubmitShortcut } from './submit-shortcut'
import { UndeliveredNotice } from './undelivered-notice'
@@ -179,8 +178,6 @@ export function SetupChoosePending({
const formRef = useRef<HTMLFormElement | null>(null)
const questions = useMemo(() => [question], [question])
- const shortcuts = pickerKind === null ? (question.choices?.length ?? 0) : pickerShortcutCount(rows ?? [])
- const pills = pickerKind === null && pillQuestion(rows ?? [])
const keys = useClarifyKeys({
columns: pickerKind === null ? undefined : PICKER_COLUMNS[pickerKind](rows ?? []),
@@ -195,7 +192,7 @@ export function SetupChoosePending({
onToggle: toggle,
other: freeText,
questions,
- shortcuts
+ shortcuts: false
})
const cursor = ready ? keys.cursorRow : null
@@ -208,8 +205,8 @@ export function SetupChoosePending({
className="my-1.5 grid gap-4"
data-clarify-batch={1}
data-clarify-batch-preview={ready ? undefined : ''}
- data-clarify-choices={ready ? shortcuts || undefined : undefined}
- data-clarify-other={freeText ? undefined : 'false'}
+ data-clarify-choices={ready ? 0 : undefined}
+ data-clarify-other="false"
data-setup-choose={kind}
onKeyDownCapture={handleClarifySubmitShortcut}
onSubmit={handleSubmit}
@@ -228,28 +225,16 @@ export function SetupChoosePending({
<Icon aria-hidden className={CLARIFY_ICON_CLASS} />
</div>
{undelivered ? <UndeliveredNotice /> : null}
- {Picker === null && pills ? (
+ {Picker === null ? (
<QuestionPills
cursor={cursor}
+ details={(rows ?? []).map(row => row.detail)}
disabled={!ready}
onActivate={() => keys.focusQuestion(0)}
onDraft={onDraft}
onOtherFocus={() => keys.onOtherFocus(0)}
onPick={index => keys.pick(0, index)}
- question={question}
- staged={{
- choices: (rows ?? []).filter(row => picked.includes(row.id)).map(row => row.label),
- draft
- }}
- />
- ) : Picker === null ? (
- <QuestionBlock
- cursor={cursor}
- 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),
diff --git a/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx b/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx
index d15498ad6d6..44a0ac86c51 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx
+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-pickers.tsx
@@ -3,13 +3,12 @@
import type { SetupChooseKind } from '@hermes/shared'
import { useStore } from '@nanostores/react'
import { Puzzle } from 'lucide-react'
-import { type CSSProperties, type FC, type ReactNode, useState } from '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 { AccentSwatch, LayoutPreviewCard, LAYOUTS, NOUS_ACCENT } from '@/components/onboarding-chat/options'
import { ConnectorLogo } from '@/components/ui/connector-logo'
-import { Kbd } from '@/components/ui/kbd'
import { SearchField } from '@/components/ui/search-field'
import { useI18n } from '@/i18n'
import { connectorIconUrl } from '@/lib/connector-tools'
@@ -19,7 +18,7 @@ import { pluginNeedsApp, useOnboardingPluginList } from '@/store/onboarding-plug
import { useTheme } from '@/themes'
import { getBaseColors } from '@/themes/context'
-import { ChoiceLabel, letterFor } from './core/choice-row'
+import { ChoiceLabel } from './core/choice-row'
import type { SetupRow } from './setup-rows'
export interface SetupPickerProps {
@@ -32,10 +31,6 @@ export interface SetupPickerProps {
const SEARCH_THRESHOLD = 12
-const PILL_MAX_OPTIONS = 6
-
-const PILL_MAX_LABEL = 40
-
export const PICKER_COLUMNS: Record<Exclude<SetupChooseKind, 'question'>, (rows: SetupRow[]) => number> = {
accent: rows => rows.length,
connectors: () => 3,
@@ -44,29 +39,9 @@ export const PICKER_COLUMNS: Record<Exclude<SetupChooseKind, 'question'>, (rows:
theme: rows => rows.length
}
-export const pillQuestion = (rows: SetupRow[]): boolean =>
- rows.length > 0 &&
- rows.length <= PILL_MAX_OPTIONS &&
- rows.every(row => !row.detail && row.label.length <= PILL_MAX_LABEL)
-
-export function pickerShortcutCount(rows: SetupRow[]): number {
- return rows.length > SEARCH_THRESHOLD ? 0 : rows.length
-}
-
-function PickerItem({
- active,
- children,
- className,
- index
-}: {
- active: boolean
- children: ReactNode
- className?: string
- index: null | number
-}) {
+function PickerItem({ active, children, className }: { active: boolean; children: ReactNode; className?: string }) {
return (
<div
- aria-keyshortcuts={index === null ? undefined : `${letterFor(index)} ${index + 1}`}
className={cn('grid min-w-0', active && 'ring-2 ring-primary/40', className)}
data-highlighted={active || undefined}
onMouseDown={event => event.preventDefault()}
@@ -91,22 +66,17 @@ function ThemePicker({ cursor, onPick, picked, rows }: SetupPickerProps) {
background: light.background,
borderColor: light.border,
'--color-foreground': light.foreground
- } as CSSProperties,
- system: {
- background: `linear-gradient(135deg, ${light.background} 50%, ${dark.background} 50%)`,
- borderColor: light.border,
- '--color-foreground': '#808080'
} as CSSProperties
}
return (
- <div className="grid grid-cols-3 gap-3 p-1" role="group">
+ <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]" index={index} key={row.id}>
+ <PickerItem active={cursor === index} className="rounded-[8px]" key={row.id}>
<LayoutPreviewCard
active={active}
name={row.label}
@@ -129,7 +99,7 @@ function AccentPicker({ cursor, onPick, onStage, picked, rows }: SetupPickerProp
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}>
+ <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>
))}
@@ -147,7 +117,7 @@ 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}>
+ <PickerItem active={cursor === index} className="rounded-[8px]" key={row.id}>
<LayoutPreviewCard
active={picked.includes(row.id)}
description={row.detail ?? undefined}
@@ -177,7 +147,6 @@ function ChipPicker({
const { t } = useI18n()
const [query, setQuery] = useState('')
const search = query.trim().toLowerCase()
- const shortcuts = pickerShortcutCount(rows)
return (
<div className="grid gap-2">
@@ -187,12 +156,7 @@ function ChipPicker({
<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 < shortcuts ? index : null}
- key={row.id}
- >
+ <PickerItem active={cursor === index} className="rounded-[6px]" key={row.id}>
<Chip
className={cn('w-full', dim?.(row) && 'opacity-60')}
icon={icon(row)}
@@ -252,33 +216,39 @@ export const SETUP_PICKERS: Record<Exclude<SetupChooseKind, 'question'>, FC<Setu
}
const PILL_CLASS =
- 'flex max-w-full shrink-0 items-center gap-1.5 rounded-full border py-1 pr-3 pl-1.5 text-left text-[12px] whitespace-normal wrap-anywhere transition-colors disabled:cursor-not-allowed disabled:opacity-50'
+ '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
@@ -295,7 +265,7 @@ export function QuestionPills({
return (
<button
aria-current={cursor === index || undefined}
- aria-keyshortcuts={cursor === null ? undefined : `${letterFor(index)} ${index + 1}`}
+ aria-describedby={cursor === index && detail ? detailId : undefined}
aria-pressed={selected}
className={cn(
PILL_CLASS,
@@ -309,14 +279,16 @@ export function QuestionPills({
disabled={disabled}
key={`${index}-${choice}`}
onClick={() => onPick(index)}
+ onFocus={() => onRowFocus(index)}
+ onPointerEnter={() => onRowFocus(index)}
type="button"
>
- <Kbd size="sm" variant={selected ? 'inverted' : 'default'}>
- {letterFor(index)}
- </Kbd>
<span>
<ChoiceLabel choice={choice} />
</span>
+ {details[index] ? (
+ <span aria-hidden className="size-1 shrink-0 rounded-full bg-current opacity-60" />
+ ) : null}
</button>
)
})}
@@ -330,20 +302,27 @@ export function QuestionPills({
)}
data-highlighted={otherActive || undefined}
>
- <Kbd size="sm">{letterFor(choices.length)}</Kbd>
<textarea
aria-current={otherActive || undefined}
- aria-keyshortcuts={cursor === null ? undefined : `${letterFor(choices.length)} ${choices.length + 1}`}
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={t.assistant.clarify.other}
+ 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.ts
index 5452fa8b3be..a344dee5ba5 100644
--- a/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts
+++ b/apps/desktop/src/components/assistant-ui/clarify/setup-rows.ts
@@ -30,6 +30,9 @@ interface RowSources {
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 }) =>
@@ -44,7 +47,7 @@ const APP_ROWS: Record<SetupChooseKind, (sources: RowSources) => null | SetupRow
label: plugin.title
})),
question: () => [],
- theme: ({ t }) => MODE_OPTIONS.map(({ id }) => ({ id, label: modeLabel(id, t) }))
+ theme: ({ t }) => THEME_TILES.map(id => ({ id, label: modeLabel(id, t) }))
}
const APP_LABELS: Record<SetupChooseKind, (id: string, sources: Pick<RowSources, 'plugins' | 't'>) => string> = {
@@ -126,7 +129,9 @@ export function useSetupRows(setup: null | SetupChooseSpec, storedId: null | str
return []
}
- return setup.options ?? APP_ROWS[setup.kind]({ connectors, dark: renderedMode === 'dark', plugins, t })
+ 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
}
export function useSetupLabel(
diff --git a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
index 32769844081..7272562ad99 100644
--- a/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
+++ b/apps/desktop/src/components/assistant-ui/start-chat-tool.tsx
@@ -13,12 +13,22 @@ import { ToolFallback } from '@/components/assistant-ui/tool/fallback'
import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'
import { Button } from '@/components/ui/button'
import { useI18n } from '@/i18n'
+import type { TimelinePartMetadata } from '@/lib/chat-messages/types'
+import { sessionTitle } from '@/lib/chat-runtime'
import { Loader2, MessageCircle } from '@/lib/icons'
+import { useStoresSelector } from '@/lib/use-session-slice'
import { notifyError } from '@/store/notifications'
import { $profiles, profileLabel } from '@/store/profile'
-import { setSessionOwnerHint } from '@/store/session'
+import { $sessions, sessionMatchesStoredId, setSessionOwnerHint } from '@/store/session'
import { isSessionOwnerRoute } from '@/store/session-request-router'
-import { isStartChatCallerWatched, readStartChatResult, takeLiveStartChat } from '@/store/start-chat'
+import {
+ $startChatRetries,
+ isStartChatCallerWatched,
+ retryStartChat,
+ startChatOutcome,
+ startChatSuperseded,
+ takeLiveStartChat
+} from '@/store/start-chat'
const TITLE_LIMIT = 40
@@ -41,19 +51,55 @@ async function openStartedChat(
}
}
-export function StartChatTool(props: ToolCallMessagePartProps) {
+export function StartChatTool(props: ToolCallMessagePartProps & Pick<TimelinePartMetadata, 'toolResultMetadata'>) {
const { t } = useI18n()
const copy = t.assistant.startChat
- const callerId = useStore(useSessionView().$storedId)
+ 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)
+ const retry = useStore($startChatRetries)[props.toolCallId]
const navigate = useNavigate()
- const outcome = useMemo(() => readStartChatResult(props.result), [props.result])
+ 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(), props.toolCallId)
+ )
+
const started = outcome?.status === 'started' ? outcome : null
const args = parseMaybeObject(props.args)
const message = typeof args.message === 'string' ? args.message.trim() : ''
+ const row = started ? sessions.find(session => sessionMatchesStoredId(session, started.sessionId)) : undefined
+
+ const title = row
+ ? sessionTitle(row)
+ : started?.title || (typeof args.title === 'string' && args.title.trim()) || message.slice(0, TITLE_LIMIT) || null
+
+ const retryChat = () => {
+ if (!callerRuntimeId) {
+ return
+ }
- const title =
- started?.title || (typeof args.title === 'string' && args.title.trim()) || message.slice(0, TITLE_LIMIT) || null
+ void retryStartChat(props.toolCallId, callerRuntimeId, {
+ message: typeof args.message === 'string' ? args.message : '',
+ profile: typeof args.profile === 'string' ? args.profile : null,
+ title: typeof args.title === 'string' ? args.title : null
+ }).then(
+ 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(props.toolCallId)) {
@@ -71,9 +117,25 @@ export function StartChatTool(props: ToolCallMessagePartProps) {
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 className="my-1.5 flex items-center gap-2" data-slot="start-chat">
+ <div className="grid min-w-0 flex-1 gap-0.5">
+ <span className="font-medium">{copy.notStarted}</span>
+ {outcome.reason ? <span className={CAPTION}>{outcome.reason}</span> : null}
+ </div>
+ {outcome.retryable && !superseded ? (
+ <Button
+ disabled={retry === 'pending' || callerBusy || !callerRuntimeId}
+ onClick={retryChat}
+ size="xs"
+ type="button"
+ variant="outline"
+ >
+ {retry === 'pending' ? (
+ <Loader2 aria-hidden className="size-3.5 animate-spin motion-reduce:animate-none" />
+ ) : null}
+ {copy.retry}
+ </Button>
+ ) : null}
</ClarifyShell>
)
}
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 73b2edb5145..ba1006f350d 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -5349,7 +5349,8 @@ export const en: Translations = {
starting: title => `Starting “${title}”…`,
startingUntitled: 'Starting a chat…',
untitled: 'New chat',
- notStarted: "The chat didn't start",
+ notStarted: "Couldn't start that chat.",
+ retry: 'Retry',
inProfile: profile => `In ${profile}`,
open: 'Open',
openFailed: "Couldn't open the chat"
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 658c041871b..5ab4421cdc1 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -4456,6 +4456,7 @@ export interface Translations {
startingUntitled: string
untitled: string
notStarted: string
+ retry: string
inProfile: (profile: string) => string
open: string
openFailed: string
diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.ts
index fb756b5de48..16fdfd8d250 100644
--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts
+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts
@@ -825,8 +825,16 @@ 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
- return typeof metadata.inline_diff === 'string' ? { inline_diff: metadata.inline_diff } : undefined
+ if (typeof metadata.inline_diff !== 'string' && retried === undefined) {
+ return undefined
+ }
+
+ return {
+ ...(typeof metadata.inline_diff === 'string' ? { inline_diff: metadata.inline_diff } : {}),
+ ...(retried === undefined ? {} : { retried })
+ }
}
export function applyStoredToolResult(messages: ChatMessage[], toolMessage: SessionMessage): boolean {
diff --git a/apps/desktop/src/lib/tool-result-metadata.ts b/apps/desktop/src/lib/tool-result-metadata.ts
index ec3dce76393..c511e2ccb22 100644
--- a/apps/desktop/src/lib/tool-result-metadata.ts
+++ b/apps/desktop/src/lib/tool-result-metadata.ts
@@ -8,6 +8,8 @@ export interface ToolResultMetadata {
preview?: string
summary?: string
todos?: 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/start-chat.ts b/apps/desktop/src/store/start-chat.ts
index ecb0204a11c..4918cbce909 100644
--- a/apps/desktop/src/store/start-chat.ts
+++ b/apps/desktop/src/store/start-chat.ts
@@ -1,9 +1,14 @@
+import type { SessionStartChatResult, StartChatArgs } from '@hermes/shared'
+import { atom } from 'nanostores'
+
import { parseMaybeObject } from '@/components/assistant-ui/tool/fallback-model/format'
-import { $focusedStoredSessionId, isSessionInForeground } from '@/store/session-states'
+import type { ChatMessage, ChatMessagePart } from '@/lib/chat-messages/types'
+import { $gateway } from '@/store/gateway'
+import { $focusedStoredSessionId, isSessionInForeground, requestForOwnedSession } from '@/store/session-states'
export type StartChatOutcome =
| { profile: string; sessionId: string; status: 'started'; title: null | string }
- | { reason: string; status: 'rejected' }
+ | { reason: string; retryable: boolean; status: 'rejected' }
export function readStartChatResult(result: unknown): null | StartChatOutcome {
const row = parseMaybeObject(result)
@@ -18,7 +23,11 @@ export function readStartChatResult(result: unknown): null | StartChatOutcome {
}
if (row.status === 'rejected') {
- return { reason: typeof row.reason === 'string' ? row.reason : '', status: 'rejected' }
+ return {
+ reason: typeof row.reason === 'string' ? row.reason : '',
+ retryable: row.retryable === true,
+ status: 'rejected'
+ }
}
return null
@@ -37,3 +46,83 @@ export function takeLiveStartChat(toolCallId: string): boolean {
export function isStartChatCallerWatched(storedId: string): boolean {
return $focusedStoredSessionId.get() !== null && isSessionInForeground(storedId)
}
+
+export const $startChatRetries = atom<Record<string, 'pending' | StartChatOutcome>>({})
+
+function setRetry(toolCallId: string, value: 'pending' | null | StartChatOutcome): void {
+ const { [toolCallId]: _previous, ...rest } = $startChatRetries.get()
+
+ $startChatRetries.set(value ? { ...rest, [toolCallId]: value } : rest)
+}
+
+type StartChatRetry = 'pending' | StartChatOutcome | undefined
+
+/** 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[], 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 ? retries[part.toolCallId] : undefined)?.status === 'started'
+ ) {
+ return true
+ }
+
+ after ||= part.toolCallId === toolCallId
+ }
+ }
+
+ return false
+}
+
+export async function retryStartChat(
+ toolCallId: string,
+ callerRuntimeId: string,
+ args: StartChatArgs
+): Promise<null | StartChatOutcome> {
+ const gateway = $gateway.get()
+
+ if (!gateway) {
+ throw new Error('Gateway not connected')
+ }
+
+ setRetry(toolCallId, '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(toolCallId, outcome)
+
+ return outcome
+ } catch (error) {
+ setRetry(toolCallId, null)
+
+ throw error
+ }
+}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index c2555e1abb9..2a397b286f7 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3546,6 +3546,30 @@ export interface LlmOneshotParams {
export interface LlmOneshotResult {
text: string
}
+/** ``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only). */
+export interface SessionStartChatParams {
+ session_id: string
+ profile?: string | null
+ tool_call_id: string
+ args: StartChatArgs
+}
+/** The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``). */
+export interface StartChatArgs {
+ message: string
+ title?: string | null
+ profile?: string | null
+}
+/** ``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same arguments may succeed on another try (``retryable``). A call already retried returns that retry's result. */
+export interface SessionStartChatResult {
+ status: StartChatStatus
+ session_id?: string | null
+ profile?: string | null
+ title?: string | null
+ message?: string | null
+ reason?: string | null
+ retryable?: boolean | null
+}
+export type StartChatStatus = 'started' | 'rejected'
export interface SystemBatteryParams {
profile?: string | null
}
@@ -5297,6 +5321,8 @@ export interface RpcMethods {
'session.save': { params: SessionSaveParams; result: SessionSaveResult }
/** Set/clear hidden (out of the default list, still resumable by its owner) on a session + lineage. */
'session.set_hidden': { params: SessionSetHiddenParams; result: SessionSetHiddenResult }
+ /** Run a start_chat request again from the session that made it (the handoff card's Retry). */
+ 'session.start_chat': { params: SessionStartChatParams; result: SessionStartChatResult }
/** Rendered /status text for the session. */
'session.status': { params: SessionStatusParams; result: SessionStatusResult }
/** Inject text into the next tool result without interrupting the turn. */
@@ -5613,6 +5639,7 @@ export const RPC_METHODS = [
'session.resume',
'session.save',
'session.set_hidden',
+ 'session.start_chat',
'session.status',
'session.steer',
'session.title',
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index f46a3b43c5a..34e718a2d83 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -3552,6 +3552,24 @@
}
}
},
+ {
+ "name": "session.start_chat",
+ "summary": "Run a start_chat request again from the session that made it (the handoff card's Retry).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionStartChatParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionStartChatResult"
+ }
+ }
+ },
{
"name": "session.status",
"summary": "Rendered /status text for the session.",
@@ -31651,6 +31669,128 @@
"title": "SessionSetHiddenResult",
"type": "object"
},
+ "SessionStartChatParams": {
+ "additionalProperties": false,
+ "description": "``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only).",
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "tool_call_id": {
+ "title": "Tool Call Id",
+ "type": "string"
+ },
+ "args": {
+ "$ref": "#/components/schemas/StartChatArgs"
+ }
+ },
+ "required": [
+ "session_id",
+ "tool_call_id",
+ "args"
+ ],
+ "title": "SessionStartChatParams",
+ "type": "object"
+ },
+ "SessionStartChatResult": {
+ "additionalProperties": false,
+ "description": "``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same\narguments may succeed on another try (``retryable``). A call already retried returns that retry's result.",
+ "properties": {
+ "status": {
+ "$ref": "#/components/schemas/StartChatStatus"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "title": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title"
+ },
+ "message": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Message"
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "retryable": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Retryable"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "title": "SessionStartChatResult",
+ "type": "object"
+ },
"SessionStatusParams": {
"additionalProperties": false,
"properties": {
@@ -34292,6 +34432,53 @@
"title": "SpawnTreeSaveResult",
"type": "object"
},
+ "StartChatArgs": {
+ "additionalProperties": false,
+ "description": "The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``).",
+ "properties": {
+ "message": {
+ "title": "Message",
+ "type": "string"
+ },
+ "title": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "required": [
+ "message"
+ ],
+ "title": "StartChatArgs",
+ "type": "object"
+ },
+ "StartChatStatus": {
+ "enum": [
+ "started",
+ "rejected"
+ ],
+ "title": "StartChatStatus",
+ "type": "string"
+ },
"StatusUpdatePayload": {
"additionalProperties": false,
"description": "``server._status_update`` and the direct emitters (goal / loop / heartbeat / process).",
diff --git a/hermes_state.py b/hermes_state.py
index dca255c379c..fc1c7b25151 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -70,6 +70,7 @@ from hermes_state_wal import (
)
from hermes_state_repair import _claim_repair_attempt, preflight_db_writability, repair_state_db_schema
from hermes_state_titles import SessionTitlesMixin
+from hermes_state_tool_retries import SessionToolRetriesMixin
from hermes_state_usage import SessionUsageMixin
from hermes_state_maintenance import SessionMaintenanceMixin
from hermes_state_gateway import SessionGatewayMixin
@@ -452,7 +453,7 @@ class SessionDB(
SessionSessionsMixin, SessionFtsSetupMixin, SessionSearchMixin, SessionSchemaMixin,
SessionPortabilityMixin, SessionTelegramTopicsMixin, SessionCompressionMixin,
SessionGatewayMixin, SessionMaintenanceMixin, SessionUsageMixin, SessionTitlesMixin,
- SessionMessagesMixin, SessionRewindMixin, SessionProfileRepairMixin,
+ SessionMessagesMixin, SessionRewindMixin, SessionProfileRepairMixin, SessionToolRetriesMixin,
):
"""SQLite-backed session storage with FTS5 search; many reader threads, one writer (WAL)."""
diff --git a/hermes_state_tool_retries.py b/hermes_state_tool_retries.py
new file mode 100644
index 00000000000..9ea73d7e588
--- /dev/null
+++ b/hermes_state_tool_retries.py
@@ -0,0 +1,66 @@
+"""Tool-retry mixin for SessionDB: a card's Retry (the start_chat handoff card) records its outcome on the
+original tool row's ``display_metadata``. The row the model replays stays byte-identical, so the cached prefix
+survives; a reload shows the outcome, and ``announced`` tells the model once, on the next user turn (the
+reactions pattern)."""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List, Optional, Tuple
+
+from hermes_state_common import _placeholders, _sql_json_extract
+from hermes_state_messages import _DISPLAY_ACTIVE_CLAUSE, _SET_DISPLAY_META_SQL
+
+
+class SessionToolRetriesMixin:
+ """Retry outcomes stamped on tool rows, and their one-time announcement to the model."""
+
+ TOOL_RETRY_METADATA_KEY = "retried"
+
+ def tool_row_retry(self, session_id: str, tool_call_id: str) -> Optional[Tuple[int, Optional[Dict[str, Any]]]]:
+ """``(row id, recorded retry outcome or None)`` of the newest visible tool row for *tool_call_id* in the
+ session's resume lineage, or ``None`` when no such row is saved."""
+ if not session_id or not tool_call_id:
+ return None
+ lineage = self._resume_lineage_ids(session_id)
+ row = self._read_one(
+ "SELECT id, display_metadata FROM messages WHERE role = 'tool' AND tool_call_id = ? "
+ f"AND session_id IN ({_placeholders(lineage)}){_DISPLAY_ACTIVE_CLAUSE} ORDER BY id DESC LIMIT 1",
+ (tool_call_id, *lineage))
+ if row is None:
+ return None
+ retried = (self._decode_display_metadata(row["display_metadata"]) or {}).get(self.TOOL_RETRY_METADATA_KEY)
+ result = retried.get("result") if isinstance(retried, dict) else None
+ return row["id"], result if isinstance(result, dict) else None
+
+ def set_tool_row_retry(self, row_id: int, outcome: Dict[str, Any]) -> None:
+ """Record *outcome* as the retry of tool row *row_id*, not yet announced to the model."""
+ def _do(conn):
+ row = conn.execute("SELECT display_metadata FROM messages WHERE id = ?", (row_id,)).fetchone()
+ if row is None:
+ return
+ meta = self._decode_display_metadata(row[0]) or {}
+ meta[self.TOOL_RETRY_METADATA_KEY] = {"result": outcome, "announced": False}
+ conn.execute(_SET_DISPLAY_META_SQL, (self._encode_display_metadata(meta), row_id))
+ self._execute_write(_do)
+
+ def take_unannounced_tool_retries(self, session_id: str) -> List[Dict[str, Any]]:
+ """``{result, tool_name}`` for each retry the model has not heard about yet, marked announced."""
+ if not session_id:
+ return []
+ lineage = self._resume_lineage_ids(session_id)
+ key = self.TOOL_RETRY_METADATA_KEY
+ def _do(conn):
+ pending = []
+ for row in conn.execute("SELECT id, tool_name, display_metadata FROM messages "
+ f"WHERE session_id IN ({_placeholders(lineage)}){_DISPLAY_ACTIVE_CLAUSE} "
+ f"AND {_sql_json_extract('display_metadata', '$.' + key)} IS NOT NULL ORDER BY id",
+ tuple(lineage)).fetchall():
+ meta = self._decode_display_metadata(row["display_metadata"]) or {}
+ retried = meta.get(key)
+ if not isinstance(retried, dict) or retried.get("announced") or not isinstance(retried.get("result"), dict):
+ continue
+ retried["announced"] = True
+ conn.execute(_SET_DISPLAY_META_SQL, (self._encode_display_metadata(meta), row["id"]))
+ pending.append({"result": retried["result"], "tool_name": row["tool_name"] or "tool"})
+ return pending
+ return self._execute_write(_do)
diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.py
index 84794935c16..68525e5232f 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -1,6 +1,7 @@
"""Session lifecycle contracts (``tui_gateway/methods_session.py``): create / resume / activate /
close, the live-session snapshot those share, history + compression + undo, mid-turn corrections,
listing/browsing stored rows, spawn-tree snapshots, event replay and the stateless one-shot LLM call.
+``session.start_chat`` lives in ``tui_gateway/methods_start_chat.py``.
"""
from __future__ import annotations
@@ -759,3 +760,43 @@ class LlmOneshotResult(Result):
method("llm.oneshot", params=LlmOneshotParams, result=LlmOneshotResult,
doc="Stateless one-shot LLM completion (titles, ideas) on the session's or the task backend.")
+
+
+# ── start_chat ────────────────────────────────────────────────────────────────────────────────
+
+
+class StartChatArgs(Params):
+ """The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``)."""
+
+ message: str
+ title: str | None = None
+ profile: str | None = None
+
+
+class SessionStartChatParams(SessionParams):
+ """``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only)."""
+
+ tool_call_id: str
+ args: StartChatArgs
+
+
+class StartChatStatus(WireEnum):
+ started = "started"
+ rejected = "rejected"
+
+
+class SessionStartChatResult(Result):
+ """``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same
+ arguments may succeed on another try (``retryable``). A call already retried returns that retry's result."""
+
+ status: StartChatStatus
+ session_id: str | None = None
+ profile: str | None = None
+ title: str | None = None
+ message: str | None = None
+ reason: str | None = None
+ retryable: bool | None = None
+
+
+method("session.start_chat", params=SessionStartChatParams, result=SessionStartChatResult,
+ doc="Run a start_chat request again from the session that made it (the handoff card's Retry).")
diff --git a/tui_gateway/methods_start_chat.py b/tui_gateway/methods_start_chat.py
new file mode 100644
index 00000000000..89062df4bb2
--- /dev/null
+++ b/tui_gateway/methods_start_chat.py
@@ -0,0 +1,64 @@
+"""``session.start_chat``: the handoff card's Retry of a rejected start_chat call, and the next-turn note that tells
+the model about it.
+
+Bodies are rebound onto server.py's globals at install time (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+import json
+import threading
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+method = _registry.method
+_profile_scoped = _registry.profile_scoped
+
+# Two clicks (two windows) must not both find the call unretried and start two chats.
+_start_chat_retry_lock = threading.Lock()
+
+
+@method("session.start_chat")
+@_profile_scoped
+def _(rid, params: dict) -> dict:
+ from tui_gateway.start_chat import _rejected, start_chat
+ session, err = _sess_nowait(params, rid)
+ if err:
+ return err
+ tool_call_id = str(params.get("tool_call_id") or "")
+ if not tool_call_id:
+ return _err(rid, 4002, "tool_call_id is required")
+ # A running turn owns its own retries (the setup skill retries a profile rejection itself).
+ if session.get("running"):
+ return _ok(rid, json.loads(_rejected("This chat is still working; retry when its turn ends.", retryable=True)))
+ with _start_chat_retry_lock, _session_db(session) as db:
+ found = None if db is None else db.tool_row_retry(str(session.get("session_key") or ""), tool_call_id)
+ if found is None:
+ return _err(rid, 4004, "no saved start_chat result for that tool_call_id")
+ row_id, retried = found
+ if retried is not None:
+ return _ok(rid, retried)
+ outcome = json.loads(start_chat(params.get("args") or {}, params["session_id"]))
+ if outcome["status"] == "started":
+ db.set_tool_row_retry(row_id, outcome)
+ return _ok(rid, outcome)
+
+
+def _pending_tool_retry_notes(session: dict) -> str:
+ """Note block for card retries since the last turn (model input only, announced once), or ""."""
+ session_key = str(session.get("session_key") or "")
+ if not session_key:
+ return ""
+ try:
+ with _session_db(session) as db:
+ pending = [] if db is None else db.take_unannounced_tool_retries(session_key)
+ except Exception:
+ logger.debug("Failed to read pending tool retries", exc_info=True)
+ return ""
+ return "\n".join(
+ f"[The user pressed Retry on your rejected {entry['tool_name']} call. {entry['result'].get('message') or ''}]"
+ for entry in pending)
+
+
+def register(server) -> None:
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index b7e373ee11c..d35ec8f854f 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -716,12 +716,13 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images
from agent.notification_presentation import event_presentation_muted
if not event_presentation_muted("message.delta", sid):
st.tts_queue, st.thinking_started = _start_turn_voice()
- # Per-turn API-message notes: barge mid-speech, reactions, HUD surface (per-turn state
+ # Per-turn API-message notes: barge mid-speech, reactions, card retries, HUD surface (per-turn state
# that must not touch the byte-stable system prompt).
from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted
if take_speech_interrupted():
run_message = _prepend_note(run_message, SPEECH_INTERRUPTED_NOTE)
run_message = _prepend_note(run_message, _pending_reaction_notes(session))
+ run_message = _prepend_note(run_message, _pending_tool_retry_notes(session))
return prompt, _prepend_note(run_message, _hud_surface_note(session)), cols, streamer
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 1f63de2c762..5554c19b019 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -3615,7 +3615,7 @@ from . import ( # noqa: E402
methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
methods_display as _methods_display, methods_display_watch as _methods_display_watch,
methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n,
- methods_shared_metrics as _methods_shared_metrics)
+ methods_shared_metrics as _methods_shared_metrics, methods_start_chat as _methods_start_chat)
for _m in (
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
@@ -3627,6 +3627,6 @@ for _m in (
_methods_bot_relay, _prompt_turn, _billing_view, _methods_projects, _methods_session_foreign,
_methods_session_control, _methods_subagents, _methods_vault, _methods_free_tier, _methods_connectors,
_methods_connectors_account, _methods_display, _methods_display_watch, _methods_onboarding,
- _methods_i18n, _methods_shared_metrics):
+ _methods_i18n, _methods_shared_metrics, _methods_start_chat):
_m.register(sys.modules[__name__])
del _m
diff --git a/tui_gateway/start_chat.py b/tui_gateway/start_chat.py
index 6a25e934c25..85476e65b4a 100644
--- a/tui_gateway/start_chat.py
+++ b/tui_gateway/start_chat.py
@@ -4,11 +4,12 @@ from pathlib import Path
TITLE_LIMIT = 40
-def _rejected(reason: str) -> str:
- return json.dumps({"status": "rejected", "reason": reason})
+def _rejected(reason: str, retryable: bool = False) -> str:
+ """``retryable``: the same arguments may start the chat on another try (the handoff card's Retry)."""
+ return json.dumps({"status": "rejected", "reason": reason, "retryable": retryable})
-def start_chat(args: dict) -> str:
+def start_chat(args: dict, caller_id: str | None = None) -> str:
from agent.onboarding import PROFILE_BUILD_FLAG, mark_seen
from gateway.session_context import get_session_env
from hermes_cli.profiles import SETUP_PROFILE_MARKER
@@ -17,7 +18,7 @@ def start_chat(args: dict) -> str:
from tui_gateway import server
from tui_gateway.transport import bind_transport, reset_transport
- caller = server._sessions.get(get_session_env("HERMES_UI_SESSION_ID", ""))
+ caller = server._sessions.get(get_session_env("HERMES_UI_SESSION_ID", "") if caller_id is None else caller_id)
if caller is None:
return _rejected("start_chat works only from a chat in the Hermes desktop app.")
caller_home = Path(caller.get("profile_home") or server._hermes_home)
@@ -39,13 +40,13 @@ def start_chat(args: dict) -> str:
created = server._create_session(
None, {"profile": profile or "", "source": caller.get("source"), "title": title})
if "error" in created:
- return _rejected(created["error"]["message"])
+ return _rejected(created["error"]["message"], retryable=True)
result = created["result"]
mark_seen(target_home / "config.yaml", PROFILE_BUILD_FLAG)
submitted = server._methods["prompt.submit"](None, {"session_id": result["session_id"], "text": message})
if "error" in submitted:
server._methods["session.close"](None, {"session_id": result["session_id"]})
- return _rejected(submitted["error"]["message"])
+ return _rejected(submitted["error"]["message"], retryable=True)
finally:
reset_transport(token)
if (caller_home / SETUP_PROFILE_MARKER).is_file() and target_home.resolve() != caller_home.resolve():