Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 51 additions & 50 deletions Sources/WeiBei/Resources/Editor/editor-entry.js

Large diffs are not rendered by default.

10 changes: 5 additions & 5 deletions Sources/WeiBei/Resources/Editor/editor-resources.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
"assets": [
{
"name": "editor-entry.js",
"bytes": 598840,
"sha256": "6c58c364c03bee4f6f5c5ef16032518586f1a8d00bf4beb42b9106e7840522f0"
"bytes": 599853,
"sha256": "e93d32a292b9c23f65c11f1ffb2e7cff9a9dee0f0b0cdb3d717dd166bcde3596"
},
{
"name": "editor.css",
Expand All @@ -14,7 +14,7 @@
{
"name": "index.html",
"bytes": 49020,
"sha256": "28437821549e01b3261c3bfb4322ef47d518484f6c97f1b0a0d97f92d9b54edb"
"sha256": "c9e555aed4ddb359758446c803e9349076d091ac4be0ef935fb24c83f764ab84"
},
{
"name": "KaTeX_AMS-Regular.ttf",
Expand Down Expand Up @@ -333,8 +333,8 @@
},
{
"name": "viewer-entry.js",
"bytes": 518708,
"sha256": "bacddcf53fea5d5b39c4a85bd73f4c558a0975692a1ae4f5b4c4a8c563f51705"
"bytes": 519721,
"sha256": "c3a09b6d95a078d9684e676a688d42133e2f974ea0cbbf9452537bf169a2a2ea"
}
]
}
2 changes: 1 addition & 1 deletion Sources/WeiBei/Resources/Editor/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -1278,7 +1278,7 @@
dissolve simultaneously at typical Chinese output rates, bridging the
33ms arrival gaps into a continuous flow. Opacity-only = cheap. */
.wb-stream-in {
animation: wb-stream-in 260ms cubic-bezier(0.2, 0.7, 0.3, 1) both;
animation: wb-stream-in 200ms cubic-bezier(0.2, 0.7, 0.3, 1) both;
}

