The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(ui-tui): gate status-rule timers on real occlusion, not $isBlocked
briandevansee8765c9300c
diff --git a/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx b/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsxindex dac6b3c9db2..d683e841aca 100644--- a/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx+++ b/ui-tui/src/__tests__/appChromeBlockedTimers.test.tsx@@ -4,9 +4,14 @@ import { renderSync } from '@hermes/ink'import React from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { OverlayState } from '../app/interfaces.js'+import { GatewayProvider } from '../app/gatewayContext.js'+import type { AppLayoutProps, OverlayState, UiState } from '../app/interfaces.js'import { patchOverlayState, resetOverlayState } from '../app/overlayStore.js'+import { patchUiState, resetUiState } from '../app/uiStore.js'import { StatusRule } from '../components/appChrome.js'+import { AppLayout } from '../components/appLayout.js'+import type { GatewayClient } from '../gatewayClient.js'+import { DEFAULT_VOICE_RECORD_KEY } from '../lib/platform.js'import { stripAnsi } from '../lib/text.js'import { DEFAULT_THEME } from '../theme.js'@@ -29,7 +34,7 @@ const mounted: Array<() => void> = []* Teardown is registered up front so a failing assertion still unmounts the* tree — a leaked instance would keep re-arming timers into the next test.*/-const mount = (props: StatusRuleProps) => {+const mountTree = (tree: React.ReactElement, { interactive = false } = {}) => {const stdout = new PassThrough()const stdin = new PassThrough()const stderr = new PassThrough()@@ -37,13 +42,18 @@ const mount = (props: StatusRuleProps) => {let output = ''Object.assign(stdout, { columns: 120, isTTY: false, rows: 20 })- Object.assign(stdin, { isTTY: false })+ // PromptZone's prompts call `useInput`, which needs raw mode; without it Ink+ // swaps the whole tree for an error panel and stops updating.+ Object.assign(+ stdin,+ interactive ? { isTTY: true, ref: () => {}, setRawMode: () => {}, unref: () => {} } : { isTTY: false }+ )Object.assign(stderr, { isTTY: false })stdout.on('data', chunk => {output += chunk.toString()})- const instance = renderSync(<StatusRule {...props} />, {+ const instance = renderSync(tree, {patchConsole: false,stderr: stderr as NodeJS.WriteStream,stdin: stdin as NodeJS.ReadStream,@@ -64,6 +74,8 @@ const mount = (props: StatusRuleProps) => {}}+const mount = (props: StatusRuleProps) => mountTree(<StatusRule {...props} />)+const idleProps: StatusRuleProps = {bgCount: 0,busy: false,@@ -96,6 +108,97 @@ const armedDelays = (spy: IntervalSpy) => spy.mock.calls.map(call => call[1])const oneSecondTimers = (spy: IntervalSpy) => armedDelays(spy).filter(delay => delay === 1000).length+/** The handlers of every 1s clock armed so far — `() => setNow(Date.now())`. */+const oneSecondTicks = (spy: IntervalSpy) =>+ spy.mock.calls.filter(call => call[1] === 1000).map(call => call[0] as () => void)++// ── AppLayout harness ────────────────────────────────────────────────+//+// teknium1's review of this file was right that mounting StatusRule alone+// proves the store pauses timers but NOT that the overlay in question covers+// the status rule. These props render the real AppLayout so the rule sits in+// its true position relative to PromptZone / FloatingOverlays / the widget+// slot, and the assertions can read what is actually on screen.++const gatewayStub = {+ gw: {+ request: () => new Promise<never>(() => {}),+ send: () => {}+ } as unknown as GatewayClient,+ rpc: (() => new Promise<never>(() => {})) as never+}++const layoutProps: AppLayoutProps = {+ actions: {+ activateLiveSession: () => {},+ answerApproval: () => {},+ answerClarify: () => {},+ answerSecret: () => {},+ answerSudo: () => {},+ clearSelection: () => {},+ closeLiveSession: () => Promise.resolve(null),+ newLiveSession: () => {},+ newPromptSession: () => {},+ onModelSelect: () => {},+ resumeById: () => {},+ setStickyPrompt: () => {}+ },+ composer: {+ cols: 120,+ compIdx: 0,+ completions: [],+ empty: true,+ handleTextPaste: () => null,+ input: '',+ inputBuf: [],+ pagerPageSize: 10,+ queueEditIdx: null,+ queuedDisplay: [],+ submit: () => {},+ updateInput: () => {},+ voiceRecordKey: DEFAULT_VOICE_RECORD_KEY+ },+ mouseTracking: 'off',+ progress: { showProgressArea: false },+ status: {+ cwdLabel: '~/repo',+ goodVibesTick: 0,+ lastTurnEndedAt: T0 - 5_000,+ sessionStartedAt: T0 - 60_000,+ showStickyPrompt: false,+ statusColor: DEFAULT_THEME.color.ok,+ stickyPrompt: '',+ turnStartedAt: null,+ voiceLabel: ''+ },+ transcript: {+ historyItems: [],+ scrollRef: { current: null },+ virtualHistory: {+ bottomSpacer: 0,+ end: 0,+ measureRef: () => () => {},+ offsets: [],+ start: 0,+ topSpacer: 0+ },+ virtualRows: []+ }+}++/** Mount the real AppLayout with the given overlay + ui state applied first. */+const mountLayout = (overlay: Partial<OverlayState> = {}, ui: Partial<UiState> = {}) => {+ patchUiState({ sessionTitle: 'test', sid: 'sid-1', status: 'ready', ...ui })+ patchOverlayState(overlay)++ return mountTree(+ <GatewayProvider value={gatewayStub}>+ <AppLayout {...layoutProps} />+ </GatewayProvider>,+ { interactive: true }+ )+}+// Give React's scheduler a turn so a store-driven re-render (and the effect// re-arm that follows it) lands before we assert.const flush = () => new Promise(resolve => setTimeout(resolve, 20))@@ -105,6 +208,7 @@ let nowSpy: ReturnType<typeof vi.spyOn<typeof Date, 'now'>>beforeEach(() => {resetOverlayState()+ resetUiState()nowSpy = vi.spyOn(Date, 'now').mockReturnValue(T0)intervalSpy = vi.spyOn(globalThis, 'setInterval')})@@ -117,16 +221,17 @@ afterEach(() => {intervalSpy.mockRestore()nowSpy.mockRestore()resetOverlayState()+ resetUiState()})-describe('status-chrome timers under a blocking overlay', () => {- it('arms the one-second SessionDuration + IdleSince clocks when nothing is blocking', () => {+describe('status-chrome timers under an occluding overlay', () => {+ it('arms the one-second SessionDuration + IdleSince clocks when nothing covers the rule', () => {mount(idleProps)expect(oneSecondTimers(intervalSpy)).toBe(2)})- it('arms no timer at all when a blocking overlay is already open', () => {+ it('arms no timer at all when an occluding overlay is already open', () => {patchOverlayState({ modelPicker: true })mount(idleProps)@@ -134,7 +239,7 @@ describe('status-chrome timers under a blocking overlay', () => {expect(oneSecondTimers(intervalSpy)).toBe(0)})- it('arms the FaceTicker glyph/verb/clock trio mid-turn when nothing is blocking', () => {+ it('arms the FaceTicker glyph/verb/clock trio mid-turn when nothing covers the rule', () => {mount(busyProps)// kaomoji cadence for the glyph + verb rotation, plus the elapsed clock.@@ -142,8 +247,8 @@ describe('status-chrome timers under a blocking overlay', () => {expect(oneSecondTimers(intervalSpy)).toBeGreaterThan(0)})- it('arms no FaceTicker timer mid-turn while a blocking overlay is open', () => {- patchOverlayState({ sudo: { requestId: 'sudo-1' } })+ it('arms no FaceTicker timer mid-turn while the modal widget slot is open', () => {+ patchOverlayState({ widget: { appId: 'demo', state: null } })mount(busyProps)@@ -151,7 +256,30 @@ describe('status-chrome timers under a blocking overlay', () => {expect(oneSecondTimers(intervalSpy)).toBe(0)})- it('re-syncs the elapsed read-outs from the wall clock on unblock instead of resuming stale', async () => {+ it('keeps the FaceTicker running mid-turn under a flow-layout sudo prompt', () => {+ // `sudo` is in `$isBlocked` but renders in PromptZone's normal flow, so it+ // pushes the rule down rather than covering it — the trio must keep going.+ patchOverlayState({ sudo: { requestId: 'sudo-1' } })++ mount(busyProps)++ expect(armedDelays(intervalSpy)).toContain(2500)+ expect(oneSecondTimers(intervalSpy)).toBeGreaterThan(0)+ })++ it('keeps the clocks running when a floating overlay cannot reach a bottom status rule', () => {+ // FloatingOverlays is `position="absolute" bottom="100%"` inside+ // ComposerPane's relative Box, so it grows UPWARD: it covers the `at="top"`+ // rule and never the `at="bottom"` one.+ patchUiState({ statusBar: 'bottom' })+ patchOverlayState({ modelPicker: true })++ mount(idleProps)++ expect(oneSecondTimers(intervalSpy)).toBe(2)+ })++ it('re-syncs the elapsed read-outs from the wall clock on reveal instead of resuming stale', async () => {// Regression guard for the naive fix: an early `return` that pauses the// interval but never re-seeds `now` leaves SessionDuration and IdleSince// frozen at the instant the overlay opened.@@ -199,7 +327,7 @@ describe('status-chrome timers under a blocking overlay', () => {expect(clearSpy).toHaveBeenCalledWith(handle)}- // … and the blocked re-run arms no replacement (still just the original two).+ // … and the occluded re-run arms no replacement (still just the original two).expect(oneSecondTimers(intervalSpy)).toBe(2)clearSpy.mockRestore()@@ -210,18 +338,35 @@ describe('status-chrome timers under a blocking overlay', () => {// overlay state that no longer exists. Pin the gate to fields the current// OverlayState actually carries so a rename breaks this file loudly.describe('status-chrome timers track the current overlay model', () => {- const blocking: Array<[string, Partial<OverlayState>]> = [- ['agents', { agents: true }],- ['journey', { journey: true }],+ // Everything that genuinely paints over the rule: the modal widget slot,+ // plus the FloatingOverlays set (with the rule at its default `top`).+ const occluding: Array<[string, Partial<OverlayState>]> = [['modelPicker', { modelPicker: true }],['pager', { pager: { lines: ['a'], offset: 0 } }],['petPicker', { petPicker: true }],['pluginsHub', { pluginsHub: true }],['sessions', { sessions: true }],- ['skillsHub', { skillsHub: true }]+ ['skillsHub', { skillsHub: true }],+ ['widget', { widget: { appId: 'demo', state: null } }]]- it.each(blocking)('pauses the status clocks while %s is open', (_name, patch) => {+ // In `$isBlocked` but NOT occluding. `agents` / `journey` unmount the whole+ // ComposerPane subtree, so React's effect cleanup already stops the clocks+ // and gating on them would be dead code; the rest are PromptZone states that+ // render in normal flow and push the rule down without covering it.+ const nonOccluding: Array<[string, Partial<OverlayState>]> = [+ ['agents', { agents: true }],+ ['approval', { approval: { command: 'ls', requestId: 'a-1' } as OverlayState['approval'] }],+ ['billing', { billing: { kind: 'credits' } as OverlayState['billing'] }],+ ['clarify', { clarify: { question: 'which?', requestId: 'c-1' } as OverlayState['clarify'] }],+ ['confirm', { confirm: { onConfirm: () => {}, prompt: 'sure?' } as OverlayState['confirm'] }],+ ['journey', { journey: true }],+ ['secret', { secret: { envVar: 'TOKEN', prompt: 'token?' } as OverlayState['secret'] }],+ ['subscription', { subscription: { kind: 'expired' } as OverlayState['subscription'] }],+ ['sudo', { sudo: { requestId: 'sudo-1' } as OverlayState['sudo'] }]+ ]++ it.each(occluding)('pauses the status clocks while %s covers the rule', (_name, patch) => {patchOverlayState(patch)mount(idleProps)@@ -229,8 +374,16 @@ describe('status-chrome timers track the current overlay model', () => {expect(oneSecondTimers(intervalSpy)).toBe(0)})- it('keeps the clocks running for the non-blocking ambient dock', () => {- // `ambient` is deliberately excluded from $isBlocked — a glanceable dock+ it.each(nonOccluding)('keeps the status clocks running while %s is open', (_name, patch) => {+ patchOverlayState(patch)++ mount(idleProps)++ expect(oneSecondTimers(intervalSpy)).toBe(2)+ })++ it('keeps the clocks running for the non-occluding ambient dock', () => {+ // `ambient` is a glanceable in-flow dock that reserves its own rows and// doesn't cover the status rule, so pausing there would be a regression.patchOverlayState({ ambient: [{ appId: 'clock', state: null }] })@@ -239,3 +392,58 @@ describe('status-chrome timers track the current overlay model', () => {expect(oneSecondTimers(intervalSpy)).toBe(2)})})++// The visibility gate teknium1 asked for: mount the REAL AppLayout so the+// status rule sits in its true position relative to PromptZone (normal flow,+// above ComposerPane) and FloatingOverlays (absolute, growing upward), then+// assert on what is actually on screen rather than on the store alone.+describe('AppLayout status-rule visibility', () => {+ it('keeps the status rule on screen AND its clock advancing under a flow-layout approval prompt', async () => {+ const layout = mountLayout({ approval: { command: 'rm -rf /', requestId: 'a-1' } as OverlayState['approval'] })++ await flush()++ // The rule is genuinely rendered — the approval prompt pushed it, it did+ // not cover it — so freezing its clock would freeze something visible.+ expect(layout.output()).toContain('~/repo')+ expect(layout.output()).toContain('1m 0s')+ expect(oneSecondTimers(intervalSpy)).toBe(2)++ // …and it really advances: drive the armed 1s handlers forward.+ nowSpy.mockReturnValue(T0 + 30_000)++ for (const tick of oneSecondTicks(intervalSpy)) {+ tick()+ }++ await flush()+ await flush()++ expect(layout.output()).toContain('1m 30s')+ })++ it('keeps the status rule on screen AND its clock advancing under a flow-layout sudo prompt', async () => {+ const layout = mountLayout({ sudo: { requestId: 'sudo-1' } as OverlayState['sudo'] })++ await flush()++ expect(layout.output()).toContain('1m 0s')+ expect(oneSecondTimers(intervalSpy)).toBe(2)+ })++ it('arms no clock under a floating model picker while the rule is at the top', async () => {+ mountLayout({ modelPicker: true }, { statusBar: 'top' })++ await flush()++ expect(oneSecondTimers(intervalSpy)).toBe(0)+ })++ it('keeps the clocks armed under a floating model picker while the rule is at the bottom', async () => {+ mountLayout({ modelPicker: true }, { statusBar: 'bottom' })++ await flush()++ expect(oneSecondTimers(intervalSpy)).toBe(2)+ })+})diff --git a/ui-tui/src/app/overlayStore.ts b/ui-tui/src/app/overlayStore.tsindex 4e26099a067..861e86685fe 100644--- a/ui-tui/src/app/overlayStore.ts+++ b/ui-tui/src/app/overlayStore.ts@@ -1,6 +1,7 @@import { atom, computed } from 'nanostores'import type { OverlayState } from './interfaces.js'+import { $uiState } from './uiStore.js'const buildOverlayState = (): OverlayState => ({agents: false,@@ -65,6 +66,60 @@ export const $isBlocked = computed())+/**+ * Does an open overlay actually PAINT OVER the status rule?+ *+ * Deliberately NOT `$isBlocked`. That aggregate answers a different+ * question — "is text input suspended" — and `appLayout` uses it only to hide+ * the input rows (`appLayout.tsx:384`). `StatusRulePane` is rendered OUTSIDE+ * that guard (`appLayout.tsx:365` for `at="top"`, `:449` for `at="bottom"`),+ * so most `$isBlocked` fields leave the rule fully visible.+ *+ * Occluding (included here):+ *+ * - `widget` — the modal widget slot renders at viewport level+ * (`ActiveWidgetSlot`, `sdk/host.tsx:209`, outside the ComposerPane+ * subtree) so it can anchor the full-screen absolute `Overlay`+ * (`components/overlay.tsx`) against the whole terminal.+ * - The FloatingOverlays set — `modelPicker`, `pager`, `petPicker`,+ * `sessions`, `skillsHub`, `pluginsHub` — but ONLY when the rule sits at+ * the top. That panel is `position="absolute" bottom="100%"` inside+ * ComposerPane's relative Box (`appOverlays.tsx:387`), so it grows UPWARD+ * over the `at="top"` rule and never reaches the `at="bottom"` one.+ *+ * NOT occluding (deliberately excluded):+ *+ * - The PromptZone flow states — `approval`, `billing`, `subscription`,+ * `confirm`, `clarify`, `sudo`, `secret` (`appOverlays.tsx:58-162`). They+ * render in NORMAL FLOW above ComposerPane (`appLayout.tsx:553-568`): they+ * push content down, they do not cover it. The rule stays on screen and+ * its clock must keep running.+ * - `agents` and `journey`. They unmount the entire ComposerPane subtree+ * (`appLayout.tsx:553`), so `StatusRule` unmounts with it and React's own+ * effect cleanup clears the intervals. Gating on them would be dead code.+ * - `ambient` — a glanceable in-flow dock that reserves its own rows.+ * - Composer completions. They share the FloatingOverlays grid and do+ * occlude, but they are a render prop rather than store state and they+ * change on every keystroke; re-arming a 1s interval per character would+ * restart the countdown each time and starve the tick outright — strictly+ * worse than the churn this gate removes.+ *+ * `statusBar: 'off'` needs no branch: `StatusRulePane` returns null for both+ * slots, so the timers are never mounted in the first place.+ */+export const $isStatusRuleOccluded = computed([$overlayState, $uiState], (overlay, ui) =>+ Boolean(+ overlay.widget ||+ (ui.statusBar === 'top' &&+ (overlay.modelPicker ||+ overlay.pager ||+ overlay.petPicker ||+ overlay.pluginsHub ||+ overlay.sessions ||+ overlay.skillsHub))+ )+)+export const getOverlayState = () => $overlayState.get()export const patchOverlayState = (next: Partial<OverlayState> | ((state: OverlayState) => OverlayState)) =>diff --git a/ui-tui/src/components/appChrome.tsx b/ui-tui/src/components/appChrome.tsxindex 5a61d36a386..1ff100f6d13 100644--- a/ui-tui/src/components/appChrome.tsx+++ b/ui-tui/src/components/appChrome.tsx@@ -5,7 +5,7 @@ import unicodeSpinners from 'unicode-animations'import { $delegationState } from '../app/delegationStore.js'import type { BatteryInfo, IndicatorStyle, Notice } from '../app/interfaces.js'-import { $isBlocked } from '../app/overlayStore.js'+import { $isStatusRuleOccluded } from '../app/overlayStore.js'import { useTurnSelector } from '../app/turnStore.js'import { DEV_CREDITS_MODE } from '../config/env.js'import { FACES } from '../content/faces.js'@@ -123,7 +123,7 @@ function FaceTicker({ color, startedAt, style }: { color: string; startedAt?: nuconst [tick, setTick] = useState(() => Math.floor(Math.random() * 1000))const [verbTick, setVerbTick] = useState(() => Math.floor(Math.random() * VERBS.length))const [now, setNow] = useState(() => Date.now())- const isBlocked = useStore($isBlocked)+ const isOccluded = useStore($isStatusRuleOccluded)// Pre-compute cadence + verb-visibility for the active style so an// `/indicator` switch re-arms the interval (and skips the verb timer@@ -132,13 +132,14 @@ function FaceTicker({ color, startedAt, style }: { color: string; startedAt?: nuconst { intervalMs, showVerb } = renderIndicator(style, 0)useEffect(() => {- // A blocking overlay (approval, model picker, pager, …) is painted over- // the status rule, so every tick below is a re-render nobody can see —- // in an Ink TUI that churn reads as the dialog tearing. Arm nothing- // while blocked. The effect re-runs on unblock and re-seeds `now` from- // the wall clock, so the elapsed read-out resumes live rather than- // frozen at the moment the overlay opened.- if (isBlocked) {+ // An overlay is painted OVER the status rule (the modal widget slot, or a+ // floating panel growing up over the top rule), so every tick below is a+ // re-render nobody can see — in an Ink TUI that churn reads as the dialog+ // tearing. Arm nothing while occluded. The effect re-runs when the rule+ // is revealed again and re-seeds `now` from the wall clock, so the elapsed+ // read-out resumes live rather than frozen at the moment it was covered.+ // See `$isStatusRuleOccluded` for why this is NOT `$isBlocked`.+ if (isOccluded) {return}@@ -158,7 +159,7 @@ function FaceTicker({ color, startedAt, style }: { color: string; startedAt?: nuclearInterval(verb)}}- }, [intervalMs, isBlocked, showVerb])+ }, [intervalMs, isOccluded, showVerb])const { frame } = renderIndicator(style, tick)const verb = VERBS[verbTick % VERBS.length] ?? ''@@ -374,13 +375,13 @@ function SpawnHud({ t }: { t: Theme }) {function SessionDuration({ startedAt }: { startedAt: number }) {const [now, setNow] = useState(() => Date.now())- const isBlocked = useStore($isBlocked)+ const isOccluded = useStore($isStatusRuleOccluded)useEffect(() => {- // Paused while a blocking overlay covers the status rule — see+ // Paused only while an overlay actually covers the status rule — see// FaceTicker. The `setNow` below already re-seeds from the wall clock- // on every re-arm, so it doubles as the unblock catch-up.- if (isBlocked) {+ // on every re-arm, so it doubles as the reveal catch-up.+ if (isOccluded) {return}@@ -388,7 +389,7 @@ function SessionDuration({ startedAt }: { startedAt: number }) {const id = setInterval(() => setNow(Date.now()), 1000)return () => clearInterval(id)- }, [isBlocked, startedAt])+ }, [isOccluded, startedAt])return fmtDuration(now - startedAt)}@@ -397,13 +398,13 @@ function IdleSince({ endedAt }: { endedAt: number }) {// Time since the last final agent response. Re-ticks every second like// SessionDuration so the read-out stays live while the session idles.const [now, setNow] = useState(() => Date.now())- const isBlocked = useStore($isBlocked)+ const isOccluded = useStore($isStatusRuleOccluded)useEffect(() => {- // Paused while a blocking overlay covers the status rule — see- // FaceTicker. The `setNow` below re-seeds from the wall clock on- // unblock so the idle read-out is not frozen when the overlay closes.- if (isBlocked) {+ // Paused only while an overlay actually covers the status rule — see+ // FaceTicker. The `setNow` below re-seeds from the wall clock on reveal+ // so the idle read-out is not frozen when the overlay closes.+ if (isOccluded) {return}@@ -411,7 +412,7 @@ function IdleSince({ endedAt }: { endedAt: number }) {const id = setInterval(() => setNow(Date.now()), 1000)return () => clearInterval(id)- }, [endedAt, isBlocked])+ }, [endedAt, isOccluded])return `✓ ${fmtDuration(now - endedAt)}`}