Skip to content

The agent that grows with you

feat(tui): standing /loop row with a live countdown above the live-work dock

Teknium2add194aa7a9
diff --git a/ui-tui/src/__tests__/loopBar.test.tsx b/ui-tui/src/__tests__/loopBar.test.tsx
new file mode 100644
index 00000000000..ada0418963f
--- /dev/null
+++ b/ui-tui/src/__tests__/loopBar.test.tsx
@@ -0,0 +1,66 @@
+import { PassThrough } from 'node:stream'
+
+import { renderSync } from '@hermes/ink'
+import type { LoopSnapshot } from '@hermes/shared/gateway-events'
+import React from 'react'
+import stripAnsi from 'strip-ansi'
+import { expect, it } from 'vitest'
+
+import { loopLine } from '../app/loopStatus.js'
+import { LoopBarView } from '../components/loopBar.js'
+import { DEFAULT_THEME } from '../theme.js'
+
+const NOW = 1_800_000_000
+
+const loop = (patch: Partial<LoopSnapshot> = {}): LoopSnapshot => ({
+ awaiting_response: false,
+ created_at: NOW - 600,
+ current_delay: 2700,
+ deferred_by_goal: false,
+ interval_seconds: 2700,
+ last_fired_at: NOW - 60,
+ max_ticks: 0,
+ mode: 'interval',
+ next_due_at: NOW + 45 * 60,
+ prompt: 'check the deploy',
+ status: 'active',
+ ticks_fired: 1,
+ times: 0,
+ until: '',
+ ...patch
+})
+
+const paint = (element: React.ReactElement): string => {
+ const stdout = Object.assign(new PassThrough(), { columns: 80, rows: 10 })
+ const frames: string[] = []
+ stdout.on('data', chunk => frames.push(chunk.toString()))
+
+ const view = renderSync(element, {
+ stdout: stdout as unknown as NodeJS.WriteStream,
+ stdin: new PassThrough() as unknown as NodeJS.ReadStream
+ })
+
+ view.unmount()
+ view.cleanup()
+
+ return stripAnsi(frames.join(''))
+}
+
+it('counts a standing loop down to its next wakeup and hides it once done or cleared', () => {
+ const at = (secondsLater: number) => loopLine(loop(), (NOW + secondsLater) * 1000)?.detail
+
+ expect(at(0)).toBe('every 45m · 1 run · next in 45m')
+ expect(at(15 * 60 - 1)).toBe('every 45m · 1 run · next in 31m')
+ expect(at(45 * 60 - 42)).toBe('every 45m · 1 run · next in 42s')
+ expect(at(45 * 60 + 5)).toBe('every 45m · 1 run · due, waiting for idle')
+ expect(loopLine(loop({ awaiting_response: true }), NOW * 1000)?.detail).toContain('running now')
+ expect(loopLine(loop({ paused_reason: 'user-paused', status: 'paused' }))).toMatchObject({
+ detail: 'user-paused · 1 run',
+ label: 'loop paused'
+ })
+ expect(loopLine(loop({ status: 'done' }))).toBeNull()
+ expect(loopLine(null)).toBeNull()
+
+ const painted = paint(<LoopBarView cols={78} line={loopLine(loop(), NOW * 1000)} t={DEFAULT_THEME} />)
+ expect(painted).toContain('↻ loop · every 45m · 1 run · next in 45m · check the deploy')
+})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 89c552151ed..f826973ffa4 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -42,6 +42,7 @@ import {
} from './gatewayCanonicalEvents.js'
import { applyGoalSnapshot } from './goalStatus.js'
import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'
+import { applyLoopSnapshot } from './loopStatus.js'
import { getOverlayState, patchOverlayState, SENSITIVE_PROMPTS } from './overlayStore.js'
import { markBubbleShown, newlyStartedRows } from './pendingBubbles.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
@@ -1119,6 +1120,7 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
case 'session.control.update':
applyGoalSnapshot(sid, ev.payload?.control.goal ?? null)
+ applyLoopSnapshot(sid, ev.payload?.control.loop ?? null)
return
diff --git a/ui-tui/src/app/loopStatus.ts b/ui-tui/src/app/loopStatus.ts
new file mode 100644
index 00000000000..2b6b4bd3ecc
--- /dev/null
+++ b/ui-tui/src/app/loopStatus.ts
@@ -0,0 +1,115 @@
+import type { LoopSnapshot } from '@hermes/shared/gateway-events'
+import { useStore } from '@nanostores/react'
+import { atom } from 'nanostores'
+import { useEffect, useState } from 'react'
+
+import { $uiState } from './uiStore.js'
+
+// The session's standing /loop, as `session.control.read` / `session.control.update` report it.
+// The gateway publishes on set/pause/resume/stop, when a wakeup fires and when it completes, so the
+// snapshot's `next_due_at` is always the live anchor; the countdown itself is computed here.
+
+export const $loopSnapshot = atom<{ loop: LoopSnapshot | null; sid: string | null }>({ loop: null, sid: null })
+
+export function applyLoopSnapshot(sid: string | null, loop: LoopSnapshot | null = null) {
+ const previous = $loopSnapshot.get()
+
+ if (previous.sid !== sid || JSON.stringify(previous.loop) !== JSON.stringify(loop)) {
+ $loopSnapshot.set({ loop, sid })
+ }
+}
+
+export interface LoopLine {
+ detail: string
+ glyph: string
+ label: string
+ prompt: string
+}
+
+/** Rounded UP: whole minutes (`1h05m`, `44m`) until the last minute, then seconds. Minute steps keep
+ * an idle TUI to one repaint a minute for a long wait. */
+export function countdown(seconds: number): string {
+ const left = Math.max(0, Math.ceil(seconds))
+
+ if (left < 60) {
+ return `${left}s`
+ }
+
+ const minutes = Math.ceil(left / 60)
+ const hours = Math.floor(minutes / 60)
+
+ return hours ? `${hours}h${String(minutes % 60).padStart(2, '0')}m` : `${minutes}m`
+}
+
+const cadence = (loop: LoopSnapshot) => {
+ if (loop.mode === 'self_paced') {
+ return 'self-paced'
+ }
+
+ const s = loop.interval_seconds
+ const every = s % 3600 === 0 ? `${s / 3600}h` : s % 60 === 0 ? `${s / 60}m` : `${s}s`
+
+ return `every ${every}`
+}
+
+/** `↻ loop · every 45m · 2 runs · next in 44m` for an active loop, `⏸ loop paused` with its reason
+ * while held, `null` once it is done or cleared (the transcript carries the verdict). */
+export function loopLine(loop: LoopSnapshot | null, nowMs = Date.now()): LoopLine | null {
+ if (!loop || (loop.status !== 'active' && loop.status !== 'paused')) {
+ return null
+ }
+
+ const runs = loop.times
+ ? `${loop.ticks_fired}/${loop.times} runs`
+ : `${loop.ticks_fired} run${loop.ticks_fired === 1 ? '' : 's'}`
+
+ if (loop.status === 'paused') {
+ const reason = loop.paused_reason ? `${loop.paused_reason} · ` : ''
+
+ return { detail: `${reason}${runs}`, glyph: '⏸', label: 'loop paused', prompt: loop.prompt }
+ }
+
+ const remaining = loop.next_due_at - nowMs / 1000
+
+ const when = loop.awaiting_response
+ ? 'running now'
+ : loop.deferred_by_goal
+ ? 'deferred to the goal'
+ : remaining > 0
+ ? `next in ${countdown(remaining)}`
+ : 'due, waiting for idle'
+
+ return { detail: `${cadence(loop)} · ${runs} · ${when}`, glyph: '↻', label: 'loop', prompt: loop.prompt }
+}
+
+/** The current session's loop line, re-derived every second while a countdown is showing. `loopLine`
+ * only changes text at minute steps (seconds in the last one), and React drops identical strings, so
+ * the bar repaints at that rate, not every second. */
+export function useLoopLine(): LoopLine | null {
+ const snapshot = useStore($loopSnapshot)
+ const { sid } = useStore($uiState)
+ const loop = snapshot.sid === sid ? snapshot.loop : null
+ const ticking = loop?.status === 'active' && !loop.awaiting_response
+ const [line, setLine] = useState(() => loopLine(loop))
+
+ useEffect(() => {
+ const update = () =>
+ setLine(previous => {
+ const next = loopLine(loop)
+
+ return JSON.stringify(previous) === JSON.stringify(next) ? previous : next
+ })
+
+ update()
+
+ if (!ticking) {
+ return
+ }
+
+ const timer = setInterval(update, 1000)
+
+ return () => clearInterval(timer)
+ }, [loop, ticking])
+
+ return line
+}
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index 7a531cdc799..36d187f9560 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -56,6 +56,7 @@ import { applyGoalSnapshot } from './goalStatus.js'
import { getInputSelection } from './inputSelectionStore.js'
import { type GatewayRpc, type SlashHandler, type StateSetter, type TranscriptRow, type UiState } from './interfaces.js'
import { requestLiveSessions } from './liveSessions.js'
+import { applyLoopSnapshot } from './loopStatus.js'
import { $overlayState, capturePromptResponseGuard, hasSensitivePrompt, patchOverlayState } from './overlayStore.js'
import { $goodVibesTick } from './petFlashStore.js'
import { applyProcessSnapshot, type ProcessEntry } from './processRoster.js'
@@ -694,7 +695,8 @@ export function useMainApp(gw: GatewayClient) {
applyAgentSnapshot(ui.sid)
applyProcessSnapshot(ui.sid)
applyGoalSnapshot(ui.sid)
- // Goal state changes only on /goal and after a judged turn, both of which push
+ applyLoopSnapshot(ui.sid)
+ // Goal/loop state changes only on their slash commands, a judged turn or a loop wakeup, all of which push
// `session.control.update`; read it once per session instead of polling state.db.
gw.request<{ control: SessionControlSnapshot }>('session.control.read', { session_id: ui.sid })
.then(raw => {
@@ -702,6 +704,7 @@ export function useMainApp(gw: GatewayClient) {
if (!stopped && result && getUiState().sid === ui.sid) {
applyGoalSnapshot(ui.sid, result.control?.goal ?? null)
+ applyLoopSnapshot(ui.sid, result.control?.loop ?? null)
}
})
.catch(() => {})
diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsx
index cc92dc9f28c..1abd5838245 100644
--- a/ui-tui/src/components/appLayout.tsx
+++ b/ui-tui/src/components/appLayout.tsx
@@ -36,6 +36,7 @@ import { FpsOverlay } from './fpsOverlay.js'
import { GoalBar } from './goalBar.js'
import { HelpHint } from './helpHint.js'
import { Journey } from './journey.js'
+import { LoopBar } from './loopBar.js'
import { MessageLine } from './messageLine.js'
import { PetKitty, PetSprite } from './petSprite.js'
import { QueuedMessages } from './queuedMessages.js'
@@ -414,6 +415,7 @@ const ComposerPane = memo(function ComposerPane({
)}
<GoalBar cols={Math.max(1, composer.cols - 2)} />
+ <LoopBar cols={Math.max(1, composer.cols - 2)} />
<LiveAgentsPanel cols={Math.max(1, composer.cols - 2)} />
<StatusRulePane at="top" composer={composer} nativeMode={nativeMode} status={status} />
<AmbientDock placement="dock-top" />
diff --git a/ui-tui/src/components/loopBar.tsx b/ui-tui/src/components/loopBar.tsx
new file mode 100644
index 00000000000..f29b5e3baad
--- /dev/null
+++ b/ui-tui/src/components/loopBar.tsx
@@ -0,0 +1,31 @@
+import { stringWidth, Text } from '@hermes/ink'
+import { useStore } from '@nanostores/react'
+
+import { type LoopLine, useLoopLine } from '../app/loopStatus.js'
+import { $uiState } from '../app/uiStore.js'
+import { compactPreview } from '../lib/text.js'
+import type { Theme } from '../theme.js'
+
+/** One `↻ loop · every 45m · 2 runs · next in 44m · <prompt>` row above the live-work dock while a
+ * /loop is standing; the countdown ticks down on its own. */
+export function LoopBarView({ cols, line, t }: { cols: number; line: LoopLine | null; t: Theme }) {
+ if (!line) {
+ return null
+ }
+
+ const head = `${line.glyph} ${line.label} · ${line.detail} · `
+
+ return (
+ <Text wrap="truncate-end">
+ <Text color={line.glyph === '↻' ? t.color.accent : t.color.warn}>{`${line.glyph} ${line.label}`}</Text>
+ <Text color={t.color.muted}>{` · ${line.detail} · `}</Text>
+ <Text color={t.color.text}>{compactPreview(line.prompt, Math.max(8, cols - stringWidth(head)))}</Text>
+ </Text>
+ )
+}
+
+export function LoopBar({ cols }: { cols: number }) {
+ const { theme } = useStore($uiState)
+
+ return <LoopBarView cols={cols} line={useLoopLine()} t={theme} />
+}