Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(console): expire unanswered confirm cards at 30 s, let Claude withdraw its own ask

Dragan Spiridonovbde274f84578
diff --git a/plugins/ruflo-console/hooks/adr-palette.ts b/plugins/ruflo-console/hooks/adr-palette.ts
index 65b521d1d7..f230f50e5e 100644
--- a/plugins/ruflo-console/hooks/adr-palette.ts
+++ b/plugins/ruflo-console/hooks/adr-palette.ts
@@ -19,9 +19,25 @@ const TO: Record<string, AdrStatus> = { 'adr-accept': 'accepted', 'adr-reject':
export function adrPalette(state: State): PaletteEntry[] {
const wired = adrWired(state)
- const why = 'the ADRs page is not wired yet: open the console first'
+ const adr = adrOf(state)
+ // Why an entry has nothing to run, most basic first: no console in this session, the ADR folder not read yet (the page reads it when opened), then the value itself.
+ const blocked = wired === undefined ? 'the console is not running in this session: open it first (console_open adrs)' : !adr.isLoaded ? 'the ADR folder has not been read this session: open the ADRs page first (console_open adrs), then run it again' : null
+ const numbered = (keyword: string) => (value: string): string => {
+ // adr-supersede takes two numbers; every other entry one, written as "3", "0003" or "adr-3".
+ const words = keyword === 'adr-supersede' ? value.trim().split(/\s+/) : [value.trim()]
+ const missing = words.find(word => docFor(word) === undefined)
+
+ const usage = keyword === 'adr-supersede' ? `type two ADR numbers, the old then the new: "${keyword} 1 3"` : `type the ADR number: "${keyword} 3"`
+
+ if (blocked !== null) return blocked
+ if (missing === undefined || (keyword === 'adr-supersede' && words.length !== 2)) return usage
+
+ const number = NUMBER.exec(missing)?.[1]
+
+ return number === undefined ? usage : `no ADR ${Number(number)} in ${adr.dir ?? 'the ADR folder'}`
+ }
const local = (label: string, run: () => void, declared?: NonNullable<ActionSpec['declared']>): ActionSpec | null => (wired === undefined ? null : { label, args: [], expect: label, isReadOnly: true, ...(declared !== undefined && { declared }), run: async () => void run() })
- const text = (keyword: string, make: (value: string) => ActionSpec | null) => ({ kind: 'text' as const, keyword, make: (value: string) => (wired === undefined ? null : make(value)), why: () => why })
+ const text = (keyword: string, make: (value: string) => ActionSpec | null) => ({ kind: 'text' as const, keyword, make: (value: string) => (wired === undefined ? null : make(value)), why: numbered(keyword) })
const docFor = (value: string) => {
const match = NUMBER.exec(value.trim())
@@ -51,7 +67,7 @@ export function adrPalette(state: State): PaletteEntry[] {
return doc === undefined ? null : local(`show ADR ${doc.number}`, () => wired?.actions.select(doc.file))
}),
},
- { id: 'adr-init', group: 'adrs', label: 'initialise ADRs here: create the folder and a first record (asks first, never overwrites)', run: { kind: 'spec', spec: wired === undefined ? null : initSpec(state, wired.host, today()), why: adrOf(state).dir === null ? why : 'this project already has an ADR folder' } },
+ { id: 'adr-init', group: 'adrs', label: 'initialise ADRs here: create the folder and a first record (asks first, never overwrites)', run: { kind: 'spec', spec: wired === undefined ? null : initSpec(state, wired.host, today()), why: blocked ?? 'this project already has an ADR folder' } },
{
id: 'adr-propose',
group: 'adrs',
@@ -62,7 +78,7 @@ export function adrPalette(state: State): PaletteEntry[] {
why: (value: string) => {
const fit = titleFit(value)
- return wired !== undefined && !fit.ok ? fit.message : why
+ return wired !== undefined && !fit.ok ? fit.message : blocked ?? (adr.dir === null ? 'this project has no ADR folder yet: adr-init first' : 'type a title: "adr-propose Use Postgres"')
},
},
},
@@ -83,7 +99,7 @@ export function adrPalette(state: State): PaletteEntry[] {
},
{ id: 'adr-attach', group: 'adrs', label: 'adr-attach <number>: attach an ADR to the active mission (Claude and the swarm are told its decision)', run: text('adr-attach', value => needDoc(value, file => wired?.actions.attach(file, true), 'attach ADR N to the active mission', 'write')) },
{ id: 'adr-detach', group: 'adrs', label: 'adr-detach <number>: detach an ADR from the active mission', run: text('adr-detach', value => needDoc(value, file => wired?.actions.attach(file, false), 'detach ADR N from the active mission', 'write')) },
- { id: 'adr-scope', group: 'adrs', label: 'compare the changed files with the paths in the active mission’s accepted ADRs (paths only)', run: { kind: 'spec', spec: local('compare changed files with the attached ADRs', () => wired?.actions.scope()), why } },
+ { id: 'adr-scope', group: 'adrs', label: 'compare the changed files with the paths in the active mission’s accepted ADRs (paths only)', run: { kind: 'spec', spec: local('compare changed files with the attached ADRs', () => wired?.actions.scope()), why: blocked ?? '' } },
].map(entry => ({ ...entry, label: plain(entry.label, 200) })) as PaletteEntry[]
}
diff --git a/plugins/ruflo-console/hooks/controller.ts b/plugins/ruflo-console/hooks/controller.ts
index c99141292e..bf2d63a96c 100644
--- a/plugins/ruflo-console/hooks/controller.ts
+++ b/plugins/ruflo-console/hooks/controller.ts
@@ -19,7 +19,7 @@ import { markPicture } from './gfx/pictures'
import type { Host } from './host'
import { agentLogs } from './ops'
import { landingRefusal } from './model-tools'
-import { createRunner, type Runner } from './runner'
+import { createRunner, EXPIRY_TIMER, type Runner } from './runner'
import { advance, loadLedger, mcOf } from './mission-control'
import { hasLiveWork } from './mission-list'
import { loadAllowed } from './remember'
@@ -400,8 +400,8 @@ export function createController(state: State, host: Host): Controller {
state.pane.isShown = false
state.pane.isClosedByPerson = true
persist()
- cancel('frames')
- cancel('watch')
+ // A waiting card's expiry timer does not outlive the pane either: past its window it is cleared at the next ask or tool call instead.
+ for (const name of ['frames', 'watch', EXPIRY_TIMER]) cancel(name)
await host.closePane(PANE_ID).catch(() => undefined)
}
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index 9daa845cda..194cbb8d03 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -146,7 +146,8 @@ export async function dispatch(control: Controller, state: State, args: string,
const confirmedAtMs = Date.now()
- await control.runner.confirm()
+ // A typed yes names no card: the runner refuses it while the card is too new or just replaced one (press the card's own Yes then).
+ await control.runner.confirmUnbound()
return { text: xruvAnswer(state, null, confirmedAtMs) ?? labAnswer(state, null, confirmedAtMs) ?? (state.outcome === null ? 'Ran.' : `${state.outcome.ok ? '✓' : '✗'} ${state.outcome.label}: ${state.outcome.detail}${state.outcome.verified === 'yes' ? ' (on disk)' : state.outcome.verified === 'no' ? ' (not on disk yet)' : ''}`) }
case 'agent': {
diff --git a/plugins/ruflo-console/hooks/model-tools.ts b/plugins/ruflo-console/hooks/model-tools.ts
index 0a556fc53c..b36c3514cf 100644
--- a/plugins/ruflo-console/hooks/model-tools.ts
+++ b/plugins/ruflo-console/hooks/model-tools.ts
@@ -15,7 +15,8 @@ import { DEV_FIELDS } from './data/devtools'
import { PROFILES, RIGORS } from './goap'
import { mcOf, setResearch } from './mission-control'
import { RESEARCH_DEPTHS } from './mission-options'
-import { filterPalette, paletteEntries } from './palette'
+import { filterPalette, paletteEntries, WITHDRAW_ID, withdrawHint } from './palette'
+import { isStale } from './runner'
import { hasSecret } from './screen'
import { catalogOf } from './plugin-catalog'
import { pluginNames, settingsOf } from './settings'
@@ -380,6 +381,9 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (state.control.turnCalls > MAX_CALLS_PER_TURN) return refuse(name, `more than ${MAX_CALLS_PER_TURN} console actions in one turn. Summarise for the person and stop.`)
try {
+ // A card past its window never blocks or reads as waiting: it is cleared first, with one event and "expired: ask again" as the last result.
+ if (state.pending !== null && isStale(state.pending)) control.runner.expireStale()
+
if (name === 'console_state') {
say(state, name, 'read the console', 'ok')
control.host.invalidate()
@@ -413,7 +417,7 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (leaksSecret(input.value, value)) return refuse(`set ${field}`, SECRET_REFUSAL)
- if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not change fields until they answer.`)
+ if (state.pending !== null) return refuse(`set ${field}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not change fields until they answer${withdrawHint(state)}.`)
const askedAt = Date.now()
const problem = asModel(state, () => setField(deps, field, value))
@@ -434,12 +438,14 @@ async function answer(name: string, input: Record<string, unknown>, deps: ModelT
if (leaksSecret(input.text, text)) return refuse(`run ${id}`, SECRET_REFUSAL)
- // The person's own waiting action is theirs to answer: never replaced, never cleared.
- if (state.pending !== null) return refuse(`run ${id}`, `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not run another until they answer.`)
+ // The person's own waiting action is theirs to answer: never replaced, never cleared. Claude may take back only its own direct ask (the runner decides).
+ const blocked = id === WITHDRAW_ID ? asModel(state, () => control.runner.withdrawRefusal()) : state.pending === null ? null : `an action is already waiting for the person ("${modelLine(state.pending.label, 80)}"). Do not run another until they answer${withdrawHint(state)}.`
+
+ if (blocked !== null) return refuse(`run ${id}`, id === WITHDRAW_ID ? `not withdrawn: ${modelLine(blocked, 160)}. Nothing changed.` : blocked)
const askedAt = state.outcome?.atMs ?? 0
- if (!asModel(state, () => control.runner.runById(id, text, { exact: true }))) return refuse(`run ${id}`, `no palette entry "${modelLine(id, 40)}" right now. Call console_state for the entries.`)
+ if (!asModel(state, () => control.runner.runById(id, text, { exact: true, direct: true }))) return refuse(`run ${id}`, `no palette entry "${modelLine(id, 40)}" right now. Call console_state for the entries.`)
await control.runner.settled()
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 0f6b317c86..089d88bedb 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -28,13 +28,23 @@ import { VIEWS, type State, type ViewId } from './state'
import { XRUV } from './xruv'
import { VEC, vecSpec, vecWhy } from './vector'
import { selection } from './views/select'
+import { plain } from './data/parse'
export type PaletteRun =
| { kind: 'spec'; spec: ActionSpec | null; why: string }
| { kind: 'view'; view: ViewId }
| { kind: 'drill'; agentId: string }
| { kind: 'text'; keyword: string; make: (text: string) => ActionSpec | null; why?: (text: string) => string }
- | { kind: 'command'; name: 'refresh' | 'help' | 'close' }
+ | { kind: 'command'; name: 'refresh' | 'help' | 'close' | 'withdraw' }
+
+/** The entry Claude uses to take back its own waiting ask; it is listed only while a card Claude raised is waiting. */
+export const WITHDRAW_ID = 'ask-withdraw'
+
+/** A card Claude raised by its own console_run, of the write class: the only kind it may withdraw (the runner also matches the card's id). */
+export const canWithdraw = (state: State): boolean => state.pending?.source === 'claude' && state.pending.origin === 'console_run' && state.pending.kind === 'write'
+
+/** How Claude can stop waiting on its own card, for a refusal's text: withdraw it. Any other card waits for the person or its window. */
+export const withdrawHint = (state: State): string => (canWithdraw(state) ? `, or withdraw your own ask with console_run ${WITHDRAW_ID}` : '')
export type PaletteEntry = { id: string; label: string; group: string; run: PaletteRun }
@@ -192,6 +202,8 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
for (const view of VIEWS) add(`view-${view.id}`, 'views', `go to ${view.label}${view.key === '' ? '' : ` (${view.key})`}`, { kind: 'view', view: view.id })
+ // Claude can take back its own waiting ask (never the person's): a read, it runs nothing and only clears the card.
+ if (canWithdraw(state) && state.pending !== null) add(WITHDRAW_ID, 'console', `withdraw Claude's waiting ask ("${plain(state.pending.label, 60)}"): nothing runs`, { kind: 'command', name: 'withdraw' })
add('refresh', 'console', 'refresh now', { kind: 'command', name: 'refresh' })
add('help', 'console', 'help: keys and commands', { kind: 'command', name: 'help' })
add('close', 'console', 'close the console', { kind: 'command', name: 'close' })
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index 43720c0372..2126b2f12c 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -20,6 +20,18 @@ import { prettyLines } from './result-lines'
export const PENDING_TTL_MS = 30_000
+/** The state.timers key of the expiry timer, so the controller's stop and close cancel it with the rest. */
+export const EXPIRY_TIMER = 'pending-expiry'
+/** A typed Yes (`/ruflo yes`, bound to no card) is refused this soon after Claude raised the card, or after a card left unanswered. */
+export const UNBOUND_FRESH_MS = 3_000
+export const UNBOUND_REPLACED_MS = 10_000
+/** Claude may withdraw at most this many asks per minute, and may not re-ask the same label this soon after withdrawing it. */
+export const WITHDRAW_MAX_PER_MIN = 3
+export const REASK_COOLDOWN_MS = 10_000
+
+/** True when a waiting card has outlived its window: a Yes for it would be refused, so it only blocks the next ask. */
+export const isStale = (pending: Pick<Pending, 'askedAtMs'>, nowMs = Date.now()): boolean => nowMs - pending.askedAtMs >= PENDING_TTL_MS
+
export type RunnerDeps = {
/** A read of the disk that starts after this call. */
freshRead: () => Promise<void>
@@ -35,9 +47,17 @@ export type Runner = {
/** `seen` is the id of the card the person said Yes to: when another card took its place meanwhile, nothing runs and the new card stays (ADR-450 T17). */
confirm: (seen?: number) => Promise<void>
cancel: () => void
+ /** Clears a card left past PENDING_TTL_MS, unrun, with one event and an "expired: ask again" outcome. True when it cleared one. */
+ expireStale: (nowMs?: number) => boolean
+ /** Clears the waiting card only when Claude raised it; the person's own card is never withdrawn. True when it cleared one. */
+ withdraw: () => boolean
+ /** Why Claude may not withdraw the waiting card now, or null when it may. */
+ withdrawRefusal: () => string | null
runEntry: (entry: PaletteEntry, text: string) => void
/** `exact` (the model path, ADR-450 T13) resolves the id as written and never falls back to fuzzy matching. */
- runById: (id: string, text: string, options?: { exact?: boolean }) => boolean
+ runById: (id: string, text: string, options?: { exact?: boolean; direct?: boolean }) => boolean
+ /** A Yes typed with no card id (`/ruflo yes`): refused while the card is too new or just replaced one, else it answers the card waiting now. */
+ confirmUnbound: () => Promise<void>
/** Resolves when the read started last has finished: `/ruflo run` waits on it to answer with what it printed. */
settled: () => Promise<void>
/** Resolves when the last action that brought its own `run` (and is not awaited by `confirm`) has finished: the model tools wait on it, with a limit. */
@@ -49,6 +69,12 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
let asks = 0
let inflight: Promise<void> = Promise.resolve()
let background: Promise<void> = Promise.resolve()
+ // The card Claude raised by its own direct console_run (its id), the only one it may withdraw; set while runById({ direct }) runs.
+ let directCardId: number | null = null
+ let isDirectRun = false
+ // When a card last left with no answer from the person (expired or withdrawn): a typed Yes soon after may be meant for it.
+ let goneUnansweredAtMs = -Infinity
+ const withdrawals: { label: string; atMs: number }[] = []
const say = (label: string, ok: boolean, detail: string, lines?: string[]) => {
state.outcome = { label, ok, verified: 'n/a', detail, atMs: Date.now(), ...(lines !== undefined && { lines }) }
@@ -165,15 +191,76 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
}
+ /** Forgets the waiting card and its expiry timer (kept in state.timers, so closing the console cancels it too). */
+ function clear(): void {
+ state.timers.get(EXPIRY_TIMER)?.cancel()
+ state.timers.delete(EXPIRY_TIMER)
+ directCardId = null
+ pendingSpec = null
+ state.pending = null
+ }
+
+ function expireStale(nowMs = Date.now()): boolean {
+ const pending = state.pending
+
+ if (pending === null || !isStale(pending, nowMs)) return false
+
+ clear()
+ goneUnansweredAtMs = nowMs
+ say(pending.label, false, `expired: ask again. Nobody answered within ${PENDING_TTL_MS / 1000} s, so it did not run`)
+ if (state.outcome !== null) state.outcome.expired = true
+ record(state.events, [{ atMs: nowMs, kind: 'tools', text: `ask for "${plain(pending.label, 60)}" expired after ${PENDING_TTL_MS / 1000} s, not run` }])
+
+ return true
+ }
+
+ /**
+ * Why Claude may not withdraw the waiting card, or null when it may. Only its own direct console_run ask, matched by id, and only of the write class:
+ * a spend, install, network or delete card is one the person must see, and it now leaves by itself at the window. At most a few per minute.
+ */
+ function withdrawRefusal(nowMs = Date.now()): string | null {
+ const pending = state.pending
+
+ if (pending === null) return 'nothing is waiting'
+ if (!state.control.viaModel) return 'only Claude withdraws its own ask; the person answers a card with Yes or No'
+ if (pending.source !== 'claude' || pending.origin !== 'console_run' || pending.id === undefined || pending.id !== directCardId) return 'that card was not raised by your own console_run: only the person answers it'
+ if (pending.kind !== 'write') return `it is a ${pending.kind ?? 'unclassed'} action the person must see; it expires by itself ${PENDING_TTL_MS / 1000} s after the ask`
+ if (withdrawals.filter(entry => nowMs - entry.atMs < 60_000).length >= WITHDRAW_MAX_PER_MIN) return `${WITHDRAW_MAX_PER_MIN} asks were withdrawn in the last minute: leave this one to the person`
+
+ return null
+ }
+
+ function withdraw(): boolean {
+ const pending = state.pending
+ const nowMs = Date.now()
+ const refused = withdrawRefusal(nowMs)
+
+ if (pending === null || refused !== null) {
+ say('withdraw', false, `not withdrawn: ${refused ?? 'nothing is waiting'}`)
+
+ return false
+ }
+
+ clear()
+ goneUnansweredAtMs = nowMs
+ withdrawals.push({ label: pending.label, atMs: nowMs })
+ if (withdrawals.length > 20) withdrawals.shift()
+ say('withdrawn ask', true, `withdrew "${plain(pending.label, 80)}": it did not run`)
+ record(state.events, [{ atMs: nowMs, kind: 'tools', text: `Claude withdrew its ask "${plain(pending.label, 60)}", not run` }])
+
+ return true
+ }
+
function ask(spec: ActionSpec | null, why: string): void {
state.palette.isOpen = false
+ // A card left past its window blocks nothing: it is cleared (and said so) before this ask is looked at.
+ expireStale()
// Where this came from: the page puts the confirm and the answer right after that element. A headless run has no press, so it falls back to the top.
state.origin = state.lastPressed
state.lastPressed = null
if (spec === null) {
- pendingSpec = null
- state.pending = null
+ clear()
say('nothing to do', false, why)
return
@@ -190,6 +277,15 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
return
}
+ // Withdrawing and asking again is not a loop Claude can run: the same ask waits out a cooldown after its withdrawal.
+ const withdrawn = byModel ? withdrawals.find(entry => entry.label === spec.label && Date.now() - entry.atMs < REASK_COOLDOWN_MS) : undefined
+
+ if (withdrawn !== undefined) {
+ say('not queued', false, `Claude withdrew this same ask ${Math.round((Date.now() - withdrawn.atMs) / 1000)} s ago: wait ${REASK_COOLDOWN_MS / 1000} s, or leave it to the person`)
+
+ return
+ }
+
// Claude's ask never replaces what the person has waiting: their Yes would run Claude's action instead of the one they read (ADR-450 T17).
if (byModel && state.pending !== null) {
say('not queued', false, `an action is already waiting for the person ("${plain(state.pending.label, 80)}"): Claude's request was dropped`)
@@ -209,7 +305,9 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
asks += 1
- const pending: Pending = { id: asks, view: state.view, ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
+ // Only an ask raised inside Claude's own console_run call (not one that landed later after a screen, nor a mission follow-up) is Claude's to withdraw.
+ const isDirect = isDirectRun && state.control.viaModel && spec.byModel !== true
+ const pending: Pending = { id: asks, view: state.view, ...(isDirect && { origin: 'console_run' as const }), ...(kind !== null && { rememberKey: kind }), ...(spec.scope !== undefined && { scope: spec.scope }), label: spec.label, args: spec.args, expect: spec.expect, askedAtMs: Date.now(), source: byModel ? 'claude' : 'you', ...(spec.shows !== undefined && { shows: spec.shows }), ...(spec.note !== undefined && { note: spec.note }), ...(spec.declared !== undefined && { declared: spec.declared }) }
// Claude's ask that was screened first lands after every tool call of Claude's returned, so no call is left to gate it: the level and Stop are
// checked now, not as they were when it was raised, and a refused ask is not queued (nothing waits for a Yes the settings no longer allow).
@@ -224,8 +322,13 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
}
+ // Only the person's own press replaces a card here (Claude's ask over a waiting card was dropped above): their typed Yes is for this new card.
+ clear()
pendingSpec = spec
state.pending = pending
+ if (isDirect) directCardId = asks
+ // At the window's end the card is cleared on the console's clock, so it never sits past it blocking every other ask.
+ if (typeof host.after === 'function') state.timers.set(EXPIRY_TIMER, host.after(PENDING_TTL_MS + 250, () => void expireStale()))
host.invalidate()
}
@@ -246,8 +349,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
if (claudes !== null && state.pending !== null) {
const label = state.pending.label
- pendingSpec = null
- state.pending = null
+ clear()
say(label, false, `not run: ${claudes}. Run it from the palette yourself if you want it`)
record(state.events, [{ atMs: Date.now(), kind: 'tools', text: `Claude's card "${plain(label, 60)}" was not run: ${claudes}` }])
@@ -259,8 +361,7 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
const waitedMs = state.pending === null ? 0 : Date.now() - state.pending.askedAtMs
- pendingSpec = null
- state.pending = null
+ clear()
if (spec === null || !isFresh || state.isActing) {
if (spec !== null && !isFresh) {
@@ -277,9 +378,29 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
await execute(spec)
}
+ async function confirmUnbound(): Promise<void> {
+ const pending = state.pending
+ const nowMs = Date.now()
+
+ if (pending === null) return confirm()
+
+ // A Yes typed with no card id could be meant for the card that was there a moment ago: a card Claude has only just raised, or one that took the
+ // place of a card that left unanswered, is answered on the card itself (its button or y), which names the card it answers.
+ const isNewClaude = pending.source === 'claude' && nowMs - pending.askedAtMs < UNBOUND_FRESH_MS
+ const isReplacement = nowMs - goneUnansweredAtMs < UNBOUND_REPLACED_MS
+
+ if (isNewClaude || isReplacement) {
+ say(pending.label, false, `not run: ${isNewClaude ? 'Claude raised this card a moment ago' : 'this card replaced one that left unanswered a moment ago'}, so a typed yes may be meant for another. Read it and press Yes on the card itself`)
+ record(state.events, [{ atMs: nowMs, kind: 'tools', text: `a typed yes did not run "${plain(pending.label, 60)}": the card was new or had just replaced another` }])
+
+ return
+ }
+
+ return confirm(pending.id)
+ }
+
function cancel(): void {
- pendingSpec = null
- state.pending = null
+ clear()
host.invalidate()
}
@@ -314,7 +435,8 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
deps.drill(entry.run.agentId)
break
case 'command':
- deps.command(entry.run.name)
+ if (entry.run.name === 'withdraw') withdraw()
+ else deps.command(entry.run.name)
break
}
@@ -322,16 +444,22 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
}
/** A palette entry by its id (`/ruflo run <id> [text]`, an approval's button): false when there is none now. */
- function runById(id: string, text: string, options: { exact?: boolean } = {}): boolean {
+ function runById(id: string, text: string, options: { exact?: boolean; direct?: boolean } = {}): boolean {
const entries = paletteEntries(state, Date.now())
const entry = entries.find(candidate => candidate.id === id) ?? (text === '' || options.exact === true ? undefined : filterPalette(entries, `${id} ${text}`, 'all')[0])
if (entry === undefined) return false
- runEntry(entry, entry.run.kind === 'text' ? textOfQuery(`${id} ${text}`, entry.run.keyword) : text)
+ isDirectRun = options.direct === true
+
+ try {
+ runEntry(entry, entry.run.kind === 'text' ? textOfQuery(`${id} ${text}`, entry.run.keyword) : text)
+ } finally {
+ isDirectRun = false
+ }
return true
}
- return { ask, confirm, cancel, runEntry, runById, settled: () => inflight, finished: () => background }
+ return { ask, confirm, confirmUnbound, cancel, expireStale, withdraw, withdrawRefusal: () => withdrawRefusal(), runEntry, runById, settled: () => inflight, finished: () => background }
}
diff --git a/plugins/ruflo-console/hooks/skills-lab.ts b/plugins/ruflo-console/hooks/skills-lab.ts
index 2d8185160b..9a11318f8f 100644
--- a/plugins/ruflo-console/hooks/skills-lab.ts
+++ b/plugins/ruflo-console/hooks/skills-lab.ts
@@ -320,7 +320,7 @@ export function moreSkillActions(state: State, host: Host, runner: Runner, load:
*/
export function skillPaletteEntries(state: State): PaletteEntry[] {
const wired = hosts.get(state)
- const why = 'the skills view is not wired yet'
+ const why = 'the console is not running in this session: open it first (console_open skills)'
const spec = (make: (host: Host) => ActionSpec): { kind: 'spec'; spec: ActionSpec | null; why: string } => ({ kind: 'spec', spec: wired === undefined ? null : make(wired.host), why })
const find = (text: string): ActionSpec | null => {
const argv = findArgv(text)
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index fe2568f8fb..ab1b46a8d2 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -150,7 +150,7 @@ export function optionsOf(raw: PluginOptions | undefined): Options {
}
/** A mutating action waiting for the person's second press; `shows` is the command line when it is not a ruflo one. */
-export type Pending = { /** Which ask this is (runner.ts hands out ids in order): a Yes names the card it answers, so another card that took its place is never the one run. */ id?: number; label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete' }
+export type Pending = { /** Which ask this is (runner.ts hands out ids in order): a Yes names the card it answers, so another card that took its place is never the one run. */ id?: number; label: string; args: readonly string[]; expect: string; askedAtMs: number; shows?: string; note?: string; /** The kind of action, when it may be remembered (see remember.ts). */ rememberKey?: string; /** Where in its view the ask came from. */ scope?: string; /** The page that raised it: the ask shows in full there, and as a pointer on every other page. */ view?: string; /** Who raised it: Claude's tool call or the person's own action (ADR-450 T14). */ source?: 'claude' | 'you'; /** The class the entry declares for itself; the gate takes the stricter of this and the class read from its words. */ declared?: 'write' | 'network' | 'install' | 'spend' | 'delete'; /** Set only on a card Claude raised by its own direct console_run in this session: the one kind of card it may withdraw (runner.ts also matches the id). */ origin?: 'console_run'; /** The class of action, set only on Claude's asks. */ kind?: 'write' | 'network' | 'install' | 'spend' | 'delete' }
/** The MetaHarness lab's last run: what it was, how it exited, its cost note, and its output as lines to scroll. */
export type LabResult = { id: string; label: string; ok: boolean; exitCode: number | null; note?: string; lines: string[]; atMs: number }
@@ -173,7 +173,7 @@ export type TermSessions = { codex?: string; claude?: string }
export const termStoreKeyOf = (cwd: string): string => `ruflo-console/term:${cwd}`
/** What an action did: what ran, how it exited, whether the disk shows the change, and anything it printed to show. */
-export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[] }
+export type Outcome = { label: string; ok: boolean; verified: 'yes' | 'no' | 'n/a'; detail: string; atMs: number; lines?: string[]; /** A confirm card that nobody answered within PENDING_TTL_MS and was cleared unrun (the Room shows it briefly). */ expired?: boolean }
/** One module seen registering since the console loaded, as the engine's scan named it. */
export type ModSeen = { name: string; provenance: string; isLoaded: boolean; reason?: string; atMs: number }
diff --git a/plugins/ruflo-console/hooks/views/room.ts b/plugins/ruflo-console/hooks/views/room.ts
index d4e6efe960..e917c3c2db 100644
--- a/plugins/ruflo-console/hooks/views/room.ts
+++ b/plugins/ruflo-console/hooks/views/room.ts
@@ -12,6 +12,8 @@ import { statsOf } from './manage'
import { modsRows } from './mods'
import { sessionRows } from './sessions'
+/** How long the Room says a card expired, after the runner cleared it. */
+const EXPIRED_SHOWN_MS = 15_000
const TONE_COLOR = { ok: THEME.ok, warn: THEME.warn, bad: THEME.bad, info: THEME.info } as const
const SOURCES: readonly { id: 'all' | RoomSource; label: string }[] = [
{ id: 'all', label: 'all' },
@@ -54,12 +56,18 @@ export function roomView(ctx: Ctx): RenderElement {
const banner = pendingBanner(state.pending, nowMs, PENDING_TTL_MS)
const rows: RenderElement[] = []
- rows.push(rule(ctx, 'Waiting for a yes', banner === null ? 'nothing' : `${banner.ageS}s of ${PENDING_TTL_MS / 1000}s`))
+ // Past the window a card is expired, never "63s of 30s": the runner clears it on its clock, and the page says so for a moment after.
+ const isLate = banner !== null && banner.leftS === 0
+ const expired = banner === null && state.outcome?.expired === true && nowMs - state.outcome.atMs < EXPIRED_SHOWN_MS ? state.outcome : null
- if (banner === null) rows.push(text(ctx, ' Nothing is waiting. Anything that asks first shows up here, unmissable, with how long you have to answer.', { dimColor: true }))
+ rows.push(rule(ctx, 'Waiting for a yes', isLate || expired !== null ? 'expired' : banner === null ? 'nothing' : `${banner.ageS}s of ${PENDING_TTL_MS / 1000}s`))
+
+ if (expired !== null) rows.push(text(ctx, `⌛ ${clip(expired.label, 100)}: expired after ${PENDING_TTL_MS / 1000} s with no answer, so it did not run. Ask again if it is still wanted.`, { color: THEME.warn }))
+ else if (banner === null) rows.push(text(ctx, ' Nothing is waiting. Anything that asks first shows up here, unmissable, with how long you have to answer.', { dimColor: true }))
+ else if (isLate) rows.push(text(ctx, `⌛ ${banner.label}: expired after ${PENDING_TTL_MS / 1000} s with no answer. It will not run: ask again.`, { color: THEME.bad }))
else {
rows.push(text(ctx, `âš  ${banner.label}`, { bold: true, color: TONE_COLOR[banner.tone] }))
- rows.push(text(ctx, ` expects: ${banner.expect}${banner.view === null ? '' : ` · raised on ${banner.view}`} · ${banner.leftS}s left to answer${banner.leftS === 0 ? ' (too late: it will not run, ask again)' : ''}`, { color: TONE_COLOR[banner.tone] }))
+ rows.push(text(ctx, ` expects: ${banner.expect}${banner.view === null ? '' : ` · raised on ${banner.view}`} · ${banner.leftS}s left to answer`, { color: TONE_COLOR[banner.tone] }))
}
rows.push(...sessionRows(ctx))
diff --git a/plugins/ruflo-console/tests/pending-expiry.spec.ts b/plugins/ruflo-console/tests/pending-expiry.spec.ts
new file mode 100644
index 0000000000..f8f5d28158
--- /dev/null
+++ b/plugins/ruflo-console/tests/pending-expiry.spec.ts
@@ -0,0 +1,457 @@
+/**
+ * A confirm card that nobody answers expires at the 30 s window instead of blocking the console: the card is cleared, one event names it,
+ * the outcome tells Claude to ask again, and the next ask is accepted. A Yes after the window still runs nothing. Claude can withdraw its own
+ * ask (never the person's). The ADR and skills palette entries say which page or console to open instead of "not wired yet".
+ * npx vitest run plugins/ruflo-console/tests/pending-expiry.spec.ts
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { ActionSpec } from '../hooks/actions'
+import { adrActions } from '../hooks/adr-actions'
+import { adrPalette } from '../hooks/adr-palette'
+import type { Host } from '../hooks/host'
+import { callTool, type ModelToolDeps } from '../hooks/model-tools'
+import { paletteEntries } from '../hooks/palette'
+import { createController } from '../hooks/controller'
+import { dispatch } from '../hooks/dispatch'
+import { createRunner, EXPIRY_TIMER, PENDING_TTL_MS } from '../hooks/runner'
+import { settingsOf } from '../hooks/settings'
+import { skillPaletteEntries } from '../hooks/skills-lab'
+import { newState, type State } from '../hooks/state'
+import type { Actions, Ctx } from '../hooks/views/common'
+import { roomView } from '../hooks/views/room'
+import { world } from './adr-world'
+
+type Timer = { ms: number; fn: () => void; cancelled: boolean }
+
+function fake() {
+ const ran: string[] = []
+ const timers: Timer[] = []
+ const host = {
+ invalidate: () => undefined,
+ after: (ms: number, fn: () => void) => {
+ const timer: Timer = { ms, fn, cancelled: false }
+
+ timers.push(timer)
+
+ return { cancel: () => void (timer.cancelled = true) }
+ },
+ } as unknown as Host
+ const state = newState({})
+ const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined })
+ const spec = (label: string, extra: Partial<ActionSpec> = {}) => ({ label, args: ['memory', 'store'], expect: 'x', run: async () => void ran.push(label), ...extra }) as unknown as ActionSpec
+ const age = (ms = PENDING_TTL_MS + 1_000) => {
+ if (state.pending !== null) state.pending = { ...state.pending, askedAtMs: Date.now() - ms }
+ }
+ const fire = () => {
+ for (const timer of timers.splice(0)) if (!timer.cancelled) timer.fn()
+ }
+
+ return { state, host, runner, spec, ran, timers, age, fire }
+}
+
+describe('a card nobody answers expires at the window', () => {
+ it('its timer clears it, records one event, and tells Claude to ask again', () => {
+ const { state, runner, spec, timers, age, fire } = fake()
+
+ runner.ask(spec('store a note'), 'why not')
+ expect(state.pending).not.toBeNull()
+ expect(timers.some(timer => timer.ms >= PENDING_TTL_MS)).toBe(true)
+
+ age()
+ fire()
+
+ expect(state.pending).toBeNull()
+ expect(state.events.filter(event => /expired/.test(event.text))).toHaveLength(1)
+ expect(state.events[0]?.text).toMatch(/ask for "store a note" expired after 30 s, not run/)
+ expect(state.outcome).toMatchObject({ label: 'store a note', ok: false, expired: true })
+ expect(state.outcome?.detail).toMatch(/^expired: ask again/)
+ })
+
+ it('a fresh ask from Claude is accepted after the stale card, not dropped', () => {
+ const { state, runner, spec, age } = fake()
+
+ runner.ask(spec('store a note', { byModel: true }), 'why not')
+ age()
+ runner.ask(spec('store another note', { byModel: true }), 'why not')
+
+ expect(state.pending?.label).toBe('store another note')
+ expect(state.events.some(event => /ask for "store a note" expired after 30 s, not run/.test(event.text))).toBe(true)
+ })
+
+ it('a Yes after the window still runs nothing', async () => {
+ const { state, runner, spec, ran, age, fire } = fake()
+
+ runner.ask(spec('store a note'), 'why not')
+
+ const id = state.pending?.id
+
+ age()
+ fire()
+ await runner.confirm(id)
+
+ expect(ran).toEqual([])
+ expect(state.pending).toBeNull()
+ })
+
+ it('an old timer never clears a newer card that is still inside its window', () => {
+ const { state, runner, spec, fire } = fake()
+
+ runner.ask(spec('store a note'), 'why not')
+ runner.cancel()
+ runner.ask(spec('store another note'), 'why not')
+ fire()
+
+ expect(state.pending?.label).toBe('store another note')
+ expect(state.events).toEqual([])
+ })
+})
+
+type El = { kind: string; props: Record<string, unknown> }
+
+const kit = { Box: (props: Record<string, unknown>): El => ({ kind: 'Box', props }), Text: (props: Record<string, unknown>): El => ({ kind: 'Text', props }), Button: (props: Record<string, unknown>): El => ({ kind: 'Button', props }), Input: (props: Record<string, unknown>): El => ({ kind: 'Input', props }) }
+const act = (() => {
+ const proxy: unknown = new Proxy(() => undefined, { get: (_t, key) => (key === 'then' ? undefined : proxy), apply: () => undefined })
+
+ return proxy as Actions
+})()
+const roomText = (state: State): string => JSON.stringify(roomView({ kit, state, nowMs: Date.now(), columns: 140, pictures: new Map(), act, cards: true } as unknown as Ctx))
+
+describe('the Room never counts past the window', () => {
+ it('a card past 30 s reads as expired, not "63s of 30s"', () => {
+ const state = newState({})
+
+ state.pending = { label: 'store a note', args: [], expect: 'x', askedAtMs: Date.now() - 63_000, source: 'claude', kind: 'delete' }
+
+ const text = roomText(state)
+
+ expect(text).not.toContain('63s of 30s')
+ expect(text).toContain('expired')
+ })
+
+ it('after it expired the Room shows that briefly, in place of the card', () => {
+ const { state, runner, spec, age, fire } = fake()
+
+ runner.ask(spec('store a note'), 'why not')
+ age()
+ fire()
+
+ const text = roomText(state)
+
+ expect(text).toContain('store a note')
+ expect(text).toContain('expired after 30 s')
+ })
+})
+
+/** The model tools over a real runner, so the pending card, its expiry and the withdraw are the runner's own. */
+function modelSetup() {
+ const f = fake()
+
+ Object.assign(settingsOf(f.state).ai, { modelControl: 'full', modelConfirm: 'ask' })
+
+ const control = { host: f.host, runner: f.runner, setView: () => undefined, open: async () => undefined, actions: {} as Actions }
+
+ return { ...f, deps: { state: f.state, control } as unknown as ModelToolDeps }
+}
+
+describe('console_run with a stale or withdrawable card', () => {
+ it('a stale card of Claude’s no longer refuses the next console_run', async () => {
+ const { state, deps, age } = modelSetup()
+
+ expect(await callTool('console_run', { id: 'mem-store', text: 'console k1 v1' }, deps)).toMatch(/Waiting for the person/)
+ age()
+
+ const again = await callTool('console_run', { id: 'mem-store', text: 'console k2 v2' }, deps)
+
+ expect(again).not.toMatch(/already waiting/)
+ expect(again).toMatch(/Waiting for the person/)
+ expect(state.pending?.label).toMatch(/k2/)
+ expect(state.events.some(event => /expired after 30 s, not run/.test(event.text))).toBe(true)
+ })
+
+ it('console_run ask-withdraw takes back Claude’s own write-class card; nothing runs', async () => {
+ const { state, deps, ran } = modelSetup()
+
+ expect(await callTool('console_run', { id: 'store', text: 'a note' }, deps)).toMatch(/Waiting for the person/)
+ expect(state.pending).toMatchObject({ source: 'claude', origin: 'console_run', kind: 'write' })
+
+ const said = await callTool('console_run', { id: 'ask-withdraw' }, deps)
+
+ expect(said).toMatch(/withdr/i)
+ expect(state.pending).toBeNull()
+ expect(ran).toEqual([])
+ expect(state.events.some(event => /Claude withdrew its ask "store "a note"/.test(event.text))).toBe(true)
+ })
+
+ it('a delete, spend, install or network card is never withdrawn: the person must see it, and it expires by itself', async () => {
+ const { state, deps } = modelSetup()
+
+ await callTool('console_run', { id: 'mem-delete', text: 'console k1' }, deps)
+ expect(state.pending?.kind).toBe('delete')
+
+ const label = state.pending?.label
+
+ expect(await callTool('console_run', { id: 'ask-withdraw' }, deps)).toMatch(/Refused.*not withdrawn.*must see/)
+ expect(state.pending?.label).toBe(label)
+ })
+
+ it('a card that landed late (a screened, deferred ask) is not Claude’s to withdraw, even of the write class', async () => {
+ const { state, runner, spec, deps } = modelSetup()
+
+ runner.ask(spec('store a screened note', { byModel: true }), 'why not')
+ state.pending = { ...state.pending!, kind: 'write' }
+ expect(await callTool('console_run', { id: 'ask-withdraw' }, deps)).toMatch(/Refused.*not withdrawn.*not raised by your own console_run/)
+ expect(state.pending?.label).toBe('store a screened note')
+ })
+
+ it('console_run ask-withdraw never cancels the person’s own card', async () => {
+ const { state, runner, spec, deps } = modelSetup()
+
+ runner.ask(spec('the person’s own action'), 'why not')
+
+ expect(await callTool('console_run', { id: 'ask-withdraw' }, deps)).toMatch(/Refused.*not withdrawn/)
+ expect(state.pending?.label).toBe('the person’s own action')
+ })
+
+ it('the person cannot use ask-withdraw: it is Claude’s, and only shows for Claude’s own card', async () => {
+ const { state, runner, deps } = modelSetup()
+
+ expect(paletteEntries(state, Date.now()).map(entry => entry.id)).not.toContain('ask-withdraw')
+ await callTool('console_run', { id: 'store', text: 'a note' }, deps)
+ expect(paletteEntries(state, Date.now()).map(entry => entry.id)).toContain('ask-withdraw')
+ expect(runner.runById('ask-withdraw', '', { exact: true })).toBe(true)
+ expect(state.pending).not.toBeNull()
+ })
+
+ it('withdraw then re-ask cannot loop: the same ask waits out a cooldown, and at most 3 withdraws a minute', async () => {
+ vi.useFakeTimers({ now: 1_000_000 })
+
+ const { state, deps } = modelSetup()
+
+ await callTool('console_run', { id: 'store', text: 'a note' }, deps)
+ await callTool('console_run', { id: 'ask-withdraw' }, deps)
+ await callTool('console_run', { id: 'store', text: 'a note' }, deps)
+ expect(state.pending).toBeNull()
+ expect(state.outcome?.detail).toMatch(/withdrew this same ask 0 s ago/)
+
+ for (const text of ['b', 'c']) {
+ await callTool('console_run', { id: 'store', text }, deps)
+ expect(await callTool('console_run', { id: 'ask-withdraw' }, deps)).not.toMatch(/Refused/)
+ }
+
+ await callTool('console_run', { id: 'store', text: 'd' }, deps)
+ expect(await callTool('console_run', { id: 'ask-withdraw' }, deps)).toMatch(/Refused.*3 asks were withdrawn in the last minute/)
+ expect(state.pending?.label).toMatch(/"d"/)
+ })
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+/** A runner on vitest's fake clock: host.after is a real setTimeout, so the expiry fires when the clock says so. */
+function clocked() {
+ vi.useFakeTimers({ now: 0 })
+
+ const ran: string[] = []
+ const host = { invalidate: () => undefined, after: (ms: number, fn: () => void) => {
+ const handle = setTimeout(fn, ms)
+
+ return { cancel: () => clearTimeout(handle) }
+ } } as unknown as Host
+ const state = newState({})
+ const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined })
+ const spec = (label: string) => ({ label, args: ['memory', 'store'], expect: 'x', run: async () => void ran.push(label) }) as unknown as ActionSpec
+
+ return { state, runner, spec, ran }
+}
+
+describe('the window to the millisecond (fake clock)', () => {
+ it('at 29.9 s the card waits and a Yes runs it', async () => {
+ const { state, runner, spec, ran } = clocked()
+
+ runner.ask(spec('store a note'), 'x')
+ vi.advanceTimersByTime(29_900)
+ expect(state.pending?.label).toBe('store a note')
+ expect(roomText(state)).not.toContain('expired')
+ await runner.confirm(state.pending?.id)
+ expect(ran).toEqual(['store a note'])
+ })
+
+ it('at 30.0 s the card is expired: the Room says so, a Yes runs nothing, the next ask replaces it', async () => {
+ const { state, runner, spec, ran } = clocked()
+
+ runner.ask(spec('store a note'), 'x')
+ vi.advanceTimersByTime(30_000)
+ expect(state.pending?.label).toBe('store a note')
+ expect(roomText(state)).toContain('expired')
+ expect(roomText(state)).not.toContain('30s of 30s')
+
+ const id = state.pending?.id
+
+ runner.ask(spec('store another note'), 'x')
+ expect(state.pending?.label).toBe('store another note')
+ expect(state.events.some(event => /ask for "store a note" expired after 30 s, not run/.test(event.text))).toBe(true)
+ await runner.confirm(id)
+ expect(ran).toEqual([])
+ })
+
+ it('at 30.3 s the timer has cleared it, with one event and "expired: ask again"', () => {
+ const { state, runner, spec } = clocked()
+
+ runner.ask(spec('store a note'), 'x')
+ vi.advanceTimersByTime(30_300)
+ expect(state.pending).toBeNull()
+ expect(state.events.filter(event => /expired after 30 s/.test(event.text))).toHaveLength(1)
+ expect(state.outcome).toMatchObject({ ok: false, expired: true })
+ expect(state.outcome?.detail).toMatch(/^expired: ask again/)
+ })
+})
+
+/** A whole console over a host whose every call resolves empty, its timers tracked, its runner real. */
+function console$() {
+ if (!vi.isFakeTimers()) vi.useFakeTimers({ now: 5_000_000 })
+
+ const timers: Timer[] = []
+ const host = new Proxy({}, {
+ get: (_target, key) => {
+ if (key === 'after' || key === 'every') return (ms: number, fn: () => void) => {
+ const timer: Timer = { ms, fn, cancelled: false }
+ const handle = key === 'after' ? setTimeout(fn, ms) : setInterval(fn, ms)
+
+ timers.push(timer)
+
+ return { cancel: () => void ((timer.cancelled = true), clearTimeout(handle)) }
+ }
+ if (key === 'pluginRoot') return '/plugin'
+ if (key === 'fs') return { read: async () => Promise.reject(new Error('ENOENT')), stat: async () => Promise.reject(new Error('ENOENT')), list: async () => Promise.reject(new Error('ENOENT')) }
+
+ return () => Promise.resolve(undefined)
+ },
+ }) as unknown as Host
+ const state = newState({ boot: false })
+
+ Object.assign(settingsOf(state).ai, { modelControl: 'full', modelConfirm: 'ask' })
+
+ const control = createController(state, host)
+ const ran: string[] = []
+ const spec = (label: string, extra: Partial<ActionSpec> = {}) => ({ label, args: ['memory', 'store'], expect: 'x', run: async () => void ran.push(label), ...extra }) as unknown as ActionSpec
+
+ return { state, control, timers, ran, spec }
+}
+
+describe('the expiry timer does not outlive the console', () => {
+ it('lives in state.timers, so closing the console cancels it and leaves no live timer', async () => {
+ const { state, control, timers, spec } = console$()
+
+ control.runner.ask(spec('store a note'), 'x')
+
+ const expiry = timers.find(timer => timer.ms === PENDING_TTL_MS + 250)
+
+ expect(expiry).toBeDefined()
+ expect(state.timers.has(EXPIRY_TIMER)).toBe(true)
+ await control.close()
+ expect(state.timers.has(EXPIRY_TIMER)).toBe(false)
+ expect(expiry?.cancelled).toBe(true)
+ })
+
+ it('answering the card cancels its timer too', async () => {
+ const { state, control, timers, spec } = console$()
+
+ control.runner.ask(spec('store a note'), 'x')
+ await control.runner.confirm(state.pending?.id)
+ expect(state.timers.has(EXPIRY_TIMER)).toBe(false)
+ expect(timers.find(timer => timer.ms === PENDING_TTL_MS + 250)?.cancelled).toBe(true)
+ })
+})
+
+describe('a typed /ruflo yes is bound to no card', () => {
+ const yes = (control: ReturnType<typeof console$>['control'], state: State) => dispatch(control, state, 'yes', async () => undefined)
+
+ it('runs the person’s own card, as before', async () => {
+ const { state, control, ran, spec } = console$()
+
+ control.runner.ask(spec('store a note'), 'x')
+ await yes(control, state)
+ expect(ran).toEqual(['store a note'])
+ })
+
+ it('is refused for a card Claude raised under 3 s ago: press the card itself', async () => {
+ vi.useFakeTimers({ now: 5_000_000 })
+
+ const { state, control, ran, spec } = console$()
+
+ control.runner.ask(spec('store a note', { byModel: true }), 'x')
+ vi.advanceTimersByTime(2_000)
+ expect((await yes(control, state)).text).toMatch(/press Yes on the card itself/)
+ expect(ran).toEqual([])
+ expect(state.pending?.label).toBe('store a note')
+ vi.advanceTimersByTime(1_500)
+ await yes(control, state)
+ expect(ran).toEqual(['store a note'])
+ })
+
+ it('is refused for a card that replaced an expired one under 10 s ago, so a Yes meant for the old card never runs the new one', async () => {
+ vi.useFakeTimers({ now: 5_000_000 })
+
+ const { state, control, ran, spec } = console$()
+
+ control.runner.ask(spec('the old card'), 'x')
+ vi.advanceTimersByTime(PENDING_TTL_MS + 500)
+ expect(state.pending).toBeNull()
+ control.runner.ask(spec('the new card'), 'x')
+ vi.advanceTimersByTime(4_000)
+ expect((await yes(control, state)).text).toMatch(/replaced one that left unanswered/)
+ expect(ran).toEqual([])
+ vi.advanceTimersByTime(6_000)
+ await yes(control, state)
+ expect(ran).toEqual(['the new card'])
+ })
+})
+
+describe('the ADR and skills entries say what to open', () => {
+ const whyOf = (state: State, id: string, text: string): string => {
+ const run = adrPalette(state).find(entry => entry.id === id)?.run
+
+ return run?.kind === 'text' ? run.why?.(text) ?? '' : run?.kind === 'spec' ? run.why : ''
+ }
+
+ it('with the console running but the ADRs page never opened, it says to open the ADRs page (console_open adrs)', () => {
+ const state = newState({})
+
+ adrActions(state, { invalidate: () => undefined } as never, { ask: () => undefined } as never)
+
+ const why = whyOf(state, 'adr-show', '3')
+
+ expect(why).not.toMatch(/not wired yet|open the console first/)
+ expect(why).toMatch(/open the ADRs page first \(console_open adrs\)/)
+ })
+
+ it('without a console, it says to open the console, naming the call', () => {
+ const why = whyOf(newState({}), 'adr-accept', '3')
+
+ expect(why).not.toMatch(/not wired yet/)
+ expect(why).toMatch(/console_open adrs/)
+ })
+
+ it('adr-supersede asks for two numbers, even when the one given exists', async () => {
+ const w = await world('nygard')
+
+ adrActions(w.state, w.host as never, { ask: () => undefined } as never)
+ expect(whyOf(w.state, 'adr-supersede', '3')).toMatch(/type two ADR numbers, the old then the new: "adr-supersede 1 3"/)
+ expect(whyOf(w.state, 'adr-accept', 'x')).toMatch(/type the ADR number: "adr-accept 3"/)
+ })
+
+ it('with the folder read, a number that is not there is named', async () => {
+ const w = await world('nygard')
+
+ adrActions(w.state, w.host as never, { ask: () => undefined } as never)
+ expect(whyOf(w.state, 'adr-show', '99')).toMatch(/no ADR 99/)
+ })
+
+ it('the skills entries name the call that opens the console', () => {
+ const update = skillPaletteEntries(newState({})).find(entry => entry.id === 'skills-update')
+
+ expect(update?.run.kind === 'spec' ? update.run.why : '').toMatch(/console_open skills/)
+ })
+})
diff --git a/plugins/ruflo-console/tests/skills-lab.spec.ts b/plugins/ruflo-console/tests/skills-lab.spec.ts
index 7062ca4c9d..634d214663 100644
--- a/plugins/ruflo-console/tests/skills-lab.spec.ts
+++ b/plugins/ruflo-console/tests/skills-lab.spec.ts
@@ -338,6 +338,6 @@ describe('the new skills actions', () => {
const state = newState({})
const update = skillPaletteEntries(state).find(entry => entry.id === 'skills-update')
- expect(update?.run).toEqual({ kind: 'spec', spec: null, why: 'the skills view is not wired yet' })
+ expect(update?.run).toEqual({ kind: 'spec', spec: null, why: 'the console is not running in this session: open it first (console_open skills)' })
})
})