From ba95595871635da89a6078350457253447f53f45 Mon Sep 17 00:00:00 2001 From: jmdiez Date: Fri, 13 Nov 2026 10:32:22 +0100 Subject: [PATCH 1/3] feat(cli): report agent lifecycle with OSC 7501 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terminals such as Herdr only list a program as an agent when it reports working/blocked/idle/done over the open Program Status Protocol. Emit those states from the CLI's own turn and ask-user state, and clear them on exit. Generated with Codebuff 🤖 Co-Authored-By: Codebuff --- cli/src/app.tsx | 4 + cli/src/hooks/use-program-status.ts | 47 +++++++ .../utils/__tests__/program-status.test.ts | 125 ++++++++++++++++++ cli/src/utils/program-status.ts | 100 ++++++++++++++ cli/src/utils/renderer-cleanup.ts | 3 + 5 files changed, 279 insertions(+) create mode 100644 cli/src/hooks/use-program-status.ts create mode 100644 cli/src/utils/__tests__/program-status.test.ts create mode 100644 cli/src/utils/program-status.ts diff --git a/cli/src/app.tsx b/cli/src/app.tsx index e95986f908..09f6fe098b 100644 --- a/cli/src/app.tsx +++ b/cli/src/app.tsx @@ -11,6 +11,7 @@ import { useAuthQuery } from './hooks/use-auth-query' import { useAuthState } from './hooks/use-auth-state' import { useFreebuffModelCatalog } from './hooks/use-freebuff-model-catalog' import { useFreebuffSession } from './hooks/use-freebuff-session' +import { useProgramStatus } from './hooks/use-program-status' import { useTerminalFocus } from './hooks/use-terminal-focus' import { getProjectRoot, startNewChat } from './project-files' import { useChatHistoryStore } from './state/chat-history-store' @@ -88,6 +89,9 @@ export const App = ({ setIsFocusSupported(true) }, [setIsFocusSupported]) + // Report lifecycle state to terminals that support the open status protocol. + useProgramStatus() + // Enable terminal focus detection to stop cursor blinking when window loses focus // Cursor starts visible but not blinking; blinking enabled once terminal support confirmed useTerminalFocus({ diff --git a/cli/src/hooks/use-program-status.ts b/cli/src/hooks/use-program-status.ts new file mode 100644 index 0000000000..453fed5fe1 --- /dev/null +++ b/cli/src/hooks/use-program-status.ts @@ -0,0 +1,47 @@ +/** + * Reports the CLI's lifecycle to terminals that understand OSC 7501. + * + * `isChainInProgress` covers a whole turn (including subagents and queued + * follow-ups); `askUserState` overrides it while Freebuff waits for an answer. + */ + +import { useEffect, useRef } from 'react' + +import { useChatStore } from '../state/chat-store' +import { + nextProgramStatusUpdate, + reportBlocked, + reportDone, + reportIdle, + reportWorking, +} from '../utils/program-status' + +export function useProgramStatus(): void { + const isChainInProgress = useChatStore((state) => state.isChainInProgress) + const isAsking = useChatStore((state) => state.askUserState !== null) + const wasWorkingRef = useRef(false) + + useEffect(() => { + const next = nextProgramStatusUpdate({ + isChainInProgress, + isAsking, + wasWorking: wasWorkingRef.current, + }) + wasWorkingRef.current = next.wasWorking + + switch (next.update.state) { + case 'blocked': + reportBlocked(next.update.kind) + break + case 'working': + reportWorking() + break + case 'done': + reportDone() + break + case 'idle': + reportIdle() + break + } + }, [isAsking, isChainInProgress]) +} diff --git a/cli/src/utils/__tests__/program-status.test.ts b/cli/src/utils/__tests__/program-status.test.ts new file mode 100644 index 0000000000..176fe9fcc0 --- /dev/null +++ b/cli/src/utils/__tests__/program-status.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, test } from 'bun:test' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' + +import { + PROGRAM_STATUS_APP, + buildProgramStatusSequence, + nextProgramStatusUpdate, + reportProgramStatus, +} from '../program-status' + +const ST = '\x1b\\' + +function withTtyFile(run: (ttyPath: string) => void): void { + const directory = mkdtempSync(join(tmpdir(), 'program-status-')) + const ttyPath = join(directory, 'tty') + writeFileSync(ttyPath, '') + + try { + run(ttyPath) + } finally { + rmSync(directory, { recursive: true, force: true }) + } +} + +describe('program status', () => { + test('builds the idle report for the running program', () => { + expect(buildProgramStatusSequence('idle')).toBe( + `\x1b]7501;state=idle:app=${PROGRAM_STATUS_APP}${ST}`, + ) + }) + + test('adds the blocked kind only while blocked', () => { + expect(buildProgramStatusSequence('blocked', { kind: 'question' })).toBe( + `\x1b]7501;state=blocked:app=${PROGRAM_STATUS_APP}:kind=question${ST}`, + ) + expect(buildProgramStatusSequence('working', { kind: 'question' })).toBe( + `\x1b]7501;state=working:app=${PROGRAM_STATUS_APP}${ST}`, + ) + }) + + test('builds clear reports', () => { + expect(buildProgramStatusSequence('clear')).toBe( + `\x1b]7501;state=clear:app=${PROGRAM_STATUS_APP}${ST}`, + ) + }) + + test('writes a report to a tty path', () => { + withTtyFile((ttyPath) => { + expect(reportProgramStatus('working', { ttyPath })).toBe(true) + expect(readFileSync(ttyPath, 'utf8')).toBe( + buildProgramStatusSequence('working'), + ) + }) + }) + + test('returns false when the terminal cannot be opened', () => { + expect( + reportProgramStatus('done', { + ttyPath: '/path/that/does/not/exist', + }), + ).toBe(false) + }) + + test('reports idle before the first turn', () => { + expect( + nextProgramStatusUpdate({ + isChainInProgress: false, + isAsking: false, + wasWorking: false, + }), + ).toEqual({ update: { state: 'idle' }, wasWorking: false }) + }) + + test('reports working for a running turn', () => { + expect( + nextProgramStatusUpdate({ + isChainInProgress: true, + isAsking: false, + wasWorking: false, + }), + ).toEqual({ update: { state: 'working' }, wasWorking: true }) + }) + + test('reports blocked while a question waits for the user', () => { + expect( + nextProgramStatusUpdate({ + isChainInProgress: true, + isAsking: true, + wasWorking: true, + }), + ).toEqual({ + update: { state: 'blocked', kind: 'question' }, + wasWorking: true, + }) + }) + + test('returns to working after the question is answered', () => { + expect( + nextProgramStatusUpdate({ + isChainInProgress: true, + isAsking: false, + wasWorking: true, + }), + ).toEqual({ update: { state: 'working' }, wasWorking: true }) + }) + + test('reports done only on the transition out of a turn', () => { + expect( + nextProgramStatusUpdate({ + isChainInProgress: false, + isAsking: false, + wasWorking: true, + }), + ).toEqual({ update: { state: 'done' }, wasWorking: false }) + expect( + nextProgramStatusUpdate({ + isChainInProgress: false, + isAsking: false, + wasWorking: false, + }), + ).toEqual({ update: { state: 'idle' }, wasWorking: false }) + }) +}) diff --git a/cli/src/utils/program-status.ts b/cli/src/utils/program-status.ts new file mode 100644 index 0000000000..31642f4bee --- /dev/null +++ b/cli/src/utils/program-status.ts @@ -0,0 +1,100 @@ +/** + * Program Status Protocol (OSC 7501) reporting. + * + * Terminals such as Herdr treat a program as an agent only when it reports its + * lifecycle through OSC 7501. We write directly to /dev/tty, like + * terminal-title.ts, because OpenTUI captures stdout. + * + * Sequence: ESC ] 7501 ; state=:app=[:kind=] ESC \ + */ + +import { IS_FREEBUFF } from './constants' +import { writeTerminalControlSync } from './terminal-io' + +export type ProgramStatusState = + | 'idle' + | 'working' + | 'blocked' + | 'done' + | 'clear' + +/** Only sent alongside `blocked`. */ +export type BlockedKind = 'permission' | 'question' + +export type ProgramStatusUpdate = + | { state: 'idle' | 'working' | 'done' } + | { state: 'blocked'; kind: BlockedKind } + +export const PROGRAM_STATUS_APP = IS_FREEBUFF ? 'freebuff' : 'codebuff' + +const OSC_7501 = '\x1b]7501;' +const OSC_TERMINATOR = '\x1b\\' // ST + +/** + * Decide the next report from the CLI's turn and prompt state. + * + * A turn that just ended reports `done`; only a CLI that has not worked yet + * reports `idle`. + */ +export function nextProgramStatusUpdate(params: { + isChainInProgress: boolean + isAsking: boolean + wasWorking: boolean +}): { update: ProgramStatusUpdate; wasWorking: boolean } { + if (params.isAsking) { + return { update: { state: 'blocked', kind: 'question' }, wasWorking: true } + } + if (params.isChainInProgress) { + return { update: { state: 'working' }, wasWorking: true } + } + if (params.wasWorking) { + return { update: { state: 'done' }, wasWorking: false } + } + return { update: { state: 'idle' }, wasWorking: false } +} + +export function buildProgramStatusSequence( + state: ProgramStatusState, + options: { kind?: BlockedKind } = {}, +): string { + const fields = [`state=${state}`, `app=${PROGRAM_STATUS_APP}`] + if (state === 'blocked' && options.kind) { + fields.push(`kind=${options.kind}`) + } + return `${OSC_7501}${fields.join(':')}${OSC_TERMINATOR}` +} + +/** + * Report one state transition. Unknown terminals ignore OSC 7501, and a + * non-interactive process has no /dev/tty, so failures are silent. + */ +export function reportProgramStatus( + state: ProgramStatusState, + options: { kind?: BlockedKind; ttyPath?: string } = {}, +): boolean { + return writeTerminalControlSync( + buildProgramStatusSequence(state, { kind: options.kind }), + options.ttyPath, + ) +} + +export function reportIdle(): boolean { + return reportProgramStatus('idle') +} + +export function reportWorking(): boolean { + return reportProgramStatus('working') +} + +export function reportBlocked(kind: BlockedKind): boolean { + return reportProgramStatus('blocked', { kind }) +} + +export function reportDone(): boolean { + return reportProgramStatus('done') +} + +/** Stop being an agent in terminals that track agents by status. */ +export function reportClear(): boolean { + return reportProgramStatus('clear') +} diff --git a/cli/src/utils/renderer-cleanup.ts b/cli/src/utils/renderer-cleanup.ts index 829f8596c6..b57b2961d5 100644 --- a/cli/src/utils/renderer-cleanup.ts +++ b/cli/src/utils/renderer-cleanup.ts @@ -10,6 +10,7 @@ import { holdsLiveFreebuffSlot } from './freebuff-session-api' import { isLauncherUpdateTermination } from './launcher-update-restart' import { logger } from './logger' import { trackHelperProcess } from './helper-process-telemetry' +import { reportClear } from './program-status' import { flushLiveChatState } from './run-state-storage' import { reportFatalErrorSync, writeTerminalControlSync } from './terminal-io' import { TERMINAL_RESET_SEQUENCES } from './terminal-reset-sequences' @@ -99,6 +100,8 @@ function resetTerminalState(): boolean { try { // Reset terminal title to default resetTerminalTitle() + // Stop counting as an agent in terminals that track OSC 7501 status. + reportClear() if (!process.stdout.isTTY) return true const resetCompletedSynchronously = writeTerminalControlSync( From da76c14700d9c596c0c10e0f14079f3ab137645b Mon Sep 17 00:00:00 2001 From: jmdiez Date: Sat, 14 Nov 2026 22:05:17 +0100 Subject: [PATCH 2/3] fix(cli): report only the ask_user kind for blocked status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The block kind advertised 'permission', but the CLI has no permission prompt, so every blocked report claimed 'question' anyway. Narrow the type to the one kind the CLI can actually raise and document how unknown OSC 7501 behaves on terminals that do not implement it. 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- cli/src/utils/program-status.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/cli/src/utils/program-status.ts b/cli/src/utils/program-status.ts index 31642f4bee..12df9a7de9 100644 --- a/cli/src/utils/program-status.ts +++ b/cli/src/utils/program-status.ts @@ -6,6 +6,12 @@ * terminal-title.ts, because OpenTUI captures stdout. * * Sequence: ESC ] 7501 ; state=:app=[:kind=] ESC \ + * + * OSC 7501 is not a registered sequence; it is Herdr's private convention. + * Terminal parsers consume an OSC string up to its terminator and discard the + * ones they do not implement, so xterm-compatible emulators (xterm, VTE, + * iTerm2, WezTerm, kitty, Alacritty, Windows Terminal) print nothing for this + * report. There is no visible fallback to design around. */ import { IS_FREEBUFF } from './constants' @@ -18,8 +24,15 @@ export type ProgramStatusState = | 'done' | 'clear' -/** Only sent alongside `blocked`. */ -export type BlockedKind = 'permission' | 'question' +/** + * Only sent alongside `blocked`. + * + * `ask_user` is the CLI's only blocking prompt, so it is the only kind we can + * report truthfully. Permission prompts do not exist in the CLI yet; adding + * `permission` before one is wired up would make the terminal announce a state + * the UI never shows. + */ +export type BlockedKind = 'question' export type ProgramStatusUpdate = | { state: 'idle' | 'working' | 'done' } @@ -34,7 +47,8 @@ const OSC_TERMINATOR = '\x1b\\' // ST * Decide the next report from the CLI's turn and prompt state. * * A turn that just ended reports `done`; only a CLI that has not worked yet - * reports `idle`. + * reports `idle`. `isAsking` means the `ask_user` prompt is waiting for the + * user, which is the `blocked`/`question` report. */ export function nextProgramStatusUpdate(params: { isChainInProgress: boolean From 940853499841dadbf0e099e2f1cf98950d4f98f4 Mon Sep 17 00:00:00 2001 From: jmdiez Date: Wed, 18 Nov 2026 18:43:26 +0100 Subject: [PATCH 3/3] comments revision --- .../utils/__tests__/program-status.test.ts | 28 ++++++++++++- cli/src/utils/__tests__/terminal-io.test.ts | 30 +++++++++++++ cli/src/utils/program-status.ts | 25 +++++++---- cli/src/utils/terminal-io.ts | 42 +++++++++++++++++++ cli/src/utils/terminal-title.ts | 32 +++----------- 5 files changed, 121 insertions(+), 36 deletions(-) diff --git a/cli/src/utils/__tests__/program-status.test.ts b/cli/src/utils/__tests__/program-status.test.ts index 176fe9fcc0..720269d2d4 100644 --- a/cli/src/utils/__tests__/program-status.test.ts +++ b/cli/src/utils/__tests__/program-status.test.ts @@ -48,13 +48,39 @@ describe('program status', () => { test('writes a report to a tty path', () => { withTtyFile((ttyPath) => { - expect(reportProgramStatus('working', { ttyPath })).toBe(true) + expect(reportProgramStatus('working', { ttyPath, env: {} })).toBe(true) expect(readFileSync(ttyPath, 'utf8')).toBe( buildProgramStatusSequence('working'), ) }) }) + test('wraps the report in a tmux passthrough', () => { + withTtyFile((ttyPath) => { + expect( + reportProgramStatus('working', { ttyPath, env: { TMUX: '/tmp/tmux' } }), + ).toBe(true) + const report = buildProgramStatusSequence('working') + expect(readFileSync(ttyPath, 'utf8')).toBe( + `\x1bPtmux;${report.replace(/\x1b/g, '\x1b\x1b')}${ST}`, + ) + }) + }) + + test('wraps the report in a screen passthrough', () => { + withTtyFile((ttyPath) => { + expect( + reportProgramStatus('done', { + ttyPath, + env: { TERM: 'screen-256color' }, + }), + ).toBe(true) + expect(readFileSync(ttyPath, 'utf8')).toBe( + `\x1bP${buildProgramStatusSequence('done')}${ST}`, + ) + }) + }) + test('returns false when the terminal cannot be opened', () => { expect( reportProgramStatus('done', { diff --git a/cli/src/utils/__tests__/terminal-io.test.ts b/cli/src/utils/__tests__/terminal-io.test.ts index 0dd605563e..8f9e14e898 100644 --- a/cli/src/utils/__tests__/terminal-io.test.ts +++ b/cli/src/utils/__tests__/terminal-io.test.ts @@ -12,6 +12,7 @@ import { join } from 'path' import { reportFatalErrorSync, + wrapForMultiplexer, writeFileDescriptorSync, writeTerminalControlSync, } from '../terminal-io' @@ -33,6 +34,35 @@ function captureDescriptorWrite(write: (fd: number) => void): string { } } +describe('multiplexer passthrough', () => { + const sequence = '\x1b]7501;state=idle:app=freebuff\x1b\\' + + test('leaves the sequence alone outside a multiplexer', () => { + expect(wrapForMultiplexer(sequence, {})).toBe(sequence) + }) + + test('wraps for tmux with doubled escapes', () => { + expect(wrapForMultiplexer(sequence, { TMUX: '/tmp/tmux-1000' })).toBe( + `\x1bPtmux;${sequence.replace(/\x1b/g, '\x1b\x1b')}\x1b\\`, + ) + }) + + test('wraps for screen without escaping', () => { + expect(wrapForMultiplexer(sequence, { TERM: 'screen-256color' })).toBe( + `\x1bP${sequence}\x1b\\`, + ) + expect(wrapForMultiplexer(sequence, { STY: '1234.pts-0' })).toBe( + `\x1bP${sequence}\x1b\\`, + ) + }) + + test('prefers the tmux passthrough inside tmux', () => { + expect( + wrapForMultiplexer(sequence, { TMUX: '/tmp/tmux-1000', STY: '1234' }), + ).toBe(`\x1bPtmux;${sequence.replace(/\x1b/g, '\x1b\x1b')}\x1b\\`) + }) +}) + describe('synchronous terminal I/O', () => { test('writes the complete byte sequence before returning', () => { const directory = mkdtempSync(join(tmpdir(), 'terminal-io-')) diff --git a/cli/src/utils/program-status.ts b/cli/src/utils/program-status.ts index 12df9a7de9..2463e3d950 100644 --- a/cli/src/utils/program-status.ts +++ b/cli/src/utils/program-status.ts @@ -1,21 +1,25 @@ /** * Program Status Protocol (OSC 7501) reporting. * - * Terminals such as Herdr treat a program as an agent only when it reports its + * Terminals and multiplexers treat a program as an agent when it reports its * lifecycle through OSC 7501. We write directly to /dev/tty, like * terminal-title.ts, because OpenTUI captures stdout. * * Sequence: ESC ] 7501 ; state=:app=[:kind=] ESC \ * - * OSC 7501 is not a registered sequence; it is Herdr's private convention. - * Terminal parsers consume an OSC string up to its terminator and discard the - * ones they do not implement, so xterm-compatible emulators (xterm, VTE, - * iTerm2, WezTerm, kitty, Alacritty, Windows Terminal) print nothing for this - * report. There is no visible fallback to design around. + * OSC 7501 is not a registered sequence; it is claimed by convention, and + * terminal parsers discard OSC codes they do not implement, so xterm-compatible + * emulators (xterm, VTE, iTerm2, WezTerm, kitty, Alacritty, Windows Terminal) + * print nothing for this report. There is no visible fallback to design around. + * + * Inside tmux or screen the report goes out in a DCS passthrough, because bare + * escape sequences written to /dev/tty are dropped there. */ import { IS_FREEBUFF } from './constants' -import { writeTerminalControlSync } from './terminal-io' +import { wrapForMultiplexer, writeTerminalControlSync } from './terminal-io' + +import type { MultiplexerEnv } from './terminal-io' export type ProgramStatusState = | 'idle' @@ -84,10 +88,13 @@ export function buildProgramStatusSequence( */ export function reportProgramStatus( state: ProgramStatusState, - options: { kind?: BlockedKind; ttyPath?: string } = {}, + options: { kind?: BlockedKind; ttyPath?: string; env?: MultiplexerEnv } = {}, ): boolean { return writeTerminalControlSync( - buildProgramStatusSequence(state, { kind: options.kind }), + wrapForMultiplexer( + buildProgramStatusSequence(state, { kind: options.kind }), + options.env, + ), options.ttyPath, ) } diff --git a/cli/src/utils/terminal-io.ts b/cli/src/utils/terminal-io.ts index 38187547a1..f5009512e0 100644 --- a/cli/src/utils/terminal-io.ts +++ b/cli/src/utils/terminal-io.ts @@ -1,5 +1,14 @@ import { closeSync, constants, openSync, writeSync } from 'fs' +import { getCliEnv } from './env' + +/** The environment fields that decide how to reach the outer terminal. */ +export type MultiplexerEnv = { + TMUX?: string | undefined + STY?: string | undefined + TERM?: string | undefined +} + /** Write every byte to an already-open file descriptor before returning. */ export function writeFileDescriptorSync(fd: number, value: string): boolean { try { @@ -57,6 +66,39 @@ function stringifyFatalValue(value: unknown): string | undefined { } } +export function isInTmux(env: MultiplexerEnv): boolean { + return Boolean(env.TMUX) +} + +export function isInScreen(env: MultiplexerEnv): boolean { + if (env.STY) return true + const term = env.TERM ?? '' + return term.startsWith('screen') && !isInTmux(env) +} + +/** + * Wrap a control sequence so multiplexers forward it to the terminal. + * + * tmux and screen drop escape sequences written to /dev/tty unless they arrive + * inside a DCS passthrough. tmux doubles the inner ESC characters so its parser + * does not end the passthrough early. Outside a multiplexer the sequence is + * returned unchanged, and with tmux's `allow-passthrough` off the wrapped bytes + * are discarded, so callers still degrade silently. + */ +export function wrapForMultiplexer( + sequence: string, + env: MultiplexerEnv = getCliEnv(), +): string { + if (isInTmux(env)) { + const escaped = sequence.replace(/\x1b/g, '\x1b\x1b') + return `\x1bPtmux;${escaped}\x1b\\` + } + if (isInScreen(env)) { + return `\x1bP${sequence}\x1b\\` + } + return sequence +} + /** * Write terminal control bytes synchronously to the controlling terminal. * OpenTUI may capture stdout, so control sequences use /dev/tty (or CON on diff --git a/cli/src/utils/terminal-title.ts b/cli/src/utils/terminal-title.ts index 1484fa5738..1fc4267dc0 100644 --- a/cli/src/utils/terminal-title.ts +++ b/cli/src/utils/terminal-title.ts @@ -11,40 +11,20 @@ import { IS_FREEBUFF } from './constants' import { getCliEnv } from './env' -import { writeTerminalControlSync } from './terminal-io' +import { wrapForMultiplexer, writeTerminalControlSync } from './terminal-io' const MAX_TITLE_LENGTH = 60 const TITLE_PREFIX = IS_FREEBUFF ? 'Freebuff: ' : 'Codebuff: ' const OSC_TERMINATOR = '\x07' // BEL -function isInTmux(env: ReturnType): boolean { - return Boolean(env.TMUX) -} - -function isInScreen(env: ReturnType): boolean { - if (env.STY) return true - const term = env.TERM ?? '' - return term.startsWith('screen') && !isInTmux(env) -} - /** * Build the OSC title sequence with tmux/screen passthrough if needed */ -function buildTitleSequence(title: string, env: ReturnType): string { - const osc = `\x1b]0;${title}${OSC_TERMINATOR}` - - // tmux passthrough: wrap in DCS and double ESC characters - if (isInTmux(env)) { - const escaped = osc.replace(/\x1b/g, '\x1b\x1b') - return `\x1bPtmux;${escaped}\x1b\\` - } - - // GNU screen passthrough: wrap in DCS - if (isInScreen(env)) { - return `\x1bP${osc}\x1b\\` - } - - return osc +function buildTitleSequence( + title: string, + env: ReturnType, +): string { + return wrapForMultiplexer(`\x1b]0;${title}${OSC_TERMINATOR}`, env) } /**