diff --git a/cli/src/chat.tsx b/cli/src/chat.tsx index 6de9f39585..e6e3e34ed9 100644 --- a/cli/src/chat.tsx +++ b/cli/src/chat.tsx @@ -9,6 +9,13 @@ import type { FeedbackCategory } from '@codebuff/common/constants/feedback' import { setFreeModeCapacityDeferralListener } from '@codebuff/sdk' import { safeOpen } from './utils/open-url' import { getAuthToken } from './utils/auth' +import { getCliEnv } from './utils/env' +import { + reportProgramStatus, + statusReportFor, + type StatusReport, +} from './utils/program-status' +import { writeTerminalControlSync } from './utils/terminal-io' import { isSponsoredProposalBlock } from './types/chat' import { runSponsoredProposalControl } from './utils/sponsored-proposal-control' import { patchSponsoredProposalBlock } from './utils/sponsored-proposal-state' @@ -2200,6 +2207,24 @@ export const Chat = ({ }) const hasStatusIndicatorContent = statusIndicatorState.kind !== 'idle' + // Report status to the terminal with OSC 7501, so a multiplexer or agent + // panel can show this pane without scraping the screen. One report per + // change; the ref keeps a finished turn reporting `done` instead of being + // overwritten by the next idle render. + const lastReport = useRef(null) + useEffect(() => { + const next = statusReportFor( + statusIndicatorState.kind, + authStatus, + lastReport.current?.state ?? null, + ) + if (!next) return + const previous = lastReport.current + if (previous?.state === next.state && previous.kind === next.kind) return + lastReport.current = next + reportProgramStatus(next, writeTerminalControlSync, getCliEnv()) + }, [statusIndicatorState.kind, authStatus]) + // Auto-show subscription limit banner when rate limit becomes active const subscriptionLimitShownRef = useRef(false) const subscriptionRateLimit = subscriptionData?.hasSubscription 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..95f747dd74 --- /dev/null +++ b/cli/src/utils/__tests__/program-status.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, test } from 'bun:test' + +import { + buildStatusSequence, + reportProgramStatus, + statusReportFor, +} from '../program-status' + +const BEL = '\x1b\\' + +describe('buildStatusSequence', () => { + test('writes one report for working', () => { + expect(buildStatusSequence({ state: 'working' }, {})).toBe( + `\x1b]7501;state=working:app=freebuff${BEL}`, + ) + }) + + test('carries kind only with blocked', () => { + expect( + buildStatusSequence({ state: 'blocked', kind: 'question' }, {}), + ).toBe(`\x1b]7501;state=blocked:kind=question:app=freebuff${BEL}`) + expect( + buildStatusSequence({ state: 'working', kind: 'question' }, {}), + ).toBe(`\x1b]7501;state=working:app=freebuff${BEL}`) + }) + + test('wraps for tmux passthrough', () => { + const sequence = buildStatusSequence( + { state: 'blocked', kind: 'auth' }, + { TMUX: '/tmp/tmux-1000/default,123,0' }, + ) + // DCS wrapper, with the inner ESC doubled as tmux requires. + expect(sequence.startsWith('\x1bPtmux;')).toBe(true) + expect(sequence).toContain(']7501;state=blocked:kind=auth:app=freebuff') + expect(sequence.endsWith(BEL)).toBe(true) + expect(sequence).toContain('\x1b\x1b]7501') + }) + + test('wraps for screen passthrough', () => { + const sequence = buildStatusSequence( + { state: 'done' }, + { TERM: 'screen-256color' }, + ) + expect(sequence.startsWith('\x1bP')).toBe(true) + expect(sequence).not.toContain('tmux;') + }) +}) + +describe('statusReportFor', () => { + test('work in every form reports working', () => { + for (const kind of [ + 'streaming', + 'waiting', + 'retrying', + 'capacityWait', + ] as const) { + expect(statusReportFor(kind, 'ok', null)).toEqual({ state: 'working' }) + } + }) + + test('ask_user is the blocked question state', () => { + expect(statusReportFor('paused', 'ok', 'working')).toEqual({ + state: 'blocked', + kind: 'question', + }) + }) + + test('unreachable auth blocks, retrying auth does not', () => { + expect(statusReportFor('connecting', 'unreachable', null)).toEqual({ + state: 'blocked', + kind: 'auth', + }) + expect(statusReportFor('connecting', 'retrying', null)).toEqual({ + state: 'working', + }) + }) + + test('a finished turn reports done exactly once, then idle', () => { + expect(statusReportFor('idle', 'ok', 'working')).toEqual({ state: 'done' }) + expect(statusReportFor('idle', 'ok', 'done')).toEqual({ state: 'idle' }) + expect(statusReportFor('idle', 'ok', null)).toEqual({ state: 'idle' }) + }) + + test('chrome-only states report nothing', () => { + for (const kind of ['clipboard', 'ctrlC', 'reconnected'] as const) { + expect(statusReportFor(kind, 'ok', 'idle')).toBeNull() + } + }) +}) + +describe('reportProgramStatus', () => { + test('returns false instead of throwing when there is no tty', () => { + const written: string[] = [] + const ok = reportProgramStatus( + { state: 'idle' }, + (s) => { + written.push(s) + return false + }, + {}, + ) + expect(ok).toBe(false) + expect(written).toHaveLength(1) + }) +}) diff --git a/cli/src/utils/program-status.ts b/cli/src/utils/program-status.ts new file mode 100644 index 0000000000..ad360c6811 --- /dev/null +++ b/cli/src/utils/program-status.ts @@ -0,0 +1,81 @@ +import { wrapForMultiplexer } from './terminal-title' + +/** OSC 7501 program status. https://www.superlogical.com/rex/docs/build/program-status */ +export type ProgramState = 'idle' | 'working' | 'done' | 'blocked' | 'error' +export type BlockedKind = 'permission' | 'question' | 'auth' + +export type StatusReport = { + state: ProgramState + kind?: BlockedKind +} + +type MultiplexerEnv = Parameters[1] +type WriteControl = (sequence: string) => boolean + +const APP = 'freebuff' +// ST, not BEL: a BEL inside a tmux passthrough can close the DCS early. +const TERMINATOR = '\x1b\\' + +/** One report per state transition. `kind` is only meaningful with `blocked`. */ +export function buildStatusSequence( + report: StatusReport, + env: MultiplexerEnv, +): string { + const pairs = [`state=${report.state}`] + if (report.state === 'blocked' && report.kind) { + pairs.push(`kind=${report.kind}`) + } + pairs.push(`app=${APP}`) + return wrapForMultiplexer(`\x1b]7501;${pairs.join(':')}${TERMINATOR}`, env) +} + +export function reportProgramStatus( + report: StatusReport, + write: WriteControl, + env: MultiplexerEnv, +): boolean { + return write(buildStatusSequence(report, env)) +} + +/** The state the CLI derives for its own UI, see `status-indicator-state.ts`. */ +export type IndicatorKind = + | 'idle' + | 'clipboard' + | 'ctrlC' + | 'connecting' + | 'retrying' + | 'capacityWait' + | 'waiting' + | 'streaming' + | 'reconnected' + | 'paused' + +/** + * Map the CLI's own indicator onto a report. `null` means "no change worth + * reporting": transient chrome, or a repeat of what is already showing. + */ +export function statusReportFor( + kind: IndicatorKind, + authStatus: 'ok' | 'retrying' | 'unreachable', + previous: ProgramState | null, +): StatusReport | null { + switch (kind) { + case 'streaming': + case 'waiting': + case 'retrying': + case 'capacityWait': + return { state: 'working' } + case 'connecting': + // Still retrying is work; unreachable means it needs credentials. + return authStatus === 'unreachable' + ? { state: 'blocked', kind: 'auth' } + : { state: 'working' } + case 'paused': + // ask_user is active: the one blocked-on-question state the CLI has. + return { state: 'blocked', kind: 'question' } + case 'idle': + return previous === 'working' ? { state: 'done' } : { state: 'idle' } + default: + return null + } +} diff --git a/cli/src/utils/terminal-title.ts b/cli/src/utils/terminal-title.ts index 1484fa5738..427db5b5cb 100644 --- a/cli/src/utils/terminal-title.ts +++ b/cli/src/utils/terminal-title.ts @@ -17,34 +17,45 @@ const MAX_TITLE_LENGTH = 60 const TITLE_PREFIX = IS_FREEBUFF ? 'Freebuff: ' : 'Codebuff: ' const OSC_TERMINATOR = '\x07' // BEL -function isInTmux(env: ReturnType): boolean { +type MultiplexerEnv = Pick< + ReturnType, + 'TMUX' | 'STY' | 'TERM' +> + +function isInTmux(env: MultiplexerEnv): boolean { return Boolean(env.TMUX) } -function isInScreen(env: ReturnType): boolean { +function isInScreen(env: MultiplexerEnv): 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}` - +/** Wrap an OSC sequence for tmux/screen passthrough, if one is in the way. */ +export function wrapForMultiplexer( + sequence: string, + env: MultiplexerEnv, +): string { // tmux passthrough: wrap in DCS and double ESC characters if (isInTmux(env)) { - const escaped = osc.replace(/\x1b/g, '\x1b\x1b') + const escaped = sequence.replace(/\x1b/g, '\x1b\x1b') return `\x1bPtmux;${escaped}\x1b\\` } // GNU screen passthrough: wrap in DCS if (isInScreen(env)) { - return `\x1bP${osc}\x1b\\` + return `\x1bP${sequence}\x1b\\` } - return osc + return sequence +} + +/** + * Build the OSC title sequence with tmux/screen passthrough if needed + */ +function buildTitleSequence(title: string, env: MultiplexerEnv): string { + return wrapForMultiplexer(`\x1b]0;${title}${OSC_TERMINATOR}`, env) } /**