Repository navigation
fix(macos): 修复长提示词导致的设置窗口卡顿 #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xionghaizhi
wants to merge
1
commit into
freestylefly:main
Choose a base branch
from
xionghaizhi:fix/macos-long-prompt-stutter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
49 changes: 49 additions & 0 deletions
49
macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptText.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import AppKit | ||
| import SwiftUI | ||
|
|
||
| /// 只读提示词保留完整文本与选择复制;视口尺寸不依赖全文排版结果。 | ||
| struct ScenePromptText: NSViewRepresentable { | ||
| let text: String | ||
| let height: CGFloat | ||
| var fontSize: CGFloat = 12 | ||
| let label: String | ||
|
|
||
| func makeNSView(context: Context) -> NSScrollView { | ||
| let scroll = NSScrollView() | ||
| scroll.drawsBackground = false | ||
| scroll.hasVerticalScroller = true | ||
| scroll.autohidesScrollers = true | ||
| let textView = NSTextView(usingTextLayoutManager: true) | ||
| textView.isEditable = false | ||
| textView.isSelectable = true | ||
| textView.isRichText = false | ||
| textView.drawsBackground = false | ||
| textView.isVerticallyResizable = true | ||
| textView.isHorizontallyResizable = false | ||
| textView.autoresizingMask = [.width] | ||
| textView.minSize = NSSize(width: 0, height: height) | ||
| textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) | ||
| textView.textContainer?.size = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) | ||
| textView.textContainer?.widthTracksTextView = true | ||
| textView.textContainer?.lineFragmentPadding = 0 | ||
| textView.textContainerInset = NSSize(width: 10, height: 8) | ||
| scroll.documentView = textView | ||
| return scroll | ||
| } | ||
|
|
||
| func updateNSView(_ scroll: NSScrollView, context: Context) { | ||
| guard let textView = scroll.documentView as? NSTextView else { return } | ||
| let font = NSFont.systemFont(ofSize: fontSize) | ||
| let color = NSColor(Theme.inkSecondary) | ||
| if textView.font != font { textView.font = font } | ||
| if textView.textColor != color { textView.textColor = color } | ||
| textView.setAccessibilityLabel(label) | ||
| // 焦点或悬停刷新不应重置选区,也不应重新设置整段长文本。 | ||
| if textView.string != text { textView.string = text } | ||
| } | ||
|
|
||
| func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSScrollView, context: Context) -> CGSize? { | ||
| let width = proposal.width ?? 0 | ||
| return CGSize(width: width.isFinite ? width : 0, height: height) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import AppKit | ||
| import SwiftUI | ||
| import WeChatBridgeCore | ||
| import XCTest | ||
| @testable import WeChatBridgeApp | ||
|
|
||
| final class SceneEditorTests: XCTestCase { | ||
| @MainActor | ||
| func testPromptEditPublishesAndPersistsOneCompleteScene() throws { | ||
| let domain = "scene-save-tests-" + UUID().uuidString | ||
| let defaults = try XCTUnwrap(UserDefaults(suiteName: domain)) | ||
| defer { defaults.removePersistentDomain(forName: domain) } | ||
| let preferences = Preferences(defaults: defaults) | ||
| let original = WeChatScene(id: "edited", name: "名称", instruction: "旧提示词", outputSpec: "旧规范", requiredSkillIDs: ["old-skill"]) | ||
| let untouched = WeChatScene(id: "untouched", name: "另一个场景", instruction: "保留内容", outputSpec: "保留规范") | ||
| preferences.scenes = SceneSettings(scenes: [original, untouched]) | ||
| var published: [WeChatScene] = [] | ||
| let scene = Binding(get: { preferences.scenes.scenes[0] }, set: { | ||
| published.append($0) | ||
| preferences.scenes.scenes[0] = $0 | ||
| }) | ||
| let root = FileManager.default.temporaryDirectory.appendingPathComponent(domain) | ||
| let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) | ||
| let editor = SceneEditor(scene: scene, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, | ||
| duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) | ||
| let text = "新提示词 {{skill:new-skill}} {{skill:new-skill}}" | ||
| editor.promptBinding.wrappedValue = text | ||
| XCTAssertEqual(published.count, 1) | ||
| XCTAssertEqual(published.first?.instruction, text) | ||
| XCTAssertEqual(published.first?.outputSpec, "") | ||
| XCTAssertEqual(published.first?.requiredSkillIDs, ["new-skill"]) | ||
| XCTAssertEqual(preferences.scenes.scenes[1], untouched) | ||
| // 重载会补齐官方模板,只比较必须原样保留的用户场景。 | ||
| XCTAssertEqual(Preferences(defaults: defaults).scenes.scenes.filter { !$0.isOfficial }, preferences.scenes.scenes) | ||
| } | ||
|
|
||
| @MainActor | ||
| func testPromptBindingPreservesWhitespaceAndExistingOutputSpec() { | ||
| var scene = WeChatScene(name: "名称", instruction: "原提示词", outputSpec: "原规范") | ||
| let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) | ||
| let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) | ||
| let binding = Binding(get: { scene }, set: { scene = $0 }) | ||
| let editor = SceneEditor(scene: binding, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, | ||
| duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) | ||
| XCTAssertTrue(editor.promptBinding.wrappedValue.contains("原提示词")) | ||
| XCTAssertTrue(editor.promptBinding.wrappedValue.contains("原规范")) | ||
| XCTAssertEqual(scene.outputSpec, "原规范") | ||
| for text in ["\n", " \n\n", "", "新内容\n\n"] { | ||
| editor.promptBinding.wrappedValue = text | ||
| XCTAssertEqual(editor.promptBinding.wrappedValue, text) | ||
| XCTAssertEqual(scene.instruction, text) | ||
| XCTAssertEqual(scene.outputSpec, "") | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| func testInsertingSkillDoesNotModifyAnotherTextResponder() { | ||
| _ = NSApplication.shared | ||
| var scene = WeChatScene(name: "名称", instruction: "提示词", outputSpec: "") | ||
| let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) | ||
| let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) | ||
| let binding = Binding(get: { scene }, set: { scene = $0 }) | ||
| let editor = SceneEditor(scene: binding, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, | ||
| duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) | ||
| let otherText = NSTextView() | ||
| otherText.string = "场景名称或预览" | ||
| otherText.setSelectedRange(NSRange(location: 2, length: 0)) | ||
| // CI 不保证桌面激活,直接传入菜单读取的响应者,验证它不会被误写。 | ||
| editor.insertSkillToken("new-skill", firstResponder: otherText) | ||
| XCTAssertEqual(otherText.string, "场景名称或预览") | ||
| XCTAssertEqual(scene.instruction, "提示词 {{skill:new-skill}}") | ||
| XCTAssertEqual(scene.name, "名称") | ||
| XCTAssertEqual(scene.requiredSkillIDs, ["new-skill"]) | ||
| } | ||
| } |
75 changes: 75 additions & 0 deletions
75
macos/Tests/WeChatBridgeAppTests/ScenePromptTextTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import AppKit | ||
| import SwiftUI | ||
| import XCTest | ||
| @testable import WeChatBridgeApp | ||
|
|
||
| final class ScenePromptTextTests: XCTestCase { | ||
| @MainActor | ||
| func testLongChinesePreviewIsBoundedReadOnlyAndSelectable() async throws { | ||
| let text = String(repeating: "只保留已确认的事实、决定与待办。\n", count: 800) | ||
| let (_, textView) = try await showPreview(text) | ||
| let scroll = try XCTUnwrap(textView.enclosingScrollView) | ||
| XCTAssertEqual(textView.string, text) | ||
| XCTAssertFalse(textView.isEditable) | ||
| XCTAssertTrue(textView.isSelectable) | ||
| XCTAssertNotNil(textView.textLayoutManager) | ||
| XCTAssertEqual(scroll.frame.height, 200, accuracy: 1) | ||
| XCTAssertGreaterThan(textView.frame.width, 0) | ||
| XCTAssertTrue(textView.textContainer?.widthTracksTextView == true) | ||
| } | ||
|
|
||
| @MainActor | ||
| func testResizingKeepsTheViewportBoundedAndTheFullText() async throws { | ||
| let text = String(repeating: "中文与 emoji 🧑🏽💻,保留末尾要求。\n", count: 800) + "这是最后一行。" | ||
| let (host, textView) = try await showPreview(text) | ||
| let scroll = try XCTUnwrap(textView.enclosingScrollView) | ||
| for width in [CGFloat(380), CGFloat(900)] { | ||
| host.setFrameSize(NSSize(width: width, height: 200)) | ||
| host.layoutSubtreeIfNeeded() | ||
| XCTAssertEqual(scroll.frame.height, 200, accuracy: 1) | ||
| XCTAssertEqual(textView.frame.width, scroll.contentSize.width, accuracy: 1) | ||
| XCTAssertEqual(textView.string, text) | ||
| XCTAssertFalse(scroll.hasHorizontalScroller) | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| func testUnchangedRefreshPreservesSelectionAndNewTextReplacesPreview() async throws { | ||
| let text = String(repeating: "保留选区与完整预览。\n", count: 80) | ||
| let (host, textView) = try await showPreview(text) | ||
| let selection = NSRange(location: 1, length: 6) | ||
| textView.setSelectedRange(selection) | ||
| host.rootView = ScenePromptText(text: text, height: 200, label: "转发提示词预览") | ||
| try await Task.sleep(nanoseconds: 100_000_000) | ||
| host.layoutSubtreeIfNeeded() | ||
| XCTAssertEqual(textView.selectedRange(), selection) | ||
| host.rootView = ScenePromptText(text: "新场景的完整提示词", height: 200, label: "转发提示词预览") | ||
| try await Task.sleep(nanoseconds: 100_000_000) | ||
| host.layoutSubtreeIfNeeded() | ||
| XCTAssertEqual(textView.string, "新场景的完整提示词") | ||
| XCTAssertEqual(textView.enclosingScrollView?.frame.height, 200) | ||
| } | ||
|
|
||
| @MainActor | ||
| private func showPreview(_ text: String) async throws -> (NSHostingView<ScenePromptText>, NSTextView) { | ||
| _ = NSApplication.shared | ||
| let host = NSHostingView(rootView: ScenePromptText(text: text, height: 200, label: "转发提示词预览")) | ||
| // 与设置窗口一致,由外层窗口给定尺寸,而不是用内容的理想尺寸收窄窗口。 | ||
| host.sizingOptions = [] | ||
| host.setFrameSize(NSSize(width: 600, height: 200)) | ||
| let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 200), styleMask: [.titled], backing: .buffered, defer: false) | ||
| window.isReleasedWhenClosed = false | ||
| window.contentView = host | ||
| addTeardownBlock { await MainActor.run { window.close() } } | ||
| window.orderFront(nil) | ||
| try await Task.sleep(nanoseconds: 100_000_000) | ||
| host.layoutSubtreeIfNeeded() | ||
| var pending = [host as NSView] | ||
| var textView: NSTextView? | ||
| while let view = pending.popLast() { | ||
| pending.append(contentsOf: view.subviews) | ||
| if let preview = view as? NSTextView { textView = preview } | ||
| } | ||
| return (host, try XCTUnwrap(textView)) | ||
| } | ||
| } |
39 changes: 39 additions & 0 deletions
39
macos/Tests/WeChatBridgeAppTests/SceneSettingsViewTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import AppKit | ||
| import SwiftUI | ||
| import WeChatBridgeCore | ||
| import XCTest | ||
| @testable import WeChatBridgeApp | ||
|
|
||
| final class SceneSettingsViewTests: XCTestCase { | ||
| @MainActor | ||
| func testLongChinesePromptUsesABoundedScrollableEditor() async throws { | ||
| _ = NSApplication.shared | ||
| let domain = "scene-editor-tests-" + UUID().uuidString | ||
| let defaults = try XCTUnwrap(UserDefaults(suiteName: domain)) | ||
| defer { defaults.removePersistentDomain(forName: domain) } | ||
| let preferences = Preferences(defaults: defaults) | ||
| let prompt = String(repeating: "只整理已确认的事实、决定和待办;保留负责人及截止时间,未明确的信息标为待确认。\n", count: 80) | ||
| let root = FileManager.default.temporaryDirectory.appendingPathComponent(domain) | ||
| let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) | ||
| preferences.scenes = SceneSettings(scenes: [WeChatScene(id: "long-prompt", name: "长提示词", instruction: prompt, outputSpec: "", enabled: true)]) | ||
| let host = NSHostingView(rootView: ScrollView { SceneSettingsView(preferences: preferences, skills: skills, router: SettingsRouter()) }.frame(width: 1100, height: 700)) | ||
| let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 700), styleMask: [.titled], backing: .buffered, defer: false) | ||
| window.isReleasedWhenClosed = false | ||
| window.contentView = host | ||
| defer { window.close() } | ||
| window.orderFront(nil) | ||
| try await Task.sleep(nanoseconds: 100_000_000) | ||
| host.layoutSubtreeIfNeeded() | ||
| var pending = [host as NSView] | ||
| var textViews: [NSTextView] = [] | ||
| while let view = pending.popLast() { | ||
| pending.append(contentsOf: view.subviews) | ||
| if let textView = view as? NSTextView { textViews.append(textView) } | ||
| } | ||
| let editor = try XCTUnwrap(textViews.first { $0.isEditable && $0.string == prompt }) | ||
| let scroll = try XCTUnwrap(editor.enclosingScrollView) | ||
| XCTAssertGreaterThan(scroll.frame.height, 0) | ||
| XCTAssertLessThanOrEqual(scroll.frame.height, 160) | ||
| XCTAssertGreaterThan(editor.bounds.height, scroll.contentSize.height) | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
当前
main的最低支持版本是 macOS 13,.focusEffectDisabled()要求 macOS 14,合并后会导致编译失败。请改用main中已有的.compatFocusEffectDisabled()。