Skip to content
Merged
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
108 changes: 54 additions & 54 deletions Sources/WeiBei/Resources/Editor/editor-entry.js

Large diffs are not rendered by default.

8 changes: 4 additions & 4 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": 598087,
"sha256": "8c23e1ece9c60b2352acbb7d8ecbdd899378739abc75b8443245d7e5caf8c328"
"bytes": 598988,
"sha256": "d7eb7f477b05b7d255e8e2d97d5c70f258db5c988c9f5ba11ac506b483b6f67f"
},
{
"name": "editor.css",
Expand Down Expand Up @@ -333,8 +333,8 @@
},
{
"name": "viewer-entry.js",
"bytes": 517955,
"sha256": "b695b452d4bca4b5023ca3a4e37229b077e64590f97f76f7ffe9c56646189cb1"
"bytes": 518856,
"sha256": "0ede6a316b2487e867fb58a695527f6558444b333e6fe78bd25dd2fb83da06e4"
}
]
}
90 changes: 45 additions & 45 deletions Sources/WeiBei/Resources/Editor/viewer-entry.js

Large diffs are not rendered by default.

25 changes: 7 additions & 18 deletions Sources/WeiBei/Views/NotesAgentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,6 @@ struct MarkdownPreviewView: View {
private static let compactPreviewMaximumHeight: CGFloat = 20_000

var onMeasuredHeight: (CGFloat) -> Void = { _ in }
@Environment(\.weibeiReduceMotion) private var reduceMotion
@State private var command: NoteEditorCommand?
@State private var contentHeight: CGFloat = Self.compactPreviewLoadingHeight
@State private var heightFrozen = false
Expand All @@ -915,21 +914,6 @@ struct MarkdownPreviewView: View {
/// during the gate would otherwise never arrive again.
@State private var latestGatedHeight: CGFloat = 0

/// Post-streaming height corrections ease instead of snapping: the finalized
/// snapshot and the async re-measures that follow (KaTeX, fonts) can land
/// tens of points from the last streamed height, and an instant frame
/// change read as the row visibly jumping at completion. Streaming keeps
/// the instant gated cadence so growth still tracks the token flow.
private func applySettledHeight(_ next: CGFloat) {
if reduceMotion || streamsMarkdownUpdates {
contentHeight = next
} else {
withAnimation(WeiBeiMotion.micro) {
contentHeight = next
}
}
}

var body: some View {
RichMarkdownEditorView(
markdown: markdown,
Expand Down Expand Up @@ -1010,7 +994,12 @@ struct MarkdownPreviewView: View {
)
return
}
applySettledHeight(nextFrameHeight)
// Instant apply: an eased frame lags the WebView content for the
// animation's duration and .clipped() cuts the last wrapped
// line mid-flight. Growth now arrives in streaming-sized steps
// (the web side types the completion tail out), so there is no
// large snap left to smooth.
contentHeight = nextFrameHeight
// Do NOT freeze on a fresh accept: KaTeX displayMode re-layout
// and font loading can still grow the content. Freeze happens
// in the jitter branch above once two consecutive measures
Expand Down Expand Up @@ -1051,7 +1040,7 @@ struct MarkdownPreviewView: View {
latestGatedHeight = 0
heightFrozen = false
acceptedMeasureCount = 0
applySettledHeight(settledHeight)
contentHeight = settledHeight
maxObservedMeasuredHeight = settledHeight
onMeasuredHeight(measuredHeight)
onContentHeightChange()
Expand Down
2 changes: 1 addition & 1 deletion Sources/WeiBei/Views/RichMarkdownEditorView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1525,7 +1525,7 @@ struct RichMarkdownEditorView: NSViewRepresentable {
webMarkdown = text
webView?.evaluateJavaScript("""
(() => {
const didFinish = window.WeiBeiEditor?.finishStreamingMarkdown(\(Self.json(text)));
const didFinish = window.WeiBeiEditor?.finishStreamingMarkdown(\(Self.json(text)), { paced: true });
return {
didFinish: didFinish === true,
height: Number(window.WeiBeiCompactPreviewHeight || 1)
Expand Down
119 changes: 108 additions & 11 deletions Sources/WeiBei/WebEditor/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2967,6 +2967,7 @@ const publishCompletedCompositionMarkdown = () => {
const streamingCommands = () => editor.action((ctx) => ctx.get(commandsCtx));

const stopStreamingMarkdown = (keep = true) => {
cancelPacedStreamingTail();
if (streamingMarkdownBuffer === null) return;
streamingCommands().call(abortStreamingCmd.key, { keep });
streamingMarkdownBuffer = null;
Expand All @@ -2976,6 +2977,7 @@ const stopStreamingMarkdown = (keep = true) => {

const updateStreamingMarkdownInternal = (markdown: any) => {
ensureEditor();
cancelPacedStreamingTail();
const fullText = String(markdown || '');
streamingFullTextBase = fullText;
const document = splitFrontmatter(fullText);
Expand Down Expand Up @@ -3024,14 +3026,55 @@ const appendStreamingMarkdownInternal = (suffix: any) => {
updateStreamingMarkdownInternal(base === null ? tail : base + tail);
};

const finishStreamingMarkdownInternal = (markdown: any) => {
streamingRawBody = null; // force the full normalize + serialization pass
updateStreamingMarkdownInternal(markdown);
/** Paced tail reveal. The completion payload often carries text that never
* streamed (the model's closing segment arrives only in the end event, and
* the native display pump drains whatever it had not revealed). Applying that
* tail in one push made the finished answer dump a block of unfaded text and
* jump its height. Instead the tail keeps typing out at the streaming
* cadence — same fade, same caret — and the session finalizes when it lands. */
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;
/** 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). */
const PACED_TAIL_MAXIMUM_TICKS = 240;

const cancelPacedStreamingTail = () => {
if (pacedTailTimer == null) return;
window.clearTimeout(pacedTailTimer);
pacedTailTimer = null;
};

/** Push a caller-normalized body through the streaming session, mirroring
* updateStreamingMarkdownInternal's session bookkeeping. */
const pushStreamingBodyForFinish = (body: string) => {
const commands = streamingCommands();
if (streamingMarkdownBuffer === null) {
commands.call(startStreamingCmd.key);
streamingMarkdownBuffer = '';
} else if (!body.startsWith(streamingMarkdownBuffer)) {
commands.call(endStreamingCmd.key, { diffReview: false });
commands.call(startStreamingCmd.key);
streamingMarkdownBuffer = '';
}
const delta = body.slice(streamingMarkdownBuffer.length);
if (delta) commands.call(pushChunkCmd.key, delta);
streamingMarkdownBuffer = body;
scheduleContentHeightReports();
};

const finalizeStreamingSession = () => {
streamingCommands().call(endStreamingCmd.key, { diffReview: false });
streamingRawBody = null;
streamingMarkdownBuffer = null;
streamingFullTextBase = null;
cancelPacedStreamingTail();
// Decorations gate on the live buffer; repaint once so the finished render
// drops the streaming caret and fade spans without dispatching a transaction.
// drops the streaming caret without dispatching a transaction.
try {
editor?.action((ctx) => {
ctx.get(editorViewCtx).updateState(ctx.get(editorViewCtx).state);
Expand All @@ -3040,14 +3083,68 @@ const finishStreamingMarkdownInternal = (markdown: any) => {
// View not ready yet; decorations clear on the next transaction anyway.
}
// Measure synchronously so the height returned to native reflects the
// finalized DOM, not the last streamed report. The finish re-layout can
// grow the document (last wrapped lines, KaTeX), and native reads
// WeiBeiCompactPreviewHeight the instant this call returns — a stale
// smaller value left the completed row clipping its final lines.
// finalized DOM, not the last streamed report.
publishContentHeight();
scheduleContentHeightReports();
};

const finishStreamingMarkdownInternal = (markdown: any, options?: { paced?: boolean }) => {
cancelPacedStreamingTail();
streamingRawBody = null; // force the full normalize + serialization pass
const fullText = String(markdown || '');
const document = splitFrontmatter(fullText);
frontmatterBlock = document.frontmatter;
syncFrontmatterPanel();
const body = normalizeMarkdownSource(document.body, 'agentGenerated');
lastMarkdown = withFrontmatter(body);
streamingFullTextBase = fullText;
const currentBuffer = streamingMarkdownBuffer;
// Pace only a pure append; a divergent prefix needs the full replace now.
// Pacing is opt-in from native: hidden/windowless WebViews suspend timers
// entirely, and a paced reveal there would strand the answer half-typed.
const pacesAppendTail = options?.paced === true
&& currentBuffer !== null
&& body.startsWith(currentBuffer)
&& body.length - currentBuffer.length > PACED_TAIL_FADE_LIMIT_CHARACTERS;
if (currentBuffer !== null && pacesAppendTail) {
let revealed = currentBuffer.length;
let ticks = 0;
const pacingStartedAt = Date.now();
const step = () => {
pacedTailTimer = null;
const now = Date.now();
ticks += 1;
revealed = Math.min(body.length, revealed + PACED_TAIL_CHUNK_CHARACTERS);
const done = revealed >= body.length
|| now - pacingStartedAt >= PACED_TAIL_MAXIMUM_MILLISECONDS
|| ticks >= PACED_TAIL_MAXIMUM_TICKS;
try {
pushStreamingBodyForFinish(done ? body : body.slice(0, revealed));
if (!done) {
pacedTailTimer = window.setTimeout(step, PACED_TAIL_TICK_MILLISECONDS);
return;
}
finalizeStreamingSession();
} 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
// land the full document through the plain replace path instead.
pacedTailTimer = null;
streamingMarkdownBuffer = null;
streamingRawBody = null;
try { streamingCommands().call(abortStreamingCmd.key, { keep: false }); } catch { /* session already gone */ }
try { setMarkdownInternal(fullText); } catch { /* nothing left to try */ }
scheduleContentHeightReports();
}
};
pacedTailTimer = window.setTimeout(step, PACED_TAIL_TICK_MILLISECONDS);
scheduleContentHeightReports();
return;
}
pushStreamingBodyForFinish(body);
finalizeStreamingSession();
};

const setMarkdownInternal = (markdown: any) => {
ensureEditor();
stopStreamingMarkdown();
Expand Down Expand Up @@ -3451,9 +3548,9 @@ window.WeiBeiEditor = {
showFailure(error);
}
},
finishStreamingMarkdown: (markdown: any) => {
finishStreamingMarkdown: (markdown: any, options?: { paced?: boolean }) => {
try {
finishStreamingMarkdownInternal(markdown);
finishStreamingMarkdownInternal(markdown, options);
return true;
} catch (error) {
showFailure(error);
Expand Down Expand Up @@ -3490,7 +3587,7 @@ if (WEIBEI_EDITOR_RUNTIME && window.weiBeiEditorCheckMode) {
setMarkdown: setMarkdownInternal,
updateStreamingMarkdown: updateStreamingMarkdownInternal,
appendStreamingMarkdown: appendStreamingMarkdownInternal,
finishStreamingMarkdown: (markdown: any) => { finishStreamingMarkdownInternal(markdown); return true; },
finishStreamingMarkdown: (markdown: any, options?: { paced?: boolean }) => { finishStreamingMarkdownInternal(markdown, options); return true; },
replaceSelection: replaceSelectionInternal,
executeSelectionCommand: executeSelectionCommandInternal,
applyAgentPatch: appendMarkdownInternal,
Expand Down
9 changes: 6 additions & 3 deletions Sources/WeiBei/WebEditor/src/streaming-appearance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,19 @@ export function streamingAppearancePlugin(isStreamingActive: () => boolean): Plu
apply(tr, previous): AppearanceState {
const now = Date.now();
let fades: FadeEntry[] = [];
const docSize = tr.doc.content.size;
for (const entry of previous.fades) {
const from = tr.mapping.map(entry.from);
const to = tr.mapping.map(entry.to);
// Big replace steps (finalization diff) can map a fade past the new
// document's end; resolve() would throw and kill the whole dispatch.
const from = Math.min(tr.mapping.map(entry.from), docSize);
const to = Math.min(tr.mapping.map(entry.to), docSize);
if (from >= to || now >= entry.expiresAt) continue;
if (tr.doc.resolve(from).parent !== tr.doc.resolve(to).parent) continue;
fades.push({ from, to, expiresAt: entry.expiresAt });
}
let caretPosition = previous.caretPosition === null
? null
: tr.mapping.map(previous.caretPosition);
: Math.min(tr.mapping.map(previous.caretPosition), docSize);
let caretExpiresAt = previous.caretExpiresAt;

if (tr.docChanged && isStreamingActive()) {
Expand Down
27 changes: 23 additions & 4 deletions Sources/WeiBeiWebEditorCheck/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2626,7 +2626,7 @@ private final class FinalizedAgentMarkdownHarness: NSObject, WKScriptMessageHand
.appendingPathComponent("Sources/WeiBei/Resources/Editor/index.html")
webView.loadFileURL(indexURL, allowingReadAccessTo: indexURL.deletingLastPathComponent())

let timeout = Date().addingTimeInterval(15)
let timeout = Date().addingTimeInterval(30)
while !isDone && Date() < timeout {
RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.05))
}
Expand Down Expand Up @@ -2792,7 +2792,8 @@ private final class FinalizedAgentMarkdownHarness: NSObject, WKScriptMessageHand
return
}
self.finishReportedHeight = height
self.validateDOM(until: Date().addingTimeInterval(3))
// 收尾尾巴按流式节奏逐字补完(大尾巴可达十余秒),验证窗口须覆盖补完后的最终态
self.validateDOM(until: Date().addingTimeInterval(14))
}
}

Expand Down Expand Up @@ -2838,12 +2839,30 @@ private final class FinalizedAgentMarkdownHarness: NSObject, WKScriptMessageHand
self.fail("finalized agent Markdown DOM check threw \(error.localizedDescription)")
return
}
guard let result = value as? [String: Any],
result["ok"] as? Bool == true else {
guard let result = value as? [String: Any] else {
self.fail("finalized agent Markdown DOM check returned no result")
return
}
// The completion tail now types out at the streaming cadence, so
// polls can land mid-reveal: structural checks retry to the
// deadline instead of failing on an intermediate document.
if result["ok"] as? Bool != true {
if Date() < deadline {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.validateDOM(until: deadline)
}
return
}
self.fail("finalized agent Markdown lost block structure: \(String(describing: value))")
return
}
if !(result["mermaidError"] as? String ?? "").isEmpty {
if Date() < deadline {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
self.validateDOM(until: deadline)
}
return
}
self.fail("finalized Agent Mermaid failed: \(String(describing: result["mermaidError"]))")
return
}
Expand Down