diff --git a/App/Sources/BlockView.swift b/App/Sources/BlockView.swift index f123ebce2..bd6578622 100644 --- a/App/Sources/BlockView.swift +++ b/App/Sources/BlockView.swift @@ -24,6 +24,12 @@ final class BlockView: UIView, UITextViewDelegate { private let selectionOverlay = CAShapeLayer() private var lastWidth: CGFloat = 0 private var lastHeight: CGFloat = 0 + private var displayedText = "" + private var displayedWidth: CGFloat = 0 + private let revealMask = CALayer() + private let settledTextMask = CAShapeLayer() + private var revealingText: [(range: NSRange, layer: CAShapeLayer, until: CFTimeInterval)] = [] + private var revealCleanup: DispatchWorkItem? override init(frame: CGRect) { super.init(frame: frame) @@ -132,6 +138,66 @@ final class BlockView: UIView, UITextViewDelegate { accessibilityIdentifier = block.id } + /// Fade only newly appended glyphs. Settled text is never redrawn with a lower opacity. + func revealAppendedText(animated: Bool) { + // Paragraph terminators belong to the renderer, not the growing text. + // Keeping them in the prefix makes every append look like a replacement. + let current = label.attributedText.string.replacingOccurrences(of: "[\\r\\n]+$", with: "", options: .regularExpression) + let previous = displayedText + defer { displayedText = current; displayedWidth = bounds.width } + guard animated, !preparedLabel.isHidden else { finishTextReveal(); return } + guard current != previous else { return } + guard current.hasPrefix(previous), displayedWidth == 0 || displayedWidth == bounds.width else { + finishTextReveal(); return + } + let range = NSRange(location: previous.utf16.count, length: current.utf16.count - previous.utf16.count) + guard range.length > 0 else { return } + let now = CACurrentMediaTime() + revealingText.removeAll { $0.until <= now } + let layer = CAShapeLayer() + layer.fillColor = UIColor.black.cgColor + revealingText.append((range, layer, now + 0.32)) + let settled = CGMutablePath() + settled.addRect(preparedLabel.bounds) + CATransaction.begin() + CATransaction.setDisableActions(true) + revealMask.frame = preparedLabel.bounds + settledTextMask.frame = preparedLabel.bounds + settledTextMask.fillColor = UIColor.black.cgColor + settledTextMask.fillRule = .evenOdd + for item in revealingText { + let path = CGMutablePath() + for rect in textGeometry().rects(for: item.range) { + let glyphs = CGRect(x: rect.minX, y: bounds.height - rect.maxY, width: rect.width, height: rect.height) + path.addRect(glyphs) + settled.addRect(glyphs) + } + item.layer.frame = preparedLabel.bounds + item.layer.path = path + } + settledTextMask.path = settled + revealMask.sublayers = [settledTextMask] + revealingText.map(\.layer) + preparedLabel.layer.mask = revealMask + CATransaction.commit() + let fade = CABasicAnimation(keyPath: "opacity") + fade.fromValue = 0 + fade.toValue = 1 + fade.duration = 0.32 + fade.timingFunction = CAMediaTimingFunction(name: .easeOut) + layer.add(fade, forKey: "stream-reveal") + revealCleanup?.cancel() + let cleanup = DispatchWorkItem { [weak self] in self?.finishTextReveal() } + revealCleanup = cleanup + DispatchQueue.main.asyncAfter(deadline: .now() + 0.32, execute: cleanup) + } + + private func finishTextReveal() { + revealCleanup?.cancel(); revealCleanup = nil + revealingText.removeAll() + preparedLabel.layer.mask = nil + revealMask.sublayers = nil + } + func measure(width: CGFloat) -> CGFloat { guard let record else { return 1 } if lastWidth != width { geometry = nil } @@ -158,7 +224,7 @@ final class BlockView: UIView, UITextViewDelegate { markdown.frame = CGRect(x: 0, y: 0, width: width, height: lastHeight) markdown.layoutIfNeeded() case .workspaceAttachment: - lastHeight = max(120, record.height) + lastHeight = max(1, record.height) case .card: lastHeight = record.collapsed ? 48 : 204 draft.isHidden = record.collapsed; save.isHidden = record.collapsed @@ -175,6 +241,7 @@ final class BlockView: UIView, UITextViewDelegate { super.layoutSubviews() guard let record else { return } if bounds.width != lastWidth { geometry = nil; lastWidth = bounds.width } + if displayedWidth != 0, displayedWidth != bounds.width { finishTextReveal() } switch record.kind { case .markdown: if preparedLabel.isHidden { markdown.frame = bounds } @@ -267,6 +334,7 @@ final class BlockView: UIView, UITextViewDelegate { func displaySelection(_ range: NSRange?) { let path = CGMutablePath() if let range, range.length > 0 { + finishTextReveal() for rect in textGeometry().rects(for: range) { path.addRect(CGRect(x: rect.minX, y: bounds.height - rect.maxY, width: rect.width, height: rect.height)) } @@ -287,7 +355,7 @@ final class BlockView: UIView, UITextViewDelegate { return text case let .card(source): return record.draft.isEmpty ? source : record.draft case let .diagram(source): return source - case .workspaceAttachment: return "[互动内容]" + case let .workspaceAttachment(identifier): return identifier.hasPrefix("activity/") ? "" : "[互动内容]" } } } diff --git a/App/Sources/CatalystConversationView.swift b/App/Sources/CatalystConversationView.swift index 8827967a5..3806b927e 100644 --- a/App/Sources/CatalystConversationView.swift +++ b/App/Sources/CatalystConversationView.swift @@ -18,6 +18,7 @@ struct CatalystConversationView: View { displayedMessages: displayedMessages, floatingThreadID: floatingThreadID, onContentHeight: onContentHeight, onFocusComposer: onFocusComposer, onReadingMessage: onReadingMessage).contentShape(Rectangle()) } private struct Bridge: UIViewControllerRepresentable { + @Environment(\.weibeiReduceMotion) private var reduceMotion @ObservedObject var workspace: WorkspaceStore @ObservedObject var streaming: AgentStreamingState var wideTypography: Bool @@ -39,6 +40,8 @@ struct CatalystConversationView: View { return controller } func updateUIViewController(_ controller: ConversationController, context: Context) { + controller.reduceMotion = reduceMotion + controller.reservesReplySpace = floatingThreadID == nil controller.workspaceBodyWidth = bodyWidth controller.readingMessageChanged = onReadingMessage controller.contentHeightChanged = onContentHeight @@ -82,8 +85,8 @@ struct CatalystConversationView: View { session.messages = displayedMessages ?? workspace.messages if let id = streaming.displayingMessageID, streaming.displayingChatID == targetID, - let index = session.messages.firstIndex(where: { $0.id == id && $0.completionState == .generating }) { - session.messages[index].text = streaming.text + let index = session.messages.firstIndex(where: { $0.id == id }) { + session.messages[index] = streaming.applyingDisplayText(to: session.messages[index]) } coordinator.enqueue(session, into: controller, refreshAppearance: appearanceChanged) } @@ -185,7 +188,9 @@ struct CatalystConversationView: View { pending = nil if displayedSessionID != session.id { auxiliaryHosts.removeAll() - await controller.showSession(session) + let firstTurn = displayedSessionID != nil && previous.isEmpty + && session.messages.contains { $0.completionState == .generating } + await controller.showSession(session, animateFirstTurn: firstTurn) displayedSessionID = session.id } else { controller.updateSavedHistory(session.messages) @@ -234,14 +239,14 @@ private struct CatalystMessageFooter: View { @ObservedObject var streaming: AgentStreamingState let wideTypography: Bool let onHeight: (CGFloat) -> Void - private var message: AgentMessage { store.messages.first { $0.id == initial.id } ?? initial } + private var message: AgentMessage { streaming.applyingDisplayText(to: store.messages.first { $0.id == initial.id } ?? initial) } var body: some View { let text = streaming.isDisplaying(message.id) ? streaming.text : message.text VStack(alignment: .leading, spacing: 8) { if message.role == .user { AgentBubble(message: message, isChatWideTypography: wideTypography) } else { - if message.completionState == .generating && text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + if message.completionState == .generating && !message.toolActivities.contains(where: { $0.state == .running }) && text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { AgentThinkingIndicator(activityText: streaming.activityText, chatWideTypography: wideTypography) } AgentBubble(message: message, isChatWideTypography: wideTypography, showsBody: false) diff --git a/App/Sources/ConversationController.swift b/App/Sources/ConversationController.swift index ea2ac1765..08d13b2b1 100644 --- a/App/Sources/ConversationController.swift +++ b/App/Sources/ConversationController.swift @@ -7,6 +7,8 @@ import QuartzCore final class ConversationController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextViewDelegate { let fixtureMode: Bool var usesWorkspaceChrome = false + var reduceMotion = false + var reservesReplySpace = false var auxiliaryView: ((LabMessage) -> UIView)? var messageLink: ((URL, AgentMessage) -> Void)? var interfaceLanguage: WeiBeiInterfaceLanguage = .chinese { @@ -80,6 +82,10 @@ final class ConversationController: UIViewController, UICollectionViewDataSource collection.keyboardDismissMode = .none collection.accessibilityLabel = "会话消息列表" flow.itemHeight = { [weak self] path in self?.itemHeight(at: path) ?? 0 } + flow.replyStartSection = { [weak self] in + guard let self, reservesReplySpace else { return nil } + return messages.lastIndex { $0.original?.role == .user } + } for child in [toolbar, status, collection, input, send, latest] { view.addSubview(child) } toolbar.spacing = 16; toolbar.alignment = .center toolbar.addArrangedSubview(button("阅读区", symbol: "sidebar.left", action: { [weak self] in self?.toggleWorkspace?() })) @@ -348,6 +354,7 @@ final class ConversationController: UIViewController, UICollectionViewDataSource let block = message.blocks[path.item - 1] let stale = block.width != bodyWidth cell.show(body: store.view(for: block, width: bodyWidth)) + cell.body?.revealAppendedText(animated: !reduceMotion && message.state == .streaming && followsLatest) selection.paint(cell.body!) // A paragraph scrolled in before the width converged was sized from its // previous width; the frame in the layout catches up on the next turn. @@ -484,7 +491,7 @@ final class ConversationController: UIViewController, UICollectionViewDataSource if submitQuestion?(input.text) == true { input.text = "" } } - func showSession(_ session: StudySession) async { + func showSession(_ session: StudySession, animateFirstTurn: Bool = false) async { loadViewIfNeeded() scenarioGeneration += 1 preparation?.cancel(); preparation = nil @@ -502,6 +509,7 @@ final class ConversationController: UIViewController, UICollectionViewDataSource messages.append(message) } collection.reloadData(); collection.layoutIfNeeded(); scrollToLatest() + if animateFirstTurn { for section in messages.indices { animateInsertion(in: section) } } status.text = session.title } @@ -518,7 +526,7 @@ final class ConversationController: UIViewController, UICollectionViewDataSource private func formattedMarkdown(_ value: AgentMessage, memo: AgentMessageMarkdownMemo) -> String { // The original right-aligned user chip is hosted by the auxiliary row. guard value.role == .assistant else { return usesWorkspaceChrome ? "" : value.text } - let text = AgentNativeMessageContent.markdown(text: value.text, blocks: value.contentBlocks) + let text = AgentNativeMessageContent.markdown(text: value.text, blocks: value.contentBlocks, activities: value.toolActivities) return memo.outputs(text: text, sources: value.sources, language: interfaceLanguage).finalized } @@ -549,6 +557,23 @@ final class ConversationController: UIViewController, UICollectionViewDataSource UIView.performWithoutAnimation { collection.insertSections(IndexSet(integer: messages.count - 1)) } collection.layoutIfNeeded() if followsLatest || value.role == .user { scrollToLatest() } + animateInsertion(in: messages.count - 1) + } + } + + private func animateInsertion(in section: Int) { + guard !reduceMotion else { return } + for path in collection.indexPathsForVisibleItems where path.section == section { + guard let cell = collection.cellForItem(at: path) else { continue } + let isQuestion = messages[section].original?.role == .user + let travel = isQuestion ? max(8, collection.bounds.maxY - cell.frame.maxY - 16) : 8 + cell.contentView.alpha = 0 + cell.contentView.transform = CGAffineTransform(translationX: 0, y: travel) + UIView.animate(withDuration: isQuestion ? 0.42 : 0.24, delay: 0, + options: [.beginFromCurrentState, .curveEaseOut, .allowUserInteraction]) { + cell.contentView.alpha = 1 + cell.contentView.transform = .identity + } } } @@ -687,6 +712,10 @@ final class ConversationController: UIViewController, UICollectionViewDataSource } guard generation == scenarioGeneration else { return } if answer.state != .stopped { answer.state = Task.isCancelled ? .stopped : .complete } + let previous = answer.blocks + _ = await store.prepare(answer, width: bodyWidth) + guard generation == scenarioGeneration else { return } + applyBlocks(answer, previous: previous) refreshFooter(answer) send.setImage(UIImage(systemName: "arrow.up.circle.fill"), for: .normal) send.accessibilityLabel = "发送并重放固定回答" @@ -1049,11 +1078,68 @@ final class ConversationController: UIViewController, UICollectionViewDataSource let message = LabMessage(author: "检查样本", markdown: "第一段:中文与 emoji 👩🏽‍💻。\n\n第二段尚在增长") _ = await store.prepare(message, width: bodyWidth) let first = message.blocks[0] + let beforeAppend = store.view(for: message.blocks.last!, width: bodyWidth) + beforeAppend.revealAppendedText(animated: false) + let oldLength = beforeAppend.copyText().trimmingCharacters(in: .newlines).utf16.count message.append(",尾字已经收到。") _ = await store.prepare(message, width: bodyWidth) try expect(message.blocks[0] === first, "流式更新替换了未改变的段落") - let rendered = store.view(for: message.blocks.last!, width: bodyWidth).copyText() + let growing = store.view(for: message.blocks.last!, width: bodyWidth) + growing.revealAppendedText(animated: true) + let rendered = growing.copyText() try expect(rendered.contains("尾字已经收到。"), "流式尾字没有显示") + try expect(growing === beforeAppend, "新增文字替换了原生段落视图") + guard let mask = growing.label.layer.mask, + let settled = (mask.sublayers?.first as? CAShapeLayer)?.path, + let oldGlyph = growing.rect(for: 0), let newGlyph = growing.rect(for: oldLength) else { + throw Failure(message: "流式正文没有进入逐字淡入路径") + } + try expect(settled.contains(CGPoint(x: oldGlyph.midX, y: oldGlyph.midY), using: .evenOdd) + && !settled.contains(CGPoint(x: newGlyph.midX, y: newGlyph.midY), using: .evenOdd), + "淡入遮罩重播了旧文字,或未覆盖新增文字") + try expect(mask.sublayers?.last?.animation(forKey: "stream-reveal") != nil, "新增文字没有淡入动画") + growing.revealAppendedText(animated: false) + try expect(growing.label.layer.mask == nil, "减少动态效果后仍保留文字动画") + + let unfinished = LabMessage(author: "显示格式检查", markdown: "**尚未闭合") + unfinished.state = .streaming + _ = await store.prepare(unfinished, width: bodyWidth) + let live = store.view(for: unfinished.blocks[0], width: bodyWidth) + try expect(live.copyText().trimmingCharacters(in: .newlines) == "尚未闭合", "流式粗体仍显示原始星号") + try expect(unfinished.copyableMarkdown == "**尚未闭合", "显示修补污染了复制原文") + unfinished.state = .stopped + _ = await store.prepare(unfinished, width: bodyWidth) + try expect(store.view(for: unfinished.blocks[0], width: bodyWidth).copyText().trimmingCharacters(in: .newlines) == "**尚未闭合", + "停止后没有恢复真实原文排版") + let pending = LabMessage(author: "链接检查", markdown: "[来源](https://example.") + pending.state = .streaming + _ = await store.prepare(pending, width: bodyWidth) + let pendingView = store.view(for: pending.blocks[0], width: bodyWidth) + let previousOpenLink = store.openLink + var openedPendingLink = false + store.openLink = { _, _ in openedPendingLink = true } + pendingView.onLink?(URL(string: MarkdownStreamingDisplay.pendingLink)!) + store.openLink = previousOpenLink + try expect(!openedPendingLink, "尚未传完的链接可被打开") + + let anchored = ConversationController(fixtureMode: false) + anchored.usesWorkspaceChrome = true + anchored.reservesReplySpace = true + anchored.reduceMotion = true + anchored.loadViewIfNeeded() + anchored.view.frame = CGRect(x: 0, y: 0, width: 720, height: 640) + anchored.view.setNeedsLayout(); anchored.view.layoutIfNeeded() + var turn = StudySession(id: UUID(), title: "发送位置检查") + turn.messages = [AgentMessage(role: .user, text: "之前的问题", source: nil), + AgentMessage(role: .assistant, text: String(repeating: "之前的一段回答。\n\n", count: 24), source: nil), + AgentMessage(role: .user, text: "新的问题", source: nil)] + await anchored.showSession(turn) + let questionTop = anchored.collection.layoutAttributesForItem(at: IndexPath(item: 0, section: 2))!.frame.minY + - anchored.flow.sectionInset.top + try expect(abs(anchored.collection.contentOffset.y - questionTop) < 1, "发送问题后没有留出回答空间") + let reply = AgentMessage(role: .assistant, text: "短回答保持原位。", source: nil, completionState: .generating) + await anchored.display(reply, streaming: true) + try expect(abs(anchored.collection.contentOffset.y - questionTop) < 1, "短回答把问题顶出了原位") message.state = .stopped try expect(message.blocks[0] === first, "停止时重建了正文") metrics.checks["stream_keeps_unchanged_blocks_and_tail"] = "passed" diff --git a/App/Sources/ConversationData.swift b/App/Sources/ConversationData.swift index 2385d4cc2..6e6999f94 100644 --- a/App/Sources/ConversationData.swift +++ b/App/Sources/ConversationData.swift @@ -10,7 +10,9 @@ final class LabMessage { var markdown: String var revision = 0 var displayedRevision = -1 - var state: State = .complete + var state: State = .complete { + didSet { if (oldValue == .streaming) != (state == .streaming) { revision += 1 } } + } var blocks: [PreparedBlock] = [] var original: AgentMessage? var parsed: MarkdownParser.ParseResult? diff --git a/App/Sources/ConversationLayout.swift b/App/Sources/ConversationLayout.swift index 0f691067f..7ca787761 100644 --- a/App/Sources/ConversationLayout.swift +++ b/App/Sources/ConversationLayout.swift @@ -8,6 +8,7 @@ final class ConversationLayout: UICollectionViewLayout { var sectionInset = UIEdgeInsets(top: 14, left: 0, bottom: 10, right: 0) var itemWidth: CGFloat = 0 var itemHeight: ((IndexPath) -> CGFloat)? + var replyStartSection: (() -> Int?)? private struct Section { var minY: CGFloat @@ -25,6 +26,7 @@ final class ConversationLayout: UICollectionViewLayout { override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { abs(newBounds.width - (collectionView?.bounds.width ?? 0)) > 0.5 + || abs(newBounds.height - (collectionView?.bounds.height ?? 0)) > 0.5 } override func prepare() { @@ -56,7 +58,11 @@ final class ConversationLayout: UICollectionViewLayout { y += sectionInset.bottom sections[section].maxY = y } + // Leave room below the latest question; a short reply grows in place. contentHeight = y + if let section = replyStartSection?(), sections.indices.contains(section) { + contentHeight = max(y, sections[section].minY + collectionView.bounds.height) + } } override var collectionViewContentSize: CGSize { diff --git a/App/Sources/MessageCell.swift b/App/Sources/MessageCell.swift index 935f25766..7c127829f 100644 --- a/App/Sources/MessageCell.swift +++ b/App/Sources/MessageCell.swift @@ -17,7 +17,7 @@ final class MessageCell: UICollectionViewCell { contentView.addSubview(actions) } required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } - override func prepareForReuse() { super.prepareForReuse(); unbind() } + override func prepareForReuse() { super.prepareForReuse(); contentView.layer.removeAllAnimations(); contentView.alpha = 1; contentView.transform = .identity; unbind() } private func unbind() { // A prepared view may already belong to the replacement cell by the // time UIKit recycles this one. Only detach views this cell still owns. diff --git a/App/Sources/PreparedContent.swift b/App/Sources/PreparedContent.swift index 7daab6902..4e62bb471 100644 --- a/App/Sources/PreparedContent.swift +++ b/App/Sources/PreparedContent.swift @@ -2,6 +2,7 @@ import UIKit import MarkdownView import MarkdownParser import Litext +import WeiBeiCore extension MarkdownTheme { static func weiBei(fontSize: CGFloat, appearance: WeiBeiAppearanceMode) -> Self { @@ -88,13 +89,14 @@ final class ContentStore { let generation = self.generation let revision = message.revision let text = message.markdown + let streaming = message.state == .streaming // ponytail: full source parsing preserves late reference definitions; // unchanged parsed blocks keep their content and layout. Use parser-owned // incremental invalidation only if this measured cost dominates. let parsed: MarkdownParser.ParseResult if message.parsedRevision == revision, let cached = message.parsed { parsed = cached } else { - parsed = await Task.detached(priority: .userInitiated) { MarkdownParser().parse(text) }.value + parsed = await Task.detached(priority: .userInitiated) { MarkdownParser().parse(streaming ? MarkdownStreamingDisplay.source(text) : text) }.value guard generation == self.generation, revision == message.revision else { return false } message.parsed = parsed; message.parsedRevision = revision parseCount += 1 @@ -169,7 +171,10 @@ final class ContentStore { guard let self, let block else { return } self.changed?(block) } - body.onLink = { [weak self] in self?.openLink?($0, block.messageID) } + body.onLink = { [weak self] url in + guard url.absoluteString != MarkdownStreamingDisplay.pendingLink else { return } + self?.openLink?(url, block.messageID) + } body.onSaveNote = { [weak self] in self?.saveNote?($0) } if block.width != width { block.height = body.measure(width: width) diff --git a/App/WeiBei.xcodeproj/project.pbxproj b/App/WeiBei.xcodeproj/project.pbxproj index 055244500..af20be7f8 100644 --- a/App/WeiBei.xcodeproj/project.pbxproj +++ b/App/WeiBei.xcodeproj/project.pbxproj @@ -139,6 +139,8 @@ 8F1C901FAB9CB7AF1CF2A5CA /* NativeAgentCredentials.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3D53F1E3B3A1F336E71C9B8 /* NativeAgentCredentials.swift */; }; 8FA1279C216C58094CD3F484 /* AgentDisplayText.swift in Sources */ = {isa = PBXBuildFile; fileRef = E739D32EBD1993C95049134D /* AgentDisplayText.swift */; }; 901A367D1400374D6392A777 /* WeiBeiConsoleLogBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D1B740D84E066DD932AD4BD /* WeiBeiConsoleLogBridge.swift */; }; + CB992375BCC4051799E63A4A /* MarkdownEmphasisNormalizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C05BF81E2C72C8B51EB3E223 /* MarkdownEmphasisNormalizer.swift */; }; + AE0D89E7DCA710ED42FEC304 /* MarkdownStreamingDisplay.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE0D89E7DCA710ED42FEC303 /* MarkdownStreamingDisplay.swift */; }; 906EBD96213A616F03F1B5F1 /* MarkdownSelectionSanitizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB8C759711B6BC1EB7095DDB /* MarkdownSelectionSanitizer.swift */; }; 90A2214DC79342A465A01D96 /* ComposerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCFA6009ED31791018CA93D2 /* ComposerView.swift */; }; 90E05FF2E561765AE3B448F1 /* LearningModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23FA1EE716CF045657BDBB93 /* LearningModels.swift */; }; @@ -179,6 +181,7 @@ BAED75D670CA5D37AC28EC72 /* ReaderWebRemarkMarks.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD62172095286419347BAD3C /* ReaderWebRemarkMarks.swift */; }; BC1350DC9BBBF2D04841DBAB /* NativeAgentSkills.swift in Sources */ = {isa = PBXBuildFile; fileRef = 435F8DC910B624960FFAD416 /* NativeAgentSkills.swift */; }; BCACAE104E607247E0FC9EF1 /* AgentNativeMessageContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2811B9DB5EB8545CCF859102 /* AgentNativeMessageContent.swift */; }; + AE0D89E7DCA710ED42FEC302 /* AgentToolActivityGroup.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE0D89E7DCA710ED42FEC301 /* AgentToolActivityGroup.swift */; }; BCDCD7A97AB5857EBAFFD2FF /* WeiBeiWindowBridge.bundle in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 1387DA2798D3308A411300F7 /* WeiBeiWindowBridge.bundle */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; BD408EC22829820BC290DB13 /* PDFOCRTextExtractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4B2307F2390AA8433E3E782 /* PDFOCRTextExtractor.swift */; }; BF06CA2E391053E4D7CCBF08 /* WeiBeiSegmentedControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B078F9A88BC6C5982B3722B /* WeiBeiSegmentedControl.swift */; }; @@ -314,6 +317,7 @@ 25EA17D4BAB16F8364338445 /* AgentFinalizedMarkdownHeightCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentFinalizedMarkdownHeightCache.swift; sourceTree = ""; }; 27CFEABFEA9E0BD9DD27C865 /* WorkspaceFileDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceFileDialog.swift; sourceTree = ""; }; 2811B9DB5EB8545CCF859102 /* AgentNativeMessageContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentNativeMessageContent.swift; sourceTree = ""; }; + AE0D89E7DCA710ED42FEC301 /* AgentToolActivityGroup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentToolActivityGroup.swift; sourceTree = ""; }; 28228E2E2950801444E2EC73 /* CourseRecordsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseRecordsView.swift; sourceTree = ""; }; 28E951E7DE3D0D3725C8C3F2 /* WindowBridgeContract.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowBridgeContract.swift; sourceTree = ""; }; 2982B9601758C42353EADB2F /* NativeAgentLedger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAgentLedger.swift; sourceTree = ""; }; @@ -452,6 +456,8 @@ C465A036B8E9C84DDDF0510D /* AgentMessageViewportWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentMessageViewportWindow.swift; sourceTree = ""; }; C4F2567841D4A49CC47E561F /* CourseLibraryRootRecovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseLibraryRootRecovery.swift; sourceTree = ""; }; C553040DCC6C552CCE0D76E2 /* AppIcon.icon */ = {isa = PBXFileReference; path = AppIcon.icon; sourceTree = ""; }; + C05BF81E2C72C8B51EB3E223 /* MarkdownEmphasisNormalizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownEmphasisNormalizer.swift; sourceTree = ""; }; + AE0D89E7DCA710ED42FEC303 /* MarkdownStreamingDisplay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownStreamingDisplay.swift; sourceTree = ""; }; CB8C759711B6BC1EB7095DDB /* MarkdownSelectionSanitizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownSelectionSanitizer.swift; sourceTree = ""; }; CD62172095286419347BAD3C /* ReaderWebRemarkMarks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReaderWebRemarkMarks.swift; sourceTree = ""; }; CFA8BD37F526A567FC7AF59A /* ConversationLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationLayout.swift; sourceTree = ""; }; @@ -662,6 +668,8 @@ 23FA1EE716CF045657BDBB93 /* LearningModels.swift */, A84083090C43A476B9185377 /* MarkdownAttachmentGC.swift */, 944C3E108DCDD3497B959C7C /* MarkdownAttachmentStore.swift */, + C05BF81E2C72C8B51EB3E223 /* MarkdownEmphasisNormalizer.swift */, + AE0D89E7DCA710ED42FEC303 /* MarkdownStreamingDisplay.swift */, CB8C759711B6BC1EB7095DDB /* MarkdownSelectionSanitizer.swift */, C0F0A58206AD58992303EE1D /* MarkdownLiteralRanges.swift */, E73953CD01471F2679025B14 /* MarkdownTagSearch.swift */, @@ -728,6 +736,7 @@ E8CB1F711E169ECC6A8E59E6 /* AgentMessagePlaceholderRow.swift */, C465A036B8E9C84DDDF0510D /* AgentMessageViewportWindow.swift */, 2811B9DB5EB8545CCF859102 /* AgentNativeMessageContent.swift */, + AE0D89E7DCA710ED42FEC301 /* AgentToolActivityGroup.swift */, BA5B0105600B718DB3416811 /* AgentProviderReadiness.swift */, 963BCB482D54E37E6DE3C842 /* AgentReplyMemoryUpdateTag.swift */, 672C78FE92DA58E70D7B494E /* AgentReplyProfileUpdateTag.swift */, @@ -1157,6 +1166,8 @@ 90E05FF2E561765AE3B448F1 /* LearningModels.swift in Sources */, 765C1A067FD1571617255E55 /* MarkdownAttachmentGC.swift in Sources */, 9CB8A7D13329BBBA8BB508C0 /* MarkdownAttachmentStore.swift in Sources */, + CB992375BCC4051799E63A4A /* MarkdownEmphasisNormalizer.swift in Sources */, + AE0D89E7DCA710ED42FEC304 /* MarkdownStreamingDisplay.swift in Sources */, 906EBD96213A616F03F1B5F1 /* MarkdownSelectionSanitizer.swift in Sources */, 0F73C11D3A3E811B090E3855 /* MarkdownLiteralRanges.swift in Sources */, CDCF17FC6DA7A37CD1F01302 /* MarkdownTagSearch.swift in Sources */, @@ -1238,6 +1249,7 @@ 67A351432C63143915C6226F /* AgentMessageViewportWindow.swift in Sources */, FB0C839223181C545553C8C6 /* AgentModelPicker.swift in Sources */, BCACAE104E607247E0FC9EF1 /* AgentNativeMessageContent.swift in Sources */, + AE0D89E7DCA710ED42FEC302 /* AgentToolActivityGroup.swift in Sources */, 91AB676A76F58C418B565222 /* AgentProviderReadiness.swift in Sources */, E7939285E4E0C9937364F5C3 /* AgentReplyMemoryUpdateTag.swift in Sources */, E818370843CF10A7F41BD707 /* AgentReplyProfileUpdateTag.swift in Sources */, diff --git a/Sources/WeiBei/Stores/AgentStreamingState.swift b/Sources/WeiBei/Stores/AgentStreamingState.swift index c9b7588cf..13061aca1 100644 --- a/Sources/WeiBei/Stores/AgentStreamingState.swift +++ b/Sources/WeiBei/Stores/AgentStreamingState.swift @@ -1,5 +1,6 @@ import Combine import Foundation +import WeiBeiCore @MainActor final class AgentStreamingState: ObservableObject { @@ -8,8 +9,21 @@ final class AgentStreamingState: ObservableObject { @Published private(set) var displayingMessageID: UUID? @Published private(set) var displayingChatID: UUID? + private var activityArrivals: [String: Date] = [:] + + func activityArrivalTimes(for ids: [String], messageID: UUID, now: Date = Date()) -> [String: Date] { + guard isDisplaying(messageID) else { return [:] } + var delay = 0.09 + for id in ids where activityArrivals[id] == nil { + activityArrivals[id] = now.addingTimeInterval(delay) + delay += 0.065 + } + return activityArrivals.filter { ids.contains($0.key) } + } + func begin(messageID: UUID, chatID: UUID) { text = "" + activityArrivals.removeAll(keepingCapacity: true) displayingMessageID = messageID displayingChatID = chatID } @@ -18,6 +32,15 @@ final class AgentStreamingState: ObservableObject { displayingMessageID == messageID } + func applyingDisplayText(to message: AgentMessage) -> AgentMessage { + guard isDisplaying(message.id) else { return message } + var visible = message + visible.text = text + // This is a presentation snapshot. The saved reply remains complete. + if visible.completionState == .completed { visible.completionState = .generating } + return visible + } + func finishDisplaying() { displayingMessageID = nil displayingChatID = nil diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index 977df6994..a80f9366c 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -1092,6 +1092,7 @@ actor CourseProjectFileWorker { } for index in portable.messages.indices { portable.messages[index].toolTrace = [] + portable.messages[index].toolActivities = [] portable.messages[index].sources = portable.messages[index].sources.filter { source in guard source.kind != .discussion else { return false } diff --git a/Sources/WeiBei/Stores/WorkspaceStore+CoursePortable.swift b/Sources/WeiBei/Stores/WorkspaceStore+CoursePortable.swift index 9765f846e..4963691bc 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+CoursePortable.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+CoursePortable.swift @@ -659,6 +659,7 @@ extension WorkspaceStore { } for index in portable.messages.indices { portable.messages[index].toolTrace = [] + portable.messages[index].toolActivities = [] portable.messages[index].sources = portable.messages[index].sources .filter { source in guard source.kind != .discussion else { return false } diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index fa0b3ddce..f418595c9 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -7621,7 +7621,7 @@ final class WorkspaceStore: ObservableObject { targetItemID: foreignItemID, proposedMarkdown: "不应进入可携带状态" ) - let reply = AgentMessage( + var reply = AgentMessage( role: .assistant, text: "课程回答正文必须保留。", source: "课程 Chat", @@ -7640,6 +7640,7 @@ final class WorkspaceStore: ObservableObject { toolTrace: ["内部工具日志不得携带"], createdAt: now ) + reply.toolActivities = [.init(id: "private-call", name: "private-tool", state: .completed)] var longHistory = [firstReply] for index in 1..<500 { longHistory.append( @@ -9923,8 +9924,9 @@ final class WorkspaceStore: ObservableObject { } if reply.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, visibleContentBlocks.isEmpty, + reply.toolTrace.isEmpty, let message = studySessions.first(where: { $0.id == target.sessionID })?.messages.first(where: { $0.id == messageID }), - message.actions.isEmpty, message.memoryUpdate == nil, message.profileUpdate == nil { + message.toolActivities.isEmpty, message.actions.isEmpty, message.memoryUpdate == nil, message.profileUpdate == nil { removeAgentMessage(messageID, from: target.sessionID) } } @@ -10243,6 +10245,14 @@ final class WorkspaceStore: ObservableObject { switch progress { case .preparing: agentStreaming.activityText = ui("正在思考", "Thinking") + case let .toolActivity(activity): + _ = updateAgentMessage(replyMessageID, in: chatID) { message in + if let index = message.toolActivities.firstIndex(where: { $0.id == activity.id }) { + message.toolActivities[index] = message.toolActivities[index].merging(activity) + } else { + message.toolActivities.append(activity) + } + } case let .usingTool(name, detail): let base: String switch name { diff --git a/Sources/WeiBei/Support/NativeChatMarkdownDocument.swift b/Sources/WeiBei/Support/NativeChatMarkdownDocument.swift index 7691c7c54..48b34b3d5 100644 --- a/Sources/WeiBei/Support/NativeChatMarkdownDocument.swift +++ b/Sources/WeiBei/Support/NativeChatMarkdownDocument.swift @@ -129,18 +129,6 @@ enum NativeChatMarkdownParser { var calloutIndex = 0 var interfaceLanguage: WeiBeiInterfaceLanguage = .chinese private static let sourceReference = try! NSRegularExpression(pattern: #"(?:^|[\s`])((?:来源:|Source:)[^`\n]+)"#) - // Match the editor's emphasis boundary rules for Chinese punctuation. - private static let emphasisRules: [(NSRegularExpression, String)] = [ - (#"([\p{L}\p{N}])(\*\*|__)(?=\p{P})"#, "$1 $2"), - (#"(^|[\s\p{P}])(\*\*|__)([^\s*_\n][^*_\n]*\p{P})\2(?=[^\s\p{P}])"#, "$1$2$3$2 "), - (#"(^|[\s\p{P}])(\*\*|__)([^\s*_\n](?:[^*_\n]*?\S)?)[ \t]+\2(?=\S)"#, "$1$2$3$2") - ].map { (try! NSRegularExpression(pattern: $0.0), $0.1) } - - private func normalizeEmphasis(_ source: String) -> String { - Self.emphasisRules.reduce(source) { text, rule in - rule.0.stringByReplacingMatches(in: text, range: NSRange(location: 0, length: text.utf16.count), withTemplate: rule.1) - } - } mutating func append(_ text: String, _ style: NativeChatMarkdownStyle, attachment: NativeChatAttachmentDescriptor? = nil) { guard !text.isEmpty else { return } runs.append(.init(text: text, style: style, attachment: attachment)) @@ -266,32 +254,7 @@ enum NativeChatMarkdownParser { /// Only the extensions absent from CommonMark are tokenized. Code remains untouched. mutating func prepare(_ source: String) -> String { - let lines = source.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) - var lineOffsets = [0] - for line in lines { lineOffsets.append(lineOffsets.last! + line.utf16.count + 1) } - func offset(_ location: SourceLocation) -> Int { - let line = lines[min(location.line - 1, lines.count - 1)] - let bytes = line.utf8.prefix(max(0, location.column - 1)) - return lineOffsets[min(location.line - 1, lines.count - 1)] + String(decoding: bytes, as: UTF8.self).utf16.count - } - var protected: [NSRange] = [] - func protect(_ node: any Markup) { - if node is CodeBlock || node is InlineCode, let range = node.range { - protected.append(NSRange(location: offset(range.lowerBound), length: offset(range.upperBound) - offset(range.lowerBound))) - } else { for child in node.children { protect(child) } } - } - protect(Document(parsing: source)) - let original = source as NSString - var normalized = "", previousEnd = 0 - var normalizedCodeRanges: [NSRange] = [] - for range in protected.sorted(by: { $0.location < $1.location }) { - normalized += normalizeEmphasis(original.substring(with: NSRange(location: previousEnd, length: range.location - previousEnd))) - normalizedCodeRanges.append(NSRange(location: normalized.utf16.count, length: range.length)) - normalized += original.substring(with: range) - previousEnd = NSMaxRange(range) - } - normalized += normalizeEmphasis(original.substring(from: previousEnd)) - protected = normalizedCodeRanges + let (normalized, protected) = MarkdownEmphasisNormalizer.prepare(source) let pattern = #"(?s)(? String { - guard blocks.contains(where: { if case .text = $0 { return false }; return true }) else { return text } + static func markdown(text: String, blocks: [AgentMessageContentBlock], activities: [AgentToolActivity] = []) -> String { + let offsets = Set(activities.map { max(0, $0.textOffset ?? text.count) }).sorted() + var inserted = Set() + func decorate(_ value: String, start: Int) -> String { + var output = "", cursor = value.startIndex, position = start + for offset in offsets where offset >= start && offset <= start + value.count && !inserted.contains(offset) { + let end = value.index(cursor, offsetBy: offset - position) + output += value[cursor.. 0 { result += text.suffix(remaining) } + if hasText, remaining > 0 { result += decorate(String(text.suffix(remaining)), start: text.count - remaining) } return result } @@ -33,6 +47,30 @@ enum AgentNativeMessageContent { } } +struct AgentInlineToolActivity: View { + @EnvironmentObject private var store: WorkspaceStore + @ObservedObject var streaming: AgentStreamingState + let messageID: UUID + let offset: Int + + private var activityMessage: AgentMessage? { + guard var message = store.studySessions.lazy.flatMap(\.messages).first(where: { $0.id == messageID }) else { return nil } + let count = message.text.count + message.toolActivities = message.toolActivities.filter { ($0.textOffset ?? count) == offset } + return message + } + + var body: some View { + if let message = activityMessage { + let visibleText = streaming.isDisplaying(message.id) ? streaming.text : message.text + let active = (streaming.isDisplaying(message.id) || message.completionState == .generating) + && visibleText.count <= offset + AgentToolActivityGroup(message: message, autoOpen: active, + arrivals: streaming.activityArrivalTimes(for: message.toolActivities.map(\.id), messageID: messageID)) + } + } +} + struct AgentNativeContentAttachment: View { @EnvironmentObject private var store: WorkspaceStore let messageID: UUID @@ -46,7 +84,11 @@ struct AgentNativeContentAttachment: View { var body: some View { Group { - if let visualization = blocks.compactMap({ block -> AgentVisualization? in + if identifier.hasPrefix("activity/"), let offset = Int(identifier.dropFirst("activity/".count)) { + AgentInlineToolActivity(streaming: store.streaming(in: store.studySessions.first(where: { session in + session.messages.contains { $0.id == messageID } + })?.id), messageID: messageID, offset: offset) + } else if let visualization = blocks.compactMap({ block -> AgentVisualization? in if case let .visualization(value) = block, value.id == identifier { return value } return nil }).first { diff --git a/Sources/WeiBei/Views/AgentToolActivityGroup.swift b/Sources/WeiBei/Views/AgentToolActivityGroup.swift new file mode 100644 index 000000000..e73032902 --- /dev/null +++ b/Sources/WeiBei/Views/AgentToolActivityGroup.swift @@ -0,0 +1,292 @@ +import SwiftUI +import WeiBeiCore + +/// Tool identity stays visible across running, completed and failed states. +enum AgentActivityIcon { + static func symbol(for name: String) -> String { + switch name { + case "$web_activity", "$web_search", "$web_search_sources": "globe" + case "$web_find", "weibei_search_workspace", "weibei_find_discussions": "magnifyingglass" + case "$web_open", "weibei_web_open", "weibei_course_read", "load_skill": "doc.text" + case "weibei_read_discussion": "text.bubble" + case "create_document": "doc.badge.plus" + case "weibei_note_proposal": "square.and.pencil" + case "weibei_course_map", "weibei_relation_proposal": "point.3.connected.trianglepath.dotted" + case "weibei_read_learning_memory": "book.closed" + case "weibei_update_learning_memory": "bookmark" + case "weibei_course_profile_update": "person.text.rectangle" + case "delegate": "person.2" + case "weibei_visual_asset": "photo" + case "weibei_course_retry_failed_pdf_pages": "doc.text.viewfinder" + case "render_ui": "rectangle.3.group" + default: "puzzlepiece.extension" + } + } +} + +struct AgentActivityRevealTiming { + let progress: Double + let connector: Double + let content: Double + init(start: Date?, now: Date, reduceMotion: Bool) { + guard let start, !reduceMotion else { progress = 1; connector = 1; content = 1; return } + let age = max(0, now.timeIntervalSince(start)) + let row = min(1, age / 0.36) + progress = row == 0 ? 0 : row == 1 ? 1 : 1 - pow(2, -10 * row) + connector = 1 - pow(1 - min(1, age / 0.48), 5) + content = min(1, max(0, (connector - 0.22) / 0.78)) + } +} + +struct AgentToolActivityGroup: View { + @EnvironmentObject private var store: WorkspaceStore + @Environment(\.weibeiReduceMotion) private var reduceMotion + let message: AgentMessage + var autoOpen: Bool? = nil + var arrivals: [String: Date] = [:] + @State private var userExpanded: Bool? + @State private var detailIDs: Set = [] + @State private var revealing = false + private var running: Bool { + message.completionState == .generating && message.toolActivities.contains { $0.state == .running } + } + private var expanded: Bool { userExpanded ?? autoOpen ?? running } + private var lastArrival: Date? { arrivals.values.max() } + private var summary: String { + let searchNames = ["$web_search", "$web_find", "weibei_search_workspace", "weibei_find_discussions"] + let readNames = ["$web_open", "load_skill", "weibei_course_read", "weibei_read_discussion", "weibei_web_open", "weibei_read_learning_memory"] + let searches = message.toolActivities.filter { searchNames.contains($0.name) }.count + let reads = message.toolActivities.filter { readNames.contains($0.name) }.count + let others = message.toolActivities.filter { + !searchNames.contains($0.name) && !readNames.contains($0.name) && $0.name != "$web_search_sources" + }.count + var parts: [String] = [] + if searches > 0 { parts.append(store.ui("搜索 \(searches) 次", "\(searches) searches")) } + if reads > 0 { parts.append(store.ui("读取 \(reads) 次", "\(reads) reads")) } + if others > 0 { parts.append(store.ui("执行 \(others) 项操作", "\(others) operations")) } + if parts.isEmpty { parts.append(store.ui("查看搜索来源", "View search sources")) } + if message.toolActivities.contains(where: { $0.state == .failed }) { parts.append(store.ui("有失败项", "Includes failures")) } + return parts.joined(separator: " · ") + } + private var heading: String { + guard running, let current = message.toolActivities.last(where: { $0.state == .running }) else { return summary } + return current.name == "$web_search" ? store.ui("正在搜索网页", "Searching the web") : store.ui("正在", "Working: ") + title(current.name) + } + var body: some View { + VStack(alignment: .leading, spacing: 0) { + Button { userExpanded = !expanded } label: { + HStack(spacing: 6) { + Image(systemName: "chevron.right") + .font(.system(size: 10, weight: .regular)) + .rotationEffect(.degrees(expanded ? 90 : 0)) + .frame(width: 22) + AgentActivityTitle(text: heading, active: running && !reduceMotion) + .transaction { $0.animation = nil } + } + .frame(height: 26, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityValue(expanded ? store.ui("已展开", "Expanded") : store.ui("已折叠", "Collapsed")) + AgentActivityRevealLayout(progress: expanded ? 1 : 0) { + TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !revealing || reduceMotion)) { tick in + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(message.toolActivities.enumerated()), id: \.element.id) { entry in + let activity = entry.element + let timing = AgentActivityRevealTiming(start: arrivals[activity.id], now: tick.date, reduceMotion: reduceMotion) + let next = message.toolActivities.dropFirst(entry.offset + 1).first + let continuation = next.map { AgentActivityRevealTiming(start: arrivals[$0.id], now: tick.date, reduceMotion: reduceMotion).connector } ?? 0 + AgentActivityRevealLayout(progress: timing.progress) { + activityRow(activity, timing: timing, continuation: continuation) + }.clipped() + } + }.padding(.top, 2).padding(.bottom, 2) + } + } + .clipped() + .opacity(expanded ? 1 : 0) + .allowsHitTesting(expanded) + .accessibilityHidden(!expanded) + } + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .frame(maxWidth: .infinity, alignment: .leading) + .animation(reduceMotion ? nil : .easeOut(duration: 0.14), value: expanded) + .animation(reduceMotion ? nil : .easeOut(duration: 0.14), value: detailIDs) + .task(id: lastArrival) { + guard !reduceMotion, let lastArrival else { revealing = false; return } + let remaining = lastArrival.addingTimeInterval(0.5).timeIntervalSinceNow + guard remaining > 0 else { revealing = false; return } + revealing = true + do { try await Task.sleep(nanoseconds: UInt64(remaining * 1_000_000_000)) } catch { return } + revealing = false + } + } + + private func activityRow(_ activity: AgentToolActivity, timing: AgentActivityRevealTiming, continuation: Double) -> some View { + let hasDetails = !(activity.detail ?? "").isEmpty || !(activity.resultSummary ?? "").isEmpty || !(activity.sourceURLs ?? []).isEmpty + return VStack(alignment: .leading, spacing: 0) { + Button { + if !detailIDs.insert(activity.id).inserted { detailIDs.remove(activity.id) } + } label: { + HStack(spacing: 8) { + Text(title(activity.name)).lineLimit(1).fixedSize() + if !detailIDs.contains(activity.id), let detail = activity.detail, !detail.isEmpty { + Text(detail.replacingOccurrences(of: "\n", with: " ")) + .lineLimit(1).truncationMode(.tail) + .foregroundStyle(WeiBeiTheme.secondaryInk.opacity(0.75)) + } else if activity.state == .running && running { + ProgressView().controlSize(.mini) + Text(store.ui("进行中", "In progress")) + .foregroundStyle(WeiBeiTheme.secondaryInk.opacity(0.75)) + } + if activity.state == .failed { + Image(systemName: "exclamationmark.circle").foregroundStyle(WeiBeiTheme.cinnabar) + } else if activity.state == .cancelled { + Text(store.ui("已取消", "Cancelled")) + } + if hasDetails { + Image(systemName: "chevron.right").font(.system(size: 8)) + .rotationEffect(.degrees(detailIDs.contains(activity.id) ? 90 : 0)) + } + } + .frame(height: 32, alignment: .leading) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(!hasDetails) + .accessibilityLabel(title(activity.name)) + .accessibilityValue(activity.state == .failed ? store.ui("失败", "Failed") : + activity.state == .cancelled ? store.ui("已取消", "Cancelled") : + activity.state == .running ? (running ? store.ui("进行中", "Running") : store.ui("已中断", "Interrupted")) : store.ui("已完成", "Completed")) + if detailIDs.contains(activity.id) { details(activity).padding(.bottom, 10) } + } + .opacity(timing.content) + .offset(y: 4 * (1 - timing.content)) + .padding(.leading, 56) + .overlay(alignment: .leading) { + GeometryReader { geometry in + AgentActivityRail(progress: timing.connector, continuation: continuation) + .stroke(WeiBeiTheme.secondaryInk.opacity(0.24), style: StrokeStyle(lineWidth: 1, lineCap: .round, lineJoin: .round)) + .frame(width: 48, height: geometry.size.height) + Image(systemName: AgentActivityIcon.symbol(for: activity.name)) + .font(.system(size: 14, weight: .regular)) + .foregroundStyle(activity.state == .failed ? WeiBeiTheme.cinnabar : WeiBeiTheme.secondaryInk) + .frame(width: 16, height: 16) + .offset(x: 32, y: 8 + 4 * (1 - timing.content)) + .opacity(timing.content) + }.allowsHitTesting(false).accessibilityHidden(true) + } + .fixedSize(horizontal: false, vertical: true) + } + + private func details(_ activity: AgentToolActivity) -> some View { + VStack(alignment: .leading, spacing: 8) { + if let detail = activity.detail, !detail.isEmpty { Text(detail).textSelection(.enabled) } + if let result = activity.resultSummary, !result.isEmpty { Text(result).textSelection(.enabled) } + else if activity.state == .failed { Text(store.ui("未能完成", "Could not complete")) } + else if activity.state == .running && !running { Text(store.ui("已中断", "Interrupted")) } + let urls = Array(Set(activity.sourceURLs ?? [])).sorted() + if !urls.isEmpty { + DisclosureGroup(store.ui("\(urls.count) 个来源", "\(urls.count) sources")) { + ScrollView { + VStack(alignment: .leading, spacing: 8) { + ForEach(urls, id: \.self) { raw in + if let url = URL(string: raw), ["http", "https"].contains(url.scheme?.lowercased() ?? "") { + Link(destination: url) { + Text((url.host ?? "") + url.path).lineLimit(2) + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + }.buttonStyle(.plain).help(raw) + } + } + }.padding(.vertical, 6) + }.frame(height: min(CGFloat(urls.count) * 38, 180)) + } + } + }.fixedSize(horizontal: false, vertical: true) + } + private func title(_ name: String) -> String { + switch name { + case "weibei_search_workspace": store.ui("搜索资料", "Search materials") + case "weibei_course_read": store.ui("读取资料", "Read materials") + case "weibei_course_map": store.ui("查看课程关联", "Explore course connections") + case "weibei_read_learning_memory": store.ui("回顾学习记忆", "Read learning memory") + case "weibei_update_learning_memory": store.ui("更新学习记忆", "Update learning memory") + case "weibei_course_profile_update": store.ui("更新课程档案", "Update course profile") + case "weibei_note_proposal": store.ui("准备笔记建议", "Prepare note proposal") + case "load_skill": store.ui("读取技能指引", "Read skill instructions") + case "create_document": store.ui("创建文档", "Create document") + case "delegate": store.ui("委派子任务", "Delegate task") + case "weibei_visual_asset": store.ui("查找视觉素材", "Find visual assets") + case "weibei_find_discussions": store.ui("查找讨论", "Find discussions") + case "weibei_read_discussion": store.ui("读取讨论", "Read discussion") + case "weibei_web_open": store.ui("读取网页", "Read web page") + case "weibei_course_retry_failed_pdf_pages": store.ui("重新识别资料页面", "Retry page recognition") + case "weibei_relation_proposal": store.ui("准备关联建议", "Prepare relationship proposal") + case "render_ui": store.ui("生成互动内容", "Create interactive content") + case "$web_activity": store.ui("浏览网页", "Browse the web") + case "$web_open": store.ui("读取网页", "Read web page") + case "$web_find": store.ui("页内查找", "Find in page") + case "$web_search": store.ui("网络搜索", "Search the web") + case "$web_search_sources": store.ui("搜索返回的来源", "Sources returned by search") + default: store.ui("执行工具", "Run tool") + " · " + name + } + } +} + +private struct AgentActivityTitle: View { + let text: String + let active: Bool + @State private var epoch = Date() + var body: some View { + Text(text).lineLimit(1) + .overlay { + if active { + TimelineView(.animation(minimumInterval: 1.0 / 30)) { tick in + GeometryReader { geometry in + let phase = tick.date.timeIntervalSince(epoch).truncatingRemainder(dividingBy: 3.4) / 3.4 + LinearGradient(colors: [.clear, WeiBeiTheme.ink.opacity(0.8), .clear], startPoint: .leading, endPoint: .trailing) + .frame(width: geometry.size.width * 0.72) + .offset(x: geometry.size.width * (phase * 1.72 - 0.72)) + } + }.mask(Text(text).lineLimit(1)).allowsHitTesting(false).accessibilityHidden(true) + } + } + } +} + +private struct AgentActivityRail: Shape { + var progress: Double + var continuation: Double + func path(in rect: CGRect) -> Path { + var branch = Path() + branch.move(to: CGPoint(x: 12.5, y: 0)) + branch.addLine(to: CGPoint(x: 12.5, y: 10)) + branch.addQuadCurve(to: CGPoint(x: 18.5, y: 16), control: CGPoint(x: 12.5, y: 16)) + branch.addLine(to: CGPoint(x: 28, y: 16)) + var result = branch.trimmedPath(from: 0, to: progress) + if continuation > 0 { + result.move(to: CGPoint(x: 12.5, y: 10)) + result.addLine(to: CGPoint(x: 12.5, y: 10 + max(0, rect.height - 10) * continuation)) + } + return result + } +} + +/// Size changes propagate to the native collection while children stay anchored. +private struct AgentActivityRevealLayout: Layout { + var progress: CGFloat + var animatableData: CGFloat { + get { progress } + set { progress = newValue } + } + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + let size = subviews.first?.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil)) ?? .zero + return CGSize(width: size.width, height: size.height * progress) + } + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + subviews.first?.place(at: bounds.origin, anchor: .topLeading, + proposal: ProposedViewSize(width: bounds.width, height: nil)) + } +} diff --git a/Sources/WeiBei/Views/NotesAgentView.swift b/Sources/WeiBei/Views/NotesAgentView.swift index ea8dfebc6..415bb4713 100644 --- a/Sources/WeiBei/Views/NotesAgentView.swift +++ b/Sources/WeiBei/Views/NotesAgentView.swift @@ -3325,7 +3325,7 @@ private struct FloatingSelectionMessageBubble: View { private var finalizedMessage: some View { AgentMessageMarkdownText( - text: isUser ? text : AgentNativeMessageContent.markdown(text: text, blocks: message.contentBlocks), + text: isUser ? text : AgentNativeMessageContent.markdown(text: text, blocks: message.contentBlocks, activities: message.toolActivities), rendersRichMarkdown: !isUser, compact: true, isChatWideTypography: false, @@ -3360,7 +3360,7 @@ private struct FloatingSelectionMessageRow: View { isError: WorkspaceStore.isAgentFailureMessage(message.text), isStreaming: isStreaming ) - if message.completionState == .generating + if message.completionState == .generating && !message.toolActivities.contains(where: { $0.state == .running }) && text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { AgentThinkingIndicator(activityText: streaming.activityText, compact: true) .id(message.id) @@ -3443,7 +3443,7 @@ struct AgentBubble: View { } } .overlay(alignment: .bottomLeading) { - if !isUser { + if !isUser && message.completionState != .generating { messageActionBar // Keep actions close to the last rendered line. .offset(x: 16, y: 2) @@ -3605,13 +3605,13 @@ struct AgentBubble: View { return true } } - let isAwaitingFirstToken = message.completionState == .generating + let isAwaitingFirstToken = message.completionState == .generating && !message.toolActivities.contains(where: { $0.state == .running }) && answerText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty return VStack(alignment: .leading, spacing: 8) { if showsBody { ZStack(alignment: .topLeading) { AgentMessageMarkdownText( - text: AgentNativeMessageContent.markdown(text: answerText, blocks: message.contentBlocks), + text: AgentNativeMessageContent.markdown(text: answerText, blocks: message.contentBlocks, activities: message.toolActivities), rendersRichMarkdown: true, isChatWideTypography: isChatWideTypography, messageID: message.id, @@ -5609,3 +5609,6 @@ private struct AgentStreamingResponse: View { .accessibilityLabel(Text(store.ui("魏碑正在回答", "WeiBei is responding"))) } } + + +/// Execution records come from the tool runner, never from streamed name fragments. diff --git a/Sources/WeiBeiCore/MarkdownEmphasisNormalizer.swift b/Sources/WeiBeiCore/MarkdownEmphasisNormalizer.swift new file mode 100644 index 000000000..0dd2de4ca --- /dev/null +++ b/Sources/WeiBeiCore/MarkdownEmphasisNormalizer.swift @@ -0,0 +1,47 @@ +import Foundation +import Markdown + +/// Shared Chinese emphasis boundaries; code remains byte-for-byte unchanged. +public enum MarkdownEmphasisNormalizer { + // Match the editor's emphasis boundary rules for Chinese punctuation. + private static let emphasisRules: [(NSRegularExpression, String)] = [ + (#"([\p{L}\p{N}])(\*\*|__)(?=[\p{Ps}\p{Pi}])"#, "$1 $2"), + (#"(^|[\s\p{P}])(\*\*|__)([^\s*_\n][^*_\n]*\p{P})\2(?=[^\s\p{P}])"#, "$1$2$3$2 "), + (#"(^|[\s\p{P}])(\*\*|__)([^\s*_\n](?:[^*_\n]*?\S)?)[ \t]+\2(?=\S)"#, "$1$2$3$2") + ].map { (try! NSRegularExpression(pattern: $0.0), $0.1) } + + private static func normalizeEmphasis(_ source: String) -> String { + Self.emphasisRules.reduce(source) { text, rule in + rule.0.stringByReplacingMatches(in: text, range: NSRange(location: 0, length: text.utf16.count), withTemplate: rule.1) + } + } + + public static func prepare(_ source: String) -> (text: String, codeRanges: [NSRange]) { + let lines = source.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + var lineOffsets = [0] + for line in lines { lineOffsets.append(lineOffsets.last! + line.utf16.count + 1) } + func offset(_ location: SourceLocation) -> Int { + let line = lines[min(location.line - 1, lines.count - 1)] + let bytes = line.utf8.prefix(max(0, location.column - 1)) + return lineOffsets[min(location.line - 1, lines.count - 1)] + String(decoding: bytes, as: UTF8.self).utf16.count + } + var protected: [NSRange] = [] + func protect(_ node: any Markup) { + if node is CodeBlock || node is InlineCode, let range = node.range { + protected.append(NSRange(location: offset(range.lowerBound), length: offset(range.upperBound) - offset(range.lowerBound))) + } else { for child in node.children { protect(child) } } + } + protect(Document(parsing: source)) + let original = source as NSString + var normalized = "", previousEnd = 0 + var normalizedCodeRanges: [NSRange] = [] + for range in protected.sorted(by: { $0.location < $1.location }) { + normalized += normalizeEmphasis(original.substring(with: NSRange(location: previousEnd, length: range.location - previousEnd))) + normalizedCodeRanges.append(NSRange(location: normalized.utf16.count, length: range.length)) + normalized += original.substring(with: range) + previousEnd = NSMaxRange(range) + } + normalized += normalizeEmphasis(original.substring(from: previousEnd)) + return (normalized, normalizedCodeRanges) + } +} diff --git a/Sources/WeiBeiCore/MarkdownStreamingDisplay.swift b/Sources/WeiBeiCore/MarkdownStreamingDisplay.swift new file mode 100644 index 000000000..dcc2012ae --- /dev/null +++ b/Sources/WeiBeiCore/MarkdownStreamingDisplay.swift @@ -0,0 +1,100 @@ +import Foundation +import Markdown + +/// Display-only tail repair, adapted from Zeron (MIT, Copyright 2026 Wing). +/// Stored, copied and completed Markdown always uses the original source. +public enum MarkdownStreamingDisplay { + public static let pendingLink = "weibei-pending-link:" + + public static func source(_ source: String) -> String { + guard let last = Array(Document(parsing: source).children).last, !(last is CodeBlock), !(last is HTMLBlock), + let start = last.range?.lowerBound else { return source } + let lines = source.split(separator: "\n", omittingEmptySubsequences: false) + let preceding = lines.prefix(start.line - 1).reduce(0) { $0 + $1.utf8.count + 1 } + let offset = preceding + max(0, start.column - 1) + let bytes = Array(source.utf8) + guard offset <= bytes.count else { return source } + return String(decoding: bytes.prefix(offset), as: UTF8.self) + + mend(String(decoding: bytes.dropFirst(offset), as: UTF8.self)) + } + + private struct Delimiter { var char: Character; var count: Int; var end: Int } + private static func mend(_ text: String) -> String { + let chars = Array(text) + var delimiters: [Delimiter] = [], brackets: [Int] = [] + var code: (count: Int, end: Int)? + var lastContent = -1, i = 0 + func at(_ index: Int) -> Character? { chars.indices.contains(index) ? chars[index] : nil } + func run(_ index: Int) -> Int { chars[index...].prefix { $0 == chars[index] }.count } + func word(_ char: Character?) -> Bool { char?.isLetter == true || char?.isNumber == true } + while i < chars.count { + let char = chars[i] + if code == nil && char == "\\" { lastContent = min(i + 1, chars.count - 1); i += 2; continue } + if char == "`" { + let count = run(i) + if let open = code { + if open.count == count { code = nil } else { lastContent = i + count - 1 } + } else { code = (count, i + count) } + i += count; continue + } + if code != nil { lastContent = i; i += 1; continue } + if char == "*" || char == "_" || char == "~" { + let count = run(i), end = i + run(i) + let previous = at(i - 1), next = at(end) + if (char == "~" && count > 2) || (word(previous) && word(next) && (char == "_" || count == 1 && char == "*")) { + lastContent = end - 1; i = end; continue + } + var remaining = count + if let previous, !previous.isWhitespace, let index = delimiters.lastIndex(where: { $0.char == char }) { + let consumed = min(remaining, delimiters[index].count) + delimiters[index].count -= consumed; remaining -= consumed + delimiters.removeSubrange((delimiters[index].count == 0 ? index : index + 1).. 0 { + // A delimiter can arrive before its first character. Keep it + // pending instead of briefly painting raw Markdown syntax. + if end == chars.count { return mend(String(chars[..<(end - remaining)])) } + if let next, !next.isWhitespace, char != "~" || remaining == 2 { + delimiters.append(.init(char: char, count: remaining, end: end)) + } else { lastContent = end - 1 } + } + i = end; continue + } + if char == "[" { brackets.append(i); i += 1; continue } + if char == "]", let open = brackets.popLast() { + delimiters.removeAll { $0.end > open } + if at(i + 1) == "(" { + var j = i + 2, depth = 0 + while j < chars.count { + if chars[j] == "\\" { j += 2; continue } + if chars[j] == "(" { depth += 1 } + if chars[j] == ")" { + if depth == 0 { break } + depth -= 1 + } + j += 1 + } + if j >= chars.count { return String(chars[..= $0.end } + .map { ($0.end, String(repeating: String($0.char), count: $0.count)) } + if let code, lastContent >= code.end { pending.append((code.end, String(repeating: "`", count: code.count))) } + if let open = brackets.last, lastContent > open { pending.append((open, "](\(pendingLink))")) } + let closers = pending.sorted { $0.0 > $1.0 }.map(\.1).joined() + if let newline = chars.lastIndex(of: "\n") { + let tail = String(chars[(newline + 1)...]).drop(while: { $0 == " " || $0 == "\t" }) + if ["-", "--", "=", "=="].contains(String(tail)), newline > 0, !chars[newline - 1].isWhitespace { + return String(chars[.. = [] private var buffers: [Int: String] = [:] public init() {} public mutating func apply(_ chunk: NativeStreamChunk) { switch chunk { + case let .blockStart(index, .serverTool): + serverToolIndices.insert(index) case let .toolCallDelta(index, id, name, argumentsDelta): + guard !serverToolIndices.contains(index) else { return } var current = calls[index] ?? NativeToolCall(id: id, name: name ?? "", arguments: "") if let name, !name.isEmpty { current.name = name } if current.id.isEmpty { current.id = id } diff --git a/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentTools.swift b/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentTools.swift index 892ef5445..a45be9651 100644 --- a/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentTools.swift +++ b/Sources/WeiBeiCore/NativeAgentRuntime/NativeAgentTools.swift @@ -1198,3 +1198,101 @@ public enum NativeBuiltinTools { return value } } + + +/// User-facing activity details use selected fields, never whole tool payloads. +public enum NativeToolActivityPresentation { + public static func activity(id: String, name: String, arguments: [String: Any], + context: NativeToolExecutionContext, result: NativeToolExecutionResult? = nil, textOffset: Int? = nil) -> AgentToolActivity { + func text(_ key: String) -> String? { arguments[key] as? String } + func short(_ value: String) -> String { String(value.prefix(240)) } + func item(_ key: String) -> String { + guard let id = text(key) else { return context.request.materialTitle.isEmpty ? "当前资料" : context.request.materialTitle } + let persistent = context.persistentAssetIDsByContextID[id] ?? id + return context.request.courseContext.items.first { $0.id == id || $0.id == persistent }?.title + ?? context.request.projectScope.items.first { $0.itemID == persistent }?.title ?? "指定资料" + } + let scope: String + switch text("scope") { + case "library": scope = "整个资料库" + case "material": scope = item("scopeID") + default: scope = context.request.projectScope.courseTitle ?? "当前课程" + } + let entries = arguments["entries"] as? [[String: Any]] ?? [] + let entryText = entries.compactMap { $0["text"] as? String }.joined(separator: ";") + let detail: String + switch name { + case "load_skill": + detail = text("id").flatMap { context.liveStores.skillRegistry.pack(named: $0)?.manifest.name } ?? "指定技能" + case "create_document": detail = (text("title") ?? "新文稿") + " · " + (text("format") ?? "markdown") + case "delegate": detail = text("task") ?? "子任务" + case "render_ui": detail = "当前回答中的互动内容" + case "weibei_visual_asset": detail = context.request.materialTitle.isEmpty ? "当前材料图像" : context.request.materialTitle + " · 图像" + case "weibei_course_map": detail = scope + (text("name").map { " · " + $0 } ?? " · 资料目录") + case "weibei_search_workspace": detail = scope + " · “" + (text("query") ?? "") + "”" + case "weibei_course_read": + detail = item("itemID") + ((arguments["page"] as? Int).map { " · 第 \($0) 页" } + ?? text("location").map { " · " + $0 } ?? (text("cursor") == nil ? " · 从开头读取" : " · 继续读取")) + case "weibei_find_discussions": + detail = (arguments["allChats"] as? Bool == true ? "全部会话" : "当前相关讨论") + (text("query").map { " · “" + $0 + "”" } ?? "") + case "weibei_read_discussion": detail = "读取选定讨论中的真实问答" + case "weibei_web_open": detail = text("url") ?? "指定网页" + case "weibei_course_retry_failed_pdf_pages": detail = item("itemID") + " · 识别失败的页面" + case "weibei_read_learning_memory": detail = (context.request.projectScope.courseTitle ?? "当前课程") + " · 学习记忆与上次位置" + case "weibei_update_learning_memory", "weibei_course_profile_update": + detail = entryText.isEmpty ? "更新已记录的学习状态" : entryText + case "weibei_note_proposal": + detail = (context.request.noteTitle.isEmpty ? "目标笔记" : context.request.noteTitle) + " · " + (text("markdown") ?? "") + case "weibei_relation_proposal": detail = item("noteItemID") + " ↔ " + item("sourceItemID") + case "$web_search": detail = text("query") ?? "模型请求的网络搜索" + default: detail = "工具请求" + } + var activity = AgentToolActivity(id: id, name: name, state: .running, detail: short(detail), textOffset: textOffset) + guard let result else { return activity } + activity.state = result.isError ? .failed : result.details["cancelled"] as? Bool == true ? .cancelled : .completed + if result.isError || activity.state == .cancelled { + activity.resultSummary = short(result.text) + return activity + } + let host = try? JSONDecoder().decode(StudyAgentHostToolResult.self, from: Data(result.text.utf8)) + if let host { + let continuation = host.nextCursor == nil ? "" : " · 还有内容可继续读取" + let titles = host.items.map { $0.item.title }.filter { !$0.isEmpty }.prefix(3).joined(separator: "、") + switch name { + case "weibei_course_map": activity.resultSummary = "返回 \(host.items.count) 项目录" + continuation + case "weibei_search_workspace": activity.resultSummary = "本次返回 \(host.items.count) 条命中" + continuation + case "weibei_find_discussions": activity.resultSummary = "找到 \(host.discussions?.count ?? 0) 段讨论" + case "weibei_read_discussion": + let discussions = host.discussions ?? [] + activity.detail = short(discussions.map(\.title).joined(separator: "、")) + activity.resultSummary = "读取 \(discussions.reduce(0) { $0 + ($1.messages?.count ?? 0) }) 条消息" + case "weibei_web_open": + activity.resultSummary = short(host.webPages.map(\.title).joined(separator: "、")) + " · 返回 \(host.webPages.reduce(0) { $0 + $1.text.count }) 字" + continuation + activity.sourceURLs = host.webPages.map(\.url) + case "weibei_course_retry_failed_pdf_pages": + activity.resultSummary = short(host.query) + default: activity.resultSummary = "返回 \(host.items.count) 段资料" + continuation + } + if !titles.isEmpty { activity.resultSummary = (activity.resultSummary ?? "") + " · " + short(titles) } + return activity + } + switch name { + case "load_skill": activity.resultSummary = result.details["alreadyLoaded"] as? Bool == true ? "本会话已加载,无需重复读取" : "技能指引已加载" + case "weibei_read_learning_memory": activity.resultSummary = "读取 \(context.request.learningContext.memories.count) 条学习记忆" + case "weibei_update_learning_memory": + activity.resultSummary = result.details["appliedMemoryUpdate"] == nil ? "更新已校验,等待保存" : short(result.text) + case "weibei_course_profile_update": + activity.resultSummary = result.details["appliedProfileUpdate"] == nil ? "档案更新已校验,等待保存" : short(result.text) + case "weibei_note_proposal": + activity.resultSummary = arguments["userRequested"] as? Bool == true ? "写入请求已登记,等待笔记保存回执" : "建议已准备,尚未写入笔记" + case "weibei_relation_proposal": activity.resultSummary = "关联建议已准备,尚未建立关系" + case "create_document": activity.resultSummary = "文稿已创建 · \(result.details["byteCount"] as? Int ?? 0) 字节" + case "delegate": activity.resultSummary = (result.details["partial"] as? Bool == true ? "子任务部分完成 · " : "子任务已返回 · ") + short(result.text) + case "render_ui": activity.resultSummary = "互动内容已提交到当前回答" + case "weibei_visual_asset": activity.resultSummary = "材料图像已读取 · \(result.details["byteCount"] as? Int ?? 0) 字节" + case "$web_search": activity.resultSummary = "搜索参数已回传,等待服务端结果" + default: activity.resultSummary = short(result.text) + } + return activity + } +} diff --git a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/AnthropicMessagesProvider.swift b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/AnthropicMessagesProvider.swift index 03fdcae9a..3f5b69257 100644 --- a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/AnthropicMessagesProvider.swift +++ b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/AnthropicMessagesProvider.swift @@ -212,12 +212,23 @@ public struct AnthropicMessagesProvider: NativeLLMAdapter { let name = block["name"] as? String return [.toolCallDelta(index: index, id: id, name: name, argumentsDelta: "")] } - // 服务端 web_search 结果块:content 里每条 web_search_result 带来源 url。 - if block["type"] as? String == "web_search_tool_result", - let results = block["content"] as? [[String: Any]] { - return results.compactMap { result in - (result["url"] as? String).map(NativeStreamChunk.webSearchSource(url:)) + if block["type"] as? String == "server_tool_use", + block["name"] as? String == "web_search", let id = block["id"] as? String { + return [.blockStart(index: index, blockType: .serverTool), + .serverToolActivity(.init(id: id, name: "$web_search", state: .running, + detail: (block["input"] as? [String: Any])?["query"] as? String))] + } + if block["type"] as? String == "web_search_tool_result" { + var chunks: [NativeStreamChunk] = [] + if let id = block["tool_use_id"] as? String { + let failed = (block["content"] as? [String: Any])?["type"] as? String == "web_search_tool_result_error" + chunks.append(.serverToolActivity(.init(id: id, name: "$web_search", state: failed ? .failed : .completed, + sourceURLs: (block["content"] as? [[String: Any]])?.compactMap { $0["url"] as? String }))) + } + for result in block["content"] as? [[String: Any]] ?? [] { + if let url = result["url"] as? String { chunks.append(.webSearchSource(url: url)) } } + return chunks } return [] case "content_block_stop": diff --git a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/OpenAIResponsesProvider.swift b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/OpenAIResponsesProvider.swift index d5f344585..b6412b666 100644 --- a/Sources/WeiBeiCore/NativeAgentRuntime/Providers/OpenAIResponsesProvider.swift +++ b/Sources/WeiBeiCore/NativeAgentRuntime/Providers/OpenAIResponsesProvider.swift @@ -74,6 +74,28 @@ public struct OpenAIResponsesProvider: NativeLLMAdapter { return urlRequest } + private static func webActivityName(_ action: [String: Any]?) -> String { + switch action?["type"] as? String { + case "search": return "$web_search" + case "open_page": return "$web_open" + case "find_in_page": return "$web_find" + default: return "$web_activity" + } + } + + private static func webActivity(_ item: [String: Any], id: String) -> AgentToolActivity { + let action = item["action"] as? [String: Any] + let queries = action?["queries"] as? [String] + let pageDetail = [action?["pattern"] as? String, action?["url"] as? String].compactMap { $0 }.joined(separator: " · ") + let detail = queries?.joined(separator: " · ") ?? action?["query"] as? String + ?? (pageDetail.isEmpty ? nil : pageDetail) + let urls = (action?["sources"] as? [[String: Any]])?.compactMap { $0["url"] as? String } + let status = item["status"] as? String + return .init(id: id, name: webActivityName(action), + state: status == "failed" ? .failed : status == "completed" ? .completed : .running, + detail: detail, sourceURLs: urls) + } + public static func payload(for request: NativeLLMRequest, webSearchSupported: Bool = true) -> [String: Any] { var tools: [[String: Any]] = request.tools.map { tool in [ @@ -198,7 +220,15 @@ public struct OpenAIResponsesProvider: NativeLLMAdapter { case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": let text = object["delta"] as? String ?? "" return text.isEmpty ? [] : [.reasoningDelta(index: index, text: text)] + case "response.web_search_call.in_progress", "response.web_search_call.searching", "response.web_search_call.completed": + guard let id = object["item_id"] as? String, !id.isEmpty else { return [] } + return [.serverToolActivity(.init(id: id, name: "$web_activity", + state: type == "response.web_search_call.completed" ? .completed : .running))] case "response.output_item.added": + if let item = object["item"] as? [String: Any], + item["type"] as? String == "web_search_call", let id = item["id"] as? String { + return [.serverToolActivity(webActivity(item, id: id))] + } guard let item = object["item"] as? [String: Any], item["type"] as? String == "function_call" else { return [] } let id = (item["call_id"] as? String) ?? (item["id"] as? String) ?? "" @@ -206,12 +236,16 @@ public struct OpenAIResponsesProvider: NativeLLMAdapter { return [.toolCallDelta(index: index, id: id, name: name, argumentsDelta: "")] case "response.output_item.done": guard let item = object["item"] as? [String: Any], - item["type"] as? String == "web_search_call", - let action = item["action"] as? [String: Any], - let sources = action["sources"] as? [[String: Any]] else { return [] } - return sources.compactMap { source in - (source["url"] as? String).map(NativeStreamChunk.webSearchSource(url:)) + item["type"] as? String == "web_search_call" else { return [] } + var chunks: [NativeStreamChunk] = [] + let action = item["action"] as? [String: Any] + if let id = item["id"] as? String { + chunks.append(.serverToolActivity(webActivity(item, id: id))) } + for source in action?["sources"] as? [[String: Any]] ?? [] { + if let url = source["url"] as? String { chunks.append(.webSearchSource(url: url)) } + } + return chunks case "response.function_call_arguments.delta": let delta = object["delta"] as? String ?? "" let id = object["call_id"] as? String ?? "" diff --git a/Sources/WeiBeiCore/StudyAgentRuntime.swift b/Sources/WeiBeiCore/StudyAgentRuntime.swift index 5e2ac78c4..6c46a08f3 100644 --- a/Sources/WeiBeiCore/StudyAgentRuntime.swift +++ b/Sources/WeiBeiCore/StudyAgentRuntime.swift @@ -871,6 +871,7 @@ public enum StudyAgentProgress: Equatable, Sendable { /// Tool name plus an optional human-readable argument excerpt /// (search query, file title…) surfaced in the chat status line. case usingTool(String, String?) + case toolActivity(AgentToolActivity) case text(String, [AgentMessageContentBlock], [AgentReplySource]) case visualization(AgentVisualization, [AgentMessageContentBlock]) } diff --git a/Sources/WeiBeiCore/WorkspaceModels.swift b/Sources/WeiBeiCore/WorkspaceModels.swift index 2ccac4787..07baccb55 100644 --- a/Sources/WeiBeiCore/WorkspaceModels.swift +++ b/Sources/WeiBeiCore/WorkspaceModels.swift @@ -1845,6 +1845,32 @@ public enum AgentMessageContentBlock: Codable, Hashable, Sendable { } } +public struct AgentToolActivity: Identifiable, Codable, Hashable, Sendable { + public enum State: String, Codable, Sendable { case running, completed, failed, cancelled } + public var id: String + public var name: String + public var state: State + public var detail: String? + public var sourceURLs: [String]? + public var resultSummary: String? + /// Character position in the cumulative answer when this activity first appeared. + public var textOffset: Int? + public init(id: String, name: String, state: State, detail: String? = nil, sourceURLs: [String]? = nil, resultSummary: String? = nil, textOffset: Int? = nil) { + self.id = id; self.name = name; self.state = state + self.detail = detail; self.sourceURLs = sourceURLs; self.resultSummary = resultSummary; self.textOffset = textOffset + } + public func merging(_ update: Self) -> Self { + var next = update + // Status-only web events cannot erase an already identified action. + if update.name == "$web_activity", ["$web_search", "$web_open", "$web_find"].contains(name) { next.name = name } + next.detail = update.detail ?? detail + next.sourceURLs = update.sourceURLs ?? sourceURLs + next.resultSummary = update.resultSummary ?? resultSummary + next.textOffset = textOffset ?? update.textOffset + return next + } +} + public struct AgentMessage: Identifiable, Codable, Hashable, Sendable { public var id: UUID public var role: AgentRole @@ -1860,6 +1886,7 @@ public struct AgentMessage: Identifiable, Codable, Hashable, Sendable { public var origin: AgentReplyOrigin? public var failureKind: AgentFailureKind? public var retryQuestion: String? + public var toolActivities: [AgentToolActivity] = [] public var requestContext: AgentRequestContext? public var toolTrace: [String] public var createdAt: Date @@ -1917,6 +1944,7 @@ public struct AgentMessage: Identifiable, Codable, Hashable, Sendable { case origin case failureKind case retryQuestion + case toolActivities case requestContext case toolTrace case createdAt @@ -2021,6 +2049,7 @@ public struct AgentMessage: Identifiable, Codable, Hashable, Sendable { forKey: .retryQuestion, marker: "reply-retry:decode-failed" ) + toolActivities = try container.decodeIfPresent([AgentToolActivity].self, forKey: .toolActivities) ?? [] requestContext = try container.decodeIfPresent(AgentRequestContext.self, forKey: .requestContext) toolTrace = decodedToolTrace createdAt = try container.decode(Date.self, forKey: .createdAt) @@ -2050,6 +2079,9 @@ public struct AgentMessage: Identifiable, Codable, Hashable, Sendable { try container.encodeIfPresent(origin, forKey: .origin) try container.encodeIfPresent(failureKind, forKey: .failureKind) try container.encodeIfPresent(retryQuestion, forKey: .retryQuestion) + if !toolActivities.isEmpty { + try container.encode(toolActivities, forKey: .toolActivities) + } try container.encodeIfPresent(requestContext, forKey: .requestContext) if !toolTrace.isEmpty { try container.encode(toolTrace, forKey: .toolTrace) diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 78f436f01..1a8814ed6 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1978,3 +1978,31 @@ SOFTWARE. ##################################################################################### ``` + +## Zeron conversation presentation + +Activity reveal timing and display-only streaming Markdown repair are adapted +from [zeronsh/zeron](https://github.com/zeronsh/zeron), commit +`8ee7a6222827f9becac84a7e8900c39c56237d2b`. + +MIT License + +Copyright (c) 2026 Wing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Tests/WeiBeiSafetyTests/AgentStreamingDisplayPumpTests.swift b/Tests/WeiBeiSafetyTests/AgentStreamingDisplayPumpTests.swift index 4a9123d95..24962ed5f 100644 --- a/Tests/WeiBeiSafetyTests/AgentStreamingDisplayPumpTests.swift +++ b/Tests/WeiBeiSafetyTests/AgentStreamingDisplayPumpTests.swift @@ -1,5 +1,7 @@ import XCTest +import SwiftUI @testable import WeiBei +import WeiBeiCore @MainActor final class AgentStreamingDisplayPumpTests: XCTestCase { @@ -115,6 +117,127 @@ final class AgentStreamingDisplayPumpTests: XCTestCase { XCTAssertEqual(rig.pump.pendingCharacterCount, 0) } + func testCompletedReplyKeepsItsVisiblePrefixUntilTheDisplayQueueDrains() { + let run = AgentConversationRun(chatID: UUID()) + let message = AgentMessage(role: .assistant, text: "一二三四五六七八九十", source: nil) + run.streaming.begin(messageID: message.id, chatID: run.chatID!) + run.pump.enqueue(cumulativeText: message.text) + run.pump.stepOnce() + run.pump.finish(cumulativeText: message.text) + XCTAssertEqual(run.streaming.applyingDisplayText(to: message).text, "一二三四") + XCTAssertEqual(message.text, "一二三四五六七八九十") + XCTAssertEqual(message.completionState, .completed) + XCTAssertEqual(run.streaming.applyingDisplayText(to: message).completionState, .generating) + while run.pump.pendingCharacterCount > 0 { run.pump.stepOnce() } + XCTAssertEqual(run.streaming.applyingDisplayText(to: message).text, message.text) + XCTAssertFalse(run.streaming.isDisplaying(message.id)) + } + + func testToolGroupsFollowTextBoundariesWithoutRevealingFutureActivity() throws { + let text = "先👨‍👩‍👧‍👦查后答" + let activities = [ + AgentToolActivity(id: "1", name: "search", state: .completed, textOffset: 2), + AgentToolActivity(id: "2", name: "read", state: .completed, textOffset: 2), + AgentToolActivity(id: "3", name: "read", state: .running, textOffset: 4) + ] + let early = AgentNativeMessageContent.markdown(text: String(text.prefix(1)), blocks: [], activities: activities) + XCTAssertEqual(early, "先") + let output = AgentNativeMessageContent.markdown(text: text, blocks: [], activities: activities) + XCTAssertEqual(output, "先👨‍👩‍👧‍👦\n\n![图示](weibei-visualization:activity/2)\n\n查后\n\n![图示](weibei-visualization:activity/4)\n\n答") + let start = activities[0] + let completed = start.merging(.init(id: "1", name: "search", state: .completed, textOffset: 5)) + XCTAssertEqual(completed.textOffset, 2) + XCTAssertEqual(try JSONDecoder().decode(AgentToolActivity.self, from: JSONEncoder().encode(completed)), completed) + } + + func testActivityInterleavesWithRichContentAndRespectsVisiblePrefix() { + let blocks: [AgentMessageContentBlock] = [.text("先查"), .unavailable(type: "example", rawJSON: "{}"), .text("后答")] + let activities = [AgentToolActivity(id: "1", name: "read", state: .completed, textOffset: 2)] + let early = AgentNativeMessageContent.markdown(text: "先", blocks: blocks, activities: activities) + XCTAssertEqual(early, "先") + let output = AgentNativeMessageContent.markdown(text: "先查后答", blocks: blocks, activities: activities) + XCTAssertEqual(output, "先查\n\n![图示](weibei-visualization:activity/2)\n\n\n\n![图示](weibei-visualization:unavailable-1)\n\n后答") + } + + func testActivityIdentityAndRevealSurviveUpdatesWithoutReplayingHistory() { + let names = ["$web_search", "weibei_course_read", "weibei_note_proposal", "delegate", "render_ui", + "weibei_course_map", "weibei_read_learning_memory", "weibei_update_learning_memory", + "weibei_course_profile_update", "weibei_visual_asset", "weibei_course_retry_failed_pdf_pages", + "create_document", "weibei_read_discussion", "weibei_search_workspace"] + for name in names { + XCTAssertNotNil(NSImage(systemSymbolName: AgentActivityIcon.symbol(for: name), accessibilityDescription: nil), name) + } + XCTAssertEqual(Set(names.prefix(5).map { AgentActivityIcon.symbol(for: $0) }).count, 5) + let state = AgentStreamingState(), message = UUID(), chat = UUID(), now = Date() + XCTAssertTrue(state.activityArrivalTimes(for: ["a"], messageID: message, now: now).isEmpty) + state.begin(messageID: message, chatID: chat) + let initial = state.activityArrivalTimes(for: ["a", "b"], messageID: message, now: now) + XCTAssertLessThan(initial["a"]!, initial["b"]!) + XCTAssertEqual(state.activityArrivalTimes(for: ["a", "b"], messageID: message, now: now.addingTimeInterval(5)), initial) + let before = AgentActivityRevealTiming(start: initial["a"], now: now, reduceMotion: false) + let middle = AgentActivityRevealTiming(start: initial["a"], now: now.addingTimeInterval(0.2), reduceMotion: false) + let settled = AgentActivityRevealTiming(start: initial["a"], now: now.addingTimeInterval(1), reduceMotion: false) + XCTAssertEqual(before.content, 0) + XCTAssertGreaterThan(middle.connector, middle.content) + XCTAssertEqual(settled.progress, 1) + XCTAssertEqual(settled.content, 1) + XCTAssertEqual(AgentActivityRevealTiming(start: initial["a"], now: now, reduceMotion: true).content, 1) + state.finishDisplaying() + XCTAssertTrue(state.activityArrivalTimes(for: ["a"], messageID: message).isEmpty) + } + + func testActivityDisclosureUsesCompactNativeLayout() throws { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: folder) } + let defaults = UserDefaults(suiteName: UUID().uuidString)! + let store = WorkspaceStore(workspaceDirectory: folder, selectionAskThreadDefaults: defaults, + startsAtBlankEntries: true, startsCourseFileMaintenance: false) + var message = AgentMessage(role: .assistant, text: "回答", source: nil) + message.toolActivities = [ + .init(id: "search", name: "$web_search", state: .completed, + detail: String(repeating: "很长的搜索查询 ", count: 20), + sourceURLs: (1...44).map { "https://example.com/article/\($0)" }), + .init(id: "read", name: "weibei_course_read", state: .completed, detail: "课程讲义,第 8 页") + ] + var heights: [CGFloat] = [] + for expanded in [false, true] { + let renderer = ImageRenderer(content: AgentToolActivityGroup(message: message, autoOpen: expanded) + .environmentObject(store).frame(width: 640).padding(24).background(WeiBeiTheme.paper)) + renderer.scale = 2 + let image = try XCTUnwrap(renderer.nsImage) + heights.append(image.size.height) + if let directory = ProcessInfo.processInfo.environment["WEIBEI_ACTIVITY_PREVIEW_DIR"] { + let url = URL(fileURLWithPath: directory, isDirectory: true) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + let bitmap = try XCTUnwrap(NSBitmapImageRep(data: XCTUnwrap(image.tiffRepresentation))) + try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: + url.appendingPathComponent(expanded ? "expanded.png" : "collapsed.png")) + } + } + XCTAssertGreaterThan(heights[1], heights[0]) + XCTAssertLessThan(heights[1], 150, "Opening a group must not lay out query details or 44 sources") + } + + func testLoadingPainterProducesDifferentFramesWithoutMovingText() throws { + let view = AgentThinkingOrbitNSView(frame: NSRect(x: 0, y: 0, width: 180, height: 40)) + var frames: [Data] = [] + for elapsed in [1.0, 1.7] { + view.apply(text: "正在搜索网页", textWidth: 120, orbitWidth: 140, pathHeight: 34, + orbitPadding: 6.5, textLineHeight: 20, lineWidth: 1.25, fontSize: 14, + motionEpoch: Date().addingTimeInterval(-elapsed), appearanceMode: .paper) + let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 180, + pixelsHigh: 40, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, + isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) + view.draw(view.bounds) + NSGraphicsContext.restoreGraphicsState() + frames.append(try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))) + XCTAssertEqual(view.intrinsicContentSize, NSSize(width: 140, height: 34)) + } + XCTAssertNotEqual(frames[0], frames[1], "Loading feedback must animate, not remain a static label") + } + private func waitUntil(_ condition: @escaping @MainActor () -> Bool) async { let deadline = ContinuousClock.now + .seconds(1) while !condition(), ContinuousClock.now < deadline { diff --git a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift index 23d6a418b..51d818045 100644 --- a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift @@ -2921,6 +2921,7 @@ enum CourseProjectRootSelfCheck { !serialized.contains(fixture.workspaceDirectory.path) && !serialized.contains(courseARoot.path) && !serialized.contains("toolTrace") + && !serialized.contains("toolActivities") && !serialized.contains("最早一条课程回答。") && !serialized.contains(foreignMaterial.id), "课程状态泄露本机路径、完整 Chat、内部日志或另一门课程 ID" diff --git a/Tests/WeiBeiSafetyTests/NativeAgentRuntimeTests.swift b/Tests/WeiBeiSafetyTests/NativeAgentRuntimeTests.swift index 2a5a70e0e..9d75472bb 100644 --- a/Tests/WeiBeiSafetyTests/NativeAgentRuntimeTests.swift +++ b/Tests/WeiBeiSafetyTests/NativeAgentRuntimeTests.swift @@ -1259,6 +1259,85 @@ final class NativeAgentRuntimeTests: XCTestCase { } } + func testEveryRegisteredToolHasDetailsAndHonestOutcome() async throws { + let registry = NativeToolRegistry() + await NativeBuiltinTools.registerAll(into: registry, skillRoot: nil) + let tools = await registry.resolved(scope: .global) + let context = NativeToolExecutionContext(request: testRequest()) + let arguments: [String: Any] = ["query": "利率", "scope": "library", "title": "复习笔记", + "page": 3, "markdown": "复习内容", "task": "整理章节", "url": "https://example.com", + "entries": [["text": "已理解利率", "kind": "understood"]]] + for tool in tools { + let start = NativeToolActivityPresentation.activity(id: "call", name: tool.name, arguments: arguments, context: context) + XCTAssertFalse(start.detail?.isEmpty ?? true, tool.name) + XCTAssertNotEqual(start.detail, "工具请求", "Registered tool missing presentation: \(tool.name)") + let failure = NativeToolActivityPresentation.activity(id: "call", name: tool.name, arguments: arguments, + context: context, result: .init(text: "读取被拒绝", isError: true)) + XCTAssertEqual(failure.state, .failed) + XCTAssertEqual(failure.resultSummary, "读取被拒绝") + XCTAssertEqual(failure.detail, start.detail) + } + let cancelled = NativeToolActivityPresentation.activity(id: "call", name: "create_document", arguments: arguments, + context: context, result: .init(text: "用户取消,未写入文件", details: ["cancelled": true])) + XCTAssertEqual(cancelled.state, .cancelled) + XCTAssertEqual(cancelled.resultSummary, "用户取消,未写入文件") + for name in ["weibei_update_learning_memory", "weibei_course_profile_update"] { + let queued = NativeToolActivityPresentation.activity(id: "call", name: name, arguments: arguments, + context: context, result: .init(text: "已提交")) + XCTAssertTrue(queued.resultSummary?.contains("等待保存") == true) + } + let host = StudyAgentHostToolResult(query: "利率", items: [], total: 50, nextCursor: "next") + let search = NativeToolActivityPresentation.activity(id: "call", name: "weibei_search_workspace", arguments: arguments, + context: context, result: .init(text: String(decoding: try JSONEncoder().encode(host), as: UTF8.self))) + XCTAssertTrue(search.resultSummary?.contains("本次返回 0 条命中") == true) + XCTAssertFalse(search.resultSummary?.contains("50") == true, "Total hits are not returned hits") + XCTAssertEqual(try JSONDecoder().decode(AgentToolActivity.self, from: JSONEncoder().encode(search)), search) + } + + func testSearchDetailsSurviveStatusUpdates() throws { + let started = try OpenAIResponsesProvider.translate(#"{"type":"response.output_item.added","item":{"type":"web_search_call","id":"search1","status":"in_progress","action":{"type":"search","queries":["Barcelona dressing room","Real Madrid dressing room"]}}}"#) + guard case let .serverToolActivity(live) = started.first else { return XCTFail("Missing running activity") } + XCTAssertEqual(live.state, .running) + XCTAssertEqual(live.detail, "Barcelona dressing room · Real Madrid dressing room", "Available queries must be visible before completion") + let chunks = try OpenAIResponsesProvider.translate(#"{"type":"response.output_item.done","item":{"type":"web_search_call","id":"search1","status":"completed","action":{"type":"search","queries":["Barcelona dressing room","Real Madrid dressing room"],"sources":[{"url":"https://example.com/story"}]}}}"#) + guard case let .serverToolActivity(activity) = chunks.first else { return XCTFail("Missing activity") } + XCTAssertEqual(activity.detail, "Barcelona dressing room · Real Madrid dressing room") + XCTAssertEqual(activity.sourceURLs, ["https://example.com/story"]) + let merged = activity.merging(.init(id: activity.id, name: activity.name, state: .completed)) + XCTAssertEqual(merged, activity, "A status-only event must not erase the query or sources") + XCTAssertEqual(try JSONDecoder().decode(AgentToolActivity.self, from: JSONEncoder().encode(merged)), activity) + } + + func testServerWebActionsKeepTheirIdentityAcrossStatusEvents() throws { + for (kind, name) in [("search", "$web_search"), ("open_page", "$web_open"), ("find_in_page", "$web_find")] { + let event: [String: Any] = ["type": "response.output_item.done", "item": [ + "type": "web_search_call", "id": "web1", "status": "completed", + "action": ["type": kind, "url": "https://example.com", "pattern": "桥长"]]] + let chunks = try OpenAIResponsesProvider.translate(String(decoding: JSONSerialization.data(withJSONObject: event), as: UTF8.self)) + guard case let .serverToolActivity(activity) = chunks.first else { return XCTFail("Missing web activity") } + XCTAssertEqual(activity.name, name) + XCTAssertEqual(activity.detail, "桥长 · https://example.com") + let merged = activity.merging(.init(id: activity.id, name: "$web_activity", state: .completed)) + XCTAssertEqual(merged.name, name) + XCTAssertEqual(merged.detail, activity.detail) + } + } + + func testServerSearchLifecycleIncludesEmptyResultsAndFailure() throws { + let start = try OpenAIResponsesProvider.translate(#"{"type":"response.web_search_call.in_progress","item_id":"search1"}"#) + let done = try OpenAIResponsesProvider.translate(#"{"type":"response.output_item.done","item":{"type":"web_search_call","id":"search1","status":"completed","action":{"sources":[]}}}"#) + XCTAssertEqual(start, [.serverToolActivity(.init(id: "search1", name: "$web_activity", state: .running))]) + XCTAssertEqual(done, [.serverToolActivity(.init(id: "search1", name: "$web_activity", state: .completed, sourceURLs: []))]) + let anthropicStart = try AnthropicMessagesProvider.translate(#"{"type":"content_block_start","content_block":{"type":"server_tool_use","name":"web_search","id":"search2"}}"#) + let failed = try AnthropicMessagesProvider.translate(#"{"type":"content_block_start","content_block":{"type":"web_search_tool_result","tool_use_id":"search2","content":{"type":"web_search_tool_result_error","error_code":"too_many_requests"}}}"#) + XCTAssertEqual(anthropicStart, [.blockStart(index: 0, blockType: .serverTool), .serverToolActivity(.init(id: "search2", name: "$web_search", state: .running))]) + XCTAssertEqual(failed, [.serverToolActivity(.init(id: "search2", name: "$web_search", state: .failed))]) + var assembler = NativeToolCallAssembler() + for chunk in start + done + anthropicStart + failed { assembler.apply(chunk) } + assembler.apply(.toolCallDelta(index: 0, id: "", name: nil, argumentsDelta: "{\"query\":\"news\"}")) + XCTAssertTrue(try assembler.completedCalls().isEmpty, "Server searches must not be executed again locally") + } + func testMalformedToolArgumentsDoNotBlockValidSiblingOrCompletion() async throws { let url = FileManager.default.temporaryDirectory.appendingPathComponent("native-mixed-tools-\(UUID().uuidString).jsonl") defer { try? FileManager.default.removeItem(at: url) } @@ -1275,23 +1354,45 @@ final class NativeAgentRuntimeTests: XCTestCase { ) ) + actor Capture { + var activities: [AgentToolActivity] = [] + func append(_ progress: StudyAgentProgress) { + if case let .toolActivity(activity) = progress { activities.append(activity) } + } + } + let capture = Capture() let result = try await NativeAgentLoop().run( request: testRequest(), ledger: ledger, registry: registry, adapter: ToolRecoveryMockLLMAdapter(toolChunks: [ + .textDelta(index: 2, text: "先说明"), + .webSearchSource(url: "https://example.com/a"), + .webSearchSource(url: "https://example.com/b"), + .serverToolActivity(.init(id: "search2", name: "$web_search", state: .running)), + .textDelta(index: 2, text: "再说明"), + .serverToolActivity(.init(id: "search2", name: "$web_search", state: .completed)), .toolCallDelta(index: 0, id: "bad", name: "test_tool", argumentsDelta: "{\"value\":"), .toolCallDelta(index: 1, id: "good", name: "test_tool", argumentsDelta: "{}"), ], expectedToolResults: 2), model: "mock", hostToolHandler: nil, systemPrompt: "test", - progress: nil + progress: { await capture.append($0) } ) + let activities = await capture.activities + XCTAssertEqual(activities.map(\.textOffset), [3, 3, 3, 6, 6, 6, 6, 6]) + XCTAssertEqual(activities[2].merging(activities[3]).textOffset, 3) + XCTAssertEqual(activities[1].sourceURLs, ["https://example.com/a", "https://example.com/b"]) + XCTAssertEqual(activities.map(\.id), ["1:server:sources", "1:server:sources", "1:server:search2", "1:server:search2", "1:bad", "1:bad", "1:good", "1:good"]) + XCTAssertEqual(activities.map(\.state), [.completed, .completed, .running, .completed, .running, .failed, .running, .completed]) + var message = AgentMessage(role: .assistant, text: result.text, source: nil) + message.toolActivities = activities.filter { $0.state != .running } + XCTAssertEqual(try JSONDecoder().decode(AgentMessage.self, from: JSONEncoder().encode(message)), message) let events = await ledger.allEvents() let toolResults = events.filter { $0.type == .toolResult } - XCTAssertEqual(result.text, "完成") + XCTAssertEqual(result.text, "先说明再说明完成") XCTAssertEqual(events.filter { $0.type == .toolCall }.map(\.toolCallID), ["bad", "good"]) XCTAssertEqual(toolResults.map(\.toolCallID), ["bad", "good"]) XCTAssertEqual(toolResults.map(\.isError), [true, false]) diff --git a/Tests/WeiBeiSafetyTests/NativeChatMarkdownTests.swift b/Tests/WeiBeiSafetyTests/NativeChatMarkdownTests.swift index 9c689bdde..6881546ab 100644 --- a/Tests/WeiBeiSafetyTests/NativeChatMarkdownTests.swift +++ b/Tests/WeiBeiSafetyTests/NativeChatMarkdownTests.swift @@ -5,6 +5,45 @@ import XCTest @testable import WeiBei final class NativeChatMarkdownTests: XCTestCase { + func testStreamingMarkdownStylesOnlyTheUnfinishedTail() { + let cases: [(String, String)] = [ + ("官方确认其**", "官方确认其"), ("**粗体 *", "**粗体** "), + ("**重点", "**重点**"), ("**重点*", "**重点**"), ("*强调", "*强调*"), + ("~~删除", "~~删除~~"), ("`print(1)", "`print(1)`"), + ("**粗体 *嵌套", "**粗体 *嵌套***"), + ("[来源](https://example.", "[来源](weibei-pending-link:)"), + ("[来源", "[来源](weibei-pending-link:)"), + ("**重点 ", "**重点** "), ("2*3 和 foo_bar", "2*3 和 foo_bar"), + (#"\*字面"#, #"\*字面"#), ("`**字面", "`**字面`"), + ("完成 **未闭合\n\n新的段落", "完成 **未闭合\n\n新的段落"), + ("```swift\nlet a = **value", "```swift\nlet a = **value"), + (" **代码", " **代码"), ("正文\n-", "正文\n-\u{200B}") + ] + for (source, expected) in cases { + XCTAssertEqual(MarkdownStreamingDisplay.source(source), expected, source) + XCTAssertEqual(MarkdownEmphasisNormalizer.prepare(source).text, source, "Completed text must not receive display-only closers") + } + let original = "**重点" + let display = MarkdownStreamingDisplay.source(original) + XCTAssertTrue(NativeChatMarkdownParser.parse(display).runs.contains { $0.style.bold && $0.text == "重点" }) + XCTAssertEqual(original, "**重点") + } + + func testChineseEmphasisIsSharedWithoutChangingCode() { + let source = "**举办国家:**美国,**球场(纽约)**举办。\n\n`**举办国家:**美国`\n\n```text\n**球场(纽约)**举办\n```" + let prepared = MarkdownEmphasisNormalizer.prepare(source) + XCTAssertTrue(prepared.text.contains("**举办国家:** 美国")) + XCTAssertTrue(prepared.text.contains("**球场(纽约)** 举办")) + let code = prepared.codeRanges.map { (prepared.text as NSString).substring(with: $0) } + XCTAssertTrue(code.contains { $0.contains("**举办国家:**美国") }) + XCTAssertTrue(code.contains { $0.contains("**球场(纽约)**举办") }) + let adjacent = NativeChatMarkdownParser.parse("如果你想问**梅西和C罗能否参加2026世界杯**,需要核实。") + XCTAssertTrue(adjacent.runs.contains { $0.style.bold && $0.text == "梅西和C罗能否参加2026世界杯" }) + let document = NativeChatMarkdownParser.parse(source) + XCTAssertTrue(document.runs.contains { $0.style.bold && $0.text == "举办国家:" }) + XCTAssertTrue(document.runs.contains { $0.style.bold && $0.text == "球场(纽约)" }) + } + // Continuous input must publish the already completed answer, then the latest snapshot. @MainActor func testPendingInputDoesNotStarveDisplay() async { let pipeline = NativeChatMarkdownPipeline()