Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-3282]): stop the flatten eating dunder identifiers and stop toggling on whitespace

[._.]/ Adam Eivy75a7d5f9c868
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index d825e24610..b200b73644 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -29,7 +29,7 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import CollapsibleText from '../components/ui/CollapsibleText';
import MarkdownOutput from '../components/cos/MarkdownOutput';
import { timeAgo, formatDateTime } from '../utils/formatters';
-import { markdownToPlainText } from '../utils/markdownText';
+import { markdownToPlainText, dropsMarkupWhenFlattened } from '../utils/markdownText';
import { coalesce } from '../utils/coalesce';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -695,7 +695,10 @@ function ReviewItem({ item, config, idScope, isEditing, onComplete, onDismiss, o
// The page re-renders on every socket event and on every keystroke in the
// quick-add input, and a body can be a multi-thousand-word agent prompt —
// flatten once per description rather than once per render, per card.
- const bodyPreview = useMemo(() => markdownToPlainText(item.description), [item.description]);
+ const body = useMemo(() => ({
+ preview: markdownToPlainText(item.description),
+ lossy: dropsMarkupWhenFlattened(item.description)
+ }), [item.description]);
useEffect(() => {
if (isEditing) {
@@ -771,15 +774,16 @@ function ReviewItem({ item, config, idScope, isEditing, onComplete, onDismiss, o
<CollapsibleText
id={`review-item-body-${idScope}-${item.id}`}
lines={3}
- text={bodyPreview}
+ text={body.preview}
className="text-xs text-gray-500 mt-0.5"
expandedContent={<MarkdownOutput content={item.description} />}
expandedClassName="max-h-80 overflow-y-auto pr-1"
// Flattening drops links, images and tables, so a body that
// fits in three lines still needs a route to its rendered
// form — otherwise a short description holding a scan-report
- // link becomes permanently inert text.
- forceToggle={bodyPreview !== item.description}
+ // link becomes permanently inert text. Markup loss only:
+ // a body that merely lost a trailing newline gets no toggle.
+ forceToggle={body.lossy}
/>
)}
{item.metadata?.reportUrl && (
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 7a41b23f64..593e41b1dc 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -24,7 +24,7 @@ grep -i "what you want to do" client/src/utils/README.md
|---|---|
| `formatters` | Date/time/duration/byte/word formatters (`formatBytes`, `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `parseSizeGb`, `recommendedRamGb`, `nameFromImageFilename`, …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. |
| `cronHelpers` | Cron preset list, `isCronExpression` detection, and `describeCron` human-readable rendering. |
-| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. |
+| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
| `timezone` | Timezone day-key helpers (`dayKeyInTimezone`, `todayKeyInTimezone`) — browser mirror of the server's `todayInTimezone`, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681). |
diff --git a/client/src/utils/markdownText.js b/client/src/utils/markdownText.js
index 202cca4e19..4a6fdb1639 100644
--- a/client/src/utils/markdownText.js
+++ b/client/src/utils/markdownText.js
@@ -16,6 +16,17 @@
// Fenced code blocks — keep the code, drop the fence lines (and any info string).
const FENCE_LINE = /^\s*(?:`{3,}|~{3,}).*$/;
+// The whitespace tail both exports share. Kept as one function so the
+// "did the flatten drop markup?" predicate below can subtract exactly the
+// whitespace normalization `markdownToPlainText` performs — no more, no less.
+const collapseWhitespace = (text) => text
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n{2,}/g, '\n') // collapse blank-line runs
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+ .join('\n');
+
/**
* Flatten markdown source to a single plain-text string suitable for a clamped
* preview. Returns `''` for anything that isn't a non-empty string.
@@ -38,7 +49,7 @@ export function markdownToPlainText(markdown) {
.replace(/^\s*[-*+]\s+/, '• ') // bullet markers
.replace(/^\s*(\d+)[.)]\s+/, '$1. ')); // ordered-list markers
- return lines
+ const flattened = lines
.join('\n')
.replace(/!\[([^\]]*)\]\([^)]*\)/g, (_, alt) => (alt ? `[${alt}]` : '[image]'))
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') // links → their text
@@ -56,15 +67,34 @@ export function markdownToPlainText(markdown) {
// `snakecase`. These bodies are stack traces and user-agent strings, so a
// corrupted-but-plausible preview is worse than an unstripped marker.
// Intra-word `*` emphasis IS conformant, so `*` needs no such gate.
- .replace(/\*\*(?=\S)([^*\n]*?\S)\*\*/g, '$1') // bold **…**
- .replace(/(^|\W)__(?=\S)([^_\n]*?\S)__(?!\w)/gm, '$1$2') // bold __…__
- .replace(/\*(?=\S)([^*\n]*?\S)\*/g, '$1') // italic *…*
- .replace(/(^|\W)_(?=\S)([^_\n]*?\S)_(?!\w)/gm, '$1$2') // italic _…_
- .replace(/~~(?=\S)([^~\n]*?\S)~~/g, '$1') // strikethrough
- .replace(/[ \t]+/g, ' ')
- .replace(/\n{2,}/g, '\n') // collapse blank-line runs
- .split('\n')
- .map(line => line.trim())
- .filter(Boolean)
- .join('\n');
+ // `__…__` additionally requires interior whitespace, because the
+ // word-boundary gate alone still eats the dunder identifiers these
+ // bodies are full of — `__init__` → `init`, `__proto__` → `proto`. Real
+ // `__strong__` prose is multi-word, and single-word bold in these bodies
+ // is written `**…**` anyway, so the trade lands on the safe side: a
+ // visible `__init__` beats a silently rewritten stack frame.
+ .replace(/\*\*(?=\S)([^*\n]*?\S)\*\*/g, '$1') // bold **…**
+ .replace(/(^|\W)__(?=\S)([^_\n]*?[ \t][^_\n]*?\S)__(?!\w)/gm, '$1$2') // bold __…__
+ .replace(/\*(?=\S)([^*\n]*?\S)\*/g, '$1') // italic *…*
+ .replace(/(^|\W)_(?=\S)([^_\n]*?\S)_(?!\w)/gm, '$1$2') // italic _…_
+ .replace(/~~(?=\S)([^~\n]*?\S)~~/g, '$1'); // strikethrough
+
+ return collapseWhitespace(flattened);
+}
+
+/**
+ * Did flattening `markdown` actually drop any markup — links, images, tables,
+ * emphasis, headings — as opposed to merely normalizing whitespace?
+ *
+ * A card previews the flattened text and hides the rendered markdown behind a
+ * disclosure. The disclosure has to appear for a SHORT body that still lost
+ * markup (a one-line description holding a scan-report link would otherwise be
+ * stranded as inert text), but must NOT appear for a body that lost nothing —
+ * comparing raw source to flattened output flags every trailing newline and
+ * double space, putting a "Show more" that reveals nothing on the most common
+ * short-body shape, on a page whose whole purpose is removing queue noise.
+ */
+export function dropsMarkupWhenFlattened(markdown) {
+ if (typeof markdown !== 'string' || !markdown) return false;
+ return markdownToPlainText(markdown) !== collapseWhitespace(markdown.replace(/\r\n?/g, '\n'));
}
diff --git a/client/src/utils/markdownText.test.js b/client/src/utils/markdownText.test.js
index b219208f6d..8283c32377 100644
--- a/client/src/utils/markdownText.test.js
+++ b/client/src/utils/markdownText.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { markdownToPlainText } from './markdownText';
+import { markdownToPlainText, dropsMarkupWhenFlattened } from './markdownText';
describe('markdownToPlainText', () => {
it('returns an empty string for non-string / empty input', () => {
@@ -21,8 +21,10 @@ describe('markdownToPlainText', () => {
it('unwraps emphasis, inline code, and links to their text', () => {
expect(markdownToPlainText('**bold** and *italic* and `code`'))
.toBe('bold and italic and code');
- expect(markdownToPlainText('__bold__ and _italic_ and ~~gone~~'))
- .toBe('bold and italic and gone');
+ // `__…__` needs interior whitespace to unwrap — single-word `__x__` is
+ // deliberately preserved so dunder identifiers survive (see below).
+ expect(markdownToPlainText('__bold text__ and _italic_ and ~~gone~~'))
+ .toBe('bold text and italic and gone');
expect(markdownToPlainText('see [the report](/data/reports/x.html)'))
.toBe('see the report');
});
@@ -43,6 +45,29 @@ describe('markdownToPlainText', () => {
expect(markdownToPlainText('do_work() then snake_case_name')).toBe('do_work() then snake_case_name');
});
+ it('leaves dunder identifiers alone even though CommonMark would emphasize them', () => {
+ // `__init__` IS valid strong emphasis, but in a stack frame it is a symbol
+ // name — rewriting it to `init` produces a frame the reader cannot tell is
+ // wrong. Real `__strong__` prose is multi-word, so interior whitespace is
+ // the discriminator.
+ expect(markdownToPlainText('at __init__ (/app/main.py:12)')).toBe('at __init__ (/app/main.py:12)');
+ expect(markdownToPlainText('__proto__ and __name__ and __dict__'))
+ .toBe('__proto__ and __name__ and __dict__');
+ // Multi-word `__strong__` still unwraps.
+ expect(markdownToPlainText('__really important__ note')).toBe('really important note');
+ });
+
+ it('stays linear on one enormous line', () => {
+ // Every emphasis content class excludes its own delimiter, which is what
+ // keeps an unmatched opener from rescanning to end-of-line per occurrence.
+ // Widening any class back to `[^\n]*?` reintroduces a multi-second
+ // main-thread hang on a pasted transcript — this pins that invariant.
+ const huge = '**word '.repeat(28000); // ~200KB, no newlines, all openers unmatched
+ const started = performance.now();
+ markdownToPlainText(huge);
+ expect(performance.now() - started).toBeLessThan(1000);
+ });
+
it('scopes emphasis to a single line so a stray marker cannot swallow the body', () => {
// An unclosed `**` in an agent-authored body must leave the rest of the
// document intact (and must not backtrack across it): the marker on the
@@ -93,3 +118,30 @@ describe('markdownToPlainText', () => {
.toBe('TypeError: x is not a function\nat foo (/app/a.js:1:2)\nat bar (/app/b.js:3:4)');
});
});
+
+describe('dropsMarkupWhenFlattened', () => {
+ it('is false for a body that only loses whitespace', () => {
+ // These are the most common short-body shapes. A "Show more" here would
+ // reveal exactly the text already on screen — pure queue noise.
+ expect(dropsMarkupWhenFlattened('Backup failed at 03:00.\n')).toBe(false);
+ expect(dropsMarkupWhenFlattened('Line one.\n\nLine two.')).toBe(false);
+ expect(dropsMarkupWhenFlattened('Backup failed. Retry queued.')).toBe(false);
+ expect(dropsMarkupWhenFlattened('plain text')).toBe(false);
+ });
+
+ it('is true when real markup would be dropped', () => {
+ expect(dropsMarkupWhenFlattened('See the [scan report](/r.html).')).toBe(true);
+ expect(dropsMarkupWhenFlattened('![diagram](/d.png)')).toBe(true);
+ expect(dropsMarkupWhenFlattened('## Heading')).toBe(true);
+ expect(dropsMarkupWhenFlattened('- a bullet')).toBe(true);
+ expect(dropsMarkupWhenFlattened('**bold**')).toBe(true);
+ expect(dropsMarkupWhenFlattened('```\ncode\n```')).toBe(true);
+ });
+
+ it('is false for non-string / empty input', () => {
+ expect(dropsMarkupWhenFlattened(undefined)).toBe(false);
+ expect(dropsMarkupWhenFlattened(null)).toBe(false);
+ expect(dropsMarkupWhenFlattened('')).toBe(false);
+ expect(dropsMarkupWhenFlattened(42)).toBe(false);
+ });
+});