The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: route Ink session controls through canonical authority
Tekniumbf0b25a90f1f
diff --git a/ui-tui/src/__tests__/canonicalSessionControls.test.ts b/ui-tui/src/__tests__/canonicalSessionControls.test.tsnew file mode 100644index 00000000000..33708c558c7--- /dev/null+++ b/ui-tui/src/__tests__/canonicalSessionControls.test.ts@@ -0,0 +1,147 @@+import { beforeEach, expect, it, vi } from 'vitest'++import { createSlashHandler } from '../app/createSlashHandler.js'+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'++const flush = () => new Promise(resolve => setImmediate(resolve))+const info = { model: 'old', skills: {}, tools: {}, execution_epoch: '1', execution_generation: 4 }++function harness() {+ let compressed = false++ const request = vi.fn(async (method: string, params: any) => {+ if (method === 'session.resume') {+ return {+ session_id: 'owner',+ revision: 8,+ execution_generation: 4,+ info: { ...info, execution_generation: compressed ? 5 : 4 },+ messages: [{ role: 'assistant', text: 'summary' }]+ }+ }++ if (method === 'session.mutate') {+ compressed = params.operation === 'compress'++ return { model: 'picked', branched_session_id: 'child', execution_generation: 5 }+ }++ return { value: params.value ?? 'queue', status: 'queued' }+ })++ const sys = vi.fn()++ const ctx = {+ slashFlightRef: { current: 0 },+ gateway: { gw: { isCanonical: true, request }, rpc: request },+ transcript: { sys, setHistoryItems: vi.fn() },+ local: { maybeWarn: vi.fn() },+ session: { resumeById: vi.fn() },+ composer: { enqueue: vi.fn() }+ }++ return { ctx, request, slash: createSlashHandler(ctx as any) }+}++beforeEach(() => {+ resetUiState()+ patchUiState({ sid: 'owner', info })+})++it('canonical model, branch and compression use generation-fenced owner mutations and hydrate results', async () => {+ const { ctx, request, slash } = harness()++ for (const [command, operation, payload] of [+ ['/model picked --provider custom --tui-session', 'model', { model: 'picked', provider: 'custom' }],+ ['/branch Child name', 'branch', { title: 'Child name' }],+ ['/compress keep context', 'compress', { focus: 'keep context' }]+ ] as const) {+ slash(command)+ await flush()+ expect(request).toHaveBeenCalledWith('session.mutate', {+ session_id: 'owner',+ request_id: expect.any(String),+ expected_revision: 8,+ expected_generation: 4,+ operation,+ payload+ })++ if (operation === 'model') {+ expect(getUiState().info?.execution_generation).toBe(5)+ }+ }++ expect(ctx.session.resumeById).toHaveBeenCalledWith('child')+ expect(ctx.transcript.setHistoryItems).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ role: 'assistant', text: 'summary' })])+ )+ expect(+ request.mock.calls.some(([method]) => ['config.set', 'session.branch', 'session.compress'].includes(method))+ ).toBe(false)+})++it('ambiguous mutations retry the frozen identity while unsupported model scopes never mutate', async () => {+ const { request, slash } = harness()+ request.mockImplementation(async (method: string) => {+ if (method === 'session.resume') {+ return { revision: 8, execution_generation: 4 } as any+ }++ throw new Error('connection lost')+ })+ slash('/branch same')+ await flush()+ slash('/branch same')+ await flush()+ const calls = request.mock.calls.filter(([method]) => method === 'session.mutate')+ expect(calls).toHaveLength(2)+ expect(calls[0]![1]).toEqual(calls[1]![1])+ slash('/model picked --global')+ await flush()+ expect(request.mock.calls.filter(([method]) => method === 'session.mutate')).toHaveLength(2)+})++it('late model or compression replies cannot replace a newer execution snapshot', async () => {+ for (const command of ['/model picked', '/compress']) {+ resetUiState()+ patchUiState({ sid: 'owner', info })+ const { ctx, request, slash } = harness()+ let release!: (value: any) => void+ request.mockImplementation(async (method: string) => {+ if (method === 'session.resume') {+ return { revision: 8, execution_generation: 4, info, messages: [] } as any+ }++ return new Promise(resolve => {+ release = resolve+ })+ })+ slash(command)+ await flush()+ patchUiState({ info: { ...info, model: 'newer', execution_generation: 6 } })+ release({ model: 'picked', execution_generation: 5 })+ await flush()+ expect(getUiState().info).toMatchObject({ model: 'newer', execution_generation: 6 })+ expect(ctx.transcript.setHistoryItems).not.toHaveBeenCalled()+ }+})++it('busy mode is session scoped and steering includes the observed execution generation', async () => {+ patchUiState({ busy: true })+ const { request, slash } = harness()+ slash('/busy steer')+ await flush()+ expect(request).toHaveBeenCalledWith('config.set', { key: 'busy', value: 'steer', session_id: 'owner' })+ expect(getUiState().busyInputMode).toBe('steer')+ slash('/busy status')+ await flush()+ expect(request).toHaveBeenCalledWith('config.get', { key: 'busy', session_id: 'owner' })+ slash('/steer correction')+ await flush()+ expect(request).toHaveBeenCalledWith('session.steer', {+ session_id: 'owner',+ text: 'correction',+ execution_generation: 4+ })+})diff --git a/ui-tui/src/__tests__/canonicalSessionPicker.test.tsx b/ui-tui/src/__tests__/canonicalSessionPicker.test.tsxnew file mode 100644index 00000000000..abc56898b85--- /dev/null+++ b/ui-tui/src/__tests__/canonicalSessionPicker.test.tsx@@ -0,0 +1,79 @@+import { PassThrough } from 'node:stream'++import { renderSync } from '@hermes/ink'+import React from 'react'+import { expect, it, vi } from 'vitest'++import { ActiveSessionSwitcher } from '../components/activeSessionSwitcher.js'+import { DEFAULT_THEME } from '../theme.js'++it('canonical sessions render and select owner rows using only the canonical list', async () => {+ const request = vi.fn(async (method: string) => {+ if (method !== 'session.list') {+ throw new Error('invalid_params')+ }++ return {+ scope: 'live',+ sessions: [+ {+ id: 'owner',+ session_id: 'owner',+ title: 'Owned conversation',+ started_at: 1,+ message_count: 2,+ running: true+ }+ ]+ }+ })++ const stdin = Object.assign(new PassThrough(), { isTTY: true, setRawMode: vi.fn(), ref: vi.fn(), unref: vi.fn() })+ let output = ''+ const stdout = Object.assign(new PassThrough(), { columns: 100, rows: 30, isTTY: false })+ stdout.on('data', chunk => {+ output += chunk.toString()+ })+ const onSelect = vi.fn()++ const instance = renderSync(+ <ActiveSessionSwitcher+ currentSessionId="owner"+ gw={{ isCanonical: true, request } as any}+ onCancel={vi.fn()}+ onClose={vi.fn()}+ onNew={vi.fn()}+ onNewPrompt={vi.fn()}+ onResume={vi.fn()}+ onSelect={onSelect}+ t={DEFAULT_THEME}+ />,+ { stdin: stdin as any, stdout: stdout as any, stderr: new PassThrough() as any, patchConsole: false }+ )++ try {+ await new Promise(resolve => setImmediate(resolve))+ instance.rerender(+ <ActiveSessionSwitcher+ currentSessionId="owner"+ gw={{ isCanonical: true, request } as any}+ onCancel={vi.fn()}+ onClose={vi.fn()}+ onNew={vi.fn()}+ onNewPrompt={vi.fn()}+ onResume={vi.fn()}+ onSelect={onSelect}+ t={DEFAULT_THEME}+ />+ )+ await new Promise(resolve => setImmediate(resolve))+ expect(request.mock.calls.every(([method]) => method === 'session.list')).toBe(true)+ expect(output).toContain('Owned conversation')+ expect(output).toContain('working')+ stdin.write('\r')+ await new Promise(resolve => setImmediate(resolve))+ expect(onSelect).toHaveBeenCalledWith('owner')+ } finally {+ instance.unmount()+ }+})diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.tsnew file mode 100644index 00000000000..eb9353da387--- /dev/null+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts@@ -0,0 +1,174 @@+import { randomUUID } from 'node:crypto'++import { introMsg, toTranscriptMessages } from '../../domain/messages.js'+import { TUI_SESSION_MODEL_FLAG } from '../../domain/slash.js'+import type { GatewayClient } from '../../gatewayClient.js'+import { asRpcResult } from '../../lib/rpc.js'+import { getUiState, patchUiState } from '../uiStore.js'++import type { SlashRunCtx } from './types.js'++// Keep the original CAS tuple after a lost reply. Reissuing the same command+// must query that receipt, not silently authorize another write at a new revision.+const pending = new WeakMap<GatewayClient, Map<string, Record<string, unknown>>>()++function modelPayload(arg: string) {+ const parts = arg.trim().split(/\s+/)+ const model = parts.shift()!+ const payload: Record<string, string> = { model }++ if (model.startsWith('--')) {+ throw new Error('usage: /model <model> [--provider <provider>] [--session]')+ }++ while (parts.length) {+ const flag = parts.shift()!++ if (flag === '--session' || flag === TUI_SESSION_MODEL_FLAG) {+ continue+ }++ if (flag === '--provider' && parts[0] && !parts[0].startsWith('--')) {+ payload.provider = parts.shift()!++ continue+ }++ throw new Error(`unsupported canonical model option: ${flag}`)+ }++ return payload+}++export async function runCanonicalSessionControl(+ operation: 'model' | 'branch' | 'compress',+ arg: string,+ ctx: SlashRunCtx+) {+ const gw = ctx.gateway.gw++ try {+ if (!ctx.sid) {+ throw new Error('no active session')+ }++ const payload =+ operation === 'model' ? modelPayload(arg) : arg ? { [operation === 'branch' ? 'title' : 'focus']: arg } : {}++ let requests = pending.get(gw)++ if (!requests) {+ requests = new Map()+ pending.set(gw, requests)+ }++ const key = JSON.stringify([ctx.sid, operation, payload])+ let params = requests.get(key)++ if (!params) {+ const snapshot = asRpcResult(await gw.request('session.resume', { session_id: ctx.sid }))++ if (ctx.stale()) {+ return+ }++ if (!Number.isSafeInteger(snapshot?.revision) || !Number.isSafeInteger(snapshot?.execution_generation)) {+ throw new Error('session execution identity unavailable; reconnect before editing')+ }++ params = {+ session_id: ctx.sid,+ request_id: randomUUID(),+ expected_revision: snapshot!.revision,+ expected_generation: snapshot!.execution_generation,+ operation,+ payload+ }+ requests.set(key, params)+ }++ let result++ try {+ result = asRpcResult(await gw.request('session.mutate', params))++ if (!result) {+ throw new Error('invalid response: session.mutate')+ }++ requests.delete(key)+ } catch (error) {+ // A structured authority refusal is definitive; transport errors are not.+ if ((error as { data?: { reason?: string } })?.data?.reason) {+ requests.delete(key)+ }++ throw error+ }++ if (ctx.stale()) {+ return+ }++ const current = getUiState().info++ if (+ operation !== 'branch' &&+ (current?.execution_epoch !== ctx.ui.info?.execution_epoch ||+ (current?.execution_generation ?? 0) > (result.execution_generation ?? params.expected_generation))+ ) {+ 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}`)+ } 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}`)+ } 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 })+ ctx.transcript.sys('✓ transcript compressed')+ }+ } catch (error) {+ ctx.guardedErr(error)+ }+}diff --git a/ui-tui/src/app/slash/commands/core.ts b/ui-tui/src/app/slash/commands/core.tsindex 794457a1686..a48241e7a5f 100644--- a/ui-tui/src/app/slash/commands/core.ts+++ b/ui-tui/src/app/slash/commands/core.ts@@ -704,7 +704,13 @@ export const coreCommands: SlashCommand[] = [}ctx.gateway- .rpc<SessionSteerResponse>('session.steer', { session_id: ctx.sid, text: payload })+ .rpc<SessionSteerResponse>('session.steer', {+ session_id: ctx.sid,+ text: payload,+ ...(ctx.gateway.gw.isCanonical && ctx.ui.info?.execution_generation !== undefined+ ? { execution_generation: ctx.ui.info.execution_generation }+ : {})+ }).then(ctx.guarded<SessionSteerResponse>(r => {if (r?.status === 'queued') {diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.tsindex b4f2e5927c8..9a1feefa963 100644--- a/ui-tui/src/app/slash/commands/session.ts+++ b/ui-tui/src/app/slash/commands/session.ts@@ -18,6 +18,7 @@ import { applyConfiguredTuiTheme } from '../../createGatewayEventHandler.js'import { DEFAULT_INDICATOR_STYLE, INDICATOR_STYLES, type IndicatorStyle } from '../../interfaces.js'import { patchOverlayState } from '../../overlayStore.js'import { getUiState, patchUiState } from '../../uiStore.js'+import { runCanonicalSessionControl } from '../canonicalSessionControls.js'import type { SlashCommand } from '../types.js'const USAGE_CTA = 'Run /subscription to change plan · /topup to add to your balance'@@ -136,6 +137,10 @@ export const sessionCommands: SlashCommand[] = [return patchOverlayState({ modelPicker: { refresh: true } })}+ if (ctx.gateway.gw.isCanonical) {+ return runCanonicalSessionControl('model', arg, ctx)+ }+const switchModel = (confirmExpensiveModel = false) =>ctx.gateway.rpc<ConfigSetResponse>('config.set', {@@ -239,6 +244,9 @@ export const sessionCommands: SlashCommand[] = [help: 'compress transcript',name: 'compress',run: (arg, ctx) => {+ if (ctx.gateway.gw.isCanonical) {+ return runCanonicalSessionControl('compress', arg, ctx)+ }ctx.gateway.rpc<SessionCompressResponse>('session.compress', {session_id: ctx.sid,@@ -247,14 +255,17 @@ export const sessionCommands: SlashCommand[] = [.then(ctx.guarded<SessionCompressResponse>(r => {const current = getUiState()- const authorityKeys = ['stored_session_id', 'execution_epoch', 'execution_generation', 'execution_state', 'running'] as const+ 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])- ) {+ if (current.busy !== ctx.ui.busy || authorityKeys.some(key => current.info?.[key] !== ctx.ui.info?.[key])) {return}@@ -317,6 +328,9 @@ export const sessionCommands: SlashCommand[] = [help: 'branch the session',name: 'branch',run: (arg, ctx) => {+ if (ctx.gateway.gw.isCanonical) {+ return runCanonicalSessionControl('branch', arg, ctx)+ }ctx.gateway.rpc<SessionBranchResponse>('session.branch', { name: arg, session_id: ctx.sid }).then(ctx.guarded<SessionBranchResponse>(r => {if (!r.session_id) {@@ -651,7 +665,10 @@ export const sessionCommands: SlashCommand[] = [if (!mode || mode === 'status') {return ctx.gateway- .rpc<ConfigGetValueResponse>('config.get', { key: 'busy' })+ .rpc<ConfigGetValueResponse>('config.get', {+ key: 'busy',+ ...(ctx.gateway.gw.isCanonical ? { session_id: ctx.sid } : {})+ }).then(ctx.guarded<ConfigGetValueResponse>(r => {const current = r.value || 'interrupt'@@ -662,10 +679,18 @@ export const sessionCommands: SlashCommand[] = [}ctx.gateway- .rpc<ConfigSetResponse>('config.set', { key: 'busy', value: mode })+ .rpc<ConfigSetResponse>('config.set', {+ key: 'busy',+ value: mode,+ ...(ctx.gateway.gw.isCanonical ? { session_id: ctx.sid } : {})+ }).then(ctx.guarded<ConfigSetResponse>(r => {const next = r.value || mode++ if (next === 'queue' || next === 'steer' || next === 'interrupt') {+ patchUiState({ busyInputMode: next })+ }ctx.transcript.sys(`busy input mode: ${next}`)}))diff --git a/ui-tui/src/components/activeSessionSwitcher.tsx b/ui-tui/src/components/activeSessionSwitcher.tsxindex beb4683f62e..2fa04b3b3e3 100644--- a/ui-tui/src/components/activeSessionSwitcher.tsx+++ b/ui-tui/src/components/activeSessionSwitcher.tsx@@ -350,11 +350,27 @@ export function ActiveSessionSwitcher({// Fetch independently (allSettled) so a failing session.list can't// wipe the live-session list: live sessions still render and the// resumable history degrades on its own.+ const canonicalList = gw.isCanonical+ ? gw.request<{ scope?: string; sessions?: (SessionListItem & { running?: boolean })[] }>('session.list', {+ limit: 200+ })+ : null+const [liveRes, histRes] = await Promise.allSettled([- gw.request<SessionActiveListResponse>('session.active_list', {- current_session_id: currentSessionId- }),- includeHistory ? gw.request<SessionListResponse>('session.list', { limit: 200 }) : Promise.resolve(null)+ canonicalList+ ? canonicalList.then(value => ({+ sessions: value.sessions?.map(row => ({+ ...row,+ current: row.id === currentSessionId,+ status: row.running ? ('working' as const) : ('idle' as const)+ }))+ }))+ : gw.request<SessionActiveListResponse>('session.active_list', { current_session_id: currentSessionId }),+ canonicalList+ ? Promise.resolve({ sessions: [] })+ : includeHistory+ ? gw.request<SessionListResponse>('session.list', { limit: 200 })+ : Promise.resolve(null)])const r = liveRes.status === 'fulfilled' ? asRpcResult<SessionActiveListResponse>(liveRes.value) : null