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
218 changes: 213 additions & 5 deletions App/Sources/CatalystBusinessCheck.swift

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions App/Sources/CatalystConversationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ struct CatalystMessageMarkdown: UIViewRepresentable {
let parsed = MarkdownParser().parse(markdown)
let content = MarkdownContent(parserResult: parsed, theme: theme)
view.setContentImmediately(content, theme: theme)
view.invalidateIntrinsicContentSize()
}
func sizeThatFits(_ proposal: ProposedViewSize, uiView: MarkdownTextView, context: Context) -> CGSize? {
let width = max(1, proposal.width ?? uiView.bounds.width)
Expand All @@ -311,3 +312,42 @@ struct CatalystMessageMarkdown: UIViewRepresentable {
var appearance: WeiBeiAppearanceMode?
}
}

struct CatalystRichAnswer: View {
let markdown: String
let fontSize: CGFloat
let appearanceMode: WeiBeiAppearanceMode
let messageID: UUID?
let contentBlocks: [AgentMessageContentBlock]
let openLink: (URL) -> Void

@EnvironmentObject private var store: WorkspaceStore
@Environment(\.weiBeiTextScale) private var textScale

var body: some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(Array(AgentAnswerMarkdownSegments.split(markdown).enumerated()), id: \.offset) { _, part in
switch part {
case .text(let text):
CatalystMessageMarkdown(
markdown: text,
fontSize: fontSize,
appearanceMode: appearanceMode,
openLink: openLink
)
case .attachment(let identifier):
if let messageID {
AgentNativeContentAttachment(
messageID: messageID,
identifier: identifier,
initialBlocks: contentBlocks,
onHeight: { _ in }
)
.environmentObject(store)
.environment(\.weiBeiTextScale, textScale)
}
}
}
}
}
}
16 changes: 15 additions & 1 deletion App/script/business-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,26 @@ def chunk(delta, finish=None):

