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..720269d2d4 --- /dev/null +++ b/cli/src/utils/__tests__/program-status.test.ts @@ -0,0 +1,151 @@ +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, 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', { + 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/__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 new file mode 100644 index 0000000000..2463e3d950 --- /dev/null +++ b/cli/src/utils/program-status.ts @@ -0,0 +1,121 @@ +/** + * Program Status Protocol (OSC 7501) reporting. + * + * 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 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 { wrapForMultiplexer, writeTerminalControlSync } from './terminal-io' + +import type { MultiplexerEnv } from './terminal-io' + +export type ProgramStatusState = + | 'idle' + | 'working' + | 'blocked' + | 'done' + | 'clear' + +/** + * 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' } + | { 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`. `isAsking` means the `ask_user` prompt is waiting for the + * user, which is the `blocked`/`question` report. + */ +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; env?: MultiplexerEnv } = {}, +): boolean { + return writeTerminalControlSync( + wrapForMultiplexer( + buildProgramStatusSequence(state, { kind: options.kind }), + options.env, + ), + 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( 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) } /**