Skip to content

The agent that grows with you

refactor(tui): split canonical session controls, compress staleness and SessionPanel guard

Tekniume8b1a7fae246
diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.ts
index c5fd4afca47..ff47920029a 100644
--- a/ui-tui/src/app/slash/canonicalSessionControls.ts
+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts
@@ -107,6 +107,85 @@ export async function mutateCanonicalSession(
return { result, expectedGeneration: params.expected_generation as number }
}
+type CanonicalControlResult = NonNullable<Awaited<ReturnType<typeof mutateCanonicalSession>>>['result']
+
+function isSupersededControl(
+ operation: 'model' | 'branch' | 'compress',
+ result: CanonicalControlResult,
+ expectedGeneration: number,
+ ctx: SlashRunCtx
+) {
+ const current = getUiState().info
+
+ return (
+ operation !== 'branch' &&
+ (current?.execution_epoch !== ctx.ui.info?.execution_epoch ||
+ (current?.execution_generation ?? 0) > (result.execution_generation ?? expectedGeneration))
+ )
+}
+
+function applyBranchResult(result: CanonicalControlResult, arg: string, ctx: SlashRunCtx) {
+ if (!result.branched_session_id) {
+ throw new Error('invalid response: branch')
+ }
+
+ ctx.session.resumeById(result.branched_session_id)
+ ctx.transcript.sys(`branched → ${arg || result.branched_session_id}`)
+}
+
+function applyModelResult(result: CanonicalControlResult, ctx: SlashRunCtx) {
+ if (!result.model) {
+ throw new Error('invalid response: model switch')
+ }
+
+ patchUiState(state => ({
+ ...state,
+ info: {
+ ...state.info,
+ model: result.model,
+ execution_generation: Math.max(state.info?.execution_generation ?? 0, result.execution_generation ?? 0),
+ skills: state.info?.skills ?? {},
+ tools: state.info?.tools ?? {}
+ }
+ }))
+ ctx.transcript.sys(`model → ${result.model}`)
+}
+
+async function applyCompressResult(gw: MutationGateway, sid: string, result: CanonicalControlResult, ctx: SlashRunCtx) {
+ const before = getUiState()
+ const snapshot = asRpcResult(await gw.request('session.resume', { session_id: sid }))
+
+ if (ctx.stale() || getUiState().info !== before.info || getUiState().busy !== before.busy) {
+ return
+ }
+
+ if (!snapshot || !Array.isArray(snapshot.messages)) {
+ throw new Error('invalid response: compressed transcript')
+ }
+
+ const info = { ...before.info, ...snapshot.info }
+
+ if (
+ info.execution_epoch !== before.info?.execution_epoch ||
+ (info.execution_generation ?? -1) < (result.execution_generation ?? 0)
+ ) {
+ throw new Error('compressed transcript is stale; reopen the session')
+ }
+
+ ctx.transcript.setHistoryItems([introMsg(info), ...toTranscriptMessages(snapshot.messages)])
+ patchUiState({ info })
+ // The authority's report (headline, token line, note), as the native /compress prints it.
+ const summary = result.summary as { headline?: string; noop?: boolean; note?: string; token_line?: string } | null
+
+ ctx.transcript.sys(summary?.headline ? `${summary.noop ? '' : '✓ '}${summary.headline}` : '✓ transcript compressed')
+
+ for (const line of [summary?.token_line, summary?.note]) {
+ if (line) {
+ ctx.transcript.sys(` ${line}`)
+ }
+ }
+}
+
export async function runCanonicalSessionControl(
operation: 'model' | 'branch' | 'compress',
arg: string,
@@ -131,75 +210,19 @@ export async function runCanonicalSessionControl(
return
}
- const current = getUiState().info
-
- if (
- operation !== 'branch' &&
- (current?.execution_epoch !== ctx.ui.info?.execution_epoch ||
- (current?.execution_generation ?? 0) > (result.execution_generation ?? expectedGeneration))
- ) {
+ if (isSupersededControl(operation, result, expectedGeneration, ctx)) {
return
}
if (operation === 'branch') {
- if (!result.branched_session_id) {
- throw new Error('invalid response: branch')
- }
-
- ctx.session.resumeById(result.branched_session_id)
- ctx.transcript.sys(`branched → ${arg || result.branched_session_id}`)
+ applyBranchResult(result, arg, ctx)
} else if (operation === 'model') {
- if (!result.model) {
- throw new Error('invalid response: model switch')
- }
-
- patchUiState(state => ({
- ...state,
- info: {
- ...state.info,
- model: result.model,
- execution_generation: Math.max(state.info?.execution_generation ?? 0, result.execution_generation ?? 0),
- skills: state.info?.skills ?? {},
- tools: state.info?.tools ?? {}
- }
- }))
- ctx.transcript.sys(`model → ${result.model}`)
+ applyModelResult(result, ctx)
} else if (result.status === 'preview') {
// `--preview` is a read-only report; nothing to re-hydrate.
ctx.transcript.sys((result.lines as string[]).join('\n'))
} else {
- const before = getUiState()
- const snapshot = asRpcResult(await gw.request('session.resume', { session_id: ctx.sid }))
-
- if (ctx.stale() || getUiState().info !== before.info || getUiState().busy !== before.busy) {
- return
- }
-
- if (!snapshot || !Array.isArray(snapshot.messages)) {
- throw new Error('invalid response: compressed transcript')
- }
-
- const info = { ...before.info, ...snapshot.info }
-
- if (
- info.execution_epoch !== before.info?.execution_epoch ||
- (info.execution_generation ?? -1) < (result.execution_generation ?? 0)
- ) {
- throw new Error('compressed transcript is stale; reopen the session')
- }
-
- ctx.transcript.setHistoryItems([introMsg(info), ...toTranscriptMessages(snapshot.messages)])
- patchUiState({ info })
- // The authority's report (headline, token line, note), as the native /compress prints it.
- const summary = result.summary as { headline?: string; noop?: boolean; note?: string; token_line?: string } | null
-
- ctx.transcript.sys(summary?.headline ? `${summary.noop ? '' : '✓ '}${summary.headline}` : '✓ transcript compressed')
-
- for (const line of [summary?.token_line, summary?.note]) {
- if (line) {
- ctx.transcript.sys(` ${line}`)
- }
- }
+ await applyCompressResult(gw, ctx.sid, result, ctx)
}
} catch (error) {
ctx.guardedErr(error)
diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.ts
index 72957abc03c..7a721834b78 100644
--- a/ui-tui/src/app/slash/commands/session.ts
+++ b/ui-tui/src/app/slash/commands/session.ts
@@ -21,12 +21,35 @@ import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '
import { patchOverlayState } from '../../overlayStore.js'
import { getUiState, patchUiState } from '../../uiStore.js'
import { runCanonicalSessionControl } from '../canonicalSessionControls.js'
-import type { SlashCommand } from '../types.js'
+import type { SlashCommand, SlashRunCtx } from '../types.js'
const TUI_SESSION_MODEL_RE = new RegExp(`(?:^|\\s)${TUI_SESSION_MODEL_FLAG}(?:\\s|$)`)
const REASONING_SESSION_FLAGS = new Set(['--session'])
const REASONING_GLOBAL_FLAGS = new Set(['--global'])
+const COMPRESS_AUTHORITY_KEYS = [
+ 'stored_session_id',
+ 'execution_epoch',
+ 'execution_generation',
+ 'execution_state',
+ 'running'
+] as const
+
+// Compression is not attachment: a delayed reply cannot replace a
+// newer turn/owner, nor replace its transcript with an old snapshot.
+function isStaleCompressReply(r: SessionCompressResponse, current: ReturnType<typeof getUiState>, ctx: SlashRunCtx) {
+ if (current.busy !== ctx.ui.busy || COMPRESS_AUTHORITY_KEYS.some(key => current.info?.[key] !== ctx.ui.info?.[key])) {
+ return true
+ }
+
+ return (
+ current.info?.execution_generation !== undefined &&
+ (r.info?.execution_epoch !== current.info.execution_epoch ||
+ !Number.isSafeInteger(r.info?.execution_generation) ||
+ (r.info?.execution_generation ?? -1) < current.info.execution_generation)
+ )
+}
+
type FastModeWord = 'fast' | 'normal' | 'ultrafast'
// `config.get/set fast` answer fast | ultrafast | normal (auto/cold windows read as normal here).
@@ -271,26 +294,7 @@ export const sessionCommands: SlashCommand[] = [
ctx.guarded<SessionCompressResponse>(r => {
const current = getUiState()
- const authorityKeys = [
- 'stored_session_id',
- 'execution_epoch',
- 'execution_generation',
- 'execution_state',
- 'running'
- ] as const
-
- // Compression is not attachment: a delayed reply cannot replace a
- // newer turn/owner, nor replace its transcript with an old snapshot.
- if (current.busy !== ctx.ui.busy || authorityKeys.some(key => current.info?.[key] !== ctx.ui.info?.[key])) {
- return
- }
-
- if (
- current.info?.execution_generation !== undefined &&
- (r.info?.execution_epoch !== current.info.execution_epoch ||
- !Number.isSafeInteger(r.info?.execution_generation) ||
- (r.info?.execution_generation ?? -1) < current.info.execution_generation)
- ) {
+ if (isStaleCompressReply(r, current, ctx)) {
return
}
diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsx
index 7f08f3e3529..cddfd2e612e 100644
--- a/ui-tui/src/components/branding.tsx
+++ b/ui-tui/src/components/branding.tsx
@@ -256,13 +256,20 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {
// The canonical authority intentionally returns a narrow metadata snapshot.
// Do not invent tool/skill inventories or crash while rendering that session.
if (!info.skills || !info.tools) {
- return <Box flexDirection="column">
- <Text><Text color={t.color.sessionLabel}>Session: </Text><Text color={t.color.sessionBorder}>{sid}</Text></Text>
- <Text color={t.color.muted}>Tool and skill inventory is not exposed by this runtime.</Text></Box>
+ return (
+ <Box flexDirection="column">
+ <Text>
+ <Text color={t.color.sessionLabel}>Session: </Text>
+ <Text color={t.color.sessionBorder}>{sid}</Text>
+ </Text>
+ <Text color={t.color.muted}>Tool and skill inventory is not exposed by this runtime.</Text>
+ </Box>
+ )
}
// ── Collapsible skills section ──
- const skills = info.skills ?? {}
+ // Non-null here: the narrow-snapshot guard above returned when either is missing.
+ const skills = info.skills
const skillEntries = Object.entries(skills).sort()
const skillsTotal = flat(skills).length
const skillsCatCount = skillEntries.length
@@ -289,7 +296,7 @@ export function SessionPanel({ info, maxWidth, sid, t }: SessionPanelProps) {
}
// ── Collapsible tools section ──
- const tools = info.tools ?? {}
+ const tools = info.tools
const toolEntries = Object.entries(tools).sort()
const toolsTotal = flat(tools).length