Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(terminal): carry a partial ANSI escape across pty chunks

Chaitanya Giri44bfb1959737
diff --git a/src/renderer/src/components/ansiText.ts b/src/renderer/src/components/ansiText.ts
index 88e9d93c..c0aa0ed3 100644
--- a/src/renderer/src/components/ansiText.ts
+++ b/src/renderer/src/components/ansiText.ts
@@ -27,3 +27,38 @@ export function stripAnsi(chunk: string): string {
.replace(CHARSET_RE, '')
.replace(ESC2_RE, '');
}
+
+/**
+ * A pty write can split an escape sequence across two chunks (`ESC[3` in one
+ * read, `2m` in the next). `stripAnsi` is stateless, so the head of the
+ * sequence was dropped as a stray two-byte escape and the tail rendered as
+ * literal text ("2m"). The stream stripper holds the unfinished tail of a
+ * chunk and prepends it to the next one.
+ *
+ * The carry is bounded: a lone ESC that is never completed (or an OSC string
+ * that never terminates) must not buffer forever, so once the carry passes
+ * MAX_CARRY it is flushed through the stateless stripper as-is.
+ */
+export const MAX_CARRY = 256;
+
+// An ESC whose sequence has not reached its final byte yet: ESC alone, a CSI
+// with params/intermediates but no final, an OSC with no BEL/ST, or a bare
+// charset-select prefix.
+const PARTIAL_TAIL_RE = /^\x1b(?:\[[0-9;:?]*[ -/]*|\][^\x07\x1b]*|[()])?$/;
+
+export function createAnsiStripper(): (chunk: string) => string {
+ let carry = '';
+ return (chunk: string): string => {
+ let input = carry + chunk;
+ carry = '';
+ const esc = input.lastIndexOf('\x1b');
+ if (esc !== -1) {
+ const tail = input.slice(esc);
+ if (PARTIAL_TAIL_RE.test(tail) && tail.length <= MAX_CARRY) {
+ carry = tail;
+ input = input.slice(0, esc);
+ }
+ }
+ return stripAnsi(input);
+ };
+}
diff --git a/src/renderer/src/hooks/usePtyParser.ts b/src/renderer/src/hooks/usePtyParser.ts
index cb544896..089481b4 100644
--- a/src/renderer/src/hooks/usePtyParser.ts
+++ b/src/renderer/src/hooks/usePtyParser.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef } from 'react';
import { useStore, type ToolKind, type StationKind } from '@/store/store';
-import { stripAnsi } from '@/components/ansiText';
+import { createAnsiStripper } from '@/components/ansiText';
// Tool call lines look like: `● Read SPEC.md`, `● Bash npm test`, `● Edit src/foo.ts`
const TOOL_RE = /●\s+([A-Za-z][A-Za-z_]*)(?:\s+(.+))?/g;
@@ -51,6 +51,8 @@ export function usePtyParser(agentId: string) {
const updateAgent = useStore(s => s.updateAgent);
const pushFeed = useStore(s => s.pushFeed);
const idleTimerRef = useRef<number | null>(null);
+ // One stripper per agent: it carries an escape split across pty chunks.
+ const stripRef = useRef(createAnsiStripper());
const scheduleIdle = useCallback(() => {
if (idleTimerRef.current !== null) {
@@ -83,7 +85,7 @@ export function usePtyParser(agentId: string) {
}, []);
return useCallback((chunk: string) => {
- const text = stripAnsi(chunk);
+ const text = stripRef.current(chunk);
if (!text.trim()) return;
// Passive context-limit sniffing from /context output (the gauge poll
@@ -115,7 +117,7 @@ export function usePtyParser(agentId: string) {
if (lastTool) {
const station = TOOL_TO_STATION[lastTool] ?? 'desk';
const carrying = TOOLKIND_BY_NAME[lastTool] ?? undefined;
- // Collapse space runs: translated cursor-forwards (see stripAnsi) can
+ // Collapse space runs: translated cursor-forwards (see ansiText) can
// stand for several columns, and the bubble shouldn't show the gaps.
const summary = (lastArg ? `${lastTool.toLowerCase()} ${lastArg}` : lastTool.toLowerCase())
.replace(/\s+/g, ' ');
diff --git a/test/ansi-text.test.cjs b/test/ansi-text.test.cjs
index 617b101d..078c9e86 100644
--- a/test/ansi-text.test.cjs
+++ b/test/ansi-text.test.cjs
@@ -55,3 +55,62 @@ test('plain text — unicode included — passes through untouched', () => {
const s = '● Bash npm test — 131/131 ✔ (déjà vu)';
assert.equal(stripAnsi(s), s);
});
+
+// An escape split across two pty chunks must not leak its tail as text.
+const { createAnsiStripper, MAX_CARRY } = loadTs('src/renderer/src/components/ansiText.ts');
+
+function feed(chunks) {
+ const strip = createAnsiStripper();
+ return chunks.map(strip).join('');
+}
+
+test('stream: SGR split mid-params joins cleanly', () => {
+ assert.equal(feed(['a\x1b[3', '2mb\x1b[0m']), 'ab');
+ assert.equal(feed(['a\x1b', '[32mb']), 'ab', 'lone ESC at the boundary');
+ assert.equal(feed(['a\x1b[', '32mb']), 'ab', 'ESC[ at the boundary');
+});
+
+test('stream: cursor-forward split across chunks still becomes spaces', () => {
+ assert.equal(feed(['col\x1b[', '3Cnext']), 'col next');
+ assert.equal(feed(['col\x1b[3', 'Cnext']), 'col next');
+});
+
+test('stream: OSC split across chunks vanishes entirely', () => {
+ assert.equal(feed(['\x1b]0;my ti', 'tle\x07text']), 'text');
+ assert.equal(feed(['\x1b]8;;https://x.dev\x1b', '\\link\x1b]8;;\x1b\\']), 'link');
+});
+
+test('stream: charset select and two-byte escapes split at the boundary', () => {
+ assert.equal(feed(['\x1b(', 'Bascii']), 'ascii');
+ assert.equal(feed(['\x1b', '7saved\x1b8']), 'saved');
+});
+
+test('stream: a complete chunk carries nothing over', () => {
+ const strip = createAnsiStripper();
+ assert.equal(strip('\x1b[36m● Read\x1b[0m foo.ts'), '● Read foo.ts');
+ assert.equal(strip('plain'), 'plain');
+});
+
+test('stream: carry is bounded, a never-completed escape is flushed', () => {
+ const strip = createAnsiStripper();
+ assert.equal(strip('\x1b]0;' + 'x'.repeat(10)), '', 'held while under the cap');
+ // Over the cap the unterminated OSC is handed to the stateless stripper (which
+ // swallows its body) and the carry is dropped, so the next chunk is not
+ // appended to a buffer that grows forever.
+ assert.equal(strip('x'.repeat(MAX_CARRY)), '');
+ assert.equal(strip('after'), 'after');
+
+ // A CSI that never gets its final byte comes out as text once over the cap,
+ // exactly as the stateless stripper would have shown it.
+ const csi = createAnsiStripper();
+ assert.equal(csi('\x1b[' + '1;'.repeat(10)), '', 'held while under the cap');
+ const out = csi('1;'.repeat(MAX_CARRY));
+ assert.ok(out.length >= MAX_CARRY * 2, 'flushed as literal, not kept');
+ assert.equal(csi('after'), 'after');
+});
+
+test('stream: the stateless stripAnsi is unchanged by the carry logic', () => {
+ // This is the leak the stream stripper exists to prevent: the head is eaten
+ // as a stray two-byte escape and the params come out as text.
+ assert.equal(stripAnsi('a\x1b[3'), 'a3');
+});