Skip to content
5 changes: 5 additions & 0 deletions .changeset/save-agent-error-newlines.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@truefoundry/trueforge-ui': patch
---

Decode common escape sequences (`\n`, `\t`, `\r`, `\uXXXX`, …) in user-facing API error messages and render them with `whitespace-pre-wrap` so multi-line Zod validation output displays correctly.
6 changes: 5 additions & 1 deletion packages/trueforge-ui/src/atoms/SaveAgentButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,11 @@ function SaveAgentButtonContent({
</div>

{error ? (
<p ref={errorRef} role="alert" className="text-failure-bg mt-3 text-sm">
<p
ref={errorRef}
role="alert"
className="text-failure-bg mt-3 text-sm wrap-break-word whitespace-pre-wrap tab-4"
>
{error}
</p>
) : null}
Expand Down
112 changes: 104 additions & 8 deletions packages/trueforge-ui/src/utils/getErrorMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,99 @@ function readNonEmptyString(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() !== '' ? value : undefined;
}

const LITERAL_ESCAPE_PATTERN = /\\(?:[nrtbfv0'"\\]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/; // literal escape sequences like \n, \t, \b, \f, \v, \uXXXX, \xHH
const REAL_CONTROL_PATTERN = /[\n\t\b\f\v]/; // real control characters like \n, \t, \b, \f, \v

function decodeLiteralEscapes(text: string): string {
let out = '';
for (let i = 0; i < text.length; i += 1) {
const char = text[i];
if (char !== '\\' || i + 1 >= text.length) {
out += char;
continue;
}

const next = text[i + 1];
switch (next) {
case 'n':
out += '\n';
i += 1;
break;
case 't':
out += '\t';
i += 1;
break;
case 'r':
out += '\r';
i += 1;
break;
case 'b':
out += '\b';
i += 1;
break;
case 'f':
out += '\f';
i += 1;
break;
case 'v':
out += '\v';
i += 1;
break;
case '0':
out += '\0';
i += 1;
break;
case '\\':
out += '\\';
i += 1;
break;
case '"':
out += '"';
i += 1;
break;
case "'":
out += "'";
i += 1;
break;
case 'u': {
const hex = text.slice(i + 2, i + 6);
if (/^[0-9a-fA-F]{4}$/.test(hex)) {
out += String.fromCharCode(Number.parseInt(hex, 16));
i += 5;
} else {
out += char;
}
break;
}
case 'x': {
const hex = text.slice(i + 2, i + 4);
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
out += String.fromCharCode(Number.parseInt(hex, 16));
i += 3;
} else {
out += char;
}
break;
}
default:
out += char;
break;
}
}
return out;
}

// Decodes JSON/C-style escape sequences (e.g., \n, \t) in error messages, preserving real control characters and normalizing line endings.
export function decodeErrorMessageEscapes(text: string): string {
const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
if (REAL_CONTROL_PATTERN.test(normalized) || !LITERAL_ESCAPE_PATTERN.test(normalized)) {
// If the string contains real control characters or no literal escape sequences, return the normalized string.
return normalized;
}
// else decode the literal escape sequences and normalize line endings
return decodeLiteralEscapes(normalized).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
Comment thread
vinit-truefoundry marked this conversation as resolved.
Resolved
}

/**
* Reads a display string from API-shaped errors: `message`, then nested
* `error.message`. When neither exists, stringifies the value.
Expand Down Expand Up @@ -36,30 +129,33 @@ function stringifyError(error: unknown): string {
* User-facing error text. Prefers HTTP body `{ error: { message } }` when
* present (e.g. TrueForgeError), then `error.message` / `error.error.message`,
* then `fallback`, then a string form of the value.
*
* Escape sequences (`\n`, `\t`, `\r`, `\uXXXX`, …) are decoded for display when
* still present as literal text.
*/
export function getErrorMessage(error: unknown, fallback?: string): string {
if (typeof error === 'string') {
const trimmed = error.trim();
if (trimmed !== '') return error;
return fallback ?? error;
if (trimmed !== '') return decodeErrorMessageEscapes(error);
return fallback != null ? decodeErrorMessageEscapes(fallback) : decodeErrorMessageEscapes(error);
}

if (isRecord(error) && 'body' in error) {
const fromBody = messageFromErrorShaped(error.body);
if (fromBody != null) return fromBody;
if (fromBody != null) return decodeErrorMessageEscapes(fromBody);
if (error.body != null) {
if (typeof error.body === 'string') {
const trimmed = error.body.trim();
if (trimmed !== '') return error.body;
if (trimmed !== '') return decodeErrorMessageEscapes(error.body);
} else {
return stringifyError(error.body);
return decodeErrorMessageEscapes(stringifyError(error.body));
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
}

const fromShape = messageFromErrorShaped(error);
if (fromShape != null) return fromShape;
if (fromShape != null) return decodeErrorMessageEscapes(fromShape);

if (fallback != null) return fallback;
return stringifyError(error);
if (fallback != null) return decodeErrorMessageEscapes(fallback);
return decodeErrorMessageEscapes(stringifyError(error));
}
22 changes: 22 additions & 0 deletions packages/trueforge-ui/test/atoms/SaveAgentButton.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -409,4 +409,26 @@ describe('SaveAgentButton', () => {

expect(await within(dialog).findByRole('alert')).toHaveTextContent('Agent name already exists');
});

it('preserves decoded escapes in validation error messages', async () => {
renderButton({
saveAgent: vi.fn(async () => {
throw {
body: {
error: {
message: 'line one\\nline two\\tindented',
},
},
};
}),
});
fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));
const dialog = await screen.findByRole('dialog', { name: 'Save agent' });
fireEvent.change(within(dialog).getByLabelText('Agent name'), { target: { value: 'bad name' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));

const alert = await within(dialog).findByRole('alert');
expect(alert).toHaveClass('whitespace-pre-wrap');
expect(alert.textContent).toBe('line one\nline two\tindented');
});
});
38 changes: 37 additions & 1 deletion packages/trueforge-ui/test/utils/getErrorMessage.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
import { describe, expect, it } from 'vitest';

import { getErrorMessage } from '@/utils/getErrorMessage.js';
import { decodeErrorMessageEscapes, getErrorMessage } from '@/utils/getErrorMessage.js';

describe('decodeErrorMessageEscapes', () => {
it('decodes common JSON/C escapes when still literal', () => {
expect(decodeErrorMessageEscapes('a\\nb\\tc\\rd')).toBe('a\nb\tc\nd');
expect(decodeErrorMessageEscapes('say \\"hi\\" and \\\\')).toBe('say "hi" and \\');
expect(decodeErrorMessageEscapes('bell\\b form\\f vert\\v null\\0')).toBe('bell\b form\f vert\v null\0');
});

it('decodes \\uXXXX and \\xHH', () => {
expect(decodeErrorMessageEscapes('cafe\\u00e9')).toBe('cafeé');
expect(decodeErrorMessageEscapes('A\\x42')).toBe('AB');
});

it('leaves already-decoded control characters unchanged and normalizes CR', () => {
expect(decodeErrorMessageEscapes('a\nb\\tstill-literal')).toBe('a\nb\\tstill-literal');
expect(decodeErrorMessageEscapes('a\nb\tc')).toBe('a\nb\tc');
expect(decodeErrorMessageEscapes('a\r\nb\rc')).toBe('a\nb\nc');
});

it('keeps unknown escapes intact', () => {
expect(decodeErrorMessageEscapes('not\\qescape')).toBe('not\\qescape');
expect(decodeErrorMessageEscapes('bad\\uXX')).toBe('bad\\uXX');
});
});

describe('getErrorMessage', () => {
it('prefers error.message', () => {
Expand All @@ -19,6 +43,18 @@ describe('getErrorMessage', () => {
expect(getErrorMessage(err)).toBe('Name taken');
});

it('decodes escapes in HTTP body error.message', () => {
const err = Object.assign(new Error('request failed'), {
statusCode: 400,
body: {
error: {
message: '✖ must be 2–64 lowercase chars\\n → at name\\tand also a tab',
},
},
});
expect(getErrorMessage(err)).toBe('✖ must be 2–64 lowercase chars\n → at name\tand also a tab');
});

it('stringifies a non-message HTTP body', () => {
const err = Object.assign(new Error('request failed'), {
statusCode: 422,
Expand Down