@keyframes wb-stream-in {
Expand Down
85 changes: 43 additions & 42 deletions Sources/WeiBei/Resources/Editor/viewer-entry.js

Large diffs are not rendered by default.

8 changes: 5 additions & 3 deletions Sources/WeiBei/Stores/AgentStreamingDisplayPump.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ final class AgentStreamingDisplayPump {
/// Lag (in characters) that adds one extra character per tick of pace, so
/// the rate ramps continuously with backlog instead of jumping between
/// integer step sizes.
static let rampLagCharacters: Double = 10.0
static let rampLagCharacters: Double = 8.0
/// Hard ceiling on characters per tick so huge backlogs drain as a fast
/// but readable rush instead of an instant dump.
static let maximumCharsPerTick = 12
/// but readable rush instead of an instant dump. Raised with the reveal
/// cadence rework: 24/tick ≈ 730 chars/s keeps up with bursty native
/// streaming without reading as an instant dump.
static let maximumCharsPerTick = 24

struct Hooks {
let targetText: @MainActor () -> String
Expand Down
39 changes: 34 additions & 5 deletions Sources/WeiBei/WebEditor/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
looksLikeMarkdownSyntax,
normalizeMarkdownSource,
splitFrontmatter,
withholdIncompleteStreamingMarkdownTail,
} from './markdownRules';
import {
addEditorMetric,
Expand Down Expand Up @@ -2968,6 +2969,7 @@ const streamingCommands = () => editor.action((ctx) => ctx.get(commandsCtx));

const stopStreamingMarkdown = (keep = true) => {
cancelPacedStreamingTail();
cancelFinalizeDelay();
if (streamingMarkdownBuffer === null) return;
streamingCommands().call(abortStreamingCmd.key, { keep });
streamingMarkdownBuffer = null;
Expand All @@ -2978,6 +2980,7 @@ const stopStreamingMarkdown = (keep = true) => {
const updateStreamingMarkdownInternal = (markdown: any) => {
ensureEditor();
cancelPacedStreamingTail();
cancelFinalizeDelay();
const fullText = String(markdown || '');
streamingFullTextBase = fullText;
const document = splitFrontmatter(fullText);
Expand All @@ -3001,6 +3004,12 @@ const updateStreamingMarkdownInternal = (markdown: any) => {
streamingRawBody = body === rawBody ? rawBody : null;
lastMarkdown = withFrontmatter(body);
}
// Withhold the trailing unclosed inline segment: streaming `**小` would
// paint raw asterisks until the closing `**` lands; holding it back shows
// nothing until the pair closes, then the bold text appears already
// rendered (the standard "hold back unsafe trailing tokens" technique).
body = withholdIncompleteStreamingMarkdownTail(body);
if (streamingRawBody !== null) streamingRawBody = body;
const commands = streamingCommands();
if (streamingMarkdownBuffer === null) {
commands.call(startStreamingCmd.key);
Expand Down Expand Up @@ -3035,14 +3044,33 @@ const appendStreamingMarkdownInternal = (suffix: any) => {
let pacedTailTimer: number | null = null;
/** Above the fade plugin's per-insert limit a chunk cannot fade, so pace it. */
const PACED_TAIL_FADE_LIMIT_CHARACTERS = 24;
const PACED_TAIL_CHUNK_CHARACTERS = 12;
const PACED_TAIL_TICK_MILLISECONDS = 33;
const PACED_TAIL_CHUNK_CHARACTERS = 16;
const PACED_TAIL_TICK_MILLISECONDS = 24;
/** Wall-clock cap: throttled (hidden/occluded) WebViews slow timers to a crawl,
* so past this the whole tail lands at once instead of stalling half-typed. */
const PACED_TAIL_MAXIMUM_MILLISECONDS = 3_000;
/** Hard stop so an abandoned tail can never pace forever (~8s at cadence). */
/** Hard stop so an abandoned tail can never pace forever. */
const PACED_TAIL_MAXIMUM_TICKS = 240;

/** Ending the session clears fade decorations instantly — for text still
* mid-fade that is a whole-answer opacity snap ("everything flashes once").
* The final body is already in the document, so the session can outlive the
* last push by one fade window and end with every animation completed. */
let finalizeDelayTimer: number | null = null;
const FINALIZE_FADE_SETTLE_MILLISECONDS = 220;
const cancelFinalizeDelay = () => {
if (finalizeDelayTimer == null) return;
window.clearTimeout(finalizeDelayTimer);
finalizeDelayTimer = null;
};
const scheduleFinalizeAfterFades = () => {
cancelFinalizeDelay();
finalizeDelayTimer = window.setTimeout(() => {
finalizeDelayTimer = null;
finalizeStreamingSession();
}, FINALIZE_FADE_SETTLE_MILLISECONDS);
};

const cancelPacedStreamingTail = () => {
if (pacedTailTimer == null) return;
window.clearTimeout(pacedTailTimer);
Expand All @@ -3068,6 +3096,7 @@ const pushStreamingBodyForFinish = (body: string) => {
};

const finalizeStreamingSession = () => {
cancelFinalizeDelay();
streamingCommands().call(endStreamingCmd.key, { diffReview: false });
streamingRawBody = null;
streamingMarkdownBuffer = null;
Expand Down Expand Up @@ -3124,7 +3153,7 @@ const finishStreamingMarkdownInternal = (markdown: any, options?: { paced?: bool
pacedTailTimer = window.setTimeout(step, PACED_TAIL_TICK_MILLISECONDS);
return;
}
finalizeStreamingSession();
scheduleFinalizeAfterFades();
} catch {
// A paced push must never strand the answer half-typed (one throwing
// tick would silently end the timer chain): tear the session down and
Expand All @@ -3142,7 +3171,7 @@ const finishStreamingMarkdownInternal = (markdown: any, options?: { paced?: bool
return;
}
pushStreamingBodyForFinish(body);
finalizeStreamingSession();
scheduleFinalizeAfterFades();
};

const setMarkdownInternal = (markdown: any) => {
Expand Down
69 changes: 69 additions & 0 deletions Sources/WeiBei/WebEditor/src/markdownRules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,75 @@ const normalizeHtmlBreaksInLine = (line: string) => /^\s*(?:>\s*)*<br\s*\/?>\s*$

export const normalizeHtmlBreaks = (markdown: string) => mapMarkdownOutsideCode(markdown, normalizeHtmlBreaksInLine);

const incompleteStreamingMarkers = ['**', '__', '~~'];
const incompleteStreamingTailLimit = 160;

/** Keeps unfinished chat emphasis syntax out of sight until its closing marker arrives. */
export const withholdIncompleteStreamingMarkdownTail = (markdown: string) => {
const source = String(markdown || '');
const lineStart = Math.max(source.lastIndexOf('\n'), source.lastIndexOf('\r')) + 1;
const line = source.slice(lineStart);
if (!/[*_~]/.test(line)) return source;
let fenceMarker = '';
let fenceLength = 0;
for (const priorLine of source.slice(0, lineStart).split(/\r?\n/)) {
const fence = priorLine.match(/^\s*(?:>\s*)*(`{3,}|~{3,})/);
if (!fence) continue;
if (!fenceMarker) {
fenceMarker = fence[1][0];
fenceLength = fence[1].length;
} else if (fence[1][0] === fenceMarker && fence[1].length >= fenceLength) {
fenceMarker = '';
fenceLength = 0;
}
}
if (fenceMarker) return source;
let cut = line.length;
let cursor = 0;
let codeMarker = '';
const openMarkers = new Map<string, number>();

while (cursor < line.length) {
if (line[cursor] === '`' && !isEscapedMarkdownPosition(line, cursor)) {
const marker = line.slice(cursor).match(/^`+/)?.[0] || '`';
if (!codeMarker) codeMarker = marker;
else if (marker === codeMarker) codeMarker = '';
cursor += marker.length;
continue;
}
if (!codeMarker) {
const marker = incompleteStreamingMarkers.find((candidate) => line.startsWith(candidate, cursor));
if (marker && !isEscapedMarkdownPosition(line, cursor)) {
if (openMarkers.has(marker)) openMarkers.delete(marker);
else openMarkers.set(marker, cursor);
cursor += marker.length;
continue;
}
}
cursor += 1;
}

for (const index of openMarkers.values()) cut = Math.min(cut, index);
const partialMarkerIndex = line.length - 1;
const partialMarker = line[partialMarkerIndex] || '';
const endsWithBalancedMarker = incompleteStreamingMarkers.some((marker) => (
marker[0] === partialMarker && line.endsWith(marker) && !openMarkers.has(marker)
));
if (
!codeMarker
&& partialMarkerIndex >= 0
&& !endsWithBalancedMarker
&& ['*', '_', '~'].includes(partialMarker)
&& !isEscapedMarkdownPosition(line, partialMarkerIndex)
) {
cut = Math.min(cut, partialMarkerIndex);
}
// ponytail: cover chat's visible emphasis markers only; use a full repair
// parser if links, math, or cross-line constructs also need withholding.
if (cut >= line.length || line.length - cut > incompleteStreamingTailLimit) return source;
return source.slice(0, lineStart + cut);
};

export type MarkdownSource = 'userDocument' | 'userPaste' | 'agentGenerated' | 'internalFragment';

export const inlineMathInputPattern = /(?<!\\)\$((?!\d)[^$\n]+)\$$/;
Expand Down
9 changes: 5 additions & 4 deletions Sources/WeiBei/WebEditor/src/streaming-appearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ const FADE_SPEC = { class: 'wb-stream-in' };
const CARET_SPEC = { side: 1 };

/** Match the CSS animation duration of .wb-stream-in in index.html. */
const FADE_MILLISECONDS = 260;
const FADE_MILLISECONDS = 200;
/** Retire the caret shortly after inserts stop flowing. */
const CARET_IDLE_MILLISECONDS = 400;
/** Only animate typing-like inserts; wholesale block rewrites skip the fade. */
const MAXIMUM_FADE_CHARACTERS = 24;
/** Only animate typing-like inserts; wholesale block rewrites skip the fade.
* Raised with the faster reveal cadence so pacing chunks still fade. */
const MAXIMUM_FADE_CHARACTERS = 32;

interface FadeEntry {
from: number;
Expand Down Expand Up @@ -105,7 +106,7 @@ export function streamingAppearancePlugin(isStreamingActive: () => boolean): Plu
props: {
// Hidden entirely once the streaming session is over: re-serving the
// remaining fades would RE-CREATE their span elements, and a fresh
// wb-stream-in span replays its 260ms fade from opacity 0 — the
// wb-stream-in span replays its 200ms fade from opacity 0 — the
// just-typed text visibly vanished and faded back in at completion.
// Unwrapping completed spans is visually silent; mid-flight ones pop
// to full opacity, which reads as the line finishing.
Expand Down
15 changes: 15 additions & 0 deletions Sources/WeiBei/WebEditor/test/markdownRules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
normalizeMarkdownOutput,
protectCurrencyDollars,
splitFrontmatter,
withholdIncompleteStreamingMarkdownTail,
} from '../src/markdownRules';

test('document boundary rules preserve frontmatter and extended Markdown on round-trip', () => {
Expand Down Expand Up @@ -96,6 +97,20 @@ test('normalization preserves valid and incomplete formula source for lossless e
assert.equal(normalizeMarkdownSource('$\\unknown{x}$', 'agentGenerated'), '$\\unknown{x}$');
});

test('chat streaming withholds only unfinished trailing emphasis syntax', () => {
assert.equal(withholdIncompleteStreamingMarkdownTail('前文 *'), '前文 ');
assert.equal(withholdIncompleteStreamingMarkdownTail('前文 **粗'), '前文 ');
assert.equal(withholdIncompleteStreamingMarkdownTail('前文 **粗体**'), '前文 **粗体**');
assert.equal(withholdIncompleteStreamingMarkdownTail('前文 ~~删除'), '前文 ');
assert.equal(withholdIncompleteStreamingMarkdownTail('链接 [材料:讲义] 与 $5'), '链接 [材料:讲义] 与 $5');
assert.equal(withholdIncompleteStreamingMarkdownTail('代码 `const value = "**"`'), '代码 `const value = "**"`');
assert.equal(withholdIncompleteStreamingMarkdownTail('转义 \\** 不隐藏'), '转义 \\** 不隐藏');
assert.equal(
withholdIncompleteStreamingMarkdownTail(`\`\`\`md\n**源码`),
`\`\`\`md\n**源码`,
);
});

test('paste probe flags Markdown clipboard text and leaves plain prose alone', () => {
const flagged = [
'# 标题',
Expand Down
7 changes: 7 additions & 0 deletions Tests/WeiBeiSafetyTests/AgentStreamingDisplayPumpTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ final class AgentStreamingDisplayPumpTests: XCTestCase {
}
}

func testVeryLargeBacklogUsesRaisedButBoundedCatchUpRate() {
let rig = Rig()
rig.target = String(repeating: "字", count: 1_000)
rig.pump.stepOnce()
XCTAssertEqual(rig.published.first?.count, AgentStreamingDisplayPump.maximumCharsPerTick)
}

func testEmptyTargetPublishesNothing() {
let rig = Rig()
for _ in 0..<5 { rig.pump.stepOnce() }
Expand Down