Skip to content

Commit 702cbba

Browse files
committed
fix(web): render Claude insight fences as callouts
Explanatory and learning styles wrap teaching notes in a ★ Insight box-drawing fence. Those rules wrap through the assistant message, so the fences are parsed out and drawn as a titled callout.
1 parent 5547d7c commit 702cbba

4 files changed

Lines changed: 215 additions & 4 deletions

File tree

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { useRenderedAppearance } from "../../hooks/useTheme";
22
import type { Root, RootContent } from "mdast";
33
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
44
import { shallow } from "zustand/vanilla/shallow";
5-
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
5+
import { splitAssistantInsights } from "@t3tools/client-runtime/assistant-insights";
66
import { MarkdownFindContext, findRevealRef } from "./markdownFindContext";
77
import { useChatCanvas } from "./ChatCanvasContext";
88
import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog";
@@ -81,6 +81,7 @@ import {
8181
useLayoutEffect,
8282
useRef,
8383
useState,
84+
type ComponentProps,
8485
type KeyboardEvent,
8586
type MouseEvent,
8687
type ReactNode,
@@ -2661,6 +2662,37 @@ function AttemptFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "at
26612662
);
26622663
}
26632664

2665+
function AssistantMessageBody({
2666+
text,
2667+
streaming,
2668+
...markdown
2669+
}: {
2670+
text: string;
2671+
streaming: boolean;
2672+
} & Omit<ComponentProps<typeof ChatMarkdown>, "text" | "lineBreaks" | "isStreaming">) {
2673+
const segments = splitAssistantInsights(text);
2674+
let cursor = 0;
2675+
return segments.map((segment, index) => {
2676+
const key = cursor;
2677+
cursor += (segment.kind === "insight" ? segment.body.length : segment.text.length) + 1;
2678+
const isStreaming = streaming && index === segments.length - 1;
2679+
if (segment.kind === "insight") {
2680+
return (
2681+
<aside key={key} role="note" className="my-2 border-l-2 border-info pl-3">
2682+
<p className="mb-1 flex items-center gap-1.5 font-medium text-info">
2683+
<span aria-hidden="true">★</span>
2684+
{segment.title}
2685+
</p>
2686+
{segment.body.length > 0 ? (
2687+
<ChatMarkdown text={segment.body} lineBreaks isStreaming={isStreaming} {...markdown} />
2688+
) : null}
2689+
</aside>
2690+
);
2691+
}
2692+
return <ChatMarkdown key={key} text={segment.text} isStreaming={isStreaming} {...markdown} />;
2693+
});
2694+
}
2695+
26642696
function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
26652697
const ctx = use(TimelineRowCtx);
26662698
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
@@ -2677,12 +2709,11 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
26772709
request={ctx.citationRequest}
26782710
listRef={ctx.listRef}
26792711
>
2680-
<ChatMarkdown
2712+
<AssistantMessageBody
26812713
text={messageText}
2714+
streaming={Boolean(row.message.streaming)}
26822715
cwd={ctx.markdownCwd}
26832716
threadRef={ctx.threadRef ?? undefined}
2684-
isStreaming={Boolean(row.message.streaming)}
2685-
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
26862717
skills={ctx.skills}
26872718
headingLevelOffset={MESSAGE_HEADING_LEVEL}
26882719
onUseArtifactTemplate={ctx.onUseArtifactTemplate}

‎packages/client-runtime/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
"private": true,
44
"type": "module",
55
"exports": {
6+
"./assistant-insights": {
7+
"types": "./src/assistantInsights.ts",
8+
"default": "./src/assistantInsights.ts"
9+
},
610
"./composerThreadItems": {
711
"types": "./src/composerThreadItems.ts",
812
"default": "./src/composerThreadItems.ts"
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import { splitAssistantInsights } from "./assistantInsights.ts";
4+
5+
const rule = "─".repeat(20);
6+
7+
function fenced(body: string, wrap = ""): string {
8+
return [`${wrap}★ Insight ${rule}${wrap}`, body, `${wrap}${rule}${wrap}`].join("\n");
9+
}
10+
11+
describe("splitAssistantInsights", () => {
12+
it("returns ordinary text, including a bare insight label, unchanged", () => {
13+
for (const text of ["A normal\nmarkdown paragraph", "★ Insight is a useful label.\r\n─────"]) {
14+
expect(splitAssistantInsights(text)).toEqual([{ kind: "markdown", text }]);
15+
}
16+
});
17+
18+
it("extracts plain and backtick-wrapped fences into a title and body", () => {
19+
for (const wrap of ["", "`"]) {
20+
const text = [
21+
"Before.",
22+
"",
23+
fenced("First observation.\nSecond **observation**.", wrap),
24+
"",
25+
"After.",
26+
].join("\n");
27+
expect(splitAssistantInsights(text)).toEqual([
28+
{ kind: "markdown", text: "Before." },
29+
{
30+
kind: "insight",
31+
title: "Insight",
32+
body: "First observation.\nSecond **observation**.",
33+
},
34+
{ kind: "markdown", text: "After." },
35+
]);
36+
}
37+
});
38+
39+
it("keeps fenced examples literal and still splits a real insight", () => {
40+
for (const marker of ["```", "~~~"]) {
41+
const example = [marker + "text", "★ Insight " + rule, "literal", rule, marker].join("\n");
42+
const text = [fenced("- Use stable keys."), "", example].join("\n");
43+
expect(splitAssistantInsights(text)).toEqual([
44+
{ kind: "insight", title: "Insight", body: "- Use stable keys." },
45+
{ kind: "markdown", text: example },
46+
]);
47+
expect(splitAssistantInsights(example)).toEqual([{ kind: "markdown", text: example }]);
48+
}
49+
});
50+
51+
it("splits several insights and holds an unfinished streaming body open", () => {
52+
const text = [fenced("One."), "Between.", "★ Insight " + rule, "Second"].join("\n");
53+
expect(splitAssistantInsights(text)).toEqual([
54+
{ kind: "insight", title: "Insight", body: "One." },
55+
{ kind: "markdown", text: "Between." },
56+
{ kind: "insight", title: "Insight", body: "Second" },
57+
]);
58+
});
59+
60+
it("does not end an insight on a dash line inside its code sample", () => {
61+
const body = ["```", rule, "```", "After the sample."].join("\n");
62+
expect(splitAssistantInsights(fenced(body))).toEqual([
63+
{ kind: "insight", title: "Insight", body },
64+
]);
65+
});
66+
67+
it("closes only on a delimiter indented like the opening fence", () => {
68+
const text = [" ★ Insight " + rule, " First.", rule, " Second.", " " + rule, "After."].join(
69+
"\n",
70+
);
71+
expect(splitAssistantInsights(text)).toEqual([
72+
{ kind: "insight", title: "Insight", body: "First.\n" + rule + "\nSecond." },
73+
{ kind: "markdown", text: "After." },
74+
]);
75+
});
76+
77+
it.each(["\r\n", "\r"])("treats %j line endings like newlines", (lineEnding) => {
78+
const lines = ["★ Insight " + rule, "First.", rule, "After."];
79+
expect(splitAssistantInsights(lines.join(lineEnding))).toEqual(
80+
splitAssistantInsights(lines.join("\n")),
81+
);
82+
});
83+
});
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
export type AssistantTextSegment =
2+
| { readonly kind: "markdown"; readonly text: string }
3+
| { readonly kind: "insight"; readonly title: "Insight"; readonly body: string };
4+
5+
const INSIGHT_START = /^([ \t]*)(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
6+
const INSIGHT_END = /^([ \t]*)(`?)─{3,}\2[ \t]*$/u;
7+
const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/u;
8+
const FENCE_CLOSE = /^ {0,3}(`+|~+)[ \t]*$/u;
9+
10+
function fenceMarker(line: string): string | undefined {
11+
const open = FENCE_OPEN.exec(line);
12+
const marker = open?.[1];
13+
if (marker === undefined) return undefined;
14+
if (marker.startsWith("`") && (open?.[2] ?? "").includes("`")) return undefined;
15+
return marker;
16+
}
17+
18+
function closesFence(line: string, marker: string): boolean {
19+
const token = FENCE_CLOSE.exec(line)?.[1];
20+
return token !== undefined && token.startsWith(marker[0] ?? "") && token.length >= marker.length;
21+
}
22+
23+
function pushMarkdown(parts: AssistantTextSegment[], lines: string[]): void {
24+
const text = lines.join("\n").replace(/^\n+|\n+$/gu, "");
25+
lines.length = 0;
26+
if (text.length > 0) parts.push({ kind: "markdown", text });
27+
}
28+
29+
function insight(body: readonly string[]): AssistantTextSegment {
30+
return { kind: "insight", title: "Insight", body: body.join("\n").replace(/^\n+|\n+$/gu, "") };
31+
}
32+
33+
/**
34+
* Explanatory and learning styles wrap notes in a `★ Insight` box-drawing fence.
35+
* Those rules wrap through the message under `overflow-wrap: anywhere`, so they
36+
* are removed here and drawn as a callout instead of markdown.
37+
*/
38+
export function splitAssistantInsights(text: string): readonly AssistantTextSegment[] {
39+
if (!text.includes("★ Insight")) return [{ kind: "markdown", text }];
40+
41+
const lines = text.split(/\r\n|\r|\n/u);
42+
const parts: AssistantTextSegment[] = [];
43+
const markdown: string[] = [];
44+
let fence: string | undefined;
45+
let insightIndent: string | undefined;
46+
const insightBody: string[] = [];
47+
let found = false;
48+
49+
const take = (bucket: string[], line: string) => {
50+
if (fence !== undefined) {
51+
bucket.push(line);
52+
if (closesFence(line, fence)) fence = undefined;
53+
return true;
54+
}
55+
const marker = fenceMarker(line);
56+
if (marker === undefined) return false;
57+
fence = marker;
58+
bucket.push(line);
59+
return true;
60+
};
61+
62+
for (const line of lines) {
63+
if (insightIndent === undefined) {
64+
if (take(markdown, line)) continue;
65+
const start = INSIGHT_START.exec(line);
66+
if (start) {
67+
pushMarkdown(parts, markdown);
68+
insightIndent = start[1] ?? "";
69+
insightBody.length = 0;
70+
found = true;
71+
continue;
72+
}
73+
markdown.push(line);
74+
continue;
75+
}
76+
77+
const content = line.startsWith(insightIndent) ? line.slice(insightIndent.length) : line;
78+
if (take(insightBody, content)) continue;
79+
const end = INSIGHT_END.exec(line);
80+
if (end && (end[1] ?? "") === insightIndent) {
81+
parts.push(insight(insightBody));
82+
insightIndent = undefined;
83+
insightBody.length = 0;
84+
continue;
85+
}
86+
insightBody.push(content);
87+
}
88+
89+
if (!found) return [{ kind: "markdown", text }];
90+
if (insightIndent !== undefined) parts.push(insight(insightBody));
91+
else pushMarkdown(parts, markdown);
92+
return parts;
93+
}

0 commit comments

Comments
 (0)