Skip to content

The agent that grows with you

refactor(tui): extract submit, paste and new-session helpers under code-health caps

Teknium9c7f0ef5ddd7
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index c20f4ebb390..3dcddbf35ab 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -59,6 +59,219 @@ function takeVoiceTurn(submitText: string): boolean {
return voice
}
+interface SubmitPromptOpts {
+ attachments?: Array<{ path: string; mime: string }>
+ skipDetectDrop?: boolean
+ destination?: SubmissionDestination
+ queueItem?: QueueItem
+ behindTurn?: boolean
+}
+
+type PendingOwner = ReturnType<typeof pendingInputOwner>
+
+function beginOwnedTurn(
+ deps: SubmitPromptDeps,
+ text: string,
+ displayOverride: string | undefined,
+ displayText: string,
+ show: boolean
+): void {
+ turnController.clearStatusTimer()
+ deps.setLastUserMsg(text)
+
+ if (show) {
+ deps.appendMessage({ role: 'user', text: displayOverride || displayText })
+ }
+
+ patchUiState({ busy: true, status: 'running…' })
+ turnController.bufRef = ''
+ turnController.interrupted = false
+}
+
+function prepareQueueItem(
+ item: QueueItem,
+ submitText: string,
+ opts: SubmitPromptOpts,
+ ownsTurn: () => boolean,
+ show: boolean
+): void {
+ item.preparedText ??= submitText
+
+ // Busy controls have no deduplication receipt: never replay after an ambiguous reply.
+ if (item.controlMethod) {
+ item.legacyAttempted = true
+ }
+
+ item.attachments ??= opts.attachments?.map(attachment => ({ ...attachment }))
+
+ if (opts.behindTurn) {
+ item.queued = true
+ }
+
+ if (ownsTurn() && show) {
+ markBubbleShown(item.submissionId)
+ }
+
+ savePendingInput(item)
+}
+
+function submitParams(
+ sid: string,
+ item: QueueItem | undefined,
+ submitText: string,
+ attachments: SubmitPromptOpts['attachments']
+) {
+ return {
+ session_id: sid,
+ text: item?.preparedText ?? submitText,
+ ...((item?.attachments ?? attachments)?.length ? { attachments: item?.attachments ?? attachments } : {}),
+ ...(item?.controlMethod ? { execution_generation: item.executionGeneration } : {}),
+ ...(item && !item.controlMethod ? { submission_id: item.submissionId, queued: item.queued !== false } : {}),
+ // A busy correction (steer/redirect) is not a turn: it never claims the voice route.
+ ...(!item?.controlMethod && takeVoiceTurn(submitText) && { voice_turn: true })
+ }
+}
+
+function settleControlReply(
+ item: QueueItem,
+ r: PromptSubmitResponse,
+ deps: SubmitPromptDeps,
+ focused: () => boolean
+): void {
+ const control = r as PromptSubmitResponse & { execution_generation?: number }
+
+ const accepted =
+ control.execution_generation === item.executionGeneration && ['queued', 'redirected'].includes(control.status ?? '')
+
+ item.settle?.(accepted)
+
+ if (focused()) {
+ deps.sys(accepted ? `correction ${control.status}` : 'correction rejected — input retained')
+ }
+}
+
+interface AdmissionContext {
+ deps: SubmitPromptDeps
+ destination: SubmissionDestination
+ focused: () => boolean
+ owner: PendingOwner
+ sid: string
+}
+
+function settleAdmissionReply(item: QueueItem, r: PromptSubmitResponse, ctx: AdmissionContext): void {
+ const { deps, destination, focused } = ctx
+
+ const accepted =
+ (r?.input_id ?? r?.admission_id) === item.submissionId &&
+ Boolean(destination.storedSid) &&
+ r?.target_session_id === destination.storedSid &&
+ r?.target_profile_home === destination.profileHome &&
+ ['queued', 'started', 'terminal', 'unknown'].includes(r?.status ?? '')
+
+ item.settle?.(accepted)
+
+ // A replay receipt ends this admission, not necessarily the current
+ // execution. Refresh the same live attachment without its transcript.
+ if (accepted && focused() && ['terminal', 'unknown'].includes(r.status ?? '')) {
+ refreshExecutionStatus(ctx)
+ }
+
+ if (!accepted && focused()) {
+ deps.sys('admission not confirmed — input retained; use Alt+K to retry with the same identity')
+ patchUiState({ status: 'admission unconfirmed' })
+ }
+}
+
+function refreshExecutionStatus({ deps, focused, owner, sid }: AdmissionContext): void {
+ const observed = getUiState().info
+
+ void deps.gw
+ .request<SessionActivateResponse>('session.activate', { session_id: sid, omit_messages: true })
+ .then(snapshot => {
+ const current = getUiState().info
+ const info = snapshot.info
+
+ // Push lifecycle events (including same-generation completion)
+ // win over an in-flight snapshot; attachment changes win too.
+ if (
+ !focused() ||
+ current !== observed ||
+ snapshot.session_id !== sid ||
+ (snapshot.session_key || info?.stored_session_id) !== owner.storedSid ||
+ typeof snapshot.running !== 'boolean' ||
+ (current?.execution_generation !== undefined &&
+ (info?.execution_epoch !== current.execution_epoch ||
+ !Number.isSafeInteger(info?.execution_generation) ||
+ (info?.execution_generation ?? -1) < current.execution_generation))
+ ) {
+ return
+ }
+
+ patchUiState({
+ busy: snapshot.running,
+ status: snapshot.running ? 'running…' : 'ready',
+ info: current && {
+ ...current,
+ execution_epoch: info?.execution_epoch ?? current.execution_epoch,
+ execution_generation: info?.execution_generation ?? current.execution_generation,
+ running: snapshot.running
+ }
+ })
+ })
+ .catch((error: Error) => {
+ if (focused()) {
+ deps.sys(`execution status unconfirmed: ${error.message}`)
+ }
+ })
+}
+
+async function submitLegacy(
+ item: QueueItem,
+ sid: string,
+ submitText: string,
+ deps: SubmitPromptDeps,
+ focused: () => boolean
+): Promise<void> {
+ if (focused()) {
+ deps.sys('durable admission unavailable for this session — using legacy delivery')
+ }
+
+ try {
+ item.legacyAttempted = true
+ savePendingInput(item)
+
+ const r = await deps.gw.request<PromptSubmitResponse>('prompt.submit', {
+ session_id: sid,
+ text: item.preparedText ?? submitText,
+ queued: item.queued !== false
+ })
+
+ const accepted = Boolean(
+ r?.voice_stopped || ['streaming', 'queued', 'steered', 'redirected'].includes(r?.status ?? '')
+ )
+
+ item.settle?.(accepted)
+
+ if (focused()) {
+ if (r?.voice_stopped) {
+ patchUiState({ busy: false, status: 'ready' })
+ } else if (!accepted) {
+ deps.sys('legacy delivery unconfirmed — input retained; check the session before sending a new input')
+ patchUiState({ status: 'delivery unconfirmed' })
+ }
+ }
+ } catch (error) {
+ item.settle?.(false)
+
+ if (focused()) {
+ deps.sys(
+ `legacy delivery unconfirmed: ${error instanceof Error ? error.message : String(error)} — input retained; check the session before sending a new input`
+ )
+ patchUiState({ status: 'delivery unconfirmed' })
+ }
+ }
+}
+
// Submit a ready prompt (already resolved to be neither a slash command nor a
// shell escape, with a live session). Pulled out of useSubmission so the
// synchronous-busy invariant above is unit-testable without React test infra.
@@ -71,7 +284,7 @@ export function submitPrompt(
deps: SubmitPromptDeps,
showUserMessage = true,
displayOverride?: string,
- opts: { attachments?: Array<{ path: string; mime: string }>; skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem; behindTurn?: boolean } = {}
+ opts: SubmitPromptOpts = {}
): void {
const destination = opts.destination ?? captureDestination()
const owner = pendingInputOwner(opts.queueItem?.ownerDestination ?? destination)
@@ -105,111 +318,39 @@ export function submitPrompt(
const startSubmit = (displayText: string, submitText: string, show = true) => {
if (ownsTurn()) {
- turnController.clearStatusTimer()
- deps.setLastUserMsg(text)
-
- if (show) {
- deps.appendMessage({ role: 'user', text: displayOverride || displayText })
- }
-
- patchUiState({ busy: true, status: 'running…' })
- turnController.bufRef = ''
- turnController.interrupted = false
+ beginOwnedTurn(deps, text, displayOverride, displayText, show)
}
const item = opts.queueItem
if (item) {
- item.preparedText ??= submitText
-
- // Busy controls have no deduplication receipt: never replay after an ambiguous reply.
- if (item.controlMethod) { item.legacyAttempted = true }
- item.attachments ??= opts.attachments?.map(attachment => ({ ...attachment }))
-
- if (opts.behindTurn) { item.queued = true }
-
- if (ownsTurn() && show) { markBubbleShown(item.submissionId) }
- savePendingInput(item)
+ prepareQueueItem(item, submitText, opts, ownsTurn, show)
}
if (item?.controlMethod && item.attachments?.length) {
item.settle?.(false)
- if (focused()) { deps.sys('busy corrections accept text only — image input retained; submit it with /queue') }
+ if (focused()) {
+ deps.sys('busy corrections accept text only — image input retained; submit it with /queue')
+ }
return
}
deps.gw
- .request<PromptSubmitResponse>(item?.controlMethod ?? 'prompt.submit', {
- session_id: sid,
- text: item?.preparedText ?? submitText,
- ...((item?.attachments ?? opts.attachments)?.length ? { attachments: item?.attachments ?? opts.attachments } : {}),
- ...(item?.controlMethod ? { execution_generation: item.executionGeneration } : {}),
- ...(item && !item.controlMethod ? { submission_id: item.submissionId, queued: item.queued !== false } : {}),
- // A busy correction (steer/redirect) is not a turn: it never claims the voice route.
- ...(!item?.controlMethod && takeVoiceTurn(submitText) && { voice_turn: true })
- })
+ .request<PromptSubmitResponse>(
+ item?.controlMethod ?? 'prompt.submit',
+ submitParams(sid, item, submitText, opts.attachments)
+ )
.then(r => {
if (item?.controlMethod) {
- const control = r as PromptSubmitResponse & { execution_generation?: number }
-
- const accepted = control.execution_generation === item.executionGeneration &&
- ['queued', 'redirected'].includes(control.status ?? '')
-
- item.settle?.(accepted)
-
- if (focused()) { deps.sys(accepted ? `correction ${control.status}` : 'correction rejected — input retained') }
+ settleControlReply(item, r, deps, focused)
return
}
if (item) {
- const accepted =
- (r?.input_id ?? r?.admission_id) === item.submissionId &&
- Boolean(destination.storedSid) &&
- r?.target_session_id === destination.storedSid &&
- r?.target_profile_home === destination.profileHome &&
- ['queued', 'started', 'terminal', 'unknown'].includes(r?.status ?? '')
-
- item.settle?.(accepted)
-
- // A replay receipt ends this admission, not necessarily the current
- // execution. Refresh the same live attachment without its transcript.
- if (accepted && focused() && ['terminal', 'unknown'].includes(r.status ?? '')) {
- const observed = getUiState().info
-
- void deps.gw.request<SessionActivateResponse>('session.activate', { session_id: sid, omit_messages: true })
- .then(snapshot => {
- const current = getUiState().info
- const info = snapshot.info
-
- // Push lifecycle events (including same-generation completion)
- // win over an in-flight snapshot; attachment changes win too.
- if (!focused() || current !== observed || snapshot.session_id !== sid ||
- (snapshot.session_key || info?.stored_session_id) !== owner.storedSid ||
- typeof snapshot.running !== 'boolean' ||
- (current?.execution_generation !== undefined &&
- (info?.execution_epoch !== current.execution_epoch ||
- !Number.isSafeInteger(info?.execution_generation) ||
- (info?.execution_generation ?? -1) < current.execution_generation))) {
- return
- }
-
- patchUiState({ busy: snapshot.running, status: snapshot.running ? 'running…' : 'ready',
- info: current && { ...current, execution_epoch: info?.execution_epoch ?? current.execution_epoch,
- execution_generation: info?.execution_generation ?? current.execution_generation,
- running: snapshot.running } })
- })
- .catch((error: Error) => {
- if (focused()) { deps.sys(`execution status unconfirmed: ${error.message}`) }
- })
- }
-
- if (!accepted && focused()) {
- deps.sys('admission not confirmed — input retained; use Alt+K to retry with the same identity')
- patchUiState({ status: 'admission unconfirmed' })
- }
+ settleAdmissionReply(item, r, { deps, destination, focused, owner, sid })
}
// The gateway consumed a typed voice stop phrase server-side (voice
@@ -227,36 +368,7 @@ export function submitPrompt(
const preAdmissionRefusal = e.code === 4094 || (e.code === 4000 && /submission_id/.test(e.message ?? ''))
if (item && preAdmissionRefusal && !deps.gw.isCanonical && !item.attachments?.length) {
- if (focused()) {deps.sys('durable admission unavailable for this session — using legacy delivery')}
-
- try {
- item.legacyAttempted = true
- savePendingInput(item)
-
- const r = await deps.gw.request<PromptSubmitResponse>('prompt.submit', {
- session_id: sid,
- text: item.preparedText ?? submitText,
- queued: item.queued !== false
- })
-
- const accepted = Boolean(r?.voice_stopped || ['streaming', 'queued', 'steered', 'redirected'].includes(r?.status ?? ''))
- item.settle?.(accepted)
-
- if (focused()) {
- if (r?.voice_stopped) {patchUiState({ busy: false, status: 'ready' })}
- else if (!accepted) {
- deps.sys('legacy delivery unconfirmed — input retained; check the session before sending a new input')
- patchUiState({ status: 'delivery unconfirmed' })
- }
- }
- } catch (error) {
- item.settle?.(false)
-
- if (focused()) {
- deps.sys(`legacy delivery unconfirmed: ${error instanceof Error ? error.message : String(error)} — input retained; check the session before sending a new input`)
- patchUiState({ status: 'delivery unconfirmed' })
- }
- }
+ await submitLegacy(item, sid, submitText, deps, focused)
return
}
@@ -315,19 +427,26 @@ export function submitPrompt(
}
if (deps.gw.isCanonical) {
- if (/^(?:["']?(?:[/.~]|[A-Za-z]:[/\\])|file:\/\/)/.test(text) && /\.(?:png|jpe?g|gif|webp)(?:["']?)(?:\s|$)/i.test(text)) {
- void stageImagePath(text, deps.gw, destination).then(image => {
- opts.attachments = [{ path: image.path, mime: image.mime }]
- startSubmit(text, image.remainder || 'What do you see in this image?', showUserMessage)
- }).catch((error: Error) => {
- opts.queueItem?.settle?.(false)
+ if (
+ /^(?:["']?(?:[/.~]|[A-Za-z]:[/\\])|file:\/\/)/.test(text) &&
+ /\.(?:png|jpe?g|gif|webp)(?:["']?)(?:\s|$)/i.test(text)
+ ) {
+ void stageImagePath(text, deps.gw, destination)
+ .then(image => {
+ opts.attachments = [{ path: image.path, mime: image.mime }]
+ startSubmit(text, image.remainder || 'What do you see in this image?', showUserMessage)
+ })
+ .catch((error: Error) => {
+ opts.queueItem?.settle?.(false)
- if (focused()) {
- deps.sys(`image not submitted: ${error.message} — input retained`)
+ if (focused()) {
+ deps.sys(`image not submitted: ${error.message} — input retained`)
- if (ownsTurn()) { patchUiState({ busy: false, status: 'image not submitted' }) }
- }
- })
+ if (ownsTurn()) {
+ patchUiState({ busy: false, status: 'image not submitted' })
+ }
+ }
+ })
return
}
diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts
index 05059831ded..e84df251751 100644
--- a/ui-tui/src/app/useComposerState.ts
+++ b/ui-tui/src/app/useComposerState.ts
@@ -66,6 +66,16 @@ function insertAtCursor(value: string, cursor: number, text: string): { cursor:
}
}
+/** Whether a paste crosses the configured line or character collapse threshold. */
+function shouldCollapsePaste(cleanedText: string, lineCount: number): boolean {
+ const pasteCollapseLines = getUiState().pasteCollapseLines
+ const pasteCollapseChars = getUiState().pasteCollapseChars
+ const linesHit = pasteCollapseLines > 0 && lineCount >= pasteCollapseLines
+ const charsHit = pasteCollapseChars > 0 && cleanedText.length >= pasteCollapseChars
+
+ return linesHit || charsHit
+}
+
/**
* Quick client-side heuristic to detect text that looks like a dropped file path.
* When this returns true the composer sends RPC calls to the server for actual
@@ -196,11 +206,20 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
* of `~/shot.png look at this` keeps the caption).
*/
const attachImageToken = useCallback(
- (attached: ImageAttachResponse & { path?: string; mime?: string }, value: string, cursor: number): ComposerPasteResult => {
+ (
+ attached: ImageAttachResponse & { path?: string; mime?: string },
+ value: string,
+ cursor: number
+ ): ComposerPasteResult => {
const index = nextImageIndex(tokensRef.current)
const label = imageToken(index)
- setComposerTokens(prev => trimTokens([...prev, { index, kind: 'image', label, path: attached.path ?? '', ...(attached.mime ? { mime: attached.mime } : {}) }]))
+ setComposerTokens(prev =>
+ trimTokens([
+ ...prev,
+ { index, kind: 'image', label, path: attached.path ?? '', ...(attached.mime ? { mime: attached.mime } : {}) }
+ ])
+ )
const withToken = insertAtCursor(value, cursor, label)
const remainder = attached.remainder?.trim() ?? ''
@@ -277,11 +296,17 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
destination,
revision,
(gw.isCanonical
- ? stageClipboardImage(gw, destination).then(image => image ? { ...image, attached: true } : null)
- : gw.request<ClipboardPasteResponse & { path?: string; mime?: string }>('clipboard.paste', { session_id: sid }))
- .catch((error: Error) => { if (!quiet) { sys(`clipboard image failed: ${error.message}`) }
+ ? stageClipboardImage(gw, destination).then(image => (image ? { ...image, attached: true } : null))
+ : gw.request<ClipboardPasteResponse & { path?: string; mime?: string }>('clipboard.paste', {
+ session_id: sid
+ })
+ ).catch((error: Error) => {
+ if (!quiet) {
+ sys(`clipboard image failed: ${error.message}`)
+ }
- return null }),
+ return null
+ }),
r => {
if (r?.attached) {
return attachImageToken(r, value, cursor)
@@ -315,9 +340,13 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const next = await resolveAttachment<ImageAttachResponse & { path?: string; mime?: string }>(
destination,
revision,
- gw.isCanonical ? stageImagePath(cleanedText, gw, destination)
- : gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path: cleanedText, session_id: sid }),
- attached => attached?.name ? attachImageToken(attached, value, cursor) : null
+ gw.isCanonical
+ ? stageImagePath(cleanedText, gw, destination)
+ : gw.request<ImageAttachResponse & { path?: string }>('image.attach', {
+ path: cleanedText,
+ session_id: sid
+ }),
+ attached => (attached?.name ? attachImageToken(attached, value, cursor) : null)
)
if (next) {
@@ -327,7 +356,9 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
// Fall back to generic file-drop detection below.
}
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {
+ return null
+ }
try {
const dropped = await gw.request<InputDetectDropResponse>('input.detect_drop', {
@@ -335,7 +366,9 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
text: cleanedText
})
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {
+ return null
+ }
if (dropped?.matched && dropped.text) {
return insertAtCursor(value, cursor, dropped.text)
@@ -345,15 +378,13 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
}
}
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {
+ return null
+ }
const lineCount = cleanedText.split('\n').length
- const pasteCollapseLines = getUiState().pasteCollapseLines
- const pasteCollapseChars = getUiState().pasteCollapseChars
- const linesHit = pasteCollapseLines > 0 && lineCount >= pasteCollapseLines
- const charsHit = pasteCollapseChars > 0 && cleanedText.length >= pasteCollapseChars
- if (!linesHit && !charsHit) {
+ if (!shouldCollapsePaste(cleanedText, lineCount)) {
return {
cursor: cursor + cleanedText.length,
value: value.slice(0, cursor) + cleanedText + value.slice(cursor)
@@ -410,7 +441,9 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
})
return readPreferredText.then(async preferredText => {
- if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {return null}
+ if (!(isCurrentDestination(destination) && revision === composerRevision.current)) {
+ return null
+ }
if (isUsableClipboardText(preferredText)) {
return handleResolvedPaste({ bracketed: false, cursor, text: preferredText, value })
@@ -437,7 +470,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
const current = inputRef.current
void attach(current, current.length).then(next => {
- if (next && (isCurrentDestination(destination) && revision === composerRevision.current)) {
+ if (next && isCurrentDestination(destination) && revision === composerRevision.current) {
setInput(next.value)
}
})
@@ -464,16 +497,17 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions
return resolveAttachment<ImageAttachResponse & { path?: string; mime?: string }>(
destination,
revision,
- (gw.isCanonical ? stageImagePath(path, gw, destination)
- : gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid }))
- .catch((e: Error) => {
- if (isCurrentDestination(destination) && revision === composerRevision.current) {
- sys(`error: ${e.message}`)
- }
+ (gw.isCanonical
+ ? stageImagePath(path, gw, destination)
+ : gw.request<ImageAttachResponse & { path?: string }>('image.attach', { path, session_id: sid })
+ ).catch((e: Error) => {
+ if (isCurrentDestination(destination) && revision === composerRevision.current) {
+ sys(`error: ${e.message}`)
+ }
- return null
- }),
- attached => attached?.name ? attachImageToken(attached, value, cursor) : null
+ return null
+ }),
+ attached => (attached?.name ? attachImageToken(attached, value, cursor) : null)
)
}),
[appendAttachment, attachImageToken, gw, resolveAttachment, sys]
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index d8c73f4e381..ba8661292bd 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -59,7 +59,7 @@ import { createSlashHandler } from './createSlashHandler.js'
import { planGatewayRecovery } from './gatewayRecovery.js'
import { applyGoalSnapshot } from './goalStatus.js'
import { getInputSelection } from './inputSelectionStore.js'
-import { type GatewayRpc, type SlashHandler, type StateSetter, type TranscriptRow } from './interfaces.js'
+import { type GatewayRpc, type SlashHandler, type StateSetter, type TranscriptRow, type UiState } from './interfaces.js'
import { $overlayState, capturePromptResponseGuard, hasSensitivePrompt, patchOverlayState } from './overlayStore.js'
import { $goodVibesTick } from './petFlashStore.js'
import { applyProcessSnapshot, type ProcessEntry } from './processRoster.js'
@@ -110,6 +110,22 @@ const statusColorOf = (status: string, t: { error: string; muted: string; ok: st
return t.muted
}
+type SubmitLiteral = (value: string, attachments?: Array<{ path: string; mime: string }>) => void
+
+/** Which transcript detail sections render, derived from the `thinking:tools` layout key. */
+const detailsVisibility = (detailsLayoutKey: string, ui: Pick<UiState, 'detailsModeCommandOverride' | 'sections'>) => {
+ const [thinkingDetailsMode, toolsDetailsMode] = detailsLayoutKey.split(':')
+ const thinkingDetailsVisible = thinkingDetailsMode !== 'hidden'
+ const toolsDetailsVisible = toolsDetailsMode !== 'hidden'
+
+ const historyThinkingExpanded =
+ thinkingDetailsVisible && (ui.detailsModeCommandOverride || ui.sections.thinking === 'expanded')
+
+ const detailsVisible = thinkingDetailsVisible || toolsDetailsVisible
+
+ return { detailsVisible, historyThinkingExpanded, thinkingDetailsVisible, toolsDetailsVisible }
+}
+
export interface PromptLiveSessionOptions {
dispatchSubmission: (full: string, destination: SubmissionDestination) => void
maybeWarn: (value: unknown) => void
@@ -263,7 +279,7 @@ export function useMainApp(gw: GatewayClient) {
const onServerRequestRef = useRef<(request: ServerRequest) => boolean>(() => false)
const sysRef = useRef<(text: string) => void>(() => {})
const submitRef = useRef<(value: string) => void>(() => {})
- const submitLiteralRef = useRef<(value: string, attachments?: Array<{ path: string; mime: string }>) => void>(() => {})
+ const submitLiteralRef = useRef<SubmitLiteral>(() => {})
const terminalHintsShownRef = useRef(new Set<string>())
const historyItemsRef = useRef(historyItems)
const lastUserMsgRef = useRef(lastUserMsg)
@@ -391,14 +407,11 @@ export function useMainApp(gw: GatewayClient) {
return `${thinking}:${tools}`
}, [ui.detailsMode, ui.detailsModeCommandOverride, ui.sections])
- const [thinkingDetailsMode, toolsDetailsMode] = detailsLayoutKey.split(':')
- const thinkingDetailsVisible = thinkingDetailsMode !== 'hidden'
- const toolsDetailsVisible = toolsDetailsMode !== 'hidden'
-
- const historyThinkingExpanded =
- thinkingDetailsVisible && (ui.detailsModeCommandOverride || ui.sections.thinking === 'expanded')
+ const { detailsVisible, historyThinkingExpanded, thinkingDetailsVisible, toolsDetailsVisible } = detailsVisibility(
+ detailsLayoutKey,
+ ui
+ )
- const detailsVisible = thinkingDetailsVisible || toolsDetailsVisible
const userPromptWidth = composerPromptWidth(ui.theme.brand.prompt)
const heightCacheKey = `${ui.sid ?? 'draft'}:${cols}:${userPromptWidth}:${ui.compact ? '1' : '0'}:${detailsLayoutKey}`
@@ -826,24 +839,31 @@ export function useMainApp(gw: GatewayClient) {
// path); an empty answer is the skip. A multi-question shared set keeps
// the per-question lock below.
if (clarify.sharedControl && clarify.questions.length === 1) {
- void rpc<SharedControlRespondResponse>('clarify.respond', { answer, ...sharedControlParams(clarify) }).then(r => {
- if (!r || !fresh()) {
- return
- }
-
- const label = toolTrailLabel('clarify')
+ void rpc<SharedControlRespondResponse>('clarify.respond', { answer, ...sharedControlParams(clarify) }).then(
+ r => {
+ if (!r || !fresh()) {
+ return
+ }
- turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
- patchTurnState({ turnTrail: turnController.turnTools })
- turnController.persistedToolLabels.add(label)
- appendMessage({ kind: 'trail', role: 'system', text: '', tools: [buildToolTrailLine('clarify', question.question)] })
- appendMessage({
- role: 'user',
- text: answer.trim() ? clarifyAnswerText(answer, question.multiSelect) : t('session.main.skipped')
- })
- patchUiState({ status: 'running…' })
- patchOverlayState({ clarify: null })
- })
+ const label = toolTrailLabel('clarify')
+
+ turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))
+ patchTurnState({ turnTrail: turnController.turnTools })
+ turnController.persistedToolLabels.add(label)
+ appendMessage({
+ kind: 'trail',
+ role: 'system',
+ text: '',
+ tools: [buildToolTrailLine('clarify', question.question)]
+ })
+ appendMessage({
+ role: 'user',
+ text: answer.trim() ? clarifyAnswerText(answer, question.multiSelect) : t('session.main.skipped')
+ })
+ patchUiState({ status: 'running…' })
+ patchOverlayState({ clarify: null })
+ }
+ )
return
}
@@ -1056,7 +1076,12 @@ export function useMainApp(gw: GatewayClient) {
// fenced to its destination and drains once `gatewayConnected` returns.
if (gw.attached) {
recoverSidRef.current = storedSid ?? recoverSidRef.current
- patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: t('session.status.reconnecting') })
+ patchUiState({
+ busy: false,
+ compacting: false,
+ gatewayConnected: false,
+ status: t('session.status.reconnecting')
+ })
if (state.sid) {
turnController.pushActivity(connectionLostActivity(), 'warn')
@@ -1201,7 +1226,10 @@ export function useMainApp(gw: GatewayClient) {
// Canonical shared controls answer through the generation-bound RPC; a
// legacy server→client request resolves its response frame locally.
if (overlay.approval.sharedControl) {
- return rpc<SharedControlRespondResponse>('approval.respond', { choice, ...sharedControlParams(overlay.approval) }).then(r => r && settle())
+ return rpc<SharedControlRespondResponse>('approval.respond', {
+ choice,
+ ...sharedControlParams(overlay.approval)
+ }).then(r => r && settle())
}
respondWith(overlay.approval.requestId, { choice }, settle)
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 37faa887985..85eae753d1b 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -51,6 +51,21 @@ const statusFromLiveSession = (status?: string, running = false) => {
return running || status === 'working' ? 'running…' : 'ready'
}
+/** Session-start notices, in their original order: credential, config, then the caller's message. */
+const reportNewSessionNotices = (info: null | SessionInfo, msg: string | undefined, sys: (text: string) => void) => {
+ if (info?.credential_warning) {
+ sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)
+ }
+
+ if (info?.config_warning) {
+ sys(`warning: ${info.config_warning}`)
+ }
+
+ if (msg) {
+ sys(msg)
+ }
+}
+
export const writeActiveSessionFile = (sessionId: null | string, file = process.env.HERMES_TUI_ACTIVE_SESSION_FILE) => {
if (!file || !sessionId) {
return
@@ -153,7 +168,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const closeSession = useCallback(
(targetSid?: null | string) =>
- targetSid && !gw.isCanonical ? rpc<SessionCloseResponse>('session.close', { session_id: targetSid }) : Promise.resolve(null),
+ targetSid && !gw.isCanonical
+ ? rpc<SessionCloseResponse>('session.close', { session_id: targetSid })
+ : Promise.resolve(null),
[gw.isCanonical, rpc]
)
@@ -164,35 +181,43 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const canonicalDetachFlights = useRef(new Map<string, Promise<void>>())
const staleAttachments = useRef(new Map<string, { session_id: string; subscription_id: string }>())
- const detachCanonical = useCallback((sessionId?: null | string, subscriptionId?: null | string) => {
- if (!gw.isCanonical || !sessionId || !subscriptionId) {
- return
- }
-
- const detach = () => rpc<SessionDetachResponse>('session.detach', {
- session_id: sessionId,
- subscription_id: subscriptionId
- }).then(result => {
- if (result?.detached && canonicalSubscriptions.current.get(sessionId) === subscriptionId) {
- canonicalSubscriptions.current.delete(sessionId)
+ const detachCanonical = useCallback(
+ (sessionId?: null | string, subscriptionId?: null | string) => {
+ if (!gw.isCanonical || !sessionId || !subscriptionId) {
+ return
}
- }).catch(() => undefined)
- const previous = canonicalDetachFlights.current.get(sessionId)
- const pending = previous ? previous.then(detach) : detach()
+ const detach = () =>
+ rpc<SessionDetachResponse>('session.detach', {
+ session_id: sessionId,
+ subscription_id: subscriptionId
+ })
+ .then(result => {
+ if (result?.detached && canonicalSubscriptions.current.get(sessionId) === subscriptionId) {
+ canonicalSubscriptions.current.delete(sessionId)
+ }
+ })
+ .catch(() => undefined)
- canonicalDetachFlights.current.set(sessionId, pending)
- void pending.then(() => {
- if (canonicalDetachFlights.current.get(sessionId) === pending) {
- canonicalDetachFlights.current.delete(sessionId)
- }
- })
- }, [gw.isCanonical, rpc])
+ const previous = canonicalDetachFlights.current.get(sessionId)
+ const pending = previous ? previous.then(detach) : detach()
+
+ canonicalDetachFlights.current.set(sessionId, pending)
+ void pending.then(() => {
+ if (canonicalDetachFlights.current.get(sessionId) === pending) {
+ canonicalDetachFlights.current.delete(sessionId)
+ }
+ })
+ },
+ [gw.isCanonical, rpc]
+ )
const disposeStaleAttachments = useCallback(() => {
// In-flight attaches can share a token before either result is adopted.
// Decide disposal only after their handlers have adopted (or refused) it.
- if (pendingAttachments.current.size) {return}
+ if (pendingAttachments.current.size) {
+ return
+ }
const stale = [...staleAttachments.current.values()]
staleAttachments.current.clear()
@@ -204,37 +229,50 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
}
}, [detachCanonical])
- const finishAttachment = useCallback((flight: number) => {
- pendingAttachments.current.delete(flight)
- disposeStaleAttachments()
- }, [disposeStaleAttachments])
+ const finishAttachment = useCallback(
+ (flight: number) => {
+ pendingAttachments.current.delete(flight)
+ disposeStaleAttachments()
+ },
+ [disposeStaleAttachments]
+ )
- const discardStaleAttachment = useCallback((result?: null | { session_id: string; subscription_id?: string }) => {
- if (result?.subscription_id) {
- staleAttachments.current.set(JSON.stringify([result.session_id, result.subscription_id]), {
- session_id: result.session_id, subscription_id: result.subscription_id
- })
- }
+ const discardStaleAttachment = useCallback(
+ (result?: null | { session_id: string; subscription_id?: string }) => {
+ if (result?.subscription_id) {
+ staleAttachments.current.set(JSON.stringify([result.session_id, result.subscription_id]), {
+ session_id: result.session_id,
+ subscription_id: result.subscription_id
+ })
+ }
- disposeStaleAttachments()
- }, [disposeStaleAttachments])
+ disposeStaleAttachments()
+ },
+ [disposeStaleAttachments]
+ )
- const adoptAttachment = useCallback((
- result: { session_id: string; subscription_id?: string },
- previousSid?: null | string,
- previousSubscription?: null | string
- ) => {
- if (!gw.isCanonical || !result.subscription_id) {
- return
- }
+ const adoptAttachment = useCallback(
+ (
+ result: { session_id: string; subscription_id?: string },
+ previousSid?: null | string,
+ previousSubscription?: null | string
+ ) => {
+ if (!gw.isCanonical || !result.subscription_id) {
+ return
+ }
- canonicalSubscriptions.current.set(result.session_id, result.subscription_id)
+ canonicalSubscriptions.current.set(result.session_id, result.subscription_id)
- if (previousSid && previousSubscription
- && (previousSid !== result.session_id || previousSubscription !== result.subscription_id)) {
- detachCanonical(previousSid, previousSubscription)
- }
- }, [detachCanonical, gw.isCanonical])
+ if (
+ previousSid &&
+ previousSubscription &&
+ (previousSid !== result.session_id || previousSubscription !== result.subscription_id)
+ ) {
+ detachCanonical(previousSid, previousSubscription)
+ }
+ },
+ [detachCanonical, gw.isCanonical]
+ )
const resetSession = useCallback(() => {
cancelResumeScrollRef.current?.()
@@ -288,7 +326,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
try {
const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})
- if (flight !== attachmentFlight.current) {return null}
+ if (flight !== attachmentFlight.current) {
+ return null
+ }
if (setup?.provider_configured === false) {
panel(setupRequiredTitle(), buildSetupRequiredSections())
@@ -300,16 +340,21 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
if (!keepCurrent) {
await closeSession(previousSid)
- if (flight !== attachmentFlight.current) {return null}
+ if (flight !== attachmentFlight.current) {
+ return null
+ }
}
// HERMES_TUI_CWD is the dashboard-picked workspace: an explicit cwd on
// session.create on both transports, so /new stays in that workspace.
const workspaceCwd = STARTUP_WORKSPACE_CWD ? { cwd: STARTUP_WORKSPACE_CWD } : {}
- const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
- ? { request_id: randomUUID(), ...localCreationOptions(), ...workspaceCwd }
- : { cols: colsRef.current, ...workspaceCwd })
+ const r = await rpc<SessionCreateResponse>(
+ 'session.create',
+ gw.isCanonical
+ ? { request_id: randomUUID(), ...localCreationOptions(), ...workspaceCwd }
+ : { cols: colsRef.current, ...workspaceCwd }
+ )
if (flight !== attachmentFlight.current) {
discardStaleAttachment(r)
@@ -345,17 +390,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
setHistoryItems([introMsg(info)])
}
- if (info?.credential_warning) {
- sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)
- }
-
- if (info?.config_warning) {
- sys(`warning: ${info.config_warning}`)
- }
-
- if (msg) {
- sys(msg)
- }
+ reportNewSessionNotices(info, msg, sys)
if (requestedTitle) {
rpc<SessionTitleResponse>('session.title', {
@@ -390,8 +425,21 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
finishAttachment(flight)
}
},
- [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw.isCanonical, onFreshSessionStarted, panel,
- resetSession, rpc, setHistoryItems, setSessionStartedAt, sys]
+ [
+ adoptAttachment,
+ closeSession,
+ colsRef,
+ discardStaleAttachment,
+ finishAttachment,
+ gw.isCanonical,
+ onFreshSessionStarted,
+ panel,
+ resetSession,
+ rpc,
+ setHistoryItems,
+ setSessionStartedAt,
+ sys
+ ]
)
const newSession = useCallback(
@@ -422,8 +470,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const pendingDetach = canonicalDetachFlights.current.get(id)
const request = pendingDetach
- ? pendingDetach.then(() => flight === attachmentFlight.current
- ? gw.request<SessionActivateResponse>('session.activate', { session_id: id }) : null)
+ ? pendingDetach.then(() =>
+ flight === attachmentFlight.current
+ ? gw.request<SessionActivateResponse>('session.activate', { session_id: id })
+ : null
+ )
: gw.request<SessionActivateResponse>('session.activate', { session_id: id })
request
@@ -476,13 +527,26 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
adoptAttachment(r, previousSid, previousSubscription)
})
.catch((e: Error) => {
- if (flight !== attachmentFlight.current) {return}
+ if (flight !== attachmentFlight.current) {
+ return
+ }
+
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
.finally(() => finishAttachment(flight))
},
- [adoptAttachment, discardStaleAttachment, finishAttachment, gw, resetSession, scrollRef, setHistoryItems, setSessionStartedAt, sys]
+ [
+ adoptAttachment,
+ discardStaleAttachment,
+ finishAttachment,
+ gw,
+ resetSession,
+ scrollRef,
+ setHistoryItems,
+ setSessionStartedAt,
+ sys
+ ]
)
const resumeById = useCallback(
@@ -493,96 +557,119 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const previousSid = current.sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
- const destination = current.sid === id || current.storedSid === id
- ? current : { ...current, sid: id, storedSid: id }
+ const destination =
+ current.sid === id || current.storedSid === id ? current : { ...current, sid: id, storedSid: id }
patchOverlayState({ sessions: false })
patchUiState({ status: t('session.status.resuming') })
- return (gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {})).then(setup => {
- if (flight !== attachmentFlight.current) {return}
+ return (gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {}))
+ .then(setup => {
+ if (flight !== attachmentFlight.current) {
+ return
+ }
- if (setup?.provider_configured === false) {
- panel(setupRequiredTitle(), buildSetupRequiredSections())
- patchUiState({ status: t('session.status.setupRequired') })
+ if (setup?.provider_configured === false) {
+ panel(setupRequiredTitle(), buildSetupRequiredSections())
+ patchUiState({ status: t('session.status.setupRequired') })
- return
- }
+ return
+ }
- const pendingDetach = canonicalDetachFlights.current.get(id)
+ const pendingDetach = canonicalDetachFlights.current.get(id)
- const request = pendingDetach
- ? pendingDetach.then(() => flight === attachmentFlight.current
- ? gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id }) : null)
- : gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })
+ const request = pendingDetach
+ ? pendingDetach.then(() =>
+ flight === attachmentFlight.current
+ ? gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })
+ : null
+ )
+ : gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })
- return request
- .then(raw => {
- const r = asRpcResult<SessionResumeResult>(raw)
+ return request
+ .then(raw => {
+ const r = asRpcResult<SessionResumeResult>(raw)
- if (flight !== attachmentFlight.current) {
- discardStaleAttachment(r)
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
- return
- }
+ return
+ }
- if (!r) {
- sys(`error: ${t('session.common.invalidResponse', 'session.resume')}`)
+ if (!r) {
+ sys(`error: ${t('session.common.invalidResponse', 'session.resume')}`)
- return patchUiState({ status: 'ready' })
- }
+ return patchUiState({ status: 'ready' })
+ }
- const storedSid = r.session_key || r.info?.stored_session_id || r.stored_session_id || r.resumed || id
- const info = r.info ? { ...r.info, stored_session_id: storedSid } : null
-
- const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')
-
- // A successful resume authorizes the requested source → canonical
- // successor mapping; ordinary focus changes never migrate input.
- migratePendingInputs(destination, r.session_id, info?.stored_session_id)
- resetSession()
- setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())
-
- const resumed = [...toTranscriptMessages(r.messages), ...liveSessionInflightMessages(r.inflight)]
-
- setHistoryItems(info ? [introMsg(info), ...resumed] : resumed)
- writeActiveSessionFile(storedSid)
- patchUiState({
- busy: running,
- info,
- sid: r.session_id,
- gatewayConnected: true,
- status: statusFromLiveSession(r.status ?? undefined, running),
- storedSid,
- usage: usageFrom(info)
- })
- gw.hydrateSharedPrompts?.(r)
- hydrateLiveSessionInflight(r.inflight)
+ const storedSid = r.session_key || r.info?.stored_session_id || r.stored_session_id || r.resumed || id
+ const info = r.info ? { ...r.info, stored_session_id: storedSid } : null
+
+ const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')
+
+ // A successful resume authorizes the requested source → canonical
+ // successor mapping; ordinary focus changes never migrate input.
+ migratePendingInputs(destination, r.session_id, info?.stored_session_id)
+ resetSession()
+ setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())
+
+ const resumed = [...toTranscriptMessages(r.messages), ...liveSessionInflightMessages(r.inflight)]
+
+ setHistoryItems(info ? [introMsg(info), ...resumed] : resumed)
+ writeActiveSessionFile(storedSid)
+ patchUiState({
+ busy: running,
+ info,
+ sid: r.session_id,
+ gatewayConnected: true,
+ status: statusFromLiveSession(r.status ?? undefined, running),
+ storedSid,
+ usage: usageFrom(info)
+ })
+ gw.hydrateSharedPrompts?.(r)
+ hydrateLiveSessionInflight(r.inflight)
+
+ if (r.pending_connection) {
+ applyConnectionRequest(r.pending_connection)
+ } else {
+ clearConnectionOperation()
+ }
- if (r.pending_connection) {
- applyConnectionRequest(r.pending_connection)
- } else {
- clearConnectionOperation()
- }
+ cancelResumeScrollRef.current?.()
+ cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
- cancelResumeScrollRef.current?.()
- cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
+ if (previousSid && previousSid !== r.session_id) {
+ void closeSession(previousSid)
+ }
- if (previousSid && previousSid !== r.session_id) {
- void closeSession(previousSid)
- }
+ adoptAttachment(r, previousSid, previousSubscription)
+ })
+ .catch((e: Error) => {
+ if (flight !== attachmentFlight.current) {
+ return
+ }
- adoptAttachment(r, previousSid, previousSubscription)
- })
- .catch((e: Error) => {
- if (flight !== attachmentFlight.current) {return}
- sys(`error: ${e.message}`)
- patchUiState({ status: 'ready' })
- })
- }).finally(() => finishAttachment(flight))
+ sys(`error: ${e.message}`)
+ patchUiState({ status: 'ready' })
+ })
+ })
+ .finally(() => finishAttachment(flight))
},
- [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw, panel, resetSession, rpc, scrollRef,
- setHistoryItems, setSessionStartedAt, sys]
+ [
+ adoptAttachment,
+ closeSession,
+ colsRef,
+ discardStaleAttachment,
+ finishAttachment,
+ gw,
+ panel,
+ resetSession,
+ rpc,
+ scrollRef,
+ setHistoryItems,
+ setSessionStartedAt,
+ sys
+ ]
)
const guardBusySessionSwitch = useCallback(