The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hermes-ink): reset SGR 22 when a style transition drops bold or dim
Brooklyn Nicholson31f62d76af06
diff --git a/ui-tui/packages/hermes-ink/src/ink/ansi-transition.test.ts b/ui-tui/packages/hermes-ink/src/ink/ansi-transition.test.tsnew file mode 100644index 00000000000..358360676f7--- /dev/null+++ b/ui-tui/packages/hermes-ink/src/ink/ansi-transition.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest'++import { transitionAnsiCodes } from './ansi-transition.js'+import { StylePool } from './screen.js'++const ESC = '\u001b'+const BOLD = { type: 'ansi' as const, code: `${ESC}[1m`, endCode: `${ESC}[22m` }+const DIM = { type: 'ansi' as const, code: `${ESC}[2m`, endCode: `${ESC}[22m` }+const FG_PINK = { type: 'ansi' as const, code: `${ESC}[38;5;204m`, endCode: `${ESC}[39m` }+const FG_GRAY = { type: 'ansi' as const, code: `${ESC}[38;5;245m`, endCode: `${ESC}[39m` }++const codes = (result: ReturnType<typeof transitionAnsiCodes>) => result.map(c => c.code)++/**+ * SGR 1 (bold) and SGR 2 (dim) are independent attributes sharing one reset+ * (SGR 22). A transition that swaps one for the other MUST pass through 22 —+ * otherwise the terminal accumulates both and every later transition is+ * computed from phantom state (the "random dimness/opacity" drift).+ */+describe('transitionAnsiCodes weight family', () => {+ it('bold → dim resets the weight family before applying dim', () => {+ expect(codes(transitionAnsiCodes([BOLD], [DIM]))).toEqual([`${ESC}[22m`, `${ESC}[2m`])+ })++ it('dim → bold resets the weight family before applying bold', () => {+ expect(codes(transitionAnsiCodes([DIM], [BOLD]))).toEqual([`${ESC}[22m`, `${ESC}[1m`])+ })++ it('carries color changes through a weight swap', () => {+ expect(codes(transitionAnsiCodes([BOLD, FG_PINK], [DIM, FG_GRAY]))).toEqual([+ `${ESC}[22m`,+ `${ESC}[38;5;245m`,+ `${ESC}[2m`+ ])+ })++ it('weight removal to plain still emits the reset', () => {+ expect(codes(transitionAnsiCodes([BOLD, FG_PINK], [FG_GRAY]))).toEqual([`${ESC}[22m`, `${ESC}[38;5;245m`])+ expect(codes(transitionAnsiCodes([DIM], []))).toEqual([`${ESC}[22m`])+ })++ it('pure additions stay minimal (no gratuitous resets)', () => {+ expect(codes(transitionAnsiCodes([], [BOLD]))).toEqual([`${ESC}[1m`])+ expect(codes(transitionAnsiCodes([FG_PINK], [FG_PINK, DIM]))).toEqual([`${ESC}[2m`])+ expect(codes(transitionAnsiCodes([BOLD], [BOLD, FG_PINK]))).toEqual([`${ESC}[38;5;204m`])+ })++ it('unchanged styles emit nothing', () => {+ expect(transitionAnsiCodes([BOLD, FG_PINK], [BOLD, FG_PINK])).toEqual([])+ })+})++describe('StylePool.transition weight correctness', () => {+ // Minimal SGR interpreter: the ground truth a real terminal applies.+ const applySgr = (state: { bold: boolean; dim: boolean; fg: string }, str: string) => {+ const re = new RegExp(`${ESC}\\[([0-9;]*)m`, 'g')+ let match: null | RegExpExecArray++ while ((match = re.exec(str)) !== null) {+ const parts = (match[1] || '0').split(';')++ for (let i = 0; i < parts.length; i++) {+ const p = parts[i]!++ if (p === '0' || p === '') {+ state.bold = false+ state.dim = false+ state.fg = 'default'+ } else if (p === '1') {+ state.bold = true+ } else if (p === '2') {+ state.dim = true+ } else if (p === '22') {+ state.bold = false+ state.dim = false+ } else if (p === '39') {+ state.fg = 'default'+ } else if (p === '38' && parts[i + 1] === '5') {+ state.fg = `ansi${parts[i + 2]}`+ i += 2+ }+ }+ }+ }++ it('every pairwise transition lands the terminal in exactly the target state', () => {+ const pool = new StylePool()++ const ids = [+ pool.none,+ pool.intern([BOLD]),+ pool.intern([DIM]),+ pool.intern([FG_PINK]),+ pool.intern([BOLD, FG_PINK]),+ pool.intern([DIM, FG_GRAY]),+ pool.intern([DIM, FG_PINK]),+ pool.intern([BOLD, FG_GRAY])+ ]++ const expected = (id: number) => {+ const styles = pool.get(id)+ const fgCode = styles.find(s => s.endCode === `${ESC}[39m`)?.code++ return {+ bold: styles.some(s => s.code === `${ESC}[1m`),+ dim: styles.some(s => s.code === `${ESC}[2m`),+ fg: fgCode ? `ansi${fgCode.slice(7, -1)}` : 'default'+ }+ }++ for (const from of ids) {+ for (const to of ids) {+ const state = expected(from)+ applySgr(state, pool.transition(from, to))+ expect(state, `transition ${from} → ${to}`).toEqual(expected(to))+ }+ }+ })+})diff --git a/ui-tui/packages/hermes-ink/src/ink/ansi-transition.ts b/ui-tui/packages/hermes-ink/src/ink/ansi-transition.tsnew file mode 100644index 00000000000..2d2d920faf1--- /dev/null+++ b/ui-tui/packages/hermes-ink/src/ink/ansi-transition.ts@@ -0,0 +1,56 @@+import { type AnsiCode, diffAnsiCodes } from '@alcalzone/ansi-tokenize'++/**+ * Bold (SGR 1) and dim (SGR 2) are INDEPENDENT terminal attributes that share+ * one reset code (SGR 22). `diffAnsiCodes` models "same endCode" as "same+ * slot, new start code overwrites" — true for fg (39) / bg (49), false here:+ * emitting `[2m` over a bold cell yields bold+dim, not dim.+ *+ * Every transition the diff renderer emits from that assumption leaves the+ * terminal's real attributes diverged from the StylePool's tracked state, and+ * because later transitions are computed FROM that tracked state, the+ * corruption compounds and sticks — visible as random spans of wrong+ * weight/brightness ("random dimness/opacity changes") that depend on which+ * cells happened to change in which order.+ */+const WEIGHT_END = '\u001b[22m'++const WEIGHT_RESET: AnsiCode = {+ type: 'ansi',+ code: WEIGHT_END,+ endCode: WEIGHT_END+}++/**+ * Like `diffAnsiCodes`, but correct for the shared-reset weight family:+ * when the bold/dim set changes in a way that removes a flag, emit SGR 22+ * first, then re-apply every weight flag the target style carries.+ */+export function transitionAnsiCodes(from: AnsiCode[], to: AnsiCode[]): AnsiCode[] {+ const fromWeights = from.filter(code => code.endCode === WEIGHT_END)+ const toWeights = to.filter(code => code.endCode === WEIGHT_END)++ if (fromWeights.length === 0) {+ // Nothing to un-set; the library's "add what's missing" pass is correct.+ return diffAnsiCodes(from, to)+ }++ const toWeightCodes = new Set(toWeights.map(code => code.code))+ const removesWeight = fromWeights.some(code => !toWeightCodes.has(code.code))++ if (!removesWeight) {+ // from's weights ⊆ to's weights — additions only, library handles it.+ return diffAnsiCodes(from, to)+ }++ // A weight flag must be dropped: SGR 22 is the only way (it clears BOTH),+ // so reset the family and re-apply the target's full weight set. The rest+ // of the style (colors, italic, underline, …) diffs normally with the+ // weight family stripped from both sides.+ const rest = diffAnsiCodes(+ from.filter(code => code.endCode !== WEIGHT_END),+ to.filter(code => code.endCode !== WEIGHT_END)+ )++ return [WEIGHT_RESET, ...rest, ...toWeights]+}diff --git a/ui-tui/packages/hermes-ink/src/ink/log-update.ts b/ui-tui/packages/hermes-ink/src/ink/log-update.tsindex a428060b97d..e0536125c9a 100644--- a/ui-tui/packages/hermes-ink/src/ink/log-update.ts+++ b/ui-tui/packages/hermes-ink/src/ink/log-update.ts@@ -1,7 +1,8 @@-import { type AnsiCode, ansiCodesToString, diffAnsiCodes } from '@alcalzone/ansi-tokenize'+import { type AnsiCode, ansiCodesToString } from '@alcalzone/ansi-tokenize'import { logForDebugging } from '../utils/debug.js'+import { transitionAnsiCodes } from './ansi-transition.js'import type { Diff, FlickerReason, Frame } from './frame.js'import type { Point } from './layout/geometry.js'import {@@ -88,7 +89,7 @@ export class LogUpdate {}const cellStyles = this.options.stylePool.get(cell.styleId)- const styleDiff = diffAnsiCodes(currentStyles, cellStyles)+ const styleDiff = transitionAnsiCodes(currentStyles, cellStyles)if (styleDiff.length > 0) {line += ansiCodesToString(styleDiff)@@ -106,7 +107,7 @@ export class LogUpdate {}// Reset styles at end of line so trimEnd doesn't leave dangling codes- const resetCodes = diffAnsiCodes(currentStyles, [])+ const resetCodes = transitionAnsiCodes(currentStyles, [])if (resetCodes.length > 0) {line += ansiCodesToString(resetCodes)diff --git a/ui-tui/packages/hermes-ink/src/ink/screen.ts b/ui-tui/packages/hermes-ink/src/ink/screen.tsindex 6916b8598e2..e101fdc0292 100644--- a/ui-tui/packages/hermes-ink/src/ink/screen.ts+++ b/ui-tui/packages/hermes-ink/src/ink/screen.ts@@ -1,5 +1,6 @@-import { type AnsiCode, ansiCodesToString, diffAnsiCodes } from '@alcalzone/ansi-tokenize'+import { type AnsiCode, ansiCodesToString } from '@alcalzone/ansi-tokenize'+import { transitionAnsiCodes } from './ansi-transition.js'import { type Point, type Rectangle, type Size, unionRect } from './layout/geometry.js'import { BEL, ESC, SEP } from './termio/ansi.js'import * as warn from './warn.js'@@ -179,7 +180,7 @@ export class StylePool {this.transitionCache.clear()}- str = ansiCodesToString(diffAnsiCodes(this.get(fromId), this.get(toId)))+ str = ansiCodesToString(transitionAnsiCodes(this.get(fromId), this.get(toId)))this.transitionCache.set(key, str)}