try:
item = re.search(r"WB452_ITEM=(\S+)", user)
floating_rich = item is not None and "WB514_FLOATING_RICH" in user
if item and "read452" not in tools:
chunk({"tool_calls": [{"index": 0, "id": "read452", "type": "function",
"function": {"name": "weibei_course_read", "arguments": json.dumps({"itemID": item[1]})}}]})
chunk({}, "tool_calls")
elif floating_rich and "floating514" not in tools:
# A separate short answer exercises the actual floating native
# text and render_ui attachment, without reusing the main fixture.
chunk({"content": "WB514_FLOATING_BODY:行内公式 $x+1$。\n\n$$\\frac{1}{2}+\\frac{1}{2}=1$$\n\n"})
chunk({"tool_calls": [{"index": 0, "id": "floating514", "type": "function",
"function": {"name": "render_ui", "arguments": json.dumps({
"id": "floating-compact-diagram",
"spec": {"items": [{"type": "mermaid", "code": "graph LR\nA[WB514_START] --> B[WB514_END]"}]},
})}}]})
chunk({}, "tool_calls")
else:
if "WB452_STOP" in user:
if floating_rich:
answer = "浮窗公式与图示结束。\n\n【候选真实业务链路结束】"
step, delay = 40, 0.05
elif "WB452_STOP" in user:
answer = "## 停止验证\n\n" + "正在输出的正文应完整保留。中文 café 👩🏽‍💻。\n\n" * 400
step, delay = 30, 0.06
elif item:
Expand Down
86 changes: 86 additions & 0 deletions App/script/business-server.test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Exercise the real fixture handler with in-memory HTTP streams; no sockets."""
import io
import json
from pathlib import Path
import runpy
import tempfile
import unittest
from unittest.mock import patch


class FixtureServer:
server_port = 0

def __init__(self, address, handler):
assert address == ("127.0.0.1", 0)

def serve_forever(self):
pass


class BusinessFixtureTests(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory(prefix="weibei-fixture-test-")
self.addCleanup(self.scratch.cleanup)
server = Path(__file__).with_name("business-server.py")
with patch("http.server.ThreadingHTTPServer", FixtureServer), patch("sys.argv", [str(server), "--output", self.scratch.name]):
self.fixture = runpy.run_path(str(server))
self.fixture["answer_ready"].set()

def request(self, messages):
body = json.dumps({"model": "catalyst-local-check", "messages": messages}).encode()
handler = object.__new__(self.fixture["Handler"])
handler.path = "/v1/chat/completions"
handler.headers = {"Authorization": "Bearer catalyst-test-only", "Content-Length": str(len(body))}
handler.rfile = io.BytesIO(body)
handler.wfile = io.BytesIO()
handler.send_response = lambda status: self.assertEqual(status, 200)
handler.send_header = lambda *_: None
handler.end_headers = lambda: None
with patch("time.sleep", lambda _: None):
handler.do_POST()
stream = handler.wfile.getvalue().decode()
self.assertTrue(stream.endswith("data: [DONE]\n\n"))
return [json.loads(line.removeprefix("data: "))["choices"][0]
for line in stream.splitlines() if line.startswith("data: ") and line != "data: [DONE]"]

def test_floating_round_trip_renders_diagram_between_native_math_and_tail(self):
user = {"role": "user", "content": "解释选区 WB452_ITEM=synthetic-material WB514_FLOATING_RICH"}
first = self.request([user])
read = first[0]["delta"]["tool_calls"][0]
self.assertEqual(read["function"]["name"], "weibei_course_read")
self.assertEqual(json.loads(read["function"]["arguments"]), {"itemID": "synthetic-material"})
read_result = {"role": "tool", "tool_call_id": "read452", "content": '{"items": []}'}
second = self.request([user, read_result])
math = second[0]["delta"]["content"]
self.assertIn("WB514_FLOATING_BODY", math)
self.assertIn("$x+1$", math)
self.assertIn("$$\\frac{1}{2}+\\frac{1}{2}=1$$", math)
render = second[1]["delta"]["tool_calls"][0]
self.assertEqual(render["id"], "floating514")
self.assertEqual(render["function"]["name"], "render_ui")
arguments = json.loads(render["function"]["arguments"])
self.assertEqual(arguments["id"], "floating-compact-diagram")
self.assertEqual(arguments["spec"]["items"], [{"type": "mermaid", "code": "graph LR\nA[WB514_START] --> B[WB514_END]"}])
self.assertEqual(second[-1]["finish_reason"], "tool_calls")
displayed = {"role": "tool", "tool_call_id": "floating514", "content": "互动界面已显示"}
third = self.request([user, read_result, displayed])
tail = "".join(chunk["delta"].get("content", "") for chunk in third)
self.assertIn("【候选真实业务链路结束】", tail)
self.assertNotIn("长正文", math + tail)
self.assertFalse(any("tool_calls" in chunk["delta"] for chunk in third))

def test_main_round_trip_keeps_its_long_answer_image_code_and_table(self):
user = {"role": "user", "content": "读取资料 WB452_ITEM=synthetic-material WB452_IMAGE=file:///synthetic.png"}
read_result = {"role": "tool", "tool_call_id": "read452", "content": '{"items": [{"source": {"label": "独立资料"}}]}'}
chunks = self.request([user, read_result])
answer = "".join(chunk["delta"].get("content", "") for chunk in chunks)
for expected in ["独立资料", "$E=mc^2$", "```swift", "|操作|结果|", "file:///synthetic.png", "第 30 段", "【候选真实业务链路结束】"]:
self.assertIn(expected, answer)
self.assertNotIn("WB514_FLOATING_BODY", answer)
self.assertFalse(any("tool_calls" in chunk["delta"] for chunk in chunks))


if __name__ == "__main__":
unittest.main()
29 changes: 26 additions & 3 deletions App/script/check-ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ set -euo pipefail
[[ "${CI:-}" == true ]] || { echo '本机候选请在画中画验收。' >&2; exit 1; }
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT"
python3 App/script/business-server.test.py
node --test App/script/floating-label-check.test.mjs App/script/mermaid-measurement-observer.test.mjs App/script/mermaid-mounted-label-geometry.test.mjs
CHECK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/weibei-business-ci.XXXXXX")"
python3 App/script/business-server.py --output "$CHECK_DIR" > "$CHECK_DIR/server.log" 2>&1 &
server_pid=$!
Expand All @@ -15,6 +17,8 @@ save_evidence() {
"${CHECK_SUPPORT:-$CHECK_DIR}/Workspace/business-failure.png" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-composers.png" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-discussion.png" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-rich-answer-11pt.png" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Results/floating-rich-diagnostic.json" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Results/reasoning-composer.png" \
"${CHECK_SUPPORT:-$CHECK_DIR}/Workspace/quit-save.json"; do
[[ ! -f "$file" ]] || cp "$file" "App/Evidence/ci-$(basename "$file")"
Expand Down Expand Up @@ -66,12 +70,31 @@ launch('--exit-after-check')
verify(business_path, 'source', 'awaiting_reopen')
launch('--exit-after-check')
business = verify(business_path, 'source', 'passed')
assert len(business['checks']) == 21, business
required_business_checks = {
'reopen_original_note_and_session_files', 'mac_idiom_and_isolated_storage',
'original_update_service_through_native_bridge', 'native_workspace_toolbar_controls',
'signed_native_window_material', 'original_import_reader_and_editor',
'original_editor_snapshot_and_note_write_gate', 'signed_bounded_pdf_worker',
'waiting_status_not_clipped', 'return_clears_original_composer',
'status_disappears_at_first_text', 'original_http_agent_tools_and_uikit_stream',
'original_source_navigation', 'original_attachment_loader',
'image_mounted_in_visible_message', 'original_answer_to_note',
'selection_chat_composers_and_citation', 'stop_preserves_received_text',
'divider_batches_widths_and_reflows_during_drag',
'conversation_appearance_and_scale_after_resize',
'history_and_long_answer_through_original_messages',
'floating_11pt_math_diagram_and_layout',
}
# Require every original gate and the new floating gate; verify() above also
# rejects any failed additional gate, including accepted PR515's language check.
assert required_business_checks <= business['checks'].keys(), business
assert business['floating_rich_answer']['body_font_size_pt'] == 11, business
assert business['floating_rich_answer']['math_images'] == 2, business
shutil.copy2(business_path, evidence / 'ci-business.json')
shutil.copy2(support / 'Results/workspace.png', evidence / 'ci-business-window.png')
for filename in ['selection-composers.png', 'selection-discussion.png', 'reasoning-composer.png']:
for filename in ['selection-composers.png', 'selection-discussion.png', 'selection-rich-answer-11pt.png', 'reasoning-composer.png']:
shutil.copy2(support / 'Results' / filename, evidence / ('ci-' + filename))
print('14 项会话检查与 21 项原业务保存重开检查通过;含原生工具栏、选区双输入框与引用定位,不替代鼠标、输入法及触控板体验验收。')
print(f"14 项会话检查与 {len(business['checks'])} 项原业务保存重开检查通过;含浮窗 11pt 公式与图示、原生工具栏、选区双输入框与引用定位,不替代鼠标、输入法及触控板体验验收。")

with tempfile.TemporaryDirectory(prefix='weibei-quit-check-') as scratch:
helper = str(Path(scratch) / 'quit')
Expand Down
148 changes: 148 additions & 0 deletions App/script/floating-label-check.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import assert from 'node:assert/strict';
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import test from 'node:test';
import { runInNewContext } from 'node:vm';

// Execute the exact acceptance program with synthetic DOM geometry. These
// fixtures test clipping decisions, not WKWebView layout or product rendering.
const source = readFileSync(new URL('../Sources/CatalystBusinessCheck.swift', import.meta.url), 'utf8');
const script = source.match(/private static let floatingDiagramCheckScript = #"""([\s\S]*?)"""#/)[1];
const rectangle = (left, top, width, height) => ({ left, top, width, height, right: left + width, bottom: top + height });
const style = (overflowX = 'visible', overflowY = 'visible') => ({
overflowX, overflowY, fontFamily: 'Synthetic Font', fontSize: '13px', lineHeight: '20.8px',
});

function fixture({ firstRangeWidth = 80, clip, missingEnd = false, svgRightOutside = false } = {}) {
const root = {
parentElement: null,
getBoundingClientRect: () => rectangle(0, 0, 352, 120),
style: style(),
contains(node) {
for (let current = node; current; current = current.parentElement) if (current === root) return true;
return false;
},
};
const svg = {
parentElement: root,
style: style(),
getBoundingClientRect: () => rectangle(20, 10, svgRightOutside ? 400 : 300, 65),
};
const labels = ['WB514_START', 'WB514_END'].map((text, index) => {
const left = index === 0 ? 40 : 200;
const foreign = {
parentElement: svg, localName: 'foreignObject', style: style(),
getBoundingClientRect: () => rectangle(left, 20, 90, 22),
getAttribute: name => name === 'width' ? '90' : '22',
};
const width = index === 0 ? firstRangeWidth : 70;
const label = {
textContent: text, parentElement: foreign, localName: 'span', style: style(),
clientWidth: 90, scrollWidth: width,
getBoundingClientRect: () => rectangle(left, 20, 90, 22),
closest: name => name === 'foreignObject' ? foreign : null,
textNodes: [{ textContent: text, rect: rectangle(left + 2, 22, width, 16) }],
};
if (index === 0 && clip) {
label.parentElement = {
parentElement: foreign, localName: 'div', style: style(clip.x, clip.y),
getBoundingClientRect: () => rectangle(left, 20, clip.width, clip.height),
};
}
return label;
});
if (missingEnd) labels.pop();
svg.textContent = 'UNRELATED_CSS_SENTINEL;' + labels.map(label => label.textContent).join('');
svg.querySelectorAll = selector => selector === '.nodeLabel' ? labels : [];
root.textContent = svg.textContent;
root.querySelector = selector => selector === 'svg' ? svg : null;
const document = {
querySelector: selector => selector === '#genui-content' ? root : null,
createTreeWalker(label) {
let index = 0;
return { nextNode: () => label.textNodes[index++] ?? null };
},
createRange() {
let selected;
return {
selectNodeContents(node) { selected = node; },
getClientRects: () => [selected.rect],
};
},
};
return runInNewContext(script, { document, NodeFilter: { SHOW_TEXT: 4 }, getComputedStyle: node => node.style,
innerWidth: 352, innerHeight: 120 }, { timeout: 1000 });
}

test('both visible labels pass and diagnostics retain geometry/fonts without SVG CSS', () => {
const result = fixture();
assert.equal(result.ok, true);
assert.equal(result.stage, 'passed');
assert.equal(result.labels.length, 2);
assert.equal(result.labels.every(label => label.visible), true);
assert.equal(result.labels[0].font.size, '13px');
assert.equal(result.labels[0].text_rects.length, 1);
assert.equal(JSON.stringify(result).includes('UNRELATED_CSS_SENTINEL'), false);
});

test('complete SVG text still fails when the label range exceeds its foreignObject', () => {
const result = fixture({ firstRangeWidth: 104 });
assert.equal(result.ok, false);
assert.equal(result.stage, 'diagram_label_foreign_object_clip');
assert.equal(result.labels[0].text, 'WB514_START');
assert.equal(result.labels[0].text_rects[0][2], 104);
assert.equal(result.labels[0].foreign_rect[2], 90);
assert.equal(result.labels[1].text, 'WB514_END');
assert.equal(result.labels[1].visible, true, 'Both labels must be observed even when the first fails');
});

test('horizontal clipping rejects overflow on x and records the clip rectangle', () => {
const result = fixture({ clip: { x: 'clip', y: 'visible', width: 50, height: 22 } });
assert.equal(result.ok, false);
assert.equal(result.stage, 'diagram_label_ancestor_clip');
assert.equal(result.labels[0].clips[0].x, 'clip');
assert.equal(result.labels[0].clips[0].visible, false);
});

test('vertical clipping rejects overflow on y', () => {
const result = fixture({ clip: { x: 'visible', y: 'clip', width: 90, height: 10 } });
assert.equal(result.ok, false);
assert.equal(result.stage, 'diagram_label_ancestor_clip');
assert.equal(result.labels[0].clips[0].y, 'clip');
});

test('a clip only constrains its declared axis', () => {
assert.equal(fixture({ clip: { x: 'clip', y: 'visible', width: 90, height: 10 } }).ok, true);
assert.equal(fixture({ clip: { x: 'visible', y: 'clip', width: 50, height: 22 } }).ok, true);
});

test('missing expected text and SVG viewport overflow retain their original rejection', () => {
assert.equal(fixture({ missingEnd: true }).stage, 'diagram_labels_or_raw_source');
assert.equal(fixture({ svgRightOutside: true }).stage, 'diagram_svg_bounds');
});

test('failure exit trap preserves the compact label diagnostic', () => {
const shell = readFileSync(new URL('check-ci.sh', import.meta.url), 'utf8');
const copy = shell.match(/save_evidence\(\) \{[\s\S]*?\n\}/)[0];
const scratch = mkdtempSync(join(tmpdir(), 'weibei-label-evidence-'));
try {
const support = join(scratch, 'Support');
mkdirSync(join(support, 'Results'), { recursive: true });
const diagnostic = JSON.stringify({ stage: 'diagram_label_foreign_object_clip', labels: ['WB514_START', 'WB514_END'] });
writeFileSync(join(support, 'Results/floating-rich-diagnostic.json'), diagnostic);
// Empty PID cannot signal a process. The real trap's kill is caught by || true.
const result = spawnSync('bash', ['-c', `server_pid=''
CHECK_SUPPORT="$1"
CHECK_DIR="$2"
mkdir -p App/Evidence
${copy}
trap save_evidence EXIT
exit 7`, 'fixture', support, scratch], { cwd: scratch, encoding: 'utf8' });
assert.equal(result.status, 7);
assert.equal(readFileSync(join(scratch, 'App/Evidence/ci-floating-rich-diagnostic.json'), 'utf8'), diagnostic);
} finally {
rmSync(scratch, { recursive: true, force: true });
}
});
Loading
Loading