From f8e740d7ea2d09ba9663ca6c967e850118a94a17 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:13:50 +0800 Subject: [PATCH 01/50] =?UTF-8?q?feat:=20=E7=BB=9F=E4=B8=80=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=AF=BC=E5=85=A5=E7=A1=AE=E8=AE=A4=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/AppDelegate.swift | 2 +- ...74\345\205\245\345\256\232\346\241\210.md" | 41 + Sources/WeiBei/Stores/WorkspaceStore.swift | 70 +- .../Views/ConfirmedFileImportView.swift | 765 ++++++++++++++++++ Sources/WeiBei/Views/ContentView.swift | 34 +- .../Views/ContextualContentPicker.swift | 67 +- .../Views/CourseDocNoteWorkspaceView.swift | 5 + Sources/WeiBei/Views/CourseHubView.swift | 80 +- .../Views/CourseWorkspaceComponents.swift | 7 +- .../Views/EmptyWorkspaceLauncherView.swift | 20 +- Sources/WeiBei/Views/SidebarView.swift | 6 +- Sources/WeiBeiCore/ImportFileCopy.swift | 67 +- .../ConfirmedFileImportTests.swift | 213 +++++ 13 files changed, 1194 insertions(+), 183 deletions(-) create mode 100644 "Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" create mode 100644 Sources/WeiBei/Views/ConfirmedFileImportView.swift create mode 100644 Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift diff --git a/App/Sources/AppDelegate.swift b/App/Sources/AppDelegate.swift index 551ff1e1c..438b06075 100644 --- a/App/Sources/AppDelegate.swift +++ b/App/Sources/AppDelegate.swift @@ -394,7 +394,7 @@ struct CatalystWeiBeiApp: App { private var workspaceContent: some View { // Native size restrictions own the minimum; scrolling panes extend under the toolbar. CatalystWorkspaceRoot(store: AppDelegate.workspace, appDelegate: appDelegate) - .onOpenURL { AppDelegate.workspace.importFiles([$0]) } + .onOpenURL { AppDelegate.workspace.receiveExternalFileForConfirmedImport($0) } #if WEIBEI_ACCEPTANCE_CHECKS .task { if CommandLine.arguments.contains("--drag-profile"), diff --git "a/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" new file mode 100644 index 000000000..db9a080a8 --- /dev/null +++ "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" @@ -0,0 +1,41 @@ +# 统一拖放导入定案 + +日期:2026-09-29。状态:已按用户确认方案实施,等待组合构建与真实拖放验收。 + +## 用户流程 + +首页、普通工作台、课程内和从 Dock 打开文件都进入同一确认面板。文件选择器入口也复用该面板。普通入口默认“通用资料”,课程入口默认当前课程;明确的笔记入口只接受 Markdown,并默认导入为笔记。 + +面板先列出实际可导入文件、不支持项、重复项和同名冲突,再选择归属。通用资料始终在首项,课程支持搜索和新建。新建课程沿用原有资料库目录与权限流程;取消新建只关闭新建面板,原批次和当前选择保留。 + +确认文案直接写目标,例如“加入《投资学》”。确认前只读取文件信息和比对内容,不创建目录、不复制文件。确认后仍在同一面板显示当前文件和进度,可停止剩余文件;已经完成的文件保留。 + +## 数据处理 + +| 情况 | 处理 | +| --- | --- | +| 支持的普通文件 | 调用现有通用资料复制或课程文件事务 | +| 内容完全相同且同名 | 标为“重复,跳过”,不再次复制 | +| 同名但内容不同 | 确认前显示新名称,确认后保留两份,不覆盖 | +| 不支持的文件 | 确认前列出并跳过;全部不支持时禁用确认 | +| 单个文件失败 | 保留本批已成功结果,显示失败原因 | +| 重试 | 只重新核对和导入失败文件 | +| 停止 | 当前正在处理的文件结束后停止剩余文件 | + +重复与冲突判断直接复用底层复制能力的同一份逐字节比较和命名规则,没有增加“内容去重”声明或另一套摘要数据库。课程写入继续使用现有可恢复事务;通用资料继续写入现有资料库目录。原文件始终保留。 + +## 完成后的去向 + +单个成功文件可直接打开。多个成功文件可进入对应的通用资料列表或课程文稿/笔记页,本批文件以朱砂浅底短暂突出三秒。结果面板分别显示成功、跳过和失败数量;停止状态另行说明未继续处理剩余文件。 + +## 验收边界 + +自动行为检查覆盖:确认前取消零写入、停止剩余任务、部分失败保留成功、只重试失败项、碰撞预检与真实复制使用同一规则。组合构建与测试由主任务统一执行,建议过滤器: + +```sh +swift test --filter ConfirmedFileImportTests +swift test --filter HTMLResourceImportTests +swift test --filter LibraryRelativeOnlyTests +``` + +真实 App 仍需在最终候选包验证:首页、工作台、课程文稿、课程笔记及 Dock 五个入口;Finder 多文件与文件夹拖入;新建课程取消/成功;停止按钮;部分失败重试;单个打开与批量定位高亮。静态代码和自动检查不能替代这些拖放体验证据。 diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 925bb2d4c..a4bc1803b 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -698,6 +698,12 @@ final class WorkspaceStore: ObservableObject { /// 展示兼容:界面与对话框仍按字符串消费保存失败文案。 var workspaceSaveError: String? { workspaceSaveFailure?.message } @Published private(set) var courseFileOperationProgress: CourseFileOperationProgress? + @Published var confirmedFileImport: ConfirmedFileImportBatch? + @Published var recentlyImportedItemIDs: Set = [] + var confirmedFileImportTask: Task? + var confirmedFileImportStopRequested = false + var confirmedFileImportSecurityScopes: [URL] = [] + var recentlyImportedClearTask: Task? @Published var notebookCreationDraft: NotebookCreationDraft? @Published var notebookRenameDraft: NotebookRenameDraft? var notebookRenameInFlight = false @@ -5891,7 +5897,7 @@ final class WorkspaceStore: ObservableObject { } func importFilesFromPanel() { - presentImportPanel(linkToActiveNote: false) + presentImportPanel() } @discardableResult @@ -5916,9 +5922,6 @@ final class WorkspaceStore: ObservableObject { func importCourseMaterialsFromPanel(courseID: UUID?) { presentImportPanel( - linkToActiveNote: false, - selectsFirstImportedItem: false, - reclassifiesExistingMarkdown: true, assigningToCourseID: courseID, panelTitle: ui("选择课程资料或文件夹", "Choose course materials or a folder") ) @@ -5930,28 +5933,20 @@ final class WorkspaceStore: ObservableObject { func importCourseNotesFromPanel(courseID: UUID?) { presentImportPanel( - linkToActiveNote: false, - selectsFirstImportedItem: false, markdownAsNotes: true, - markdownOnly: true, - reclassifiesExistingMarkdown: true, assigningToCourseID: courseID, panelTitle: ui("选择 Markdown 笔记或文件夹", "Choose Markdown notes or a folder") ) } private func presentImportPanel( - linkToActiveNote: Bool, - selectsFirstImportedItem: Bool = true, markdownAsNotes: Bool = false, - markdownOnly: Bool = false, - reclassifiesExistingMarkdown: Bool = false, assigningToCourseID: UUID? = nil, panelTitle: String? = nil ) { #if targetEnvironment(macCatalyst) Task { @MainActor in - let types: [UTType] = markdownOnly + let types: [UTType] = markdownAsNotes ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] let urls = await WorkspaceFileDialog.pick( @@ -5960,22 +5955,12 @@ final class WorkspaceStore: ObservableObject { ) guard !urls.isEmpty else { return } let scoped = urls.filter { $0.startAccessingSecurityScopedResource() } - let releaseScopes = { scoped.forEach { $0.stopAccessingSecurityScopedResource() } } - if let assigningToCourseID { - importCourseFilesFromURLs(urls, asNotes: markdownAsNotes, courseID: assigningToCourseID) { _ in releaseScopes() } - return - } - let targetNoteID = linkToActiveNote ? activeNotebookItemID : nil - importFiles(urls, selectsFirstImportedItem: selectsFirstImportedItem, - markdownAsNotes: markdownAsNotes, markdownOnly: markdownOnly, - reclassifiesExistingMarkdown: reclassifiesExistingMarkdown) { selectedItems in - defer { releaseScopes() } - if let targetNoteID, self.activeNotebookItemID == targetNoteID { - self.setLinkedSourceIDsForActiveNote( - Set(self.linkedSourceIDsForActiveNote).union(selectedItems.map(\.id)) - ) - } - } + prepareConfirmedFileImport( + urls, + courseID: assigningToCourseID, + asNotes: markdownAsNotes, + securityScopedURLs: scoped + ) } #else let panel = NSOpenPanel() @@ -5983,33 +5968,16 @@ final class WorkspaceStore: ObservableObject { panel.allowsMultipleSelection = true panel.canChooseDirectories = true panel.canChooseFiles = true - panel.allowedContentTypes = markdownOnly + panel.allowedContentTypes = markdownAsNotes ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] guard panel.runModal() == .OK else { return } - if let assigningToCourseID { - importCourseFilesFromURLs( - panel.urls, - asNotes: markdownAsNotes, - courseID: assigningToCourseID - ) - return - } - let targetNoteID = linkToActiveNote ? activeNotebookItemID : nil - importFiles( + prepareConfirmedFileImport( panel.urls, - selectsFirstImportedItem: selectsFirstImportedItem, - markdownAsNotes: markdownAsNotes, - markdownOnly: markdownOnly, - reclassifiesExistingMarkdown: reclassifiesExistingMarkdown - ) { selectedItems in - if let targetNoteID, self.activeNotebookItemID == targetNoteID { - self.setLinkedSourceIDsForActiveNote( - Set(self.linkedSourceIDsForActiveNote).union(selectedItems.map(\.id)) - ) - } - } + courseID: assigningToCourseID, + asNotes: markdownAsNotes + ) #endif } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift new file mode 100644 index 000000000..1ca93810d --- /dev/null +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -0,0 +1,765 @@ +import Foundation +import SwiftUI +import WeiBeiCore + +enum ConfirmedFileImportStage: Equatable, Sendable { + case preparing + case reviewing + case importing + case finished +} + +enum ConfirmedFileImportDisposition: Equatable, Sendable { + case ready + case duplicate + case conflict(suggestedFileName: String) +} + +struct ConfirmedFileImportCandidate: Identifiable, Equatable, Sendable { + let sourceURL: URL + var disposition: ConfirmedFileImportDisposition + var id: String { sourceURL.path } +} + +struct ConfirmedFileImportFailure: Identifiable, Equatable, Sendable { + let sourceURL: URL + let message: String + var id: String { sourceURL.path } +} + +struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { + let id: UUID + var sourceURLs: [URL] + var sourceFolderNames: [String] + var courseID: UUID? + var importsMarkdownAsNotes: Bool + var stage: ConfirmedFileImportStage = .preparing + var candidates: [ConfirmedFileImportCandidate] = [] + var unsupportedNames: [String] = [] + var importedItems: [StudyItem] = [] + var failures: [ConfirmedFileImportFailure] = [] + var previousSkippedCount = 0 + var completed = 0 + var total = 0 + var currentFileName: String? + var stopped = false + var destinationError: String? + + var confirmableCount: Int { + candidates.count + } + + var skippedCount: Int { + previousSkippedCount + + unsupportedNames.count + + candidates.filter { $0.disposition == .duplicate }.count + } +} + +extension WorkspaceStore { + func prepareConfirmedFileImport( + _ urls: [URL], + courseID: UUID? = nil, + asNotes: Bool = false, + securityScopedURLs: [URL] = [] + ) { + guard !urls.isEmpty else { return } + guard confirmedFileImport?.stage != .importing else { return } + dismissConfirmedFileImport() + confirmedFileImportSecurityScopes = securityScopedURLs + let folders = urls.filter { + (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + }.map(\.lastPathComponent) + confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: urls, + sourceFolderNames: folders, + courseID: courseID, + importsMarkdownAsNotes: asNotes + ) + refreshConfirmedFileImportPlan() + } + + func receiveExternalFileForConfirmedImport(_ url: URL) { + if confirmedFileImport?.stage == .importing { return } + if var batch = confirmedFileImport, + batch.courseID == nil, + !batch.importsMarkdownAsNotes, + (batch.stage == .preparing || batch.stage == .reviewing) { + if !batch.sourceURLs.contains(where: { + $0.standardizedFileURL == url.standardizedFileURL + }) { + batch.sourceURLs.append(url) + confirmedFileImport = batch + refreshConfirmedFileImportPlan() + } + return + } + prepareConfirmedFileImport([url]) + } + + func setConfirmedFileImportDestination(courseID: UUID?) { + guard var batch = confirmedFileImport, + batch.stage == .reviewing || batch.stage == .preparing else { return } + batch.courseID = courseID + confirmedFileImport = batch + refreshConfirmedFileImportPlan() + } + + func selectNewCourseForConfirmedFileImport(_ courseID: UUID) { + setConfirmedFileImportDestination(courseID: courseID) + } + + func dismissConfirmedFileImport() { + confirmedFileImportTask?.cancel() + confirmedFileImportTask = nil + confirmedFileImportSecurityScopes.forEach { $0.stopAccessingSecurityScopedResource() } + confirmedFileImportSecurityScopes = [] + confirmedFileImportStopRequested = false + confirmedFileImport = nil + } + + func stopConfirmedFileImport() { + guard confirmedFileImport?.stage == .importing else { return } + confirmedFileImportStopRequested = true + } + + func retryFailedConfirmedFileImport() { + guard let batch = confirmedFileImport, + batch.stage == .finished, + !batch.failures.isEmpty else { return } + let failedURLs = batch.failures.map(\.sourceURL) + confirmedFileImport = ConfirmedFileImportBatch( + id: batch.id, + sourceURLs: failedURLs, + sourceFolderNames: batch.sourceFolderNames, + courseID: batch.courseID, + importsMarkdownAsNotes: batch.importsMarkdownAsNotes, + importedItems: batch.importedItems, + previousSkippedCount: batch.skippedCount + ) + refreshConfirmedFileImportPlan() + } + + func confirmFileImport() { + guard var batch = confirmedFileImport, + batch.stage == .reviewing, + batch.confirmableCount > 0, + batch.destinationError == nil else { return } + batch.stage = .importing + batch.failures = [] + batch.completed = 0 + batch.total = batch.candidates.count + batch.unsupportedNames.count + batch.currentFileName = nil + batch.stopped = false + confirmedFileImportStopRequested = false + confirmedFileImport = batch + + let initialBatch = batch + confirmedFileImportTask = Task { @MainActor [weak self] in + guard let self else { return } + var batch = initialBatch + var imported = batch.importedItems + var failures: [ConfirmedFileImportFailure] = [] + var completed = batch.unsupportedNames.count + for candidate in batch.candidates { + if confirmedFileImportStopRequested { + batch.stopped = true + break + } + batch.currentFileName = candidate.sourceURL.lastPathComponent + batch.completed = completed + confirmedFileImport = batch + defer { + completed += 1 + batch.completed = completed + confirmedFileImport = batch + } + if candidate.disposition == .duplicate { continue } + do { + let item = try await importConfirmedFile(candidate, batch: batch) + imported.append(item) + } catch { + if let recovered = await recoverConfirmedCourseImport( + candidate, + batch: batch + ) { + imported.append(recovered) + continue + } + WeiBeiLog.workspace.error( + "code=confirmed_import_failed underlying=\(WeiBeiLog.code(error), privacy: .public) path=\(candidate.sourceURL.path, privacy: .private) detail=\(WeiBeiLog.truncated(error.localizedDescription), privacy: .private)" + ) + failures.append(ConfirmedFileImportFailure( + sourceURL: candidate.sourceURL, + message: confirmedImportFailureMessage(error) + )) + } + } + batch.stage = .finished + batch.currentFileName = nil + batch.importedItems = imported + batch.failures = failures + batch.completed = completed + batch.stopped = batch.stopped || confirmedFileImportStopRequested + confirmedFileImportStopRequested = false + confirmedFileImportTask = nil + confirmedFileImport = batch + } + } + + func openSingleConfirmedImport() { + guard let batch = confirmedFileImport, batch.importedItems.count == 1, + let item = batch.importedItems.first else { return } + if let courseID = batch.courseID { + if batch.importsMarkdownAsNotes { + _ = openCourseNote(item.id, in: courseID) + } else { + _ = openCourseMaterial(item.id, in: courseID) + } + } else { + if courseWorkspacePresented { dismissCourseWorkspace() } + selectMeasured(itemID: item.id, opensNotebook: batch.importsMarkdownAsNotes) + } + dismissConfirmedFileImport() + } + + func showConfirmedImportBatch() { + guard let batch = confirmedFileImport, !batch.importedItems.isEmpty else { return } + recentlyImportedItemIDs = Set(batch.importedItems.map(\.id)) + recentlyImportedClearTask?.cancel() + recentlyImportedClearTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(3)) + guard !Task.isCancelled else { return } + self?.recentlyImportedItemIDs = [] + } + if let courseID = batch.courseID { + presentCourseWorkspace(batch.importsMarkdownAsNotes ? .notes : .materials, courseID: courseID) + } else { + if courseWorkspacePresented { dismissCourseWorkspace() } + showLibrary = true + } + dismissConfirmedFileImport() + } + + private func refreshConfirmedFileImportPlan() { + guard var batch = confirmedFileImport else { return } + confirmedFileImportTask?.cancel() + batch.stage = .preparing + batch.candidates = [] + batch.unsupportedNames = [] + batch.destinationError = nil + confirmedFileImport = batch + + let batchID = batch.id + let urls = batch.sourceURLs + let asNotes = batch.importsMarkdownAsNotes + let courseID = batch.courseID + let destination: URL? + if let courseID { + destination = courseRootURL(for: courseID)?.appendingPathComponent( + asNotes ? CourseOwnedFileRole.note.directoryName : CourseOwnedFileRole.material.directoryName, + isDirectory: true + ) + } else { + destination = courseLibraryRootURL?.appendingPathComponent( + asNotes ? CourseOwnedFileRole.note.commonDirectoryName : CourseOwnedFileRole.material.commonDirectoryName, + isDirectory: true + ) + } + guard let destination else { + batch.stage = .reviewing + batch.destinationError = ui( + "目标文件夹当前不可用,请先重新连接资料库或课程文件夹。", + "The destination folder is unavailable. Reconnect the library or course folder first." + ) + confirmedFileImport = batch + return + } + + confirmedFileImportTask = Task { @MainActor [weak self] in + let plan = await Task.detached(priority: .userInitiated) { + Self.makeConfirmedFileImportPlan( + urls: urls, + destination: destination, + markdownOnly: asNotes + ) + }.value + guard let self, !Task.isCancelled, + var current = confirmedFileImport, + current.id == batchID else { return } + current.stage = .reviewing + current.candidates = plan.candidates + current.unsupportedNames = plan.unsupportedNames + confirmedFileImportTask = nil + confirmedFileImport = current + } + } + + nonisolated static func makeConfirmedFileImportPlan( + urls: [URL], destination: URL, markdownOnly: Bool + ) -> (candidates: [ConfirmedFileImportCandidate], unsupportedNames: [String]) { + let expanded = CourseProjectFileWorker.expandedSupportedFiles( + from: urls, + markdownOnly: markdownOnly + ) + let expandedPaths = Set(expanded.map { $0.standardizedFileURL.path }) + var unsupported = urls.compactMap { url -> String? in + let values = try? url.resourceValues(forKeys: [.isDirectoryKey]) + if values?.isDirectory == true { + return CourseProjectFileWorker.expandedSupportedFiles( + from: [url], + markdownOnly: markdownOnly + ).isEmpty ? url.lastPathComponent : nil + } + return expandedPaths.contains(url.standardizedFileURL.path) ? nil : url.lastPathComponent + } + var candidates: [ConfirmedFileImportCandidate] = [] + var reservedTargetNames = Set() + for url in expanded { + var disposition: ConfirmedFileImportDisposition + do { + switch try ImportFileCopy.collision(from: url, into: destination) { + case .available: disposition = .ready + case .duplicate: disposition = .duplicate + case .conflict(let suggested): disposition = .conflict(suggestedFileName: suggested) + } + } catch { + disposition = .ready + } + if disposition != .duplicate { + let targetName = nextConfirmedImportTargetName( + for: url, + in: destination, + reserved: reservedTargetNames + ) + if targetName != url.lastPathComponent { + disposition = .conflict(suggestedFileName: targetName) + } + reservedTargetNames.insert(targetName) + } + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) + } + if markdownOnly { + unsupported = unsupported.map { "\($0)(仅支持 Markdown)" } + } + return (candidates, unsupported.sorted()) + } + + nonisolated private static func nextConfirmedImportTargetName( + for sourceURL: URL, + in directory: URL, + reserved: Set + ) -> String { + let preferred = sourceURL.lastPathComponent + if !reserved.contains(preferred), + !FileManager.default.fileExists(atPath: directory.appendingPathComponent(preferred).path) { + return preferred + } + let stem = sourceURL.deletingPathExtension().lastPathComponent + let pathExtension = sourceURL.pathExtension + for suffix in 2...9_999 { + let name = pathExtension.isEmpty + ? "\(stem) \(suffix)" + : "\(stem) \(suffix).\(pathExtension)" + if !reserved.contains(name), + !FileManager.default.fileExists(atPath: directory.appendingPathComponent(name).path) { + return name + } + } + return pathExtension.isEmpty + ? "\(stem) \(UUID().uuidString.lowercased())" + : "\(stem) \(UUID().uuidString.lowercased()).\(pathExtension)" + } + + private func importConfirmedFile( + _ candidate: ConfirmedFileImportCandidate, + batch: ConfirmedFileImportBatch + ) async throws -> StudyItem { + if let courseID = batch.courseID { + let resolution: CourseFileConflictResolution + switch candidate.disposition { + case .conflict(let suggested): + resolution = .keepBoth(preferredFileName: suggested) + case .ready, .duplicate: + resolution = .cancel + } + return try await importFileIntoCourse( + candidate.sourceURL, + courseID: courseID, + role: batch.importsMarkdownAsNotes ? .note : .material, + conflictResolution: resolution + ).item + } + + guard let root = courseLibraryRootURL else { + throw CocoaError(.fileNoSuchFile) + } + let copiedURL = try await Task.detached(priority: .userInitiated) { + try Self.copyExternalFileIntoLibrary( + root: root, + sourceURL: candidate.sourceURL, + isNote: batch.importsMarkdownAsNotes + ) + }.value + guard let item = applyImportedCommonFiles( + [(copiedURL, batch.importsMarkdownAsNotes)], + selectsFirstImportedItem: false, + reclassifiesExistingMarkdown: false + ).first else { + throw CocoaError(.fileWriteUnknown) + } + return item + } + + private func confirmedImportFailureMessage(_ error: Error) -> String { + let cocoaCode = (error as? CocoaError)?.code + if cocoaCode == .fileNoSuchFile || cocoaCode == .fileReadNoSuchFile { + return ui( + "文件已移动、删除或暂时无法访问。请恢复文件后重试。", + "The file was moved, deleted, or is temporarily unavailable. Restore it, then retry." + ) + } + if cocoaCode == .fileReadNoPermission || cocoaCode == .fileWriteNoPermission { + return ui( + "没有读取来源或写入目标的权限。请重新选择可访问的文件夹后重试。", + "WeiBei cannot read the source or write to the destination. Re-select an accessible folder, then retry." + ) + } + return ui( + "复制或登记没有完成,原文件仍保留。请检查文件与目标文件夹后重试。", + "Copying or registration did not finish. The original is still kept. Check the file and destination, then retry." + ) + } + + private func recoverConfirmedCourseImport( + _ candidate: ConfirmedFileImportCandidate, + batch: ConfirmedFileImportBatch + ) async -> StudyItem? { + guard case .ready = candidate.disposition, + let courseID = batch.courseID, + let root = courseRootURL(for: courseID) else { return nil } + let role: CourseOwnedFileRole = batch.importsMarkdownAsNotes ? .note : .material + let directory = root.appendingPathComponent(role.directoryName, isDirectory: true) + guard (try? ImportFileCopy.collision( + from: candidate.sourceURL, + into: directory + )) == .duplicate else { return nil } + _ = await reconcileCourseFilesNow(courseID: courseID) + let expectedStorage = StudyItemStorage.courseOwned( + ownerCourseID: courseID, + relativePath: "\(role.directoryName)/\(candidate.sourceURL.lastPathComponent)" + ) + return importedItems.first { $0.storage == expectedStorage } + } +} + +struct ConfirmedFileImportView: View { + @EnvironmentObject private var store: WorkspaceStore + @State private var courseSearch = "" + @State private var creatingCourse = false + + private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } + private var matchingCourses: [Course] { + let query = courseSearch.trimmingCharacters(in: .whitespacesAndNewlines) + return query.isEmpty ? store.courses : store.courses.filter { + $0.title.localizedCaseInsensitiveContains(query) + } + } + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + if let batch { + heading(batch) + switch batch.stage { + case .preparing: + Text(store.ui("正在核对文件与目标…", "Checking files and destination…")) + .weiBeiText(13) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .frame(maxWidth: .infinity, minHeight: 220, alignment: .center) + case .reviewing: + review(batch) + case .importing: + progress(batch) + case .finished: + result(batch) + } + } + } + .padding(24) + .frame(width: 540, height: 600, alignment: .topLeading) +#if targetEnvironment(macCatalyst) + .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) +#endif + .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) + .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) + .foregroundStyle(WeiBeiTheme.ink) + .preferredColorScheme(store.appearanceMode.colorScheme) + .interactiveDismissDisabled(batch?.stage == .importing) + .sheet(isPresented: $creatingCourse) { + CourseProjectEntrySheet( + cancel: { creatingCourse = false }, + openCourse: { courseID in + creatingCourse = false + store.selectNewCourseForConfirmedFileImport(courseID) + }, + allowsInitialImport: false + ) + .environmentObject(store) + } + } + + private func heading(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 5) { + Text(store.ui("确认导入", "Confirm Import")) + .weiBeiBrandFont(language: store.interfaceLanguage, size: 22, weight: .semibold) + Text(store.ui( + "导入副本,原文件保留。确认前不会复制文件。", + "A copy will be imported and the original kept. Nothing is copied before confirmation." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + } + + private func review(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 14) { + fileSummary(batch) + destinationPicker(batch) + if let error = batch.destinationError { + Label(error, systemImage: "exclamationmark.triangle") + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.cinnabar) + } + Spacer(minLength: 0) + HStack { + Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiTextActionButtonStyle()) + .keyboardShortcut(.cancelAction) + Spacer() + Button(confirmTitle(batch)) { store.confirmFileImport() } + .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + .keyboardShortcut(.defaultAction) + .disabled(batch.confirmableCount == 0 || batch.destinationError != nil) + } + } + } + + private func fileSummary(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(store.ui( + "本批内容 · \(batch.candidates.count + batch.unsupportedNames.count) 个", + "This batch · \(batch.candidates.count + batch.unsupportedNames.count) items" + )) + .weiBeiText(12, weight: .semibold) + if !batch.sourceFolderNames.isEmpty { + Text(store.ui( + "来源文件夹:\(batch.sourceFolderNames.joined(separator: "、"))", + "Source folders: \(batch.sourceFolderNames.joined(separator: ", "))" + )) + .weiBeiText(10.5) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .lineLimit(2) + } + ScrollView { + VStack(alignment: .leading, spacing: 7) { + ForEach(batch.candidates) { candidate in + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: StudyItemKind.detect(from: candidate.sourceURL).systemImage) + .foregroundStyle(WeiBeiTheme.secondaryInk) + Text(candidate.sourceURL.lastPathComponent) + .weiBeiText(12) + .lineLimit(1) + Spacer(minLength: 8) + Text(StudyItemKind.detect(from: candidate.sourceURL).label(language: store.interfaceLanguage)) + .weiBeiText(10.5) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + Text(candidateLabel(candidate)) + .weiBeiText(10.5, weight: .medium) + .foregroundStyle(candidateColor(candidate)) + } + } + ForEach(batch.unsupportedNames, id: \.self) { name in + HStack(spacing: 8) { + Image(systemName: "nosign") + Text(name).lineLimit(1) + Spacer() + Text(store.ui("不支持", "Unsupported")) + } + .weiBeiText(11) + .foregroundStyle(WeiBeiTheme.cinnabar) + } + } + } + .frame(maxHeight: 150) + if !batch.sourceFolderNames.isEmpty { + Text(store.ui( + "文件夹内仅导入 PDF、Word、PPT、HTML、文本和 Markdown;隐藏文件与应用包会跳过。", + "Folders include PDF, Word, PPT, HTML, text, and Markdown only; hidden files and app bundles are skipped." + )) + .weiBeiText(10.5) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + } + } + .padding(12) + .weibeiEtchedBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.30), + stroke: WeiBeiTheme.hairline.opacity(0.28), + cornerRadius: 12 + ) + } + + private func destinationPicker(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(store.ui("归属", "Destination")) + .weiBeiText(12, weight: .semibold) + WeiBeiSearchField( + text: $courseSearch, + prompt: store.ui("搜索课程", "Search courses"), + isFocused: .constant(false), + fontSize: 12, + focusesOnAppear: false, + chromeHeight: 30 + ) + ScrollView { + VStack(alignment: .leading, spacing: 3) { + destinationButton( + title: batch.importsMarkdownAsNotes + ? store.ui("通用笔记", "Common Notes") + : store.ui("通用资料", "Common Materials"), + courseID: nil, + selected: batch.courseID == nil + ) + ForEach(matchingCourses) { course in + destinationButton( + title: course.title, + courseID: course.id, + selected: batch.courseID == course.id + ) + } + } + } + .frame(maxHeight: 120) + Button(store.ui("新建课程…", "Create Course…")) { creatingCourse = true } + .buttonStyle(WeiBeiTextActionButtonStyle()) + } + } + + private func destinationButton(title: String, courseID: UUID?, selected: Bool) -> some View { + Button { store.setConfirmedFileImportDestination(courseID: courseID) } label: { + HStack(spacing: 8) { + Image(systemName: courseID == nil ? "tray" : "folder") + Text(title).lineLimit(1) + Spacer() + if selected { Image(systemName: "checkmark") } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(WeiBeiTextActionButtonStyle(active: selected, fontSize: 12, height: 30)) + } + + private func progress(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 16) { + Text(destinationDescription(batch)) + .weiBeiText(13, weight: .semibold) + if let current = batch.currentFileName { + Text(current).weiBeiText(12).lineLimit(2) + } + ProgressView(value: Double(batch.completed), total: Double(max(1, batch.total))) + .tint(WeiBeiTheme.cinnabar) + Text("\(batch.completed) / \(batch.total)") + .weiBeiText(11, design: .monospaced) + .foregroundStyle(WeiBeiTheme.secondaryInk) + Spacer() + HStack { + Spacer() + Button(store.ui("停止剩余导入", "Stop Remaining")) { + store.stopConfirmedFileImport() + } + .buttonStyle(WeiBeiTextActionButtonStyle()) + } + } + } + + private func result(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 14) { + Text(store.ui( + "成功 \(batch.importedItems.count) 个 · 跳过 \(batch.skippedCount) 个 · 失败 \(batch.failures.count) 个", + "\(batch.importedItems.count) succeeded · \(batch.skippedCount) skipped · \(batch.failures.count) failed" + )) + .weiBeiText(15, weight: .semibold) + if batch.stopped { + Text(store.ui("已停止剩余任务;已完成的导入仍然保留。", "Remaining work stopped; completed imports were kept.")) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + if !batch.failures.isEmpty { + ScrollView { + VStack(alignment: .leading, spacing: 8) { + ForEach(batch.failures) { failure in + VStack(alignment: .leading, spacing: 3) { + Text(failure.sourceURL.lastPathComponent).weiBeiText(12, weight: .semibold) + Text(failure.message).weiBeiText(11).foregroundStyle(WeiBeiTheme.secondaryInk) + } + } + } + } + .frame(maxHeight: 220) + } + Spacer() + HStack(spacing: 8) { + if !batch.failures.isEmpty { + Button(store.ui("只重试失败项", "Retry Failed Only")) { + store.retryFailedConfirmedFileImport() + } + .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + } + Spacer() + if batch.importedItems.count == 1 { + Button(store.ui("打开文稿", "Open Document")) { + store.openSingleConfirmedImport() + } + .buttonStyle(WeiBeiTextActionButtonStyle()) + } else if batch.importedItems.count > 1 { + Button(store.ui("查看已导入资料", "View Imported Items")) { + store.showConfirmedImportBatch() + } + .buttonStyle(WeiBeiTextActionButtonStyle()) + } + Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiTextActionButtonStyle()) + .keyboardShortcut(.defaultAction) + } + } + } + + private func confirmTitle(_ batch: ConfirmedFileImportBatch) -> String { + if let courseID = batch.courseID, + let course = store.courses.first(where: { $0.id == courseID }) { + return store.ui("加入《\(course.title)》", "Add to \(course.title)") + } + return batch.importsMarkdownAsNotes + ? store.ui("加入通用笔记", "Add to Common Notes") + : store.ui("加入通用资料", "Add to Common Materials") + } + + private func destinationDescription(_ batch: ConfirmedFileImportBatch) -> String { + store.ui("正在\(confirmTitle(batch))", confirmTitle(batch)) + } + + private func candidateLabel(_ candidate: ConfirmedFileImportCandidate) -> String { + switch candidate.disposition { + case .ready: return store.ui("可导入", "Ready") + case .duplicate: return store.ui("重复,跳过", "Duplicate, skip") + case .conflict(let name): return store.ui("同名,另存为 \(name)", "Name conflict, save as \(name)") + } + } + + private func candidateColor(_ candidate: ConfirmedFileImportCandidate) -> Color { + switch candidate.disposition { + case .ready: WeiBeiTheme.secondaryInk + case .duplicate: WeiBeiTheme.tertiaryInk + case .conflict: WeiBeiTheme.cinnabar + } + } +} diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index 1e2cbaf07..37e3cf094 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -16,6 +16,7 @@ struct ContentView: View { @FocusState private var topSearchFocused: Bool @State private var floatingAgentExpanded = false @State private var windowIsFullScreen = false + @State private var isFileDropTargeted = false /// Size of the document area under the top bar. The float uses it for placement /// and must not measure that area with a GeometryReader laid over the reader. @State private var documentCanvas = CGSize.zero @@ -99,9 +100,14 @@ struct ContentView: View { } } } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + .onDrop(of: [.fileURL], isTargeted: $isFileDropTargeted) { providers in WeiBeiDroppedFileURLs.load(providers) { urls in - store.importFiles(urls) + store.prepareConfirmedFileImport(urls) + } + } + .overlay { + if isFileDropTargeted { + WeiBeiFileDropPrompt() } } .allowsHitTesting(!store.courseWorkspacePresented) @@ -175,6 +181,12 @@ struct ContentView: View { ExcerptBookView(courseID: store.excerptBookCourseID) .environmentObject(store) } + .sheet(isPresented: Binding( + get: { store.confirmedFileImport != nil }, + set: { if !$0 { store.dismissConfirmedFileImport() } } + )) { + ConfirmedFileImportView().environmentObject(store) + } .background(WindowFullScreenReader(isFullScreen: $windowIsFullScreen)) .background { // Focus / reader-search sync observes paneState so ContentView does not. @@ -201,6 +213,24 @@ struct ContentView: View { } } +private struct WeiBeiFileDropPrompt: View { + @EnvironmentObject private var store: WorkspaceStore + + var body: some View { + Label(store.ui("松开以导入资料", "Drop to import"), systemImage: "tray.and.arrow.down") + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) + } +} + #if !targetEnvironment(macCatalyst) private struct WindowFullScreenReader: NSViewRepresentable { @Binding var isFullScreen: Bool diff --git a/Sources/WeiBei/Views/ContextualContentPicker.swift b/Sources/WeiBei/Views/ContextualContentPicker.swift index ceb50eaf0..8e000c5d1 100644 --- a/Sources/WeiBei/Views/ContextualContentPicker.swift +++ b/Sources/WeiBei/Views/ContextualContentPicker.swift @@ -6,8 +6,6 @@ struct ContextualContentPicker: View { @Environment(\.weibeiReduceMotion) private var reduceMotion let kind: ContextualContentKind @State private var courseEntry: CourseProjectEntryPresentation? - @State private var choosingImportTarget = false - @State private var pendingImport: (() -> Void)? @State private var search = "" @State private var searchFocused = false @@ -83,38 +81,6 @@ struct ContextualContentPicker: View { openCourse: { _ in courseEntry = nil } ).environmentObject(store) } - .sheet(isPresented: $choosingImportTarget, onDismiss: { - let action = pendingImport - pendingImport = nil - action?() - }) { - VStack(alignment: .leading, spacing: 16) { - Text(store.ui("导入到哪里?", "Import into…")).weiBeiText(17, weight: .semibold) - ScrollView { - VStack(alignment: .leading, spacing: 4) { - importTargetButton(commonTitle, symbol: "tray", courseID: nil) - ForEach(store.courses) { course in - importTargetButton(course.title, symbol: "folder", courseID: course.id) - } - }.frame(maxWidth: .infinity, alignment: .leading) - }.frame(maxHeight: 300) - HStack { - Spacer() - Button(store.ui("取消", "Cancel")) { choosingImportTarget = false } - .buttonStyle(WeiBeiDialogButtonStyle()) - .keyboardShortcut(.cancelAction) - } - } - .padding(24) - .frame(minWidth: 320, idealWidth: 400, maxWidth: .infinity) -#if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) -#endif - .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) - .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) - .foregroundStyle(WeiBeiTheme.ink) - .preferredColorScheme(store.appearanceMode.colorScheme) - } .accessibilityIdentifier(kind == .note ? "contextual-note-picker" : "contextual-material-picker") } @@ -122,21 +88,6 @@ struct ContextualContentPicker: View { kind == .note ? store.ui("通用笔记", "Common Notes") : store.ui("通用资料", "Common Materials") } - private func importTargetButton(_ title: String, symbol: String, courseID: UUID?) -> some View { - Button { importFiles(into: courseID) } label: { - HStack(spacing: 10) { - Label(title, systemImage: symbol) - .lineLimit(2) - .multilineTextAlignment(.leading) - Spacer(minLength: 8) - Image(systemName: "chevron.right").weiBeiText(10) - } - .frame(maxWidth: .infinity, alignment: .leading) - } - .buttonStyle(WeiBeiTextActionButtonStyle(fontSize: 13, height: 36)) - .help(title) - } - private func courseBlock(_ group: Group) -> some View { VStack(alignment: .leading, spacing: 12) { HStack(alignment: .firstTextBaseline, spacing: 8) { @@ -206,11 +157,7 @@ struct ContextualContentPicker: View { } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) Button(kind == .note ? store.ui("导入笔记…", "Import Notes…") : store.ui("导入资料…", "Import Materials…")) { - if store.courses.isEmpty { - importFiles(into: nil) - } else { - choosingImportTarget = true - } + importFiles(into: nil) } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) } @@ -219,16 +166,8 @@ struct ContextualContentPicker: View { } private func importFiles(into courseID: UUID?) { - let action = { [store, kind] in - if kind == .note { store.importCourseNotesFromPanel(courseID: courseID) } - else { store.importCourseMaterialsFromPanel(courseID: courseID) } - } - if choosingImportTarget { - pendingImport = action - choosingImportTarget = false - } else { - action() - } + if kind == .note { store.importCourseNotesFromPanel(courseID: courseID) } + else { store.importCourseMaterialsFromPanel(courseID: courseID) } } } diff --git a/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift b/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift index 05c5d4304..b4fe71d55 100644 --- a/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift +++ b/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift @@ -306,6 +306,11 @@ struct CourseDocNoteWorkspaceView: View { select(item, kind: kind) } } + .background( + store.recentlyImportedItemIDs.contains(item.id) + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : Color.clear + ) } @ViewBuilder diff --git a/Sources/WeiBei/Views/CourseHubView.swift b/Sources/WeiBei/Views/CourseHubView.swift index 3f1365479..b76506bc7 100644 --- a/Sources/WeiBei/Views/CourseHubView.swift +++ b/Sources/WeiBei/Views/CourseHubView.swift @@ -1,6 +1,5 @@ import Foundation import SwiftUI -import UniformTypeIdentifiers import WeiBeiCore /// A quiet course landing page: resume reading first, then browse recent course content. @@ -326,6 +325,26 @@ struct CourseHubView: View { .onDrop(of: [.fileURL], isTargeted: $isMaterialDropTargeted) { providers in handleDrop(providers, asNotes: false) } + .overlay { + if isMaterialDropTargeted || isNoteDropTargeted { + Label( + isNoteDropTargeted + ? store.ui("松开以导入笔记", "Drop to import notes") + : store.ui("松开以导入资料", "Drop to import"), + systemImage: "tray.and.arrow.down" + ) + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) + } + } } @ViewBuilder @@ -506,6 +525,7 @@ struct CourseHubView: View { noteID: selectedNoteID, sessionID: selectedSessionID ), + highlighted: entry.itemID.map(store.recentlyImportedItemIDs.contains) ?? false, action: { open(entry) } ) @@ -757,50 +777,10 @@ struct CourseHubView: View { private func handleDrop(_ providers: [NSItemProvider], asNotes: Bool) -> Bool { guard let courseID else { return false } - var urls: [URL] = [] - let urlsLock = NSLock() - let group = DispatchGroup() - - for provider in providers { - group.enter() - provider.loadItem( - forTypeIdentifier: UTType.fileURL.identifier, - options: nil - ) { item, _ in - defer { group.leave() } - let url: URL? - if let data = item as? Data { - url = URL(dataRepresentation: data, relativeTo: nil) - } else { - url = item as? URL - } - guard let url else { return } - urlsLock.lock() - urls.append(url) - urlsLock.unlock() - } - } - - group.notify(queue: .main) { - guard !urls.isEmpty, - store.courseWorkspaceCourseID == courseID else { - return - } - store.importCourseFilesFromURLs( - urls, - asNotes: asNotes, - courseID: courseID - ) { imported in - if asNotes { - selectedNoteID = selectedNoteID - ?? imported.first(where: \.isNotebookNote)?.id - } else { - selectedMaterialID = selectedMaterialID - ?? imported.first(where: \.isCourseMaterial)?.id - } - } + return WeiBeiDroppedFileURLs.load(providers) { urls in + guard store.courseWorkspaceCourseID == courseID else { return } + store.prepareConfirmedFileImport(urls, courseID: courseID, asNotes: asNotes) } - return true } // MARK: - Display helpers @@ -916,6 +896,13 @@ private struct CourseHomeEntry: Identifiable { let detail: String let date: Date + var itemID: String? { + switch kind { + case .material(let item), .note(let item): item.id + case .chat: nil + } + } + func isSelected( materialID: String?, noteID: String?, @@ -1066,6 +1053,7 @@ private struct CourseHubContentRow: View { var snippet: String? = nil var courseBadge: String? = nil let selected: Bool + var highlighted = false let action: () -> Void @State private var hovering = false @@ -1124,7 +1112,9 @@ private struct CourseHubContentRow: View { .frame(minHeight: snippet == nil ? 58 : 72) .contentShape(Rectangle()) .background( - selected + highlighted + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : selected ? WeiBeiTheme.paperInset.opacity(0.34) : (hovering ? WeiBeiTheme.paperInset.opacity(0.16) : .clear) ) diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 2b6a2c41e..d55267be4 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -300,6 +300,7 @@ struct CourseProjectEntrySheet: View { @EnvironmentObject private var store: WorkspaceStore let cancel: () -> Void let openCourse: (UUID) -> Void + let allowsInitialImport: Bool @State private var intent: CourseProjectEntryIntent @State private var title = "" @@ -314,11 +315,13 @@ struct CourseProjectEntrySheet: View { init( initialIntent: CourseProjectEntryIntent = .create, cancel: @escaping () -> Void, - openCourse: @escaping (UUID) -> Void + openCourse: @escaping (UUID) -> Void, + allowsInitialImport: Bool = true ) { _intent = State(initialValue: initialIntent) self.cancel = cancel self.openCourse = openCourse + self.allowsInitialImport = allowsInitialImport } private var needsLibrary: Bool { @@ -356,7 +359,7 @@ struct CourseProjectEntrySheet: View { path: libraryPath ) } - if intent == .create { + if intent == .create && allowsInitialImport { importPicker } } diff --git a/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift b/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift index a5d7177f4..f869f56b1 100644 --- a/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift +++ b/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift @@ -22,6 +22,7 @@ struct EmptyWorkspaceLauncherView: View { @AppStorage("weibei.libraryPlacementConfirmed") private var libraryPlacementConfirmed = false @State private var selectedInspirationID: String? + @State private var isFileDropTargeted = false /// Bumped on theme change so a long-lived NSHostingView cannot keep a stale paper snapshot. @State private var appearanceEpoch = 0 @@ -105,9 +106,24 @@ struct EmptyWorkspaceLauncherView: View { } .accessibilityElement(children: .contain) .accessibilityIdentifier("empty-workspace-launcher") - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + .onDrop(of: [.fileURL], isTargeted: $isFileDropTargeted) { providers in WeiBeiDroppedFileURLs.load(providers) { urls in - store.importFiles(urls) + store.prepareConfirmedFileImport(urls) + } + } + .overlay { + if isFileDropTargeted { + Label(store.ui("松开以导入资料", "Drop to import"), systemImage: "tray.and.arrow.down") + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) } } } diff --git a/Sources/WeiBei/Views/SidebarView.swift b/Sources/WeiBei/Views/SidebarView.swift index d7aab288a..da29579d0 100644 --- a/Sources/WeiBei/Views/SidebarView.swift +++ b/Sources/WeiBei/Views/SidebarView.swift @@ -369,7 +369,11 @@ struct CourseSidebarList: View { bottom: 1, trailing: 2 )) - .listRowBackground(Color.clear) + .listRowBackground( + store.recentlyImportedItemIDs.contains(item.id) + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : Color.clear + ) .listRowSeparator(.hidden) // 显示名与标签共用同一条异步正文管线:compact 行(课程分组内)不展示标签, // 但展示解析后的笔记名,所以笔记行无论 compact 与否都要加载。 diff --git a/Sources/WeiBeiCore/ImportFileCopy.swift b/Sources/WeiBeiCore/ImportFileCopy.swift index ce304a026..c18639a3f 100644 --- a/Sources/WeiBeiCore/ImportFileCopy.swift +++ b/Sources/WeiBeiCore/ImportFileCopy.swift @@ -1,5 +1,11 @@ import Foundation +public enum ImportFileCollision: Equatable, Sendable { + case available + case duplicate + case conflict(suggestedFileName: String) +} + /// Kernel-side import copying for the course library. /// /// Dedupe semantics: byte-identical content resolves to the existing library @@ -11,30 +17,61 @@ public enum ImportFileCopy { static let comparisonChunkSize = 1 << 20 public static func copyPreservingOriginal(from sourceURL: URL, into directory: URL) throws -> URL { - if let html = try HTMLResourceImport.dataIfHTML(at: sourceURL) { - let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) - var target = preferred - if FileManager.default.fileExists(atPath: preferred.path) { - if try preferred.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count, - try Data(contentsOf: preferred) == html { return preferred } - target = uniqueCopyURL(in: directory, preferred: preferred) + let html = try HTMLResourceImport.dataIfHTML(at: sourceURL) + switch try collision(from: sourceURL, into: directory, preparedHTML: html) { + case .available: + break + case .duplicate: + return directory.appendingPathComponent(sourceURL.lastPathComponent) + case .conflict(let suggestedFileName): + let target = directory.appendingPathComponent(suggestedFileName) + if let html { + try html.write(to: target, options: .withoutOverwriting) + } else { + try FileManager.default.copyItem(at: sourceURL, to: target) } - try html.write(to: target, options: .withoutOverwriting) return target } let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) - if FileManager.default.fileExists(atPath: preferred.path) { - if try filesHaveIdenticalContents(sourceURL, preferred) { - return preferred - } - let unique = uniqueCopyURL(in: directory, preferred: preferred) - try FileManager.default.copyItem(at: sourceURL, to: unique) - return unique + if let html { + try html.write(to: preferred, options: .withoutOverwriting) + return preferred } try FileManager.default.copyItem(at: sourceURL, to: preferred) return preferred } + /// Read-only counterpart of `copyPreservingOriginal`. The confirmation UI + /// uses the same comparison and naming rules without creating directories + /// or copying bytes before the user confirms. + public static func collision(from sourceURL: URL, into directory: URL) throws -> ImportFileCollision { + try collision( + from: sourceURL, + into: directory, + preparedHTML: HTMLResourceImport.dataIfHTML(at: sourceURL) + ) + } + + private static func collision( + from sourceURL: URL, + into directory: URL, + preparedHTML: Data? + ) throws -> ImportFileCollision { + let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) + guard FileManager.default.fileExists(atPath: preferred.path) else { + return .available + } + if let html = preparedHTML { + if try preferred.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count, + try Data(contentsOf: preferred) == html { + return .duplicate + } + } else if try filesHaveIdenticalContents(sourceURL, preferred) { + return .duplicate + } + return .conflict(suggestedFileName: uniqueCopyURL(in: directory, preferred: preferred).lastPathComponent) + } + static func filesHaveIdenticalContents(_ lhs: URL, _ rhs: URL) throws -> Bool { let lhsSize = try lhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 let rhsSize = try rhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift new file mode 100644 index 000000000..9ed40bce2 --- /dev/null +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -0,0 +1,213 @@ +import Foundation +@testable import WeiBei +import WeiBeiCore +import XCTest + +@MainActor +final class ConfirmedFileImportTests: XCTestCase { + override class func setUp() { + super.setUp() + setenv("WEIBEI_SAFETY_TEST_MODE", "1", 1) + } + + func testCancelBeforeConfirmationWritesNothing() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + try Data("source".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library + .appendingPathComponent("通用资料/讲义.txt") + .path + )) + fixture.store.dismissConfirmedFileImport() + XCTAssertTrue(FileManager.default.fileExists(atPath: source.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library + .appendingPathComponent("通用资料/讲义.txt") + .path + )) + } + + func testPartialFailureKeepsSuccessAndRetriesOnlyFailure() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: second) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.map(\.subtitle), ["一.txt"]) + XCTAssertEqual(batch.failures.map(\.sourceURL.lastPathComponent), ["二.txt"]) + XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) + XCTAssertTrue(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/一.txt").path + )) + + try Data("two".utf8).write(to: second) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [second]) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(Set(batch.importedItems.map(\.subtitle)), Set(["一.txt", "二.txt"])) + XCTAssertTrue(batch.failures.isEmpty) + XCTAssertEqual( + try String(contentsOf: fixture.library.appendingPathComponent("通用资料/一.txt")), + "one" + ) + } + + func testStopBeforeNextTaskLeavesSourcesUntouched() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + fixture.store.stopConfirmedFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertTrue(batch.stopped) + XCTAssertTrue(batch.importedItems.isEmpty) + XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: second.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/一.txt").path + )) + } + + func testDockFilesJoinOneCommonBatchBeforeConfirmation() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + + fixture.store.receiveExternalFileForConfirmedImport(first) + fixture.store.receiveExternalFileForConfirmedImport(second) + waitForStage(.reviewing, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertNil(batch.courseID) + XCTAssertEqual(Set(batch.sourceURLs), Set([first, second])) + XCTAssertEqual(batch.candidates.count, 2) + XCTAssertTrue(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ).isEmpty) + } + + func testCollisionPlanUsesCopyKernelWithoutWriting() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-collision-\(UUID().uuidString)", isDirectory: true) + let sourceDirectory = root.appendingPathComponent("source", isDirectory: true) + let destination = root.appendingPathComponent("destination", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: sourceDirectory, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let source = sourceDirectory.appendingPathComponent("同名.txt") + let existing = destination.appendingPathComponent("同名.txt") + try Data("new".utf8).write(to: source) + try Data("old".utf8).write(to: existing) + + XCTAssertEqual( + try ImportFileCopy.collision(from: source, into: destination), + .conflict(suggestedFileName: "同名 2.txt") + ) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: destination.path), ["同名.txt"]) + try Data("old".utf8).write(to: source) + XCTAssertEqual(try ImportFileCopy.collision(from: source, into: destination), .duplicate) + } + + func testSameNameInsideBatchIsShownAsConflictBeforeConfirmation() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-batch-collision-\(UUID().uuidString)", isDirectory: true) + let firstDirectory = root.appendingPathComponent("a", isDirectory: true) + let secondDirectory = root.appendingPathComponent("b", isDirectory: true) + let destination = root.appendingPathComponent("destination", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + for directory in [firstDirectory, secondDirectory, destination] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = firstDirectory.appendingPathComponent("同名.txt") + let second = secondDirectory.appendingPathComponent("同名.txt") + try Data("first".utf8).write(to: first) + try Data("second".utf8).write(to: second) + + let candidates = try WorkspaceStore.makeConfirmedFileImportPlan( + urls: [first, second], + destination: destination, + markdownOnly: false + ) + + XCTAssertEqual(candidates.count, 2) + XCTAssertEqual(candidates[0].disposition, .ready) + XCTAssertEqual(candidates[1].disposition, .conflict(suggestedFileName: "同名 2.txt")) + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: destination.path).isEmpty) + } + + private func waitForStage( + _ stage: ConfirmedFileImportStage, + in store: WorkspaceStore, + file: StaticString = #filePath, + line: UInt = #line + ) { + let deadline = Date().addingTimeInterval(10) + while store.confirmedFileImport?.stage != stage, Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.02)) + } + XCTAssertEqual(store.confirmedFileImport?.stage, stage, file: file, line: line) + } + + private func makeFixture() throws -> ( + root: URL, + library: URL, + outside: URL, + store: WorkspaceStore + ) { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-import-\(UUID().uuidString)", isDirectory: true) + let workspace = root.appendingPathComponent("workspace", isDirectory: true) + let library = root.appendingPathComponent("library", isDirectory: true) + let outside = root.appendingPathComponent("outside", isDirectory: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let store = WorkspaceStore( + workspaceDirectory: workspace, + courseRootBookmarkMaker: { Data($0.standardizedFileURL.path.utf8) }, + courseRootBookmarkResolver: { data in + guard let path = String(data: data, encoding: .utf8) else { return nil } + return CourseProjectResolvedBookmark( + url: URL(fileURLWithPath: path), + isStale: false + ) + }, + courseSecurityScopeStarter: { _ in true }, + courseSecurityScopeStopper: { _ in }, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + try store.configureCourseLibrary(at: library) + return (root, library, outside, store) + } +} From 13aa1af2de0f88939811647e9a05b0b655946c36 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:18:12 +0800 Subject: [PATCH 02/50] =?UTF-8?q?test:=20=E4=BF=AE=E6=AD=A3=E5=AF=BC?= =?UTF-8?q?=E5=85=A5=E8=AE=A1=E5=88=92=E6=96=AD=E8=A8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index 9ed40bce2..c3e46c7e3 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -153,15 +153,15 @@ final class ConfirmedFileImportTests: XCTestCase { try Data("first".utf8).write(to: first) try Data("second".utf8).write(to: second) - let candidates = try WorkspaceStore.makeConfirmedFileImportPlan( + let plan = WorkspaceStore.makeConfirmedFileImportPlan( urls: [first, second], destination: destination, markdownOnly: false ) - XCTAssertEqual(candidates.count, 2) - XCTAssertEqual(candidates[0].disposition, .ready) - XCTAssertEqual(candidates[1].disposition, .conflict(suggestedFileName: "同名 2.txt")) + XCTAssertEqual(plan.candidates.count, 2) + XCTAssertEqual(plan.candidates[0].disposition, .ready) + XCTAssertEqual(plan.candidates[1].disposition, .conflict(suggestedFileName: "同名 2.txt")) XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: destination.path).isEmpty) } From 0ec638d493797582fe69e485a24ffb1822ac0d03 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:27:51 +0800 Subject: [PATCH 03/50] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=AF=BC=E5=85=A5=E8=BE=B9=E7=95=8C=E8=A1=8C=E4=B8=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/WeiBei.xcodeproj/project.pbxproj | 4 + ...74\345\205\245\345\256\232\346\241\210.md" | 4 + .../Stores/CourseProjectRootSupport.swift | 67 ++++++-- .../Views/ConfirmedFileImportView.swift | 156 ++++++++++++++---- .../Views/CourseWorkspaceComponents.swift | 14 +- Sources/WeiBeiCore/ImportFileCopy.swift | 16 ++ .../ConfirmedFileImportTests.swift | 103 ++++++++++++ 7 files changed, 308 insertions(+), 56 deletions(-) diff --git a/App/WeiBei.xcodeproj/project.pbxproj b/App/WeiBei.xcodeproj/project.pbxproj index af20be7f8..28237e653 100644 --- a/App/WeiBei.xcodeproj/project.pbxproj +++ b/App/WeiBei.xcodeproj/project.pbxproj @@ -156,6 +156,7 @@ 9E35B424552BEC714D64E69B /* HTMLResourceImport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E587D2C74173406238893D89 /* HTMLResourceImport.swift */; }; 9E82B06347DF8AAD02442C3D /* WorkspaceStore+NativeAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74D3DDD62890E2095AE206E6 /* WorkspaceStore+NativeAgent.swift */; }; 9FB05F925099B527532D6EB2 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C114483E09D9B95115B4EF5 /* ContentView.swift */; }; + CF1A00000000000000000001 /* ConfirmedFileImportView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF1A00000000000000000002 /* ConfirmedFileImportView.swift */; }; 9FD230DCC3C1CCEE79F5B1C1 /* EmptyWorkspaceInspiration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA378A62D30B6A6251AD9DA6 /* EmptyWorkspaceInspiration.swift */; }; 9FF041C038C5AB9C8A27287A /* PDFReaderOpenSafety.swift in Sources */ = {isa = PBXBuildFile; fileRef = 178A366B5659AC7A47E7AA30 /* PDFReaderOpenSafety.swift */; }; A29105E5484EFF5BE88B2979 /* PaneSeatMotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = A434A3C22BC374DD87D0E041 /* PaneSeatMotion.swift */; }; @@ -348,6 +349,7 @@ 4639CC2F72655275FF9EF5C5 /* WorkspaceStore+GlobalSearch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+GlobalSearch.swift"; sourceTree = ""; }; 4787853DDB4CD028D2FABC51 /* ContentRailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentRailView.swift; sourceTree = ""; }; 4C114483E09D9B95115B4EF5 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + CF1A00000000000000000002 /* ConfirmedFileImportView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmedFileImportView.swift; sourceTree = ""; }; 4CDF85F80AC46C5FE414E777 /* NativeAgentSSE.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAgentSSE.swift; sourceTree = ""; }; 4D52600F1258F2C0DAB31B39 /* ConversationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationController.swift; sourceTree = ""; }; 50D90DFD2794222AD19D98DD /* WeiBeiUpdateService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeiBeiUpdateService.swift; sourceTree = ""; }; @@ -746,6 +748,7 @@ BCFA6009ED31791018CA93D2 /* ComposerView.swift */, 4787853DDB4CD028D2FABC51 /* ContentRailView.swift */, 4C114483E09D9B95115B4EF5 /* ContentView.swift */, + CF1A00000000000000000002 /* ConfirmedFileImportView.swift */, E51AB9EF50CCEDB319397D8C /* ContextualContentPicker.swift */, E59061F53CCAA6551A4ABABC /* ConversationWebClippingView.swift */, ED28080243B8A8B552763344 /* CourseDocNoteWorkspaceView.swift */, @@ -1271,6 +1274,7 @@ 90A2214DC79342A465A01D96 /* ComposerView.swift in Sources */, 186031B66D5FC7464EB6CB2C /* ContentRailView.swift in Sources */, 9FB05F925099B527532D6EB2 /* ContentView.swift in Sources */, + CF1A00000000000000000001 /* ConfirmedFileImportView.swift in Sources */, 24D17FE22AAD67D99C583D71 /* ContextualContentPicker.swift in Sources */, 82A9C07B68A5A0E9C1844E14 /* ConversationController.swift in Sources */, C2683F836E4926D9F60998FD /* ConversationData.swift in Sources */, diff --git "a/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" index db9a080a8..8235caa2b 100644 --- "a/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" +++ "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" @@ -6,6 +6,8 @@ 首页、普通工作台、课程内和从 Dock 打开文件都进入同一确认面板。文件选择器入口也复用该面板。普通入口默认“通用资料”,课程入口默认当前课程;明确的笔记入口只接受 Markdown,并默认导入为笔记。 +课程创建页里预先选择的初始文件也只在课程创建完成后进入同一确认面板,不会直接复制。若当前批次正在导入时又从 Dock 打开文件,新文件会显示为下一批待处理项;用户可以在当前结果页继续核对,不会静默丢掉选择。 + 面板先列出实际可导入文件、不支持项、重复项和同名冲突,再选择归属。通用资料始终在首项,课程支持搜索和新建。新建课程沿用原有资料库目录与权限流程;取消新建只关闭新建面板,原批次和当前选择保留。 确认文案直接写目标,例如“加入《投资学》”。确认前只读取文件信息和比对内容,不创建目录、不复制文件。确认后仍在同一面板显示当前文件和进度,可停止剩余文件;已经完成的文件保留。 @@ -18,6 +20,8 @@ | 内容完全相同且同名 | 标为“重复,跳过”,不再次复制 | | 同名但内容不同 | 确认前显示新名称,确认后保留两份,不覆盖 | | 不支持的文件 | 确认前列出并跳过;全部不支持时禁用确认 | +| 文件夹内不支持的文件 | 沿用既有安全遍历范围递归列出;隐藏项、应用包、符号链接和 `node_modules` 不越界展开 | +| 同批同名且内容相同 | 第二份标为重复并跳过,只登记一次成功 | | 单个文件失败 | 保留本批已成功结果,显示失败原因 | | 重试 | 只重新核对和导入失败文件 | | 停止 | 当前正在处理的文件结束后停止剩余文件 | diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index d7904a28e..67c8c76e7 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -3147,16 +3147,33 @@ actor CourseProjectFileWorker { from urls: [URL], markdownOnly: Bool ) -> [URL] { + expandedImportSelection(from: urls, markdownOnly: markdownOnly).supported + } + + nonisolated static func expandedImportSelection( + from urls: [URL], + markdownOnly: Bool + ) -> (supported: [URL], unsupportedNames: [String]) { let fileManager = FileManager.default - var seen = Set() - var result: [URL] = [] + var seenSupported = Set() + var seenUnsupported = Set() + var supported: [URL] = [] + var unsupportedNames: [String] = [] for rawURL in urls { var isDirectory: ObjCBool = false guard fileManager.fileExists(atPath: rawURL.path, isDirectory: &isDirectory) else { continue } if !isDirectory.boolValue { - appendSupported(rawURL, markdownOnly: markdownOnly, seen: &seen, result: &result) + appendImportSelection( + rawURL, + displayName: rawURL.lastPathComponent, + markdownOnly: markdownOnly, + seenSupported: &seenSupported, + seenUnsupported: &seenUnsupported, + supported: &supported, + unsupportedNames: &unsupportedNames + ) continue } guard !Self.ignoresImportDirectory(rawURL) else { continue } @@ -3178,10 +3195,26 @@ actor CourseProjectFileWorker { enumerator.skipDescendants() continue } - appendSupported(fileURL, markdownOnly: markdownOnly, seen: &seen, result: &result) + let rootPath = rawURL.standardizedFileURL.path + let filePath = fileURL.standardizedFileURL.path + let relativePath = filePath.hasPrefix(rootPath + "/") + ? String(filePath.dropFirst(rootPath.count + 1)) + : fileURL.lastPathComponent + appendImportSelection( + fileURL, + displayName: "\(rawURL.lastPathComponent)/\(relativePath)", + markdownOnly: markdownOnly, + seenSupported: &seenSupported, + seenUnsupported: &seenUnsupported, + supported: &supported, + unsupportedNames: &unsupportedNames + ) } } - return result.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } + return ( + supported.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }, + unsupportedNames.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + ) } private func copyVisibleCourseTree( @@ -3593,16 +3626,16 @@ actor CourseProjectFileWorker { } } - nonisolated private static func appendSupported( + nonisolated private static func appendImportSelection( _ rawURL: URL, + displayName: String, markdownOnly: Bool, - seen: inout Set, - result: inout [URL] + seenSupported: inout Set, + seenUnsupported: inout Set, + supported: inout [URL], + unsupportedNames: inout [String] ) { - let pathExtension = rawURL.pathExtension.lowercased() - guard Self.supportedExtensions.contains(pathExtension), - !markdownOnly || ["md", "markdown"].contains(pathExtension), - let values = try? rawURL.resourceValues(forKeys: [ + guard let values = try? rawURL.resourceValues(forKeys: [ .isRegularFileKey, .isSymbolicLinkKey, .isAliasFileKey, @@ -3613,8 +3646,14 @@ actor CourseProjectFileWorker { return } let url = rawURL.standardizedFileURL - guard seen.insert(url.path).inserted else { return } - result.append(url) + let pathExtension = rawURL.pathExtension.lowercased() + if Self.supportedExtensions.contains(pathExtension), + !markdownOnly || ["md", "markdown"].contains(pathExtension) { + guard seenSupported.insert(url.path).inserted else { return } + supported.append(url) + } else if seenUnsupported.insert(url.path).inserted { + unsupportedNames.append(displayName) + } } nonisolated static func identity(at url: URL) -> ImportedFileIdentity? { diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 1ca93810d..8fee92d56 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -44,6 +44,7 @@ struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { var currentFileName: String? var stopped = false var destinationError: String? + var pendingSourceURLs: [URL] = [] var confirmableCount: Int { candidates.count @@ -81,7 +82,16 @@ extension WorkspaceStore { } func receiveExternalFileForConfirmedImport(_ url: URL) { - if confirmedFileImport?.stage == .importing { return } + if var batch = confirmedFileImport, batch.stage == .importing { + let knownURLs = batch.sourceURLs + batch.pendingSourceURLs + if !knownURLs.contains(where: { + $0.standardizedFileURL == url.standardizedFileURL + }) { + batch.pendingSourceURLs.append(url) + confirmedFileImport = batch + } + return + } if var batch = confirmedFileImport, batch.courseID == nil, !batch.importsMarkdownAsNotes, @@ -124,6 +134,24 @@ extension WorkspaceStore { confirmedFileImportStopRequested = true } + func continuePendingConfirmedFileImport() { + guard let batch = confirmedFileImport, + batch.stage == .finished, + !batch.pendingSourceURLs.isEmpty else { return } + prepareConfirmedFileImport(batch.pendingSourceURLs) + } + + func prepareInitialCourseImportAfterEntryDismissal( + _ urls: [URL], + courseID: UUID + ) { + guard !urls.isEmpty else { return } + Task { @MainActor [weak self] in + await Task.yield() + self?.prepareConfirmedFileImport(urls, courseID: courseID) + } + } + func retryFailedConfirmedFileImport() { guard let batch = confirmedFileImport, batch.stage == .finished, @@ -136,7 +164,8 @@ extension WorkspaceStore { courseID: batch.courseID, importsMarkdownAsNotes: batch.importsMarkdownAsNotes, importedItems: batch.importedItems, - previousSkippedCount: batch.skippedCount + previousSkippedCount: batch.skippedCount, + pendingSourceURLs: batch.pendingSourceURLs ) refreshConfirmedFileImportPlan() } @@ -169,22 +198,26 @@ extension WorkspaceStore { } batch.currentFileName = candidate.sourceURL.lastPathComponent batch.completed = completed - confirmedFileImport = batch + publishConfirmedFileImportProgress(batch) defer { completed += 1 batch.completed = completed - confirmedFileImport = batch + publishConfirmedFileImportProgress(batch) } if candidate.disposition == .duplicate { continue } do { let item = try await importConfirmedFile(candidate, batch: batch) - imported.append(item) + if !imported.contains(where: { $0.id == item.id }) { + imported.append(item) + } } catch { if let recovered = await recoverConfirmedCourseImport( candidate, batch: batch ) { - imported.append(recovered) + if !imported.contains(where: { $0.id == recovered.id }) { + imported.append(recovered) + } continue } WeiBeiLog.workspace.error( @@ -204,10 +237,22 @@ extension WorkspaceStore { batch.stopped = batch.stopped || confirmedFileImportStopRequested confirmedFileImportStopRequested = false confirmedFileImportTask = nil - confirmedFileImport = batch + publishConfirmedFileImportProgress(batch) } } + private func publishConfirmedFileImportProgress(_ batch: ConfirmedFileImportBatch) { + var next = batch + if let current = confirmedFileImport, current.id == batch.id { + for url in current.pendingSourceURLs where !next.pendingSourceURLs.contains(where: { + $0.standardizedFileURL == url.standardizedFileURL + }) { + next.pendingSourceURLs.append(url) + } + } + confirmedFileImport = next + } + func openSingleConfirmedImport() { guard let batch = confirmedFileImport, batch.importedItems.count == 1, let item = batch.importedItems.first else { return } @@ -299,45 +344,59 @@ extension WorkspaceStore { nonisolated static func makeConfirmedFileImportPlan( urls: [URL], destination: URL, markdownOnly: Bool ) -> (candidates: [ConfirmedFileImportCandidate], unsupportedNames: [String]) { - let expanded = CourseProjectFileWorker.expandedSupportedFiles( + let expansion = CourseProjectFileWorker.expandedImportSelection( from: urls, markdownOnly: markdownOnly ) - let expandedPaths = Set(expanded.map { $0.standardizedFileURL.path }) - var unsupported = urls.compactMap { url -> String? in + let expanded = expansion.supported + var unsupported = expansion.unsupportedNames + unsupported.append(contentsOf: urls.compactMap { url -> String? in let values = try? url.resourceValues(forKeys: [.isDirectoryKey]) - if values?.isDirectory == true { - return CourseProjectFileWorker.expandedSupportedFiles( + guard values?.isDirectory == true else { return nil } + let nested = CourseProjectFileWorker.expandedImportSelection( from: [url], markdownOnly: markdownOnly - ).isEmpty ? url.lastPathComponent : nil - } - return expandedPaths.contains(url.standardizedFileURL.path) ? nil : url.lastPathComponent - } + ) + return nested.supported.isEmpty && nested.unsupportedNames.isEmpty + ? url.lastPathComponent + : nil + }) var candidates: [ConfirmedFileImportCandidate] = [] var reservedTargetNames = Set() + var reservedSourcesByTargetName: [String: URL] = [:] for url in expanded { - var disposition: ConfirmedFileImportDisposition + let initialTargetName: String do { switch try ImportFileCopy.collision(from: url, into: destination) { - case .available: disposition = .ready - case .duplicate: disposition = .duplicate - case .conflict(let suggested): disposition = .conflict(suggestedFileName: suggested) + case .available: + initialTargetName = url.lastPathComponent + case .duplicate: + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) + continue + case .conflict(let suggested): + initialTargetName = suggested } } catch { - disposition = .ready + initialTargetName = url.lastPathComponent } - if disposition != .duplicate { - let targetName = nextConfirmedImportTargetName( - for: url, - in: destination, - reserved: reservedTargetNames - ) - if targetName != url.lastPathComponent { - disposition = .conflict(suggestedFileName: targetName) - } - reservedTargetNames.insert(targetName) + if let reservedSource = reservedSourcesByTargetName[initialTargetName], + (try? ImportFileCopy.sourcesHaveIdenticalImportedContents( + reservedSource, + url + )) == true { + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) + continue } + let targetName = nextConfirmedImportTargetName( + for: url, + in: destination, + reserved: reservedTargetNames + ) + let disposition: ConfirmedFileImportDisposition = targetName == url.lastPathComponent + ? .ready + : .conflict(suggestedFileName: targetName) + reservedTargetNames.insert(targetName) + reservedSourcesByTargetName[targetName] = url candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) } if markdownOnly { @@ -670,6 +729,14 @@ struct ConfirmedFileImportView: View { Text("\(batch.completed) / \(batch.total)") .weiBeiText(11, design: .monospaced) .foregroundStyle(WeiBeiTheme.secondaryInk) + if !batch.pendingSourceURLs.isEmpty { + Text(store.ui( + "另有 \(batch.pendingSourceURLs.count) 个从 Dock 打开的文件等待本批完成。", + "\(batch.pendingSourceURLs.count) file(s) opened from the Dock are waiting for this batch." + )) + .weiBeiText(11) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } Spacer() HStack { Spacer() @@ -693,6 +760,14 @@ struct ConfirmedFileImportView: View { .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) } + if !batch.pendingSourceURLs.isEmpty { + Text(store.ui( + "另有 \(batch.pendingSourceURLs.count) 个文件尚未处理,原文件仍保留。", + "\(batch.pendingSourceURLs.count) file(s) are still waiting; their originals are unchanged." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } if !batch.failures.isEmpty { ScrollView { VStack(alignment: .leading, spacing: 8) { @@ -708,6 +783,15 @@ struct ConfirmedFileImportView: View { } Spacer() HStack(spacing: 8) { + if !batch.pendingSourceURLs.isEmpty { + Button(store.ui( + "处理待导入文件(\(batch.pendingSourceURLs.count))", + "Review Waiting Files (\(batch.pendingSourceURLs.count))" + )) { + store.continuePendingConfirmedFileImport() + } + .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + } if !batch.failures.isEmpty { Button(store.ui("只重试失败项", "Retry Failed Only")) { store.retryFailedConfirmedFileImport() @@ -715,18 +799,22 @@ struct ConfirmedFileImportView: View { .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) } Spacer() - if batch.importedItems.count == 1 { + if batch.pendingSourceURLs.isEmpty, batch.importedItems.count == 1 { Button(store.ui("打开文稿", "Open Document")) { store.openSingleConfirmedImport() } .buttonStyle(WeiBeiTextActionButtonStyle()) - } else if batch.importedItems.count > 1 { + } else if batch.pendingSourceURLs.isEmpty, batch.importedItems.count > 1 { Button(store.ui("查看已导入资料", "View Imported Items")) { store.showConfirmedImportBatch() } .buttonStyle(WeiBeiTextActionButtonStyle()) } - Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + Button( + batch.pendingSourceURLs.isEmpty + ? store.ui("完成", "Done") + : store.ui("暂不处理待导入文件", "Leave Waiting Files") + ) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiTextActionButtonStyle()) .keyboardShortcut(.defaultAction) } diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index d55267be4..4e0180014 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -781,15 +781,13 @@ struct CourseProjectEntrySheet: View { let courseID = try await store.createCourseInLibraryAsync( title: cleanedTitle ) - if selectedImportURLs.isEmpty { - openCourse(courseID) - } else { - store.importCourseFilesFromURLs( - selectedImportURLs, + let initialImportURLs = selectedImportURLs + openCourse(courseID) + if !initialImportURLs.isEmpty { + store.prepareInitialCourseImportAfterEntryDismissal( + initialImportURLs, courseID: courseID - ) { _ in - openCourse(courseID) - } + ) } } } diff --git a/Sources/WeiBeiCore/ImportFileCopy.swift b/Sources/WeiBeiCore/ImportFileCopy.swift index c18639a3f..b49ad9945 100644 --- a/Sources/WeiBeiCore/ImportFileCopy.swift +++ b/Sources/WeiBeiCore/ImportFileCopy.swift @@ -52,6 +52,22 @@ public enum ImportFileCopy { ) } + public static func sourcesHaveIdenticalImportedContents( + _ lhs: URL, + _ rhs: URL + ) throws -> Bool { + let lhsHTML = try HTMLResourceImport.dataIfHTML(at: lhs) + let rhsHTML = try HTMLResourceImport.dataIfHTML(at: rhs) + switch (lhsHTML, rhsHTML) { + case let (.some(lhsData), .some(rhsData)): + return lhsData == rhsData + case (.none, .none): + return try filesHaveIdenticalContents(lhs, rhs) + default: + return false + } + } + private static func collision( from sourceURL: URL, into directory: URL, diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index c3e46c7e3..fd68aaa34 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -116,6 +116,53 @@ final class ConfirmedFileImportTests: XCTestCase { ).isEmpty) } + func testDockFileOpenedDuringImportWaitsForNextBatch() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let current = fixture.outside.appendingPathComponent("当前.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("current".utf8).write(to: current) + try Data("waiting".utf8).write(to: waiting) + + fixture.store.prepareConfirmedFileImport([current]) + waitForStage(.reviewing, in: fixture.store) + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + batch.stage = .importing + fixture.store.confirmedFileImport = batch + + fixture.store.receiveExternalFileForConfirmedImport(waiting) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.sourceURLs, [current]) + XCTAssertEqual(batch.pendingSourceURLs, [waiting]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/稍后.txt").path + )) + + batch.stage = .finished + fixture.store.confirmedFileImport = batch + fixture.store.continuePendingConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + } + + func testInitialCourseFilesWaitForUnifiedConfirmation() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("课程讲义.pdf") + try Data("pdf".utf8).write(to: source) + let courseID = try fixture.store.createCourseInLibrary(title: "确认课") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + + fixture.store.prepareInitialCourseImportAfterEntryDismissal([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.courseID, courseID) + XCTAssertFalse(FileManager.default.fileExists( + atPath: courseRoot.appendingPathComponent("文稿/课程讲义.pdf").path + )) + } + func testCollisionPlanUsesCopyKernelWithoutWriting() throws { let root = FileManager.default.temporaryDirectory .appendingPathComponent("weibei-confirmed-collision-\(UUID().uuidString)", isDirectory: true) @@ -165,6 +212,62 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: destination.path).isEmpty) } + func testSameNameAndContentInsideBatchSkipsSecondCopy() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let firstDirectory = fixture.outside.appendingPathComponent("a", isDirectory: true) + let secondDirectory = fixture.outside.appendingPathComponent("b", isDirectory: true) + try FileManager.default.createDirectory(at: firstDirectory, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: secondDirectory, withIntermediateDirectories: true) + let first = firstDirectory.appendingPathComponent("同名.txt") + let second = secondDirectory.appendingPathComponent("同名.txt") + try Data("same".utf8).write(to: first) + try Data("same".utf8).write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.disposition), + [.ready, .duplicate] + ) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.count, 1) + XCTAssertEqual(batch.skippedCount, 1) + XCTAssertEqual( + try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ), + ["同名.txt"] + ) + } + + func testMixedFolderListsRecursiveUnsupportedFilesWithoutFollowingSymlinks() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let folder = fixture.outside.appendingPathComponent("资料包", isDirectory: true) + let nested = folder.appendingPathComponent("附件", isDirectory: true) + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + try Data("pdf".utf8).write(to: folder.appendingPathComponent("讲义.pdf")) + try Data("zip".utf8).write(to: nested.appendingPathComponent("原件.zip")) + let outsideSecret = fixture.root.appendingPathComponent("边界外.zip") + try Data("secret".utf8).write(to: outsideSecret) + try FileManager.default.createSymbolicLink( + at: nested.appendingPathComponent("边界外.zip"), + withDestinationURL: outsideSecret + ) + + fixture.store.prepareConfirmedFileImport([folder]) + waitForStage(.reviewing, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.candidates.map { $0.sourceURL.lastPathComponent }, ["讲义.pdf"]) + XCTAssertEqual(batch.unsupportedNames, ["资料包/附件/原件.zip"]) + XCTAssertEqual(batch.skippedCount, 1) + } + private func waitForStage( _ stage: ConfirmedFileImportStage, in store: WorkspaceStore, From eb5383296445158e3aa2f1a9c64854d707790444 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:39:02 +0800 Subject: [PATCH 04/50] =?UTF-8?q?fix:=20=E6=A0=B9=E6=B2=BB=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=AF=BC=E5=85=A5=E5=89=A9=E4=BD=99=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Stores/CourseProjectRootSupport.swift | 26 ++- .../Views/ConfirmedFileImportView.swift | 46 ++--- .../ConfirmedFileImportTests.swift | 158 ++++++++++++++++++ 3 files changed, 206 insertions(+), 24 deletions(-) diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index 67c8c76e7..87bc78b60 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -3160,11 +3160,16 @@ actor CourseProjectFileWorker { var supported: [URL] = [] var unsupportedNames: [String] = [] for rawURL in urls { - var isDirectory: ObjCBool = false - guard fileManager.fileExists(atPath: rawURL.path, isDirectory: &isDirectory) else { + guard let rootValues = try? rawURL.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]), + rootValues.isSymbolicLink != true, + rootValues.isAliasFile != true else { continue } - if !isDirectory.boolValue { + if rootValues.isDirectory != true { appendImportSelection( rawURL, displayName: rawURL.lastPathComponent, @@ -3180,6 +3185,7 @@ actor CourseProjectFileWorker { guard let enumerator = fileManager.enumerator( at: rawURL, includingPropertiesForKeys: [ + .isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .isAliasFileKey, @@ -3190,8 +3196,20 @@ actor CourseProjectFileWorker { continue } for case let fileURL as URL in enumerator { + guard let values = try? fileURL.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]) else { + enumerator.skipDescendants() + continue + } + if values.isSymbolicLink == true || values.isAliasFile == true { + enumerator.skipDescendants() + continue + } if Self.ignoresImportDirectory(fileURL), - (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { + values.isDirectory == true { enumerator.skipDescendants() continue } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 8fee92d56..59a7a2bbf 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -134,10 +134,11 @@ extension WorkspaceStore { confirmedFileImportStopRequested = true } - func continuePendingConfirmedFileImport() { + func continuePendingConfirmedFileImport(abandoningFailures: Bool = false) { guard let batch = confirmedFileImport, batch.stage == .finished, - !batch.pendingSourceURLs.isEmpty else { return } + !batch.pendingSourceURLs.isEmpty, + batch.failures.isEmpty || abandoningFailures else { return } prepareConfirmedFileImport(batch.pendingSourceURLs) } @@ -363,27 +364,26 @@ extension WorkspaceStore { }) var candidates: [ConfirmedFileImportCandidate] = [] var reservedTargetNames = Set() - var reservedSourcesByTargetName: [String: URL] = [:] + var reservedSourcesByOriginalName: [String: [URL]] = [:] for url in expanded { - let initialTargetName: String do { switch try ImportFileCopy.collision(from: url, into: destination) { - case .available: - initialTargetName = url.lastPathComponent + case .available, .conflict: + break case .duplicate: candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) continue - case .conflict(let suggested): - initialTargetName = suggested } - } catch { - initialTargetName = url.lastPathComponent - } - if let reservedSource = reservedSourcesByTargetName[initialTargetName], - (try? ImportFileCopy.sourcesHaveIdenticalImportedContents( - reservedSource, - url - )) == true { + } catch {} + let originalName = url.lastPathComponent + let duplicatesReservedSource = reservedSourcesByOriginalName[originalName, default: []] + .contains { reservedSource in + (try? ImportFileCopy.sourcesHaveIdenticalImportedContents( + reservedSource, + url + )) == true + } + if duplicatesReservedSource { candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) continue } @@ -396,7 +396,7 @@ extension WorkspaceStore { ? .ready : .conflict(suggestedFileName: targetName) reservedTargetNames.insert(targetName) - reservedSourcesByTargetName[targetName] = url + reservedSourcesByOriginalName[originalName, default: []].append(url) candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) } if markdownOnly { @@ -785,10 +785,16 @@ struct ConfirmedFileImportView: View { HStack(spacing: 8) { if !batch.pendingSourceURLs.isEmpty { Button(store.ui( - "处理待导入文件(\(batch.pendingSourceURLs.count))", - "Review Waiting Files (\(batch.pendingSourceURLs.count))" + batch.failures.isEmpty + ? "处理待导入文件(\(batch.pendingSourceURLs.count))" + : "放弃失败项并处理待导入文件(\(batch.pendingSourceURLs.count))", + batch.failures.isEmpty + ? "Review Waiting Files (\(batch.pendingSourceURLs.count))" + : "Leave Failures and Review Waiting Files (\(batch.pendingSourceURLs.count))" )) { - store.continuePendingConfirmedFileImport() + store.continuePendingConfirmedFileImport( + abandoningFailures: !batch.failures.isEmpty + ) } .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) } diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index fd68aaa34..a00925688 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -146,6 +146,59 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) } + func testPendingBatchCannotSilentlyDiscardFailures() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let failed = fixture.outside.appendingPathComponent("失败.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("failed".utf8).write(to: failed) + try Data("waiting".utf8).write(to: waiting) + let failure = ConfirmedFileImportFailure(sourceURL: failed, message: "失败") + fixture.store.confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: [failed], + sourceFolderNames: [], + courseID: nil, + importsMarkdownAsNotes: false, + stage: .finished, + failures: [failure], + pendingSourceURLs: [waiting] + ) + + fixture.store.continuePendingConfirmedFileImport() + XCTAssertEqual(fixture.store.confirmedFileImport?.failures, [failure]) + XCTAssertEqual(fixture.store.confirmedFileImport?.pendingSourceURLs, [waiting]) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [failed]) + XCTAssertEqual(fixture.store.confirmedFileImport?.pendingSourceURLs, [waiting]) + } + + func testPendingBatchContinuesAfterExplicitlyAbandoningFailures() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let failed = fixture.outside.appendingPathComponent("失败.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("failed".utf8).write(to: failed) + try Data("waiting".utf8).write(to: waiting) + fixture.store.confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: [failed], + sourceFolderNames: [], + courseID: nil, + importsMarkdownAsNotes: false, + stage: .finished, + failures: [ConfirmedFileImportFailure(sourceURL: failed, message: "失败")], + pendingSourceURLs: [waiting] + ) + + fixture.store.continuePendingConfirmedFileImport(abandoningFailures: true) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + XCTAssertTrue(fixture.store.confirmedFileImport?.failures.isEmpty == true) + } + func testInitialCourseFilesWaitForUnifiedConfirmation() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } @@ -244,6 +297,66 @@ final class ConfirmedFileImportTests: XCTestCase { ) } + func testSameNameCollisionGroupComparesEveryEarlierContent() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b", "c"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + try Data("A".utf8).write(to: files[0]) + try Data("B".utf8).write(to: files[1]) + try Data("B".utf8).write(to: files[2]) + + fixture.store.prepareConfirmedFileImport(files) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.disposition), + [.ready, .conflict(suggestedFileName: "同名 2.txt"), .duplicate] + ) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.importedItems.count, 2) + XCTAssertEqual(fixture.store.confirmedFileImport?.skippedCount, 1) + XCTAssertEqual( + try Set(FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + )), + Set(["同名.txt", "同名 2.txt"]) + ) + } + + func testSameNameHTMLUsesNormalizedImportedContentsForDuplicates() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = directories[0].appendingPathComponent("同名.html") + let second = directories[1].appendingPathComponent("同名.html") + try Data("".utf8).write(to: first) + try Data("".utf8).write(to: second) + let image = Data([0x89, 0x50, 0x4e, 0x47]) + try image.write(to: directories[0].appendingPathComponent("甲.png")) + try image.write(to: directories[1].appendingPathComponent("乙.png")) + XCTAssertNotEqual(try Data(contentsOf: first), try Data(contentsOf: second)) + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [first, second], + destination: fixture.library.appendingPathComponent("通用资料", isDirectory: true), + markdownOnly: false + ) + + XCTAssertEqual(plan.candidates.map(\.disposition), [.ready, .duplicate]) + } + func testMixedFolderListsRecursiveUnsupportedFilesWithoutFollowingSymlinks() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } @@ -268,6 +381,51 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(batch.skippedCount, 1) } + func testSelectedRootDirectorySymlinkIsNotTraversed() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + try Data("outside".utf8).write(to: outsideDirectory.appendingPathComponent("边界外.pdf")) + let linkedRoot = fixture.outside.appendingPathComponent("链接资料包", isDirectory: true) + try FileManager.default.createSymbolicLink( + at: linkedRoot, + withDestinationURL: outsideDirectory + ) + + let expansion = CourseProjectFileWorker.expandedImportSelection( + from: [linkedRoot], + markdownOnly: false + ) + + XCTAssertTrue(expansion.supported.isEmpty) + XCTAssertTrue(expansion.unsupportedNames.isEmpty) + } + + func testNestedDirectorySymlinkIsNotTraversed() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let selectedRoot = fixture.outside.appendingPathComponent("资料包", isDirectory: true) + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try FileManager.default.createDirectory(at: selectedRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + let safe = selectedRoot.appendingPathComponent("安全.pdf") + try Data("safe".utf8).write(to: safe) + try Data("outside".utf8).write(to: outsideDirectory.appendingPathComponent("边界外.pdf")) + try FileManager.default.createSymbolicLink( + at: selectedRoot.appendingPathComponent("链接目录", isDirectory: true), + withDestinationURL: outsideDirectory + ) + + let expansion = CourseProjectFileWorker.expandedImportSelection( + from: [selectedRoot], + markdownOnly: false + ) + + XCTAssertEqual(expansion.supported, [safe.standardizedFileURL]) + XCTAssertTrue(expansion.unsupportedNames.isEmpty) + } + private func waitForStage( _ stage: ConfirmedFileImportStage, in store: WorkspaceStore, From 9ab59c9356fb74d9c10f0feeea4e3e26342c489d Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 02:43:14 +0800 Subject: [PATCH 05/50] =?UTF-8?q?fix:=20=E6=8C=89=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E6=98=BE=E7=A4=BA=E5=AF=BC=E5=85=A5=E9=99=90?= =?UTF-8?q?=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../WeiBei/Views/ConfirmedFileImportView.swift | 9 +++++---- .../ConfirmedFileImportTests.swift | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 59a7a2bbf..418a8fc3b 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -399,9 +399,6 @@ extension WorkspaceStore { reservedSourcesByOriginalName[originalName, default: []].append(url) candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) } - if markdownOnly { - unsupported = unsupported.map { "\($0)(仅支持 Markdown)" } - } return (candidates, unsupported.sorted()) } @@ -643,7 +640,11 @@ struct ConfirmedFileImportView: View { Image(systemName: "nosign") Text(name).lineLimit(1) Spacer() - Text(store.ui("不支持", "Unsupported")) + Text( + batch.importsMarkdownAsNotes + ? store.ui("仅支持 Markdown", "Markdown only") + : store.ui("不支持", "Unsupported") + ) } .weiBeiText(11) .foregroundStyle(WeiBeiTheme.cinnabar) diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index a00925688..1d015e73f 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -238,6 +238,22 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(try ImportFileCopy.collision(from: source, into: destination), .duplicate) } + func testMarkdownOnlyPlanKeepsUnsupportedFilenameUnlocalized() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let unsupported = fixture.outside.appendingPathComponent("讲义.pdf") + try Data("pdf".utf8).write(to: unsupported) + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [unsupported], + destination: fixture.library.appendingPathComponent("通用笔记", isDirectory: true), + markdownOnly: true + ) + + XCTAssertTrue(plan.candidates.isEmpty) + XCTAssertEqual(plan.unsupportedNames, ["讲义.pdf"]) + } + func testSameNameInsideBatchIsShownAsConflictBeforeConfirmation() throws { let root = FileManager.default.temporaryDirectory .appendingPathComponent("weibei-confirmed-batch-collision-\(UUID().uuidString)", isDirectory: true) From deb71f0c18c3a52227d3221c9ada5cd9aaedb893 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 03:10:03 +0800 Subject: [PATCH 06/50] =?UTF-8?q?fix:=20=E6=8C=89=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E5=8C=BA=E5=88=86=20Markdown=20=E8=B5=84?= =?UTF-8?q?=E6=96=99=E4=B8=8E=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Stores/WorkspaceStore+CourseLibrary.swift | 2 +- .../WorkspaceStore+CourseMaintenance.swift | 6 ++-- .../Stores/WorkspaceStore+LibraryRoot.swift | 4 +-- .../ConfirmedFileImportTests.swift | 35 +++++++++++++++++++ .../CourseProjectRootSelfCheck.swift | 29 ++++++--------- .../FileModelPhase0BaselineTests.swift | 6 ++-- .../LibraryMigrationSafetyTests.swift | 2 +- .../PoetryIncidentRegressionTests.swift | 2 +- .../TransientToleranceSafetyTests.swift | 4 +-- .../WriteGateSafetyTests.swift | 6 ++-- 10 files changed, 60 insertions(+), 36 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift b/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift index 76988cb30..4193b6ec6 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift @@ -2914,7 +2914,7 @@ extension WorkspaceStore { urlPath: resolvedTarget.path, importedFileIdentity: targetIdentity, isSample: false, - isNotebookNote: role == .note || detectedKind == .markdown, + isNotebookNote: role == .note, appearsInMaterials: role == .material, storage: itemStorage, contentRevision: replacingItemIndex == nil diff --git a/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift b/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift index 98568f043..939187211 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift @@ -420,7 +420,6 @@ extension WorkspaceStore { relativePath: "\(directoryName)/\(observation.relativePath)" ) - nextItem.isNotebookNote = isNote || nextItem.kind == .markdown nextItem.appearsInMaterials = nextItem.appearsInMaterials ?? !isNote nextItem.contentRevision = revision nextItem.contentDigest = digest @@ -452,7 +451,7 @@ extension WorkspaceStore { urlPath: observation.url.path, importedFileIdentity: observation.identity, isSample: false, - isNotebookNote: isNote || StudyItemKind.detect(from: observation.url) == .markdown, + isNotebookNote: isNote, appearsInMaterials: !isNote, storage: .common( relativePath: @@ -758,7 +757,6 @@ extension WorkspaceStore { nextItem.kind = StudyItemKind.detect(from: observation.url) nextItem.urlPath = observation.url.path nextItem.importedFileIdentity = observation.identity - nextItem.isNotebookNote = observation.isNote || nextItem.kind == .markdown nextItem.appearsInMaterials = nextItem.appearsInMaterials ?? !observation.isNote nextItem.contentRevision = nextRevision nextItem.contentDigest = nextDigest @@ -801,7 +799,7 @@ extension WorkspaceStore { urlPath: observation.url.path, importedFileIdentity: observation.identity, isSample: false, - isNotebookNote: observation.isNote || StudyItemKind.detect(from: observation.url) == .markdown, + isNotebookNote: observation.isNote, appearsInMaterials: !observation.isNote, storage: .courseOwned( ownerCourseID: courseID, diff --git a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift index b16cb7883..8950f1e6b 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift @@ -554,7 +554,7 @@ extension WorkspaceStore { let nextTitle = url.deletingPathExtension().lastPathComponent let nextSubtitle = url.lastPathComponent let nextKind = StudyItemKind.detect(from: url) - let nextRole = Self.isMarkdownFile(url) + let nextRole = importsIntoNotes let nextMaterialVisibility = !importsIntoNotes if importedItems[matchingIndex].isNotebookNote != nextRole { roleChanged = true @@ -583,7 +583,7 @@ extension WorkspaceStore { kind: StudyItemKind.detect(from: url), urlPath: url.path, isSample: false, - isNotebookNote: Self.isMarkdownFile(url), + isNotebookNote: importsIntoNotes, appearsInMaterials: !importsIntoNotes, storage: .common(relativePath: relativePath) ) diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index 1d015e73f..80ff13460 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -116,6 +116,41 @@ final class ConfirmedFileImportTests: XCTestCase { ).isEmpty) } + func testCommonMarkdownStaysMaterialAfterConfirmationOpenAndMaintenance() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("阅读材料.md") + try Data("# 阅读材料\n\n正文".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let imported = try XCTUnwrap(fixture.store.confirmedFileImport?.importedItems.first) + XCTAssertEqual(imported.kind, .markdown) + XCTAssertFalse(imported.isNotebookNote) + XCTAssertTrue(imported.isCourseMaterial) + XCTAssertEqual( + imported.storage, + .common(relativePath: "通用资料/阅读材料.md") + ) + + fixture.store.openSingleConfirmedImport() + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + XCTAssertNotEqual(fixture.store.activeNoteItemID, imported.id) + + try fixture.store.waitForCourseFileOperation { + await fixture.store.reconcileCourseFilesNow() + } + let maintained = try XCTUnwrap( + fixture.store.importedItems.first { $0.id == imported.id } + ) + XCTAssertFalse(maintained.isNotebookNote) + XCTAssertTrue(maintained.isCourseMaterial) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + } + func testDockFileOpenedDuringImportWaitsForNextBatch() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } diff --git a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift index 51d818045..3683db2ed 100644 --- a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift @@ -62,8 +62,8 @@ enum CourseProjectRootSelfCheck { try step("新建课程原子落盘") { try newCourseCreatesAtomicProjectAndManifest() } - try step("Markdown 单文件同时作为文稿与笔记") { - try markdownMaterialUsesOneItemInBothSurfaces() + try step("Markdown 资料保持文稿角色") { + try markdownMaterialStaysMaterialThroughImportRace() } try step("书签失效后仍按本机资料库相对路径打开文稿") { try brokenBookmarkStillOpensInLibraryCourseFile() @@ -174,8 +174,8 @@ enum CourseProjectRootSelfCheck { } @MainActor - private static func markdownMaterialUsesOneItemInBothSurfaces() throws { - let fixture = try Fixture(name: "markdown-dual-surface") + private static func markdownMaterialStaysMaterialThroughImportRace() throws { + let fixture = try Fixture(name: "markdown-material-role") defer { fixture.remove() } let library = try fixture.makeDirectory("课程资料库") let source = fixture.root.appendingPathComponent("第一讲.md") @@ -221,30 +221,21 @@ enum CourseProjectRootSelfCheck { "Markdown 导入失败" ) try check( - item.isCourseMaterial && item.isNotebookNote + item.isCourseMaterial && !item.isNotebookNote && store?.courseMaterials(in: courseID).map(\.id) == [item.id] - && store?.courseNotes(in: courseID).map(\.id) == [item.id] + && store?.courseNotes(in: courseID).isEmpty == true && store?.importedItems.filter({ $0.id == item.id }).count == 1, - "Markdown 没有以同一条目同时出现在文稿和笔记,或扫描竞态产生了重复条目" + "Markdown 资料被错误转成笔记,或扫描竞态产生了重复条目" ) try check(store?.openCourseMaterial(item.id, in: courseID) == true, "文稿入口无法打开") - store?.openCourseNote(item.id, in: courseID) - try store?.waitForCourseNoteLoadsForSelfCheck() - try check(store?.noteText.contains("原始内容") == true, "笔记入口首轮读盘后正文为空") - store?.updateNote("# 第一讲\n\n已同步更新") - store?.flushPendingNotePersistence() - try check( - try String(contentsOf: require(item.url, "Markdown 路径丢失"), encoding: .utf8) - .contains("已同步更新"), - "笔记编辑没有写回文稿对应的同一个文件" - ) try check(store?.flushPendingWorkspaceSave() == true, "工作区保存失败") store = makeStore(fixture: fixture) try check( store?.courseMaterials(in: courseID).map(\.id) == [item.id] - && store?.courseNotes(in: courseID).map(\.id) == [item.id] + && store?.courseNotes(in: courseID).isEmpty == true + && store?.importedItems.first(where: { $0.id == item.id })?.isNotebookNote == false && store?.importedItems.filter({ $0.id == item.id }).count == 1, - "重开后 Markdown 双入口或单文件身份丢失" + "重开后 Markdown 资料角色或单文件身份丢失" ) } diff --git a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift b/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift index cfb95c543..bf83fb656 100644 --- a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift +++ b/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift @@ -57,7 +57,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "外删课") let source = base.appendingPathComponent("诗歌.md") try "原始正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let unsavedInput = "用户正在输入、尚未落盘的新内容" @@ -89,7 +89,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "冲突课") let source = base.appendingPathComponent("笔记.md") try "磁盘版本".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) @@ -171,7 +171,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "移除课") let source = base.appendingPathComponent("草稿.md") try "原稿".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) diff --git a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift b/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift index 07f45b5ed..c919c673a 100644 --- a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift @@ -393,7 +393,7 @@ final class LibraryMigrationSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "挂起课") let source = base.appendingPathComponent("笔记.md") try "原始内容".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) diff --git a/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift b/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift index 78e64e6f1..aac009d72 100644 --- a/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift +++ b/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift @@ -62,7 +62,7 @@ final class PoetryIncidentRegressionTests: XCTestCase { ) throws -> (item: StudyItem, url: URL) { let source = base.appendingPathComponent("诗歌.md") try "# 诗歌\n\n真实正文:山川异域,风月同天。".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) return (imported.item, url) } diff --git a/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift b/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift index 9fe1af779..cf1d1fab2 100644 --- a/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift @@ -109,7 +109,7 @@ final class TransientToleranceSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "断链课") let source = base.appendingPathComponent("笔记.md") try "原始正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) @@ -181,7 +181,7 @@ final class TransientToleranceSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "横幅课") let source = base.appendingPathComponent("笔记.md") try "正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) store.select(itemID: item.id) diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index b1f5be4d0..e484ac28f 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -70,7 +70,7 @@ final class WriteGateSafetyTests: XCTestCase { let source = base.appendingPathComponent("\(fileName ?? "笔记-\(UUID().uuidString)").md") try content.write(to: source, atomically: true, encoding: .utf8) let imported = try await store.importFileIntoCourse( - source, courseID: courseID, role: .material + source, courseID: courseID, role: .note ) let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) return (imported.item, url) @@ -86,7 +86,7 @@ final class WriteGateSafetyTests: XCTestCase { let source = base.appendingPathComponent("\(fileName ?? "笔记-\(UUID().uuidString)").md") try content.write(to: source, atomically: true, encoding: .utf8) let imported = try store.importFileIntoCourseForSelfCheck( - source, courseID: courseID, role: .material + source, courseID: courseID, role: .note ) let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) return (imported.item, url) @@ -292,7 +292,7 @@ final class WriteGateSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "闸门课") let source = base.appendingPathComponent("笔记.md") try "第一版".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let url = try XCTUnwrap(store.resolvedLibraryURL(for: item)) store.noteEditingSession.replaceDocument(with: item.id) From 2a6cc5ea7c4684a544240337dbdb14bf70284b2c Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 03:13:10 +0800 Subject: [PATCH 07/50] =?UTF-8?q?test:=20=E6=98=8E=E7=A1=AE=E5=86=99?= =?UTF-8?q?=E9=97=B8=E9=97=A8=E6=97=A0=E5=9F=BA=E7=BA=BF=E5=9C=BA=E6=99=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index e484ac28f..ddc7498cb 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -146,6 +146,8 @@ final class WriteGateSafetyTests: XCTestCase { let store = try makeStore(base: base, library: library, backupRoot: backupRoot) let courseID = try store.createCourseInLibrary(title: "闸门课") let (item, url) = try importNote(store, base: base, courseID: courseID, content: "原始内容") + // 真实笔记导入会建立可信基线;本场景专门验证“没有基线且无法重读”。 + store.noteBackingContentDigestsByItemID[item.id] = nil try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: url.path) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path) } From bd2b0e7b33c94b43e21d329db6bc71ffbfd27500 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 03:34:28 +0800 Subject: [PATCH 08/50] =?UTF-8?q?=E6=94=B6=E7=B4=A7=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E7=A1=AE=E8=AE=A4=E9=9D=A2=E6=9D=BF=E5=B8=83?= =?UTF-8?q?=E5=B1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 436 +++++++++++------- 1 file changed, 279 insertions(+), 157 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 418a8fc3b..08fa55345 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -524,26 +524,31 @@ struct ConfirmedFileImportView: View { } var body: some View { - VStack(alignment: .leading, spacing: 16) { + VStack(alignment: .leading, spacing: 0) { if let batch { heading(batch) - switch batch.stage { - case .preparing: - Text(store.ui("正在核对文件与目标…", "Checking files and destination…")) - .weiBeiText(13) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .frame(maxWidth: .infinity, minHeight: 220, alignment: .center) - case .reviewing: - review(batch) - case .importing: - progress(batch) - case .finished: - result(batch) + .padding(.horizontal, 22) + .padding(.top, 20) + .padding(.bottom, 15) + Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) + ViewThatFits(in: .vertical) { + stageContent(batch) + .fixedSize(horizontal: false, vertical: true) + ScrollView { + stageContent(batch) + } + .scrollBounceBehavior(.basedOnSize) } + .padding(.horizontal, 22) + .padding(.vertical, 16) + .frame(maxHeight: 350, alignment: .top) + Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) + footer(batch) + .padding(.horizontal, 22) + .padding(.vertical, 13) } } - .padding(24) - .frame(width: 540, height: 600, alignment: .topLeading) + .frame(width: 500, alignment: .topLeading) #if targetEnvironment(macCatalyst) .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) #endif @@ -565,16 +570,83 @@ struct ConfirmedFileImportView: View { } } + @ViewBuilder + private func stageContent(_ batch: ConfirmedFileImportBatch) -> some View { + switch batch.stage { + case .preparing: + HStack(spacing: 10) { + ProgressView().controlSize(.small) + Text(store.ui("正在核对文件与目标…", "Checking files and destination…")) + .weiBeiText(13) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + .frame(maxWidth: .infinity, alignment: .leading) + case .reviewing: + review(batch) + case .importing: + progress(batch) + case .finished: + result(batch) + } + } + + @ViewBuilder + private func footer(_ batch: ConfirmedFileImportBatch) -> some View { + HStack(spacing: 8) { + Spacer(minLength: 0) + switch batch.stage { + case .preparing: + Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + .keyboardShortcut(.cancelAction) + case .reviewing: + Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + .keyboardShortcut(.cancelAction) + Button(store.ui("导入", "Import")) { store.confirmFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + .disabled(batch.confirmableCount == 0 || batch.destinationError != nil) + case .importing: + Button(store.ui("停止剩余导入", "Stop Remaining")) { + store.stopConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + case .finished: + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { resultButtons(batch) } + VStack(alignment: .trailing, spacing: 8) { resultButtons(batch) } + } + } + } + } + private func heading(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 5) { - Text(store.ui("确认导入", "Confirm Import")) + Text(headingTitle(batch)) .weiBeiBrandFont(language: store.interfaceLanguage, size: 22, weight: .semibold) - Text(store.ui( - "导入副本,原文件保留。确认前不会复制文件。", - "A copy will be imported and the original kept. Nothing is copied before confirmation." - )) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) + Text(headingDetail(batch)) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + } + + private func headingTitle(_ batch: ConfirmedFileImportBatch) -> String { + switch batch.stage { + case .preparing, .reviewing: store.ui("确认导入", "Confirm Import") + case .importing: store.ui("正在导入", "Importing") + case .finished: store.ui("导入结果", "Import Results") + } + } + + private func headingDetail(_ batch: ConfirmedFileImportBatch) -> String { + switch batch.stage { + case .preparing, .reviewing: + store.ui("导入副本,保留原文件。", "Import a copy and keep the original.") + case .importing: + destinationDescription(batch) + case .finished: + store.ui("已完成的导入已经保留。", "Completed imports have been kept.") } } @@ -586,17 +658,7 @@ struct ConfirmedFileImportView: View { Label(error, systemImage: "exclamationmark.triangle") .weiBeiText(12) .foregroundStyle(WeiBeiTheme.cinnabar) - } - Spacer(minLength: 0) - HStack { - Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } - .buttonStyle(WeiBeiTextActionButtonStyle()) - .keyboardShortcut(.cancelAction) - Spacer() - Button(confirmTitle(batch)) { store.confirmFileImport() } - .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) - .keyboardShortcut(.defaultAction) - .disabled(batch.confirmableCount == 0 || batch.destinationError != nil) + .fixedSize(horizontal: false, vertical: true) } } } @@ -617,41 +679,18 @@ struct ConfirmedFileImportView: View { .foregroundStyle(WeiBeiTheme.tertiaryInk) .lineLimit(2) } - ScrollView { - VStack(alignment: .leading, spacing: 7) { - ForEach(batch.candidates) { candidate in - HStack(alignment: .firstTextBaseline, spacing: 8) { - Image(systemName: StudyItemKind.detect(from: candidate.sourceURL).systemImage) - .foregroundStyle(WeiBeiTheme.secondaryInk) - Text(candidate.sourceURL.lastPathComponent) - .weiBeiText(12) - .lineLimit(1) - Spacer(minLength: 8) - Text(StudyItemKind.detect(from: candidate.sourceURL).label(language: store.interfaceLanguage)) - .weiBeiText(10.5) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - Text(candidateLabel(candidate)) - .weiBeiText(10.5, weight: .medium) - .foregroundStyle(candidateColor(candidate)) - } - } - ForEach(batch.unsupportedNames, id: \.self) { name in - HStack(spacing: 8) { - Image(systemName: "nosign") - Text(name).lineLimit(1) - Spacer() - Text( - batch.importsMarkdownAsNotes - ? store.ui("仅支持 Markdown", "Markdown only") - : store.ui("不支持", "Unsupported") - ) - } - .weiBeiText(11) - .foregroundStyle(WeiBeiTheme.cinnabar) + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(batch.candidates.enumerated()), id: \.element.id) { index, candidate in + if index > 0 { Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) } + candidateRow(candidate) + } + ForEach(Array(batch.unsupportedNames.enumerated()), id: \.offset) { index, name in + if !batch.candidates.isEmpty || index > 0 { + Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) } + unsupportedRow(name, asNotes: batch.importsMarkdownAsNotes) } } - .frame(maxHeight: 150) if !batch.sourceFolderNames.isEmpty { Text(store.ui( "文件夹内仅导入 PDF、Word、PPT、HTML、文本和 Markdown;隐藏文件与应用包会跳过。", @@ -661,45 +700,100 @@ struct ConfirmedFileImportView: View { .foregroundStyle(WeiBeiTheme.tertiaryInk) } } - .padding(12) - .weibeiEtchedBackground( - fill: WeiBeiTheme.paperRaised.opacity(0.30), - stroke: WeiBeiTheme.hairline.opacity(0.28), - cornerRadius: 12 - ) + } + + private func candidateRow(_ candidate: ConfirmedFileImportCandidate) -> some View { + let kind = StudyItemKind.detect(from: candidate.sourceURL) + return HStack(alignment: .top, spacing: 10) { + Image(systemName: kind.systemImage) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .frame(width: 16) + .padding(.top, 2) + VStack(alignment: .leading, spacing: 3) { + HStack(alignment: .firstTextBaseline, spacing: 10) { + Text(candidate.sourceURL.lastPathComponent) + .weiBeiText(12) + .lineLimit(2) + .truncationMode(.middle) + Spacer(minLength: 6) + Text(kind.label(language: store.interfaceLanguage)) + .weiBeiText(10.5) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .fixedSize() + } + if candidate.disposition != .ready { + Text(candidateLabel(candidate)) + .weiBeiText(10.5, weight: .medium) + .foregroundStyle(candidateColor(candidate)) + .fixedSize(horizontal: false, vertical: true) + } + } + } + .padding(.vertical, 6) + .help(candidate.sourceURL.lastPathComponent) + } + + private func unsupportedRow(_ name: String, asNotes: Bool) -> some View { + HStack(alignment: .top, spacing: 10) { + Image(systemName: "nosign") + .frame(width: 16) + VStack(alignment: .leading, spacing: 3) { + Text(name) + .lineLimit(2) + .truncationMode(.middle) + Text( + asNotes + ? store.ui("仅支持 Markdown,已跳过", "Markdown only; skipped") + : store.ui("不支持,已跳过", "Unsupported; skipped") + ) + .weiBeiText(10.5, weight: .medium) + } + } + .weiBeiText(11) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.vertical, 6) + .help(name) } private func destinationPicker(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 8) { - Text(store.ui("归属", "Destination")) + Text(store.ui("导入到", "Import to")) .weiBeiText(12, weight: .semibold) - WeiBeiSearchField( - text: $courseSearch, - prompt: store.ui("搜索课程", "Search courses"), - isFocused: .constant(false), - fontSize: 12, - focusesOnAppear: false, - chromeHeight: 30 - ) - ScrollView { - VStack(alignment: .leading, spacing: 3) { + if !store.courses.isEmpty { + WeiBeiSearchField( + text: $courseSearch, + prompt: store.ui("搜索课程", "Search courses"), + isFocused: .constant(false), + fontSize: 12, + focusesOnAppear: false, + chromeHeight: 30 + ) + } + VStack(alignment: .leading, spacing: 3) { + destinationButton( + title: batch.importsMarkdownAsNotes + ? store.ui("通用笔记", "Common Notes") + : store.ui("通用资料", "Common Materials"), + courseID: nil, + selected: batch.courseID == nil + ) + ForEach(matchingCourses) { course in destinationButton( - title: batch.importsMarkdownAsNotes - ? store.ui("通用笔记", "Common Notes") - : store.ui("通用资料", "Common Materials"), - courseID: nil, - selected: batch.courseID == nil + title: course.title, + courseID: course.id, + selected: batch.courseID == course.id ) - ForEach(matchingCourses) { course in - destinationButton( - title: course.title, - courseID: course.id, - selected: batch.courseID == course.id - ) - } + } + if !courseSearch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + matchingCourses.isEmpty { + Text(store.ui("没有匹配的课程", "No matching courses")) + .weiBeiText(11) + .foregroundStyle(WeiBeiTheme.tertiaryInk) + .padding(.vertical, 5) + .padding(.horizontal, 8) } } - .frame(maxHeight: 120) Button(store.ui("新建课程…", "Create Course…")) { creatingCourse = true } .buttonStyle(WeiBeiTextActionButtonStyle()) } @@ -707,21 +801,33 @@ struct ConfirmedFileImportView: View { private func destinationButton(title: String, courseID: UUID?, selected: Bool) -> some View { Button { store.setConfirmedFileImportDestination(courseID: courseID) } label: { - HStack(spacing: 8) { + HStack(alignment: .top, spacing: 8) { Image(systemName: courseID == nil ? "tray" : "folder") - Text(title).lineLimit(1) - Spacer() + .frame(width: 15) + .padding(.top, 2) + Text(title) + .multilineTextAlignment(.leading) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 8) if selected { Image(systemName: "checkmark") } } + .weiBeiText(12, weight: selected ? .semibold : .regular) + .foregroundStyle(selected ? WeiBeiTheme.cinnabar : WeiBeiTheme.ink) + .padding(.horizontal, 9) + .padding(.vertical, 6) .frame(maxWidth: .infinity, alignment: .leading) + .background( + selected ? WeiBeiTheme.cinnabarSoft : Color.clear, + in: RoundedRectangle(cornerRadius: 8, style: .continuous) + ) + .contentShape(Rectangle()) } - .buttonStyle(WeiBeiTextActionButtonStyle(active: selected, fontSize: 12, height: 30)) + .buttonStyle(.plain) + .help(title) } private func progress(_ batch: ConfirmedFileImportBatch) -> some View { - VStack(alignment: .leading, spacing: 16) { - Text(destinationDescription(batch)) - .weiBeiText(13, weight: .semibold) + VStack(alignment: .leading, spacing: 12) { if let current = batch.currentFileName { Text(current).weiBeiText(12).lineLimit(2) } @@ -737,14 +843,7 @@ struct ConfirmedFileImportView: View { )) .weiBeiText(11) .foregroundStyle(WeiBeiTheme.secondaryInk) - } - Spacer() - HStack { - Spacer() - Button(store.ui("停止剩余导入", "Stop Remaining")) { - store.stopConfirmedFileImport() - } - .buttonStyle(WeiBeiTextActionButtonStyle()) + .fixedSize(horizontal: false, vertical: true) } } } @@ -760,6 +859,7 @@ struct ConfirmedFileImportView: View { Text(store.ui("已停止剩余任务;已完成的导入仍然保留。", "Remaining work stopped; completed imports were kept.")) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) } if !batch.pendingSourceURLs.isEmpty { Text(store.ui( @@ -768,63 +868,85 @@ struct ConfirmedFileImportView: View { )) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) } if !batch.failures.isEmpty { - ScrollView { - VStack(alignment: .leading, spacing: 8) { - ForEach(batch.failures) { failure in - VStack(alignment: .leading, spacing: 3) { - Text(failure.sourceURL.lastPathComponent).weiBeiText(12, weight: .semibold) - Text(failure.message).weiBeiText(11).foregroundStyle(WeiBeiTheme.secondaryInk) - } + VStack(alignment: .leading, spacing: 8) { + Text(store.ui("未导入", "Not imported")) + .weiBeiText(12, weight: .semibold) + ForEach(batch.failures) { failure in + VStack(alignment: .leading, spacing: 3) { + Text(failure.sourceURL.lastPathComponent) + .weiBeiText(12, weight: .semibold) + .lineLimit(2) + .truncationMode(.middle) + Text(failure.message) + .weiBeiText(11) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) } } } - .frame(maxHeight: 220) } - Spacer() - HStack(spacing: 8) { - if !batch.pendingSourceURLs.isEmpty { - Button(store.ui( - batch.failures.isEmpty - ? "处理待导入文件(\(batch.pendingSourceURLs.count))" - : "放弃失败项并处理待导入文件(\(batch.pendingSourceURLs.count))", - batch.failures.isEmpty - ? "Review Waiting Files (\(batch.pendingSourceURLs.count))" - : "Leave Failures and Review Waiting Files (\(batch.pendingSourceURLs.count))" - )) { - store.continuePendingConfirmedFileImport( - abandoningFailures: !batch.failures.isEmpty - ) - } - .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + } + } + + @ViewBuilder + private func resultButtons(_ batch: ConfirmedFileImportBatch) -> some View { + if !batch.pendingSourceURLs.isEmpty { + Button(store.ui("结束本次导入", "End This Import")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + if batch.failures.isEmpty { + Button(store.ui( + "处理待导入文件(\(batch.pendingSourceURLs.count))", + "Review Waiting Files (\(batch.pendingSourceURLs.count))" + )) { + store.continuePendingConfirmedFileImport() } - if !batch.failures.isEmpty { - Button(store.ui("只重试失败项", "Retry Failed Only")) { - store.retryFailedConfirmedFileImport() - } - .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else { + Button(store.ui( + "放弃失败项并继续(\(batch.pendingSourceURLs.count))", + "Leave Failures and Continue (\(batch.pendingSourceURLs.count))" + )) { + store.continuePendingConfirmedFileImport(abandoningFailures: true) } - Spacer() - if batch.pendingSourceURLs.isEmpty, batch.importedItems.count == 1 { - Button(store.ui("打开文稿", "Open Document")) { - store.openSingleConfirmedImport() - } - .buttonStyle(WeiBeiTextActionButtonStyle()) - } else if batch.pendingSourceURLs.isEmpty, batch.importedItems.count > 1 { - Button(store.ui("查看已导入资料", "View Imported Items")) { - store.showConfirmedImportBatch() - } - .buttonStyle(WeiBeiTextActionButtonStyle()) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("只重试失败项", "Retry Failed Only")) { + store.retryFailedConfirmedFileImport() } - Button( - batch.pendingSourceURLs.isEmpty - ? store.ui("完成", "Done") - : store.ui("暂不处理待导入文件", "Leave Waiting Files") - ) { store.dismissConfirmedFileImport() } - .buttonStyle(WeiBeiTextActionButtonStyle()) - .keyboardShortcut(.defaultAction) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } + } else if !batch.failures.isEmpty { + Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("只重试失败项", "Retry Failed Only")) { + store.retryFailedConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else if batch.importedItems.count == 1 { + Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("打开文稿", "Open Document")) { + store.openSingleConfirmedImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else if batch.importedItems.count > 1 { + Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("查看已导入资料", "View Imported Items")) { + store.showConfirmedImportBatch() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else { + Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) } } From db39261ff514ac05267d0f91ea5fd5cb307d9be3 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 03:43:26 +0800 Subject: [PATCH 09/50] =?UTF-8?q?=E8=AE=A9=E5=AF=BC=E5=85=A5=E9=9D=A2?= =?UTF-8?q?=E6=9D=BF=E6=8C=89=E6=AD=A3=E6=96=87=E9=AB=98=E5=BA=A6=E6=94=B6?= =?UTF-8?q?=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 49 ++++++++++++++++--- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 08fa55345..d7078bd85 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -514,6 +514,9 @@ struct ConfirmedFileImportView: View { @EnvironmentObject private var store: WorkspaceStore @State private var courseSearch = "" @State private var creatingCourse = false + @State private var bodyContentHeight: CGFloat = 40 + + private static let maximumBodyHeight: CGFloat = 350 private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } private var matchingCourses: [Course] { @@ -531,17 +534,32 @@ struct ConfirmedFileImportView: View { .padding(.top, 20) .padding(.bottom, 15) Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) - ViewThatFits(in: .vertical) { + ScrollView { stageContent(batch) - .fixedSize(horizontal: false, vertical: true) - ScrollView { - stageContent(batch) + .frame(maxWidth: .infinity, alignment: .leading) + .background { + GeometryReader { geometry in + Color.clear.preference( + key: ConfirmedImportBodyHeightKey.self, + value: geometry.size.height + ) + } + } + } + .scrollDisabled(bodyContentHeight <= Self.maximumBodyHeight) + .scrollBounceBehavior(.basedOnSize) + .frame( + height: min(bodyContentHeight, Self.maximumBodyHeight), + alignment: .top + ) + .onPreferenceChange(ConfirmedImportBodyHeightKey.self) { height in + let measured = max(1, ceil(height)) + if abs(bodyContentHeight - measured) > 0.5 { + bodyContentHeight = measured } - .scrollBounceBehavior(.basedOnSize) } .padding(.horizontal, 22) .padding(.vertical, 16) - .frame(maxHeight: 350, alignment: .top) Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) footer(batch) .padding(.horizontal, 22) @@ -556,6 +574,7 @@ struct ConfirmedFileImportView: View { .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) .foregroundStyle(WeiBeiTheme.ink) .preferredColorScheme(store.appearanceMode.colorScheme) + .modifier(ConfirmedImportFittedPresentation()) .interactiveDismissDisabled(batch?.stage == .importing) .sheet(isPresented: $creatingCourse) { CourseProjectEntrySheet( @@ -980,3 +999,21 @@ struct ConfirmedFileImportView: View { } } } + +private struct ConfirmedImportBodyHeightKey: PreferenceKey { + static var defaultValue: CGFloat = 0 + static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { + value = max(value, nextValue()) + } +} + +private struct ConfirmedImportFittedPresentation: ViewModifier { + @ViewBuilder + func body(content: Content) -> some View { + if #available(iOS 18.0, macOS 15.0, *) { + content.presentationSizing(.fitted) + } else { + content + } + } +} From e4b556b54dff8ca21ea81283d576d3a8fc318625 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 03:49:59 +0800 Subject: [PATCH 10/50] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E9=9D=A2=E6=9D=BF=E5=9B=BA=E6=9C=89=E9=AB=98=E5=BA=A6=E8=A3=81?= =?UTF-8?q?=E5=88=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 30 ++----------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index d7078bd85..6592b0b7b 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -514,7 +514,6 @@ struct ConfirmedFileImportView: View { @EnvironmentObject private var store: WorkspaceStore @State private var courseSearch = "" @State private var creatingCourse = false - @State private var bodyContentHeight: CGFloat = 40 private static let maximumBodyHeight: CGFloat = 350 @@ -537,27 +536,10 @@ struct ConfirmedFileImportView: View { ScrollView { stageContent(batch) .frame(maxWidth: .infinity, alignment: .leading) - .background { - GeometryReader { geometry in - Color.clear.preference( - key: ConfirmedImportBodyHeightKey.self, - value: geometry.size.height - ) - } - } } - .scrollDisabled(bodyContentHeight <= Self.maximumBodyHeight) .scrollBounceBehavior(.basedOnSize) - .frame( - height: min(bodyContentHeight, Self.maximumBodyHeight), - alignment: .top - ) - .onPreferenceChange(ConfirmedImportBodyHeightKey.self) { height in - let measured = max(1, ceil(height)) - if abs(bodyContentHeight - measured) > 0.5 { - bodyContentHeight = measured - } - } + .fixedSize(horizontal: false, vertical: true) + .frame(maxHeight: Self.maximumBodyHeight, alignment: .top) .padding(.horizontal, 22) .padding(.vertical, 16) Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) @@ -567,6 +549,7 @@ struct ConfirmedFileImportView: View { } } .frame(width: 500, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true) #if targetEnvironment(macCatalyst) .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) #endif @@ -1000,13 +983,6 @@ struct ConfirmedFileImportView: View { } } -private struct ConfirmedImportBodyHeightKey: PreferenceKey { - static var defaultValue: CGFloat = 0 - static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { - value = max(value, nextValue()) - } -} - private struct ConfirmedImportFittedPresentation: ViewModifier { @ViewBuilder func body(content: Content) -> some View { From 436fb5109783b016607250757693fab5bec96bbc Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:08:13 +0800 Subject: [PATCH 11/50] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=B5=8B=E9=87=8F?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E9=9D=A2=E6=9D=BF=E6=AD=A3=E6=96=87=E9=AB=98?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 92 ++++++++++++++++++- 1 file changed, 87 insertions(+), 5 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 6592b0b7b..ae4aabb23 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -515,6 +515,7 @@ struct ConfirmedFileImportView: View { @State private var courseSearch = "" @State private var creatingCourse = false + private static let bodyWidth: CGFloat = 456 private static let maximumBodyHeight: CGFloat = 350 private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } @@ -533,13 +534,24 @@ struct ConfirmedFileImportView: View { .padding(.top, 20) .padding(.bottom, 15) Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) - ScrollView { + ConfirmedImportCappedBodyLayout( + width: Self.bodyWidth, + maximumHeight: Self.maximumBodyHeight, + stage: batch.stage + ) { stageContent(batch) - .frame(maxWidth: .infinity, alignment: .leading) + .frame(width: Self.bodyWidth, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .hidden() + .allowsHitTesting(false) + .accessibilityHidden(true) + ScrollView { + stageContent(batch) + .frame(width: Self.bodyWidth, alignment: .leading) + } + .scrollBounceBehavior(.basedOnSize) } - .scrollBounceBehavior(.basedOnSize) - .fixedSize(horizontal: false, vertical: true) - .frame(maxHeight: Self.maximumBodyHeight, alignment: .top) + .clipped() .padding(.horizontal, 22) .padding(.vertical, 16) Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) @@ -983,6 +995,76 @@ struct ConfirmedFileImportView: View { } } +private struct ConfirmedImportCappedBodyLayout: Layout { + let width: CGFloat + let maximumHeight: CGFloat + let stage: ConfirmedFileImportStage + + struct Cache { + var lastLoggedContentHeight: CGFloat? + var lastLoggedSize: CGSize? + } + + func makeCache(subviews: Subviews) -> Cache { Cache() } + + func sizeThatFits( + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout Cache + ) -> CGSize { + guard let measurement = subviews.first else { return .zero } + let contentSize = measurement.sizeThatFits( + ProposedViewSize(width: width, height: nil) + ) + let result = CGSize( + width: width, + height: min(maximumHeight, max(1, ceil(contentSize.height))) + ) + logMeasurementIfNeeded(contentHeight: contentSize.height, result: result, cache: &cache) + return result + } + + func placeSubviews( + in bounds: CGRect, + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout Cache + ) { + guard subviews.count == 2 else { return } + let contentSize = subviews[0].sizeThatFits( + ProposedViewSize(width: width, height: nil) + ) + subviews[0].place( + at: bounds.origin, + anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: contentSize.height) + ) + subviews[1].place( + at: bounds.origin, + anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: bounds.height) + ) + } + + private func logMeasurementIfNeeded( + contentHeight: CGFloat, + result: CGSize, + cache: inout Cache + ) { + let roundedContentHeight = ceil(contentHeight) + guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926", + cache.lastLoggedContentHeight != roundedContentHeight + || cache.lastLoggedSize != result else { return } + cache.lastLoggedContentHeight = roundedContentHeight + cache.lastLoggedSize = result + print( + "[ConfirmedImportLayout] stage=\(stage) " + + "contentHeight=\(roundedContentHeight) " + + "viewport=\(result.width)x\(result.height)" + ) + } +} + private struct ConfirmedImportFittedPresentation: ViewModifier { @ViewBuilder func body(content: Content) -> some View { From 2365177f3d2a8b3ac8e2d652754183c543c38496 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:09:21 +0800 Subject: [PATCH 12/50] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=B8=83=E5=B1=80=E4=B8=B4=E6=97=B6=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 58 +++---------------- 1 file changed, 7 insertions(+), 51 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index ae4aabb23..2925148c8 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -536,8 +536,7 @@ struct ConfirmedFileImportView: View { Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) ConfirmedImportCappedBodyLayout( width: Self.bodyWidth, - maximumHeight: Self.maximumBodyHeight, - stage: batch.stage + maximumHeight: Self.maximumBodyHeight ) { stageContent(batch) .frame(width: Self.bodyWidth, alignment: .leading) @@ -998,46 +997,21 @@ struct ConfirmedFileImportView: View { private struct ConfirmedImportCappedBodyLayout: Layout { let width: CGFloat let maximumHeight: CGFloat - let stage: ConfirmedFileImportStage - struct Cache { - var lastLoggedContentHeight: CGFloat? - var lastLoggedSize: CGSize? - } - - func makeCache(subviews: Subviews) -> Cache { Cache() } - - func sizeThatFits( - proposal: ProposedViewSize, - subviews: Subviews, - cache: inout Cache - ) -> CGSize { + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { guard let measurement = subviews.first else { return .zero } - let contentSize = measurement.sizeThatFits( + let contentHeight = measurement.sizeThatFits( ProposedViewSize(width: width, height: nil) - ) - let result = CGSize( - width: width, - height: min(maximumHeight, max(1, ceil(contentSize.height))) - ) - logMeasurementIfNeeded(contentHeight: contentSize.height, result: result, cache: &cache) - return result + ).height + return CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) } - func placeSubviews( - in bounds: CGRect, - proposal: ProposedViewSize, - subviews: Subviews, - cache: inout Cache - ) { + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { guard subviews.count == 2 else { return } - let contentSize = subviews[0].sizeThatFits( - ProposedViewSize(width: width, height: nil) - ) subviews[0].place( at: bounds.origin, anchor: .topLeading, - proposal: ProposedViewSize(width: width, height: contentSize.height) + proposal: ProposedViewSize(width: width, height: nil) ) subviews[1].place( at: bounds.origin, @@ -1045,24 +1019,6 @@ private struct ConfirmedImportCappedBodyLayout: Layout { proposal: ProposedViewSize(width: width, height: bounds.height) ) } - - private func logMeasurementIfNeeded( - contentHeight: CGFloat, - result: CGSize, - cache: inout Cache - ) { - let roundedContentHeight = ceil(contentHeight) - guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926", - cache.lastLoggedContentHeight != roundedContentHeight - || cache.lastLoggedSize != result else { return } - cache.lastLoggedContentHeight = roundedContentHeight - cache.lastLoggedSize = result - print( - "[ConfirmedImportLayout] stage=\(stage) " - + "contentHeight=\(roundedContentHeight) " - + "viewport=\(result.width)x\(result.height)" - ) - } } private struct ConfirmedImportFittedPresentation: ViewModifier { From be1649bfdaadc83501360d06d7922e4c552d3a73 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:17:28 +0800 Subject: [PATCH 13/50] =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=AE=8C=E6=95=B4=E5=B0=BA=E5=AF=B8=E9=93=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 77 +++++++++++++++- .../Views/ConfirmedFileImportView.swift | 88 +++++++++++++++++-- 2 files changed, 159 insertions(+), 6 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 902212cbd..576e9de77 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -586,10 +586,17 @@ struct CatalystWindowChrome: UIViewRepresentable { // SwiftUI's Mac Catalyst sheet is hosted in a separate UIKit window. struct CatalystSheetBackground: UIViewRepresentable { let color: UIColor + var diagnosticContext: String? = nil func makeUIView(context: Context) -> Probe { Probe() } - func updateUIView(_ view: Probe, context: Context) { view.color = color; view.configure() } + func updateUIView(_ view: Probe, context: Context) { + view.color = color + view.diagnosticContext = diagnosticContext + view.configure() + } final class Probe: UIView { var color = UIColor.clear + var diagnosticContext: String? + private var lastDiagnosticSignature: String? override func didMoveToWindow() { super.didMoveToWindow(); configure() } func configure() { guard let window else { return } @@ -601,6 +608,74 @@ struct CatalystSheetBackground: UIViewRepresentable { } responder = current.next } + recordDiagnostics(window: window) + } + + private func recordDiagnostics(window: UIWindow) { + guard diagnosticContext != nil else { return } + var controllerRecords: [[String: Any]] = [] + var controllerSignatures: [String] = [] + var controllerIDs = Set() + var responder: UIResponder? = self + while let current = responder { + if let controller = current as? UIViewController, + controllerIDs.insert(ObjectIdentifier(controller)).inserted { + controllerRecords.append(Self.record(for: controller)) + controllerSignatures.append(Self.signature(for: controller)) + } + responder = current.next + } + let root = window.rootViewController + if let root, controllerIDs.insert(ObjectIdentifier(root)).inserted { + controllerRecords.append(Self.record(for: root)) + controllerSignatures.append(Self.signature(for: root)) + } + let rootBounds = root?.view.bounds ?? .zero + let rootPreferred = root?.preferredContentSize ?? .zero + let signature = [ + "\(window.bounds)", + "\(rootBounds)", + "\(rootPreferred)", + controllerSignatures.joined(separator: ";") + ].joined(separator: "|") + guard signature != lastDiagnosticSignature else { return } + lastDiagnosticSignature = signature + ConfirmedImportLayoutDiagnostics.append( + event: "catalyst-sheet", + values: [ + "context": diagnosticContext ?? "", + "windowBounds": Self.record(for: window.bounds), + "rootViewBounds": Self.record(for: rootBounds), + "rootPreferredContentSize": Self.record(for: rootPreferred), + "rootControllerType": root.map { String(reflecting: type(of: $0)) } ?? "", + "responderControllers": controllerRecords + ] + ) + } + + private static func record(for controller: UIViewController) -> [String: Any] { + [ + "type": String(reflecting: type(of: controller)), + "viewBounds": record(for: controller.view.bounds), + "preferredContentSize": record(for: controller.preferredContentSize) + ] + } + + private static func signature(for controller: UIViewController) -> String { + "\(String(reflecting: type(of: controller)))|\(controller.view.bounds)|\(controller.preferredContentSize)" + } + + private static func record(for rect: CGRect) -> [String: Any] { + [ + "x": rect.origin.x, + "y": rect.origin.y, + "width": rect.size.width, + "height": rect.size.height + ] + } + + private static func record(for size: CGSize) -> [String: Any] { + ["width": size.width, "height": size.height] } } } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 2925148c8..fcc592e8f 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -536,7 +536,8 @@ struct ConfirmedFileImportView: View { Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) ConfirmedImportCappedBodyLayout( width: Self.bodyWidth, - maximumHeight: Self.maximumBodyHeight + maximumHeight: Self.maximumBodyHeight, + stage: batch.stage ) { stageContent(batch) .frame(width: Self.bodyWidth, alignment: .leading) @@ -561,8 +562,19 @@ struct ConfirmedFileImportView: View { } .frame(width: 500, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true) + .background { + GeometryReader { geometry in + Color.clear + .onAppear { logRootSize(geometry.size) } + .onChange(of: geometry.size) { _, size in logRootSize(size) } + .onChange(of: batch?.stage) { _, _ in logRootSize(geometry.size) } + } + } #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) + .background(CatalystSheetBackground( + color: WeiBeiNativePalette.paper(), + diagnosticContext: "confirmed-file-import" + )) #endif .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) @@ -992,21 +1004,61 @@ struct ConfirmedFileImportView: View { case .conflict: WeiBeiTheme.cinnabar } } + + private func logRootSize(_ size: CGSize) { + ConfirmedImportLayoutDiagnostics.append( + event: "root-view", + values: [ + "stage": String(describing: batch?.stage), + "width": size.width, + "height": size.height + ] + ) + } } private struct ConfirmedImportCappedBodyLayout: Layout { let width: CGFloat let maximumHeight: CGFloat + let stage: ConfirmedFileImportStage - func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + struct Cache { + var lastStage: ConfirmedFileImportStage? + var lastContentHeight: CGFloat? + var lastResult: CGSize? + } + + func makeCache(subviews: Subviews) -> Cache { Cache() } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) -> CGSize { guard let measurement = subviews.first else { return .zero } let contentHeight = measurement.sizeThatFits( ProposedViewSize(width: width, height: nil) ).height - return CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) + let result = CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) + let roundedContentHeight = ceil(contentHeight) + if cache.lastStage != stage + || cache.lastContentHeight != roundedContentHeight + || cache.lastResult != result { + cache.lastStage = stage + cache.lastContentHeight = roundedContentHeight + cache.lastResult = result + ConfirmedImportLayoutDiagnostics.append( + event: "body-layout", + values: [ + "stage": String(describing: stage), + "contentHeight": roundedContentHeight, + "resultWidth": result.width, + "resultHeight": result.height, + "proposalWidth": proposal.width.map { $0 as Any } ?? NSNull(), + "proposalHeight": proposal.height.map { $0 as Any } ?? NSNull() + ] + ) + } + return result } - func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) { guard subviews.count == 2 else { return } subviews[0].place( at: bounds.origin, @@ -1021,6 +1073,32 @@ private struct ConfirmedImportCappedBodyLayout: Layout { } } +enum ConfirmedImportLayoutDiagnostics { + private static let qaBundleIdentifier = "com.changfenhuang.weibei.qa.cursorcloseout20260926" + private static let outputURL = URL(fileURLWithPath: "/tmp/weibei-import-layout-diagnostics.jsonl") + + static func append(event: String, values: [String: Any]) { + guard Bundle.main.bundleIdentifier == qaBundleIdentifier else { return } + var record = values + record["event"] = event + record["timestamp"] = Date().timeIntervalSince1970 + guard let data = try? JSONSerialization.data(withJSONObject: record), + let lineBreak = "\n".data(using: .utf8) else { return } + if !FileManager.default.fileExists(atPath: outputURL.path) { + FileManager.default.createFile(atPath: outputURL.path, contents: nil) + } + guard let handle = try? FileHandle(forWritingTo: outputURL) else { return } + defer { try? handle.close() } + do { + try handle.seekToEnd() + try handle.write(contentsOf: data) + try handle.write(contentsOf: lineBreak) + } catch { + return + } + } +} + private struct ConfirmedImportFittedPresentation: ViewModifier { @ViewBuilder func body(content: Content) -> some View { From ec28145bddc6a2bfa0a223cf61693611d4d75d96 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:27:52 +0800 Subject: [PATCH 14/50] =?UTF-8?q?=E8=AE=A9=E5=AF=BC=E5=85=A5=E5=BC=B9?= =?UTF-8?q?=E7=AA=97=E6=8C=81=E7=BB=AD=E8=B7=9F=E9=9A=8F=E9=A6=96=E9=80=89?= =?UTF-8?q?=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 576e9de77..5b2600a19 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -612,7 +612,7 @@ struct CatalystSheetBackground: UIViewRepresentable { } private func recordDiagnostics(window: UIWindow) { - guard diagnosticContext != nil else { return } + guard diagnosticContext == "confirmed-file-import" else { return } var controllerRecords: [[String: Any]] = [] var controllerSignatures: [String] = [] var controllerIDs = Set() @@ -632,10 +632,15 @@ struct CatalystSheetBackground: UIViewRepresentable { } let rootBounds = root?.view.bounds ?? .zero let rootPreferred = root?.preferredContentSize ?? .zero + let presentation = root?.presentationController + let sheetPresentation = root?.sheetPresentationController + let prefersPageSizingBefore = sheetPresentation?.prefersPageSizing + sheetPresentation?.prefersPageSizing = false let signature = [ "\(window.bounds)", "\(rootBounds)", "\(rootPreferred)", + String(describing: prefersPageSizingBefore), controllerSignatures.joined(separator: ";") ].joined(separator: "|") guard signature != lastDiagnosticSignature else { return } @@ -648,7 +653,15 @@ struct CatalystSheetBackground: UIViewRepresentable { "rootViewBounds": Self.record(for: rootBounds), "rootPreferredContentSize": Self.record(for: rootPreferred), "rootControllerType": root.map { String(reflecting: type(of: $0)) } ?? "", - "responderControllers": controllerRecords + "responderControllers": controllerRecords, + "presentationControllerType": presentation.map { + String(reflecting: type(of: $0)) + } ?? "", + "sheetPresentationControllerType": sheetPresentation.map { + String(reflecting: type(of: $0)) + } ?? "", + "prefersPageSizingBefore": prefersPageSizingBefore.map { $0 as Any } ?? NSNull(), + "prefersPageSizingAfter": sheetPresentation?.prefersPageSizing.map { $0 as Any } ?? NSNull() ] ) } From 6ce36005eb71ee4ddc8092e06f62870fe89e8e9a Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:35:42 +0800 Subject: [PATCH 15/50] =?UTF-8?q?=E6=8B=86=E5=88=86=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E8=AF=8A=E6=96=AD=E8=A1=A8=E8=BE=BE=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 45 ++++++++++++++++++----- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 5b2600a19..595e0c143 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -636,6 +636,37 @@ struct CatalystSheetBackground: UIViewRepresentable { let sheetPresentation = root?.sheetPresentationController let prefersPageSizingBefore = sheetPresentation?.prefersPageSizing sheetPresentation?.prefersPageSizing = false + let prefersPageSizingAfter = sheetPresentation?.prefersPageSizing + let rootControllerType: String + let presentationControllerType: String + let sheetPresentationControllerType: String + if let root { + rootControllerType = String(reflecting: type(of: root)) + } else { + rootControllerType = "" + } + if let presentation { + presentationControllerType = String(reflecting: type(of: presentation)) + } else { + presentationControllerType = "" + } + if let sheetPresentation { + sheetPresentationControllerType = String(reflecting: type(of: sheetPresentation)) + } else { + sheetPresentationControllerType = "" + } + let prefersPageSizingBeforeValue: Any + let prefersPageSizingAfterValue: Any + if let prefersPageSizingBefore { + prefersPageSizingBeforeValue = prefersPageSizingBefore + } else { + prefersPageSizingBeforeValue = NSNull() + } + if let prefersPageSizingAfter { + prefersPageSizingAfterValue = prefersPageSizingAfter + } else { + prefersPageSizingAfterValue = NSNull() + } let signature = [ "\(window.bounds)", "\(rootBounds)", @@ -652,16 +683,12 @@ struct CatalystSheetBackground: UIViewRepresentable { "windowBounds": Self.record(for: window.bounds), "rootViewBounds": Self.record(for: rootBounds), "rootPreferredContentSize": Self.record(for: rootPreferred), - "rootControllerType": root.map { String(reflecting: type(of: $0)) } ?? "", + "rootControllerType": rootControllerType, "responderControllers": controllerRecords, - "presentationControllerType": presentation.map { - String(reflecting: type(of: $0)) - } ?? "", - "sheetPresentationControllerType": sheetPresentation.map { - String(reflecting: type(of: $0)) - } ?? "", - "prefersPageSizingBefore": prefersPageSizingBefore.map { $0 as Any } ?? NSNull(), - "prefersPageSizingAfter": sheetPresentation?.prefersPageSizing.map { $0 as Any } ?? NSNull() + "presentationControllerType": presentationControllerType, + "sheetPresentationControllerType": sheetPresentationControllerType, + "prefersPageSizingBefore": prefersPageSizingBeforeValue, + "prefersPageSizingAfter": prefersPageSizingAfterValue ] ) } From 2535bd5c6ac75ca5919ddad9af499e10ec42ddbc Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:41:54 +0800 Subject: [PATCH 16/50] =?UTF-8?q?=E6=8C=89=E5=8E=9F=E7=94=9F=E9=99=84?= =?UTF-8?q?=E5=B1=9E=E7=AA=97=E5=8F=A3=E5=90=8C=E6=AD=A5=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 36 +++++++++++++++------ App/WindowBridge/NativeWindowBridge.swift | 13 ++++++++ App/WindowBridge/WindowBridgeContract.swift | 1 + 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 595e0c143..3b464e572 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -597,7 +597,9 @@ struct CatalystSheetBackground: UIViewRepresentable { var color = UIColor.clear var diagnosticContext: String? private var lastDiagnosticSignature: String? + private var lastResizeDiagnosticSignature: String? override func didMoveToWindow() { super.didMoveToWindow(); configure() } + override func layoutSubviews() { super.layoutSubviews(); configure() } func configure() { guard let window else { return } window.backgroundColor = color @@ -609,6 +611,29 @@ struct CatalystSheetBackground: UIViewRepresentable { responder = current.next } recordDiagnostics(window: window) + resizeImportSheetIfNeeded(window: window) + } + + private func resizeImportSheetIfNeeded(window: UIWindow) { + guard diagnosticContext == "confirmed-file-import", + let preferred = window.rootViewController?.preferredContentSize, + preferred.width.isFinite, preferred.height.isFinite, + preferred.width > 0, preferred.height > 0 else { return } + let result = CatalystDesktopWindow.shared.resizeWorkspaceSheetContent( + width: preferred.width, + height: preferred.height + ) + let signature = "\(preferred)|\(window.bounds)|\(result)" + guard signature != lastResizeDiagnosticSignature else { return } + lastResizeDiagnosticSignature = signature + ConfirmedImportLayoutDiagnostics.append( + event: "native-sheet-resize", + values: [ + "result": result, + "preferredContentSize": Self.record(for: preferred), + "actualWindowBounds": Self.record(for: window.bounds) + ] + ) } private func recordDiagnostics(window: UIWindow) { @@ -635,8 +660,6 @@ struct CatalystSheetBackground: UIViewRepresentable { let presentation = root?.presentationController let sheetPresentation = root?.sheetPresentationController let prefersPageSizingBefore = sheetPresentation?.prefersPageSizing - sheetPresentation?.prefersPageSizing = false - let prefersPageSizingAfter = sheetPresentation?.prefersPageSizing let rootControllerType: String let presentationControllerType: String let sheetPresentationControllerType: String @@ -656,17 +679,11 @@ struct CatalystSheetBackground: UIViewRepresentable { sheetPresentationControllerType = "" } let prefersPageSizingBeforeValue: Any - let prefersPageSizingAfterValue: Any if let prefersPageSizingBefore { prefersPageSizingBeforeValue = prefersPageSizingBefore } else { prefersPageSizingBeforeValue = NSNull() } - if let prefersPageSizingAfter { - prefersPageSizingAfterValue = prefersPageSizingAfter - } else { - prefersPageSizingAfterValue = NSNull() - } let signature = [ "\(window.bounds)", "\(rootBounds)", @@ -687,8 +704,7 @@ struct CatalystSheetBackground: UIViewRepresentable { "responderControllers": controllerRecords, "presentationControllerType": presentationControllerType, "sheetPresentationControllerType": sheetPresentationControllerType, - "prefersPageSizingBefore": prefersPageSizingBeforeValue, - "prefersPageSizingAfter": prefersPageSizingAfterValue + "prefersPageSizingBefore": prefersPageSizingBeforeValue ] ) } diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index b70dff2a2..8c2b04900 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -115,6 +115,19 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { func open(_ url: URL) -> Bool { NSWorkspace.shared.open(url) } func reveal(_ url: URL) { NSWorkspace.shared.activateFileViewerSelecting([url]) } func materialWindowCount() -> Int { materials.count } + @MainActor func resizeWorkspaceSheetContent(width: Double, height: Double) -> Bool { + guard width.isFinite, height.isFinite, width > 0, height > 0, + let keyWindow = NSApp.keyWindow else { return false } + let sheet = keyWindow.isSheet ? keyWindow : keyWindow.attachedSheet + guard let sheet, sheet.isSheet, + sheet.sheetParent?.toolbar?.identifier == "weibei.workspace" else { return false } + let requested = NSSize(width: width, height: height) + let actual = sheet.contentLayoutRect.size + if abs(actual.width - requested.width) >= 1 || abs(actual.height - requested.height) >= 1 { + sheet.setContentSize(requested) + } + return true + } @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) { updateObservation = updateService.$status.combineLatest(updateService.$availableUpdate) .sink { status, update in diff --git a/App/WindowBridge/WindowBridgeContract.swift b/App/WindowBridge/WindowBridgeContract.swift index da39141c2..3f3c9d678 100644 --- a/App/WindowBridge/WindowBridgeContract.swift +++ b/App/WindowBridge/WindowBridgeContract.swift @@ -10,6 +10,7 @@ import Foundation func open(_ url: URL) -> Bool func reveal(_ url: URL) func materialWindowCount() -> Int + @MainActor func resizeWorkspaceSheetContent(width: Double, height: Double) -> Bool @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) @MainActor func checkForUpdates() @MainActor func installAvailableUpdate() From 7791118dcd61bcb94cd3cbcf6e04d21e05e77a9d Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:46:20 +0800 Subject: [PATCH 17/50] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=20Markdown=20=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E9=80=89=E6=8B=A9=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 8 ++++---- Sources/WeiBei/Support/WorkspaceFileDialog.swift | 5 +++++ Sources/WeiBei/Views/CourseWorkspaceComponents.swift | 5 ++--- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index a4bc1803b..b4211ff7e 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -5947,8 +5947,8 @@ final class WorkspaceStore: ObservableObject { #if targetEnvironment(macCatalyst) Task { @MainActor in let types: [UTType] = markdownAsNotes - ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] + ? [WorkspaceFileDialog.markdownType, .folder] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, WorkspaceFileDialog.markdownType, .folder] let urls = await WorkspaceFileDialog.pick( title: panelTitle ?? ui("选择学习资料或课程文件夹", "Choose study materials or a course folder"), types: types, multiple: true @@ -5969,8 +5969,8 @@ final class WorkspaceStore: ObservableObject { panel.canChooseDirectories = true panel.canChooseFiles = true panel.allowedContentTypes = markdownAsNotes - ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] + ? [WorkspaceFileDialog.markdownType] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, WorkspaceFileDialog.markdownType] guard panel.runModal() == .OK else { return } prepareConfirmedFileImport( diff --git a/Sources/WeiBei/Support/WorkspaceFileDialog.swift b/Sources/WeiBei/Support/WorkspaceFileDialog.swift index ec89ca286..61067598a 100644 --- a/Sources/WeiBei/Support/WorkspaceFileDialog.swift +++ b/Sources/WeiBei/Support/WorkspaceFileDialog.swift @@ -9,6 +9,11 @@ import AppKit /// The same file-operation choices on both hosts. A dismissed dialog cancels. @MainActor enum WorkspaceFileDialog { + static let markdownType = UTType( + importedAs: "net.daringfireball.markdown", + conformingTo: .plainText + ) + struct Choice { let index: Int let text: String? diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 4e0180014..5f9bf05db 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -720,7 +720,7 @@ struct CourseProjectEntrySheet: View { private func chooseImportContentWithPicker() async { #if targetEnvironment(macCatalyst) - let urls = await WorkspaceFileDialog.pick(title: store.ui("选择课程内容", "Choose Course Content"), types: [.folder, .pdf, .html, .plainText, UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation")], multiple: true) + let urls = await WorkspaceFileDialog.pick(title: store.ui("选择课程内容", "Choose Course Content"), types: [.folder, .pdf, .html, .plainText, WorkspaceFileDialog.markdownType, UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation")], multiple: true) #else let panel = NSOpenPanel() panel.title = store.ui("选择课程内容", "Choose Course Content") @@ -738,8 +738,7 @@ struct CourseProjectEntrySheet: View { .pdf, .html, .plainText, - UTType(filenameExtension: "md") ?? .plainText, - UTType(filenameExtension: "markdown") ?? .plainText, + WorkspaceFileDialog.markdownType, ] guard panel.runModal() == .OK else { return } let urls = panel.urls From a46f08375d65971cd1f7da058eec0f566c1670fa Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:49:46 +0800 Subject: [PATCH 18/50] =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E9=99=84=E5=B1=9E=E7=AA=97=E5=8F=A3=E5=8E=9F=E7=94=9F=E5=87=A0?= =?UTF-8?q?=E4=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 22 ++++++- App/WindowBridge/NativeWindowBridge.swift | 79 +++++++++++++++++++++++ 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 3b464e572..defcf8660 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -623,6 +623,23 @@ struct CatalystSheetBackground: UIViewRepresentable { width: preferred.width, height: preferred.height ) + let scene = window.windowScene + var sceneWindowRecords: [[String: Any]] = [] + if let scene { + for sceneWindow in scene.windows { + let rootType: String + if let root = sceneWindow.rootViewController { + rootType = String(reflecting: type(of: root)) + } else { + rootType = "" + } + sceneWindowRecords.append([ + "isSourceWindow": sceneWindow === window, + "bounds": Self.record(for: sceneWindow.bounds), + "rootControllerType": rootType + ]) + } + } let signature = "\(preferred)|\(window.bounds)|\(result)" guard signature != lastResizeDiagnosticSignature else { return } lastResizeDiagnosticSignature = signature @@ -631,7 +648,10 @@ struct CatalystSheetBackground: UIViewRepresentable { values: [ "result": result, "preferredContentSize": Self.record(for: preferred), - "actualWindowBounds": Self.record(for: window.bounds) + "actualWindowBounds": Self.record(for: window.bounds), + "sceneIdentifier": scene?.session.persistentIdentifier ?? "", + "sceneEffectiveFrame": Self.record(for: scene?.effectiveGeometry.systemFrame ?? .zero), + "sceneWindows": sceneWindowRecords ] ) } diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index 8c2b04900..42da9ef3e 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -8,6 +8,7 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { private var intensity = 1.0 private let materials = NSMapTable.weakToStrongObjects() private var observers: [NSObjectProtocol] = [] + private var lastSheetResizeDiagnosticSignature: String? @MainActor private lazy var updateService = WeiBeiUpdateService() @MainActor private var updateObservation: AnyCancellable? @@ -123,11 +124,89 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { sheet.sheetParent?.toolbar?.identifier == "weibei.workspace" else { return false } let requested = NSSize(width: width, height: height) let actual = sheet.contentLayoutRect.size + let diagnosticSignature = "\(sheet.windowNumber)|\(requested)|\(actual)|\(sheet.frame)" + let shouldRecord = diagnosticSignature != lastSheetResizeDiagnosticSignature + if shouldRecord { + lastSheetResizeDiagnosticSignature = diagnosticSignature + recordSheetResize(event: "native-appkit-sheet-before", sheet: sheet, requested: requested) + } if abs(actual.width - requested.width) >= 1 || abs(actual.height - requested.height) >= 1 { sheet.setContentSize(requested) } + if shouldRecord { + recordSheetResize(event: "native-appkit-sheet-after-immediate", sheet: sheet, requested: requested) + DispatchQueue.main.async { [weak self, weak sheet] in + guard let self, let sheet else { return } + self.recordSheetResize( + event: "native-appkit-sheet-after-next-runloop", + sheet: sheet, + requested: requested + ) + } + } return true } + + @MainActor private func recordSheetResize(event: String, sheet: NSWindow, requested: NSSize) { + guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926" else { + return + } + let outputURL = URL(fileURLWithPath: "/tmp/weibei-import-layout-diagnostics.jsonl") + let parent = sheet.sheetParent + let record: [String: Any] = [ + "event": event, + "timestamp": Date().timeIntervalSince1970, + "requested": Self.diagnosticSize(requested), + "windowClass": NSStringFromClass(type(of: sheet)), + "isKey": sheet.isKeyWindow, + "isVisible": sheet.isVisible, + "windowNumber": sheet.windowNumber, + "sheetParentWindowNumber": parent?.windowNumber ?? -1, + "frame": Self.diagnosticRect(sheet.frame), + "contentLayoutRect": Self.diagnosticRect(sheet.contentLayoutRect), + "contentViewBounds": Self.diagnosticRect(sheet.contentView?.bounds ?? .zero), + "minSize": Self.diagnosticSize(sheet.minSize), + "maxSize": Self.diagnosticSize(sheet.maxSize), + "contentMinSize": Self.diagnosticSize(sheet.contentMinSize), + "contentMaxSize": Self.diagnosticSize(sheet.contentMaxSize) + ] + guard let data = try? JSONSerialization.data(withJSONObject: record) else { return } + if !FileManager.default.fileExists(atPath: outputURL.path) { + FileManager.default.createFile(atPath: outputURL.path, contents: nil) + } + guard let handle = try? FileHandle(forWritingTo: outputURL) else { return } + defer { try? handle.close() } + do { + try handle.seekToEnd() + try handle.write(contentsOf: data + Data([0x0A])) + } catch { + return + } + } + + private static func diagnosticRect(_ rect: NSRect) -> [String: Any] { + [ + "x": diagnosticNumber(rect.origin.x), + "y": diagnosticNumber(rect.origin.y), + "width": diagnosticNumber(rect.size.width), + "height": diagnosticNumber(rect.size.height) + ] + } + + private static func diagnosticSize(_ size: NSSize) -> [String: Any] { + [ + "width": diagnosticNumber(size.width), + "height": diagnosticNumber(size.height) + ] + } + + private static func diagnosticNumber(_ value: CGFloat) -> Any { + if value.isFinite { + return Double(value) + } + return String(describing: value) + } + @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) { updateObservation = updateService.$status.combineLatest(updateService.$availableUpdate) .sink { status, update in From e5c78db2cc2b22d2a04a9122f601f0547302a8f4 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 10:57:40 +0800 Subject: [PATCH 19/50] =?UTF-8?q?=E6=8C=89=E7=8B=AC=E7=AB=8B=E5=9C=BA?= =?UTF-8?q?=E6=99=AF=E5=90=8C=E6=AD=A5=E5=AF=BC=E5=85=A5=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 113 ++++++++++++++------ App/WindowBridge/NativeWindowBridge.swift | 92 ---------------- App/WindowBridge/WindowBridgeContract.swift | 1 - 3 files changed, 82 insertions(+), 124 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index defcf8660..dc125312a 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -597,7 +597,7 @@ struct CatalystSheetBackground: UIViewRepresentable { var color = UIColor.clear var diagnosticContext: String? private var lastDiagnosticSignature: String? - private var lastResizeDiagnosticSignature: String? + private var lastGeometryRequestSignature: String? override func didMoveToWindow() { super.didMoveToWindow(); configure() } override func layoutSubviews() { super.layoutSubviews(); configure() } func configure() { @@ -618,42 +618,80 @@ struct CatalystSheetBackground: UIViewRepresentable { guard diagnosticContext == "confirmed-file-import", let preferred = window.rootViewController?.preferredContentSize, preferred.width.isFinite, preferred.height.isFinite, - preferred.width > 0, preferred.height > 0 else { return } - let result = CatalystDesktopWindow.shared.resizeWorkspaceSheetContent( - width: preferred.width, - height: preferred.height + preferred.width > 0, preferred.height > 0, + !Self.sameSize(window.bounds.size, preferred), + let scene = window.windowScene else { return } + let sourceFrame = scene.effectiveGeometry.systemFrame + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard Self.sameSize(sourceFrame.size, window.bounds.size), + rootedWindows.count == 1, + rootedWindows[0] === window else { return } + let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) + let signature = "\(sourceFrame)|\(targetFrame)" + guard signature != lastGeometryRequestSignature else { return } + lastGeometryRequestSignature = signature + ConfirmedImportLayoutDiagnostics.append( + event: "scene-geometry-update-scheduled", + values: [ + "sceneIdentifier": scene.session.persistentIdentifier, + "sourceFrame": Self.record(for: sourceFrame), + "targetFrame": Self.record(for: targetFrame), + "sourceWindowBounds": Self.record(for: window.bounds) + ] ) - let scene = window.windowScene - var sceneWindowRecords: [[String: Any]] = [] - if let scene { - for sceneWindow in scene.windows { - let rootType: String - if let root = sceneWindow.rootViewController { - rootType = String(reflecting: type(of: root)) - } else { - rootType = "" - } - sceneWindowRecords.append([ - "isSourceWindow": sceneWindow === window, - "bounds": Self.record(for: sceneWindow.bounds), - "rootControllerType": rootType - ]) - } + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self, let window, let scene, + window.windowScene === scene else { return } + self.requestImportSheetGeometryUpdate( + window: window, + scene: scene, + preferred: preferred + ) } - let signature = "\(preferred)|\(window.bounds)|\(result)" - guard signature != lastResizeDiagnosticSignature else { return } - lastResizeDiagnosticSignature = signature + } + + private func requestImportSheetGeometryUpdate( + window: UIWindow, + scene: UIWindowScene, + preferred: CGSize + ) { + let sourceFrame = scene.effectiveGeometry.systemFrame + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard !Self.sameSize(window.bounds.size, preferred), + Self.sameSize(sourceFrame.size, window.bounds.size), + rootedWindows.count == 1, + rootedWindows[0] === window else { return } + let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) ConfirmedImportLayoutDiagnostics.append( - event: "native-sheet-resize", + event: "scene-geometry-update-requested", values: [ - "result": result, - "preferredContentSize": Self.record(for: preferred), - "actualWindowBounds": Self.record(for: window.bounds), - "sceneIdentifier": scene?.session.persistentIdentifier ?? "", - "sceneEffectiveFrame": Self.record(for: scene?.effectiveGeometry.systemFrame ?? .zero), - "sceneWindows": sceneWindowRecords + "sceneIdentifier": scene.session.persistentIdentifier, + "sourceFrame": Self.record(for: sourceFrame), + "targetFrame": Self.record(for: targetFrame) ] ) + scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { error in + ConfirmedImportLayoutDiagnostics.append( + event: "scene-geometry-update-error", + values: [ + "sceneIdentifier": scene.session.persistentIdentifier, + "message": String(describing: error) + ] + ) + } + DispatchQueue.main.async { [weak window, weak scene] in + guard let window, let scene else { return } + ConfirmedImportLayoutDiagnostics.append( + event: "scene-geometry-update-result", + values: [ + "sceneIdentifier": scene.session.persistentIdentifier, + "effectiveFrame": Self.record(for: scene.effectiveGeometry.systemFrame), + "sourceWindowBounds": Self.record(for: window.bounds), + "preferredContentSize": Self.record(for: preferred), + "matchesPreferred": Self.sameSize(window.bounds.size, preferred) + ] + ) + } } private func recordDiagnostics(window: UIWindow) { @@ -753,5 +791,18 @@ struct CatalystSheetBackground: UIViewRepresentable { private static func record(for size: CGSize) -> [String: Any] { ["width": size.width, "height": size.height] } + + private static func sameSize(_ lhs: CGSize, _ rhs: CGSize) -> Bool { + abs(lhs.width - rhs.width) < 1 && abs(lhs.height - rhs.height) < 1 + } + + private static func centeredFrame(size: CGSize, in frame: CGRect) -> CGRect { + CGRect( + x: frame.midX - size.width / 2, + y: frame.midY - size.height / 2, + width: size.width, + height: size.height + ) + } } } diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index 42da9ef3e..b70dff2a2 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -8,7 +8,6 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { private var intensity = 1.0 private let materials = NSMapTable.weakToStrongObjects() private var observers: [NSObjectProtocol] = [] - private var lastSheetResizeDiagnosticSignature: String? @MainActor private lazy var updateService = WeiBeiUpdateService() @MainActor private var updateObservation: AnyCancellable? @@ -116,97 +115,6 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { func open(_ url: URL) -> Bool { NSWorkspace.shared.open(url) } func reveal(_ url: URL) { NSWorkspace.shared.activateFileViewerSelecting([url]) } func materialWindowCount() -> Int { materials.count } - @MainActor func resizeWorkspaceSheetContent(width: Double, height: Double) -> Bool { - guard width.isFinite, height.isFinite, width > 0, height > 0, - let keyWindow = NSApp.keyWindow else { return false } - let sheet = keyWindow.isSheet ? keyWindow : keyWindow.attachedSheet - guard let sheet, sheet.isSheet, - sheet.sheetParent?.toolbar?.identifier == "weibei.workspace" else { return false } - let requested = NSSize(width: width, height: height) - let actual = sheet.contentLayoutRect.size - let diagnosticSignature = "\(sheet.windowNumber)|\(requested)|\(actual)|\(sheet.frame)" - let shouldRecord = diagnosticSignature != lastSheetResizeDiagnosticSignature - if shouldRecord { - lastSheetResizeDiagnosticSignature = diagnosticSignature - recordSheetResize(event: "native-appkit-sheet-before", sheet: sheet, requested: requested) - } - if abs(actual.width - requested.width) >= 1 || abs(actual.height - requested.height) >= 1 { - sheet.setContentSize(requested) - } - if shouldRecord { - recordSheetResize(event: "native-appkit-sheet-after-immediate", sheet: sheet, requested: requested) - DispatchQueue.main.async { [weak self, weak sheet] in - guard let self, let sheet else { return } - self.recordSheetResize( - event: "native-appkit-sheet-after-next-runloop", - sheet: sheet, - requested: requested - ) - } - } - return true - } - - @MainActor private func recordSheetResize(event: String, sheet: NSWindow, requested: NSSize) { - guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926" else { - return - } - let outputURL = URL(fileURLWithPath: "/tmp/weibei-import-layout-diagnostics.jsonl") - let parent = sheet.sheetParent - let record: [String: Any] = [ - "event": event, - "timestamp": Date().timeIntervalSince1970, - "requested": Self.diagnosticSize(requested), - "windowClass": NSStringFromClass(type(of: sheet)), - "isKey": sheet.isKeyWindow, - "isVisible": sheet.isVisible, - "windowNumber": sheet.windowNumber, - "sheetParentWindowNumber": parent?.windowNumber ?? -1, - "frame": Self.diagnosticRect(sheet.frame), - "contentLayoutRect": Self.diagnosticRect(sheet.contentLayoutRect), - "contentViewBounds": Self.diagnosticRect(sheet.contentView?.bounds ?? .zero), - "minSize": Self.diagnosticSize(sheet.minSize), - "maxSize": Self.diagnosticSize(sheet.maxSize), - "contentMinSize": Self.diagnosticSize(sheet.contentMinSize), - "contentMaxSize": Self.diagnosticSize(sheet.contentMaxSize) - ] - guard let data = try? JSONSerialization.data(withJSONObject: record) else { return } - if !FileManager.default.fileExists(atPath: outputURL.path) { - FileManager.default.createFile(atPath: outputURL.path, contents: nil) - } - guard let handle = try? FileHandle(forWritingTo: outputURL) else { return } - defer { try? handle.close() } - do { - try handle.seekToEnd() - try handle.write(contentsOf: data + Data([0x0A])) - } catch { - return - } - } - - private static func diagnosticRect(_ rect: NSRect) -> [String: Any] { - [ - "x": diagnosticNumber(rect.origin.x), - "y": diagnosticNumber(rect.origin.y), - "width": diagnosticNumber(rect.size.width), - "height": diagnosticNumber(rect.size.height) - ] - } - - private static func diagnosticSize(_ size: NSSize) -> [String: Any] { - [ - "width": diagnosticNumber(size.width), - "height": diagnosticNumber(size.height) - ] - } - - private static func diagnosticNumber(_ value: CGFloat) -> Any { - if value.isFinite { - return Double(value) - } - return String(describing: value) - } - @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) { updateObservation = updateService.$status.combineLatest(updateService.$availableUpdate) .sink { status, update in diff --git a/App/WindowBridge/WindowBridgeContract.swift b/App/WindowBridge/WindowBridgeContract.swift index 3f3c9d678..da39141c2 100644 --- a/App/WindowBridge/WindowBridgeContract.swift +++ b/App/WindowBridge/WindowBridgeContract.swift @@ -10,7 +10,6 @@ import Foundation func open(_ url: URL) -> Bool func reveal(_ url: URL) func materialWindowCount() -> Int - @MainActor func resizeWorkspaceSheetContent(width: Double, height: Double) -> Bool @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) @MainActor func checkForUpdates() @MainActor func installAvailableUpdate() From cddfde24d4c0f431ce66e71a5c3500a2d439fc42 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:09:00 +0800 Subject: [PATCH 20/50] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E5=9C=BA=E6=99=AF=E7=9A=84=E5=AF=BC=E5=85=A5=E7=AA=97=E5=8F=A3?= =?UTF-8?q?=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 104 ++++++++++++++++++++-- 1 file changed, 96 insertions(+), 8 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index dc125312a..11ea8ad95 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -640,12 +640,16 @@ struct CatalystSheetBackground: UIViewRepresentable { ] ) DispatchQueue.main.async { [weak self, weak window, weak scene] in - guard let self, let window, let scene, - window.windowScene === scene else { return } + guard let self else { return } + guard let window, let scene, window.windowScene === scene else { + self.clearGeometryRequest(signature) + return + } self.requestImportSheetGeometryUpdate( window: window, scene: scene, - preferred: preferred + preferred: preferred, + signature: signature ) } } @@ -653,14 +657,18 @@ struct CatalystSheetBackground: UIViewRepresentable { private func requestImportSheetGeometryUpdate( window: UIWindow, scene: UIWindowScene, - preferred: CGSize + preferred: CGSize, + signature: String ) { let sourceFrame = scene.effectiveGeometry.systemFrame let rootedWindows = scene.windows.filter { $0.rootViewController != nil } guard !Self.sameSize(window.bounds.size, preferred), Self.sameSize(sourceFrame.size, window.bounds.size), rootedWindows.count == 1, - rootedWindows[0] === window else { return } + rootedWindows[0] === window else { + clearGeometryRequest(signature) + return + } let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) ConfirmedImportLayoutDiagnostics.append( event: "scene-geometry-update-requested", @@ -670,7 +678,8 @@ struct CatalystSheetBackground: UIViewRepresentable { "targetFrame": Self.record(for: targetFrame) ] ) - scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { error in + scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { [weak self] error in + self?.clearGeometryRequest(signature) ConfirmedImportLayoutDiagnostics.append( event: "scene-geometry-update-error", values: [ @@ -679,18 +688,90 @@ struct CatalystSheetBackground: UIViewRepresentable { ] ) } - DispatchQueue.main.async { [weak window, weak scene] in - guard let window, let scene else { return } + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self, let window, let scene else { return } + let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) ConfirmedImportLayoutDiagnostics.append( event: "scene-geometry-update-result", values: [ "sceneIdentifier": scene.session.persistentIdentifier, "effectiveFrame": Self.record(for: scene.effectiveGeometry.systemFrame), + "coordinateSpaceBounds": Self.record(for: coordinateSpaceBounds), "sourceWindowBounds": Self.record(for: window.bounds), + "sourceWindowFrame": Self.record(for: window.frame), + "sourceWindowAutoresizingMask": Int(window.autoresizingMask.rawValue), "preferredContentSize": Self.record(for: preferred), "matchesPreferred": Self.sameSize(window.bounds.size, preferred) ] ) + self.synchronizeWindowWithSceneIfNeeded( + window: window, + scene: scene, + preferred: preferred + ) + } + } + + private func synchronizeWindowWithSceneIfNeeded( + window: UIWindow, + scene: UIWindowScene, + preferred: CGSize + ) { + let effectiveFrame = scene.effectiveGeometry.systemFrame + let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard window.windowScene === scene, + rootedWindows.count == 1, + rootedWindows[0] === window, + Self.sameSize(effectiveFrame.size, preferred), + !Self.sameSize(window.bounds.size, preferred) else { return } + let targetWindowFrame = Self.sameSize(coordinateSpaceBounds.size, preferred) + ? coordinateSpaceBounds + : CGRect(origin: coordinateSpaceBounds.origin, size: preferred) + ConfirmedImportLayoutDiagnostics.append( + event: "uiwindow-scene-sync-before", + values: [ + "effectiveFrame": Self.record(for: effectiveFrame), + "coordinateSpaceBounds": Self.record(for: coordinateSpaceBounds), + "coordinateSpaceMatchesPreferred": Self.sameSize( + coordinateSpaceBounds.size, + preferred + ), + "targetWindowFrame": Self.record(for: targetWindowFrame), + "windowFrame": Self.record(for: window.frame), + "windowBounds": Self.record(for: window.bounds), + "autoresizingMask": Int(window.autoresizingMask.rawValue) + ] + ) + window.frame = targetWindowFrame + ConfirmedImportLayoutDiagnostics.append( + event: "uiwindow-scene-sync-after-immediate", + values: [ + "windowFrame": Self.record(for: window.frame), + "windowBounds": Self.record(for: window.bounds), + "rootViewBounds": Self.record(for: window.rootViewController?.view.bounds ?? .zero), + "autoresizingMask": Int(window.autoresizingMask.rawValue) + ] + ) + DispatchQueue.main.async { [weak window, weak scene] in + guard let window, let scene else { return } + ConfirmedImportLayoutDiagnostics.append( + event: "uiwindow-scene-sync-after-next-runloop", + values: [ + "effectiveFrame": Self.record(for: scene.effectiveGeometry.systemFrame), + "coordinateSpaceBounds": Self.record(for: Self.coordinateSpaceBounds(for: scene)), + "windowFrame": Self.record(for: window.frame), + "windowBounds": Self.record(for: window.bounds), + "rootViewBounds": Self.record(for: window.rootViewController?.view.bounds ?? .zero), + "autoresizingMask": Int(window.autoresizingMask.rawValue) + ] + ) + } + } + + private func clearGeometryRequest(_ signature: String) { + if lastGeometryRequestSignature == signature { + lastGeometryRequestSignature = nil } } @@ -804,5 +885,12 @@ struct CatalystSheetBackground: UIViewRepresentable { height: size.height ) } + + private static func coordinateSpaceBounds(for scene: UIWindowScene) -> CGRect { + if #available(iOS 26.0, *) { + return scene.effectiveGeometry.coordinateSpace.bounds + } + return scene.coordinateSpace.bounds + } } } From 7ad96aaca3ac1eb953d581c2b63e2eba5afa0259 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:10:51 +0800 Subject: [PATCH 21/50] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E6=97=A0=E6=84=8F=E4=B9=89=E5=88=86=E9=9A=94?= =?UTF-8?q?=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Views/ConfirmedFileImportView.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index fcc592e8f..3b71acff0 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -533,7 +533,6 @@ struct ConfirmedFileImportView: View { .padding(.horizontal, 22) .padding(.top, 20) .padding(.bottom, 15) - Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) ConfirmedImportCappedBodyLayout( width: Self.bodyWidth, maximumHeight: Self.maximumBodyHeight, @@ -554,7 +553,6 @@ struct ConfirmedFileImportView: View { .clipped() .padding(.horizontal, 22) .padding(.vertical, 16) - Divider().overlay(WeiBeiTheme.hairline.opacity(0.45)) footer(batch) .padding(.horizontal, 22) .padding(.vertical, 13) From 7ff0ebb0e3d5353d1997c934e75b8b6575086a52 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:14:30 +0800 Subject: [PATCH 22/50] =?UTF-8?q?=E7=B2=BE=E7=AE=80=E6=96=B0=E5=BB=BA?= =?UTF-8?q?=E8=AF=BE=E7=A8=8B=E7=AA=97=E5=8F=A3=E5=B9=B6=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E6=A0=B7=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Support/Theme.swift | 11 ++++++ .../Views/ConfirmedFileImportView.swift | 13 +------ .../Views/CourseWorkspaceComponents.swift | 39 +++++++++---------- 3 files changed, 31 insertions(+), 32 deletions(-) diff --git a/Sources/WeiBei/Support/Theme.swift b/Sources/WeiBei/Support/Theme.swift index 8c19e21f7..bd1e7993f 100644 --- a/Sources/WeiBei/Support/Theme.swift +++ b/Sources/WeiBei/Support/Theme.swift @@ -2000,3 +2000,14 @@ extension Image { } extension WeiBeiMetric { static let courseDrawerWidth: CGFloat = 252 } + +struct WeiBeiFittedSheetPresentation: ViewModifier { + @ViewBuilder + func body(content: Content) -> some View { + if #available(iOS 18.0, macOS 15.0, *) { + content.presentationSizing(.fitted) + } else { + content + } + } +} diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 3b71acff0..49fe69889 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -578,7 +578,7 @@ struct ConfirmedFileImportView: View { .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) .foregroundStyle(WeiBeiTheme.ink) .preferredColorScheme(store.appearanceMode.colorScheme) - .modifier(ConfirmedImportFittedPresentation()) + .modifier(WeiBeiFittedSheetPresentation()) .interactiveDismissDisabled(batch?.stage == .importing) .sheet(isPresented: $creatingCourse) { CourseProjectEntrySheet( @@ -1096,14 +1096,3 @@ enum ConfirmedImportLayoutDiagnostics { } } } - -private struct ConfirmedImportFittedPresentation: ViewModifier { - @ViewBuilder - func body(content: Content) -> some View { - if #available(iOS 18.0, macOS 15.0, *) { - content.presentationSizing(.fitted) - } else { - content - } - } -} diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 5f9bf05db..950b798cc 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -188,7 +188,9 @@ struct CourseManagementSheet: View { } } .padding(22) - .frame(width: 460) + .frame(width: 440) + .fixedSize(horizontal: false, vertical: true) + .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) #endif @@ -339,21 +341,23 @@ struct CourseProjectEntrySheet: View { } var body: some View { - VStack(alignment: .leading, spacing: 18) { - VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 5) { Text(heading) - .weiBeiBrandFont(language: store.interfaceLanguage, size: 22, weight: .semibold) - Text(detail) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) + .weiBeiBrandFont(language: store.interfaceLanguage, size: 20, weight: .semibold) + if let detail { + Text(detail) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } } if needsLibrary { libraryPicker } else { courseTitleField - if let libraryPath = store.courseLibraryRootURL?.path { + if intent == .adopt, let libraryPath = store.courseLibraryRootURL?.path { pathLine( label: store.ui("魏碑资料库", "WeiBei Library"), path: libraryPath @@ -410,7 +414,7 @@ struct CourseProjectEntrySheet: View { } } - private var detail: String { + private var detail: String? { if rebindProposal != nil { return store.ui( "魏碑认出了同一门课程,原文件夹当前无法访问。确认后会重新连接所选文件夹,读取其中的课程状态并扫描实际资料;本机未落盘草稿会保留。", @@ -431,10 +435,7 @@ struct CourseProjectEntrySheet: View { } switch intent { case .create: - return store.ui( - "魏碑会为这门课创建文稿、笔记和课程记录。对话始终是全局的,进入这门课只会把它设为当前课程。", - "WeiBei will create documents, notes, and a course record. Chats stay global; entering this course only makes it the current course." - ) + return nil case .adopt: return store.ui( "原地登记一个已有文件夹为课程;不会复制、移动或重排其中的可见内容。", @@ -597,7 +598,7 @@ struct CourseProjectEntrySheet: View { selectedFolder = nil errorMessage = nil } - .buttonStyle(WeiBeiTextActionButtonStyle()) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) .disabled(isWorking) } @@ -610,7 +611,7 @@ struct CourseProjectEntrySheet: View { } Button(store.ui("取消", "Cancel"), action: cancel) - .buttonStyle(WeiBeiTextActionButtonStyle()) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) .keyboardShortcut(.cancelAction) .disabled(isWorking) @@ -622,9 +623,7 @@ struct CourseProjectEntrySheet: View { ), action: confirmRebind ) - .buttonStyle( - WeiBeiTextActionButtonStyle(active: true) - ) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) .disabled(isWorking) } else if !needsLibrary { @@ -634,7 +633,7 @@ struct CourseProjectEntrySheet: View { : store.ui("创建并导入", "Create and Import"), action: createCourse ) - .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) .disabled(cleanedTitle.isEmpty || isWorking) } From 231bf86aeec42bc078cfa2edcb8f75f508049a22 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:23:42 +0800 Subject: [PATCH 23/50] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=B0=BA=E5=AF=B8=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 212 ++---------------- .../Views/ConfirmedFileImportView.swift | 90 +------- .../Views/CourseWorkspaceComponents.swift | 26 ++- 3 files changed, 57 insertions(+), 271 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 11ea8ad95..f64ace079 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -584,22 +584,32 @@ struct CatalystWindowChrome: UIViewRepresentable { } // SwiftUI's Mac Catalyst sheet is hosted in a separate UIKit window. -struct CatalystSheetBackground: UIViewRepresentable { +struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let color: UIColor - var diagnosticContext: String? = nil + var followsContentSize = false + var contentSizeRevision = "" + func makeUIView(context: Context) -> Probe { Probe() } + func updateUIView(_ view: Probe, context: Context) { view.color = color - view.diagnosticContext = diagnosticContext + view.followsContentSize = followsContentSize + view.contentSizeRevision = contentSizeRevision view.configure() + if followsContentSize { + DispatchQueue.main.async { [weak view] in view?.configure() } + } } + final class Probe: UIView { var color = UIColor.clear - var diagnosticContext: String? - private var lastDiagnosticSignature: String? + var followsContentSize = false + var contentSizeRevision = "" private var lastGeometryRequestSignature: String? + override func didMoveToWindow() { super.didMoveToWindow(); configure() } override func layoutSubviews() { super.layoutSubviews(); configure() } + func configure() { guard let window else { return } window.backgroundColor = color @@ -610,13 +620,12 @@ struct CatalystSheetBackground: UIViewRepresentable { } responder = current.next } - recordDiagnostics(window: window) - resizeImportSheetIfNeeded(window: window) + guard followsContentSize else { return } + resizeSheetIfNeeded(window: window) } - private func resizeImportSheetIfNeeded(window: UIWindow) { - guard diagnosticContext == "confirmed-file-import", - let preferred = window.rootViewController?.preferredContentSize, + private func resizeSheetIfNeeded(window: UIWindow) { + guard let preferred = window.rootViewController?.preferredContentSize, preferred.width.isFinite, preferred.height.isFinite, preferred.width > 0, preferred.height > 0, !Self.sameSize(window.bounds.size, preferred), @@ -630,22 +639,13 @@ struct CatalystSheetBackground: UIViewRepresentable { let signature = "\(sourceFrame)|\(targetFrame)" guard signature != lastGeometryRequestSignature else { return } lastGeometryRequestSignature = signature - ConfirmedImportLayoutDiagnostics.append( - event: "scene-geometry-update-scheduled", - values: [ - "sceneIdentifier": scene.session.persistentIdentifier, - "sourceFrame": Self.record(for: sourceFrame), - "targetFrame": Self.record(for: targetFrame), - "sourceWindowBounds": Self.record(for: window.bounds) - ] - ) DispatchQueue.main.async { [weak self, weak window, weak scene] in guard let self else { return } guard let window, let scene, window.windowScene === scene else { self.clearGeometryRequest(signature) return } - self.requestImportSheetGeometryUpdate( + self.requestGeometryUpdate( window: window, scene: scene, preferred: preferred, @@ -654,7 +654,7 @@ struct CatalystSheetBackground: UIViewRepresentable { } } - private func requestImportSheetGeometryUpdate( + private func requestGeometryUpdate( window: UIWindow, scene: UIWindowScene, preferred: CGSize, @@ -670,40 +670,11 @@ struct CatalystSheetBackground: UIViewRepresentable { return } let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) - ConfirmedImportLayoutDiagnostics.append( - event: "scene-geometry-update-requested", - values: [ - "sceneIdentifier": scene.session.persistentIdentifier, - "sourceFrame": Self.record(for: sourceFrame), - "targetFrame": Self.record(for: targetFrame) - ] - ) - scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { [weak self] error in + scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { [weak self] _ in self?.clearGeometryRequest(signature) - ConfirmedImportLayoutDiagnostics.append( - event: "scene-geometry-update-error", - values: [ - "sceneIdentifier": scene.session.persistentIdentifier, - "message": String(describing: error) - ] - ) } DispatchQueue.main.async { [weak self, weak window, weak scene] in guard let self, let window, let scene else { return } - let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) - ConfirmedImportLayoutDiagnostics.append( - event: "scene-geometry-update-result", - values: [ - "sceneIdentifier": scene.session.persistentIdentifier, - "effectiveFrame": Self.record(for: scene.effectiveGeometry.systemFrame), - "coordinateSpaceBounds": Self.record(for: coordinateSpaceBounds), - "sourceWindowBounds": Self.record(for: window.bounds), - "sourceWindowFrame": Self.record(for: window.frame), - "sourceWindowAutoresizingMask": Int(window.autoresizingMask.rawValue), - "preferredContentSize": Self.record(for: preferred), - "matchesPreferred": Self.sameSize(window.bounds.size, preferred) - ] - ) self.synchronizeWindowWithSceneIfNeeded( window: window, scene: scene, @@ -725,48 +696,9 @@ struct CatalystSheetBackground: UIViewRepresentable { rootedWindows[0] === window, Self.sameSize(effectiveFrame.size, preferred), !Self.sameSize(window.bounds.size, preferred) else { return } - let targetWindowFrame = Self.sameSize(coordinateSpaceBounds.size, preferred) + window.frame = Self.sameSize(coordinateSpaceBounds.size, preferred) ? coordinateSpaceBounds : CGRect(origin: coordinateSpaceBounds.origin, size: preferred) - ConfirmedImportLayoutDiagnostics.append( - event: "uiwindow-scene-sync-before", - values: [ - "effectiveFrame": Self.record(for: effectiveFrame), - "coordinateSpaceBounds": Self.record(for: coordinateSpaceBounds), - "coordinateSpaceMatchesPreferred": Self.sameSize( - coordinateSpaceBounds.size, - preferred - ), - "targetWindowFrame": Self.record(for: targetWindowFrame), - "windowFrame": Self.record(for: window.frame), - "windowBounds": Self.record(for: window.bounds), - "autoresizingMask": Int(window.autoresizingMask.rawValue) - ] - ) - window.frame = targetWindowFrame - ConfirmedImportLayoutDiagnostics.append( - event: "uiwindow-scene-sync-after-immediate", - values: [ - "windowFrame": Self.record(for: window.frame), - "windowBounds": Self.record(for: window.bounds), - "rootViewBounds": Self.record(for: window.rootViewController?.view.bounds ?? .zero), - "autoresizingMask": Int(window.autoresizingMask.rawValue) - ] - ) - DispatchQueue.main.async { [weak window, weak scene] in - guard let window, let scene else { return } - ConfirmedImportLayoutDiagnostics.append( - event: "uiwindow-scene-sync-after-next-runloop", - values: [ - "effectiveFrame": Self.record(for: scene.effectiveGeometry.systemFrame), - "coordinateSpaceBounds": Self.record(for: Self.coordinateSpaceBounds(for: scene)), - "windowFrame": Self.record(for: window.frame), - "windowBounds": Self.record(for: window.bounds), - "rootViewBounds": Self.record(for: window.rootViewController?.view.bounds ?? .zero), - "autoresizingMask": Int(window.autoresizingMask.rawValue) - ] - ) - } } private func clearGeometryRequest(_ signature: String) { @@ -775,104 +707,6 @@ struct CatalystSheetBackground: UIViewRepresentable { } } - private func recordDiagnostics(window: UIWindow) { - guard diagnosticContext == "confirmed-file-import" else { return } - var controllerRecords: [[String: Any]] = [] - var controllerSignatures: [String] = [] - var controllerIDs = Set() - var responder: UIResponder? = self - while let current = responder { - if let controller = current as? UIViewController, - controllerIDs.insert(ObjectIdentifier(controller)).inserted { - controllerRecords.append(Self.record(for: controller)) - controllerSignatures.append(Self.signature(for: controller)) - } - responder = current.next - } - let root = window.rootViewController - if let root, controllerIDs.insert(ObjectIdentifier(root)).inserted { - controllerRecords.append(Self.record(for: root)) - controllerSignatures.append(Self.signature(for: root)) - } - let rootBounds = root?.view.bounds ?? .zero - let rootPreferred = root?.preferredContentSize ?? .zero - let presentation = root?.presentationController - let sheetPresentation = root?.sheetPresentationController - let prefersPageSizingBefore = sheetPresentation?.prefersPageSizing - let rootControllerType: String - let presentationControllerType: String - let sheetPresentationControllerType: String - if let root { - rootControllerType = String(reflecting: type(of: root)) - } else { - rootControllerType = "" - } - if let presentation { - presentationControllerType = String(reflecting: type(of: presentation)) - } else { - presentationControllerType = "" - } - if let sheetPresentation { - sheetPresentationControllerType = String(reflecting: type(of: sheetPresentation)) - } else { - sheetPresentationControllerType = "" - } - let prefersPageSizingBeforeValue: Any - if let prefersPageSizingBefore { - prefersPageSizingBeforeValue = prefersPageSizingBefore - } else { - prefersPageSizingBeforeValue = NSNull() - } - let signature = [ - "\(window.bounds)", - "\(rootBounds)", - "\(rootPreferred)", - String(describing: prefersPageSizingBefore), - controllerSignatures.joined(separator: ";") - ].joined(separator: "|") - guard signature != lastDiagnosticSignature else { return } - lastDiagnosticSignature = signature - ConfirmedImportLayoutDiagnostics.append( - event: "catalyst-sheet", - values: [ - "context": diagnosticContext ?? "", - "windowBounds": Self.record(for: window.bounds), - "rootViewBounds": Self.record(for: rootBounds), - "rootPreferredContentSize": Self.record(for: rootPreferred), - "rootControllerType": rootControllerType, - "responderControllers": controllerRecords, - "presentationControllerType": presentationControllerType, - "sheetPresentationControllerType": sheetPresentationControllerType, - "prefersPageSizingBefore": prefersPageSizingBeforeValue - ] - ) - } - - private static func record(for controller: UIViewController) -> [String: Any] { - [ - "type": String(reflecting: type(of: controller)), - "viewBounds": record(for: controller.view.bounds), - "preferredContentSize": record(for: controller.preferredContentSize) - ] - } - - private static func signature(for controller: UIViewController) -> String { - "\(String(reflecting: type(of: controller)))|\(controller.view.bounds)|\(controller.preferredContentSize)" - } - - private static func record(for rect: CGRect) -> [String: Any] { - [ - "x": rect.origin.x, - "y": rect.origin.y, - "width": rect.size.width, - "height": rect.size.height - ] - } - - private static func record(for size: CGSize) -> [String: Any] { - ["width": size.width, "height": size.height] - } - private static func sameSize(_ lhs: CGSize, _ rhs: CGSize) -> Bool { abs(lhs.width - rhs.width) < 1 && abs(lhs.height - rhs.height) < 1 } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 49fe69889..d9a84c413 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -519,6 +519,9 @@ struct ConfirmedFileImportView: View { private static let maximumBodyHeight: CGFloat = 350 private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } + private var contentSizeRevision: String { + "\(String(reflecting: batch))|\(courseSearch)|\(creatingCourse)" + } private var matchingCourses: [Course] { let query = courseSearch.trimmingCharacters(in: .whitespacesAndNewlines) return query.isEmpty ? store.courses : store.courses.filter { @@ -535,8 +538,7 @@ struct ConfirmedFileImportView: View { .padding(.bottom, 15) ConfirmedImportCappedBodyLayout( width: Self.bodyWidth, - maximumHeight: Self.maximumBodyHeight, - stage: batch.stage + maximumHeight: Self.maximumBodyHeight ) { stageContent(batch) .frame(width: Self.bodyWidth, alignment: .leading) @@ -560,18 +562,11 @@ struct ConfirmedFileImportView: View { } .frame(width: 500, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true) - .background { - GeometryReader { geometry in - Color.clear - .onAppear { logRootSize(geometry.size) } - .onChange(of: geometry.size) { _, size in logRootSize(size) } - .onChange(of: batch?.stage) { _, _ in logRootSize(geometry.size) } - } - } #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground( + .background(CatalystIndependentSheetSizingProbe( color: WeiBeiNativePalette.paper(), - diagnosticContext: "confirmed-file-import" + followsContentSize: true, + contentSizeRevision: contentSizeRevision )) #endif .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) @@ -1003,60 +998,21 @@ struct ConfirmedFileImportView: View { } } - private func logRootSize(_ size: CGSize) { - ConfirmedImportLayoutDiagnostics.append( - event: "root-view", - values: [ - "stage": String(describing: batch?.stage), - "width": size.width, - "height": size.height - ] - ) - } } private struct ConfirmedImportCappedBodyLayout: Layout { let width: CGFloat let maximumHeight: CGFloat - let stage: ConfirmedFileImportStage - struct Cache { - var lastStage: ConfirmedFileImportStage? - var lastContentHeight: CGFloat? - var lastResult: CGSize? - } - - func makeCache(subviews: Subviews) -> Cache { Cache() } - - func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) -> CGSize { + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { guard let measurement = subviews.first else { return .zero } let contentHeight = measurement.sizeThatFits( ProposedViewSize(width: width, height: nil) ).height - let result = CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) - let roundedContentHeight = ceil(contentHeight) - if cache.lastStage != stage - || cache.lastContentHeight != roundedContentHeight - || cache.lastResult != result { - cache.lastStage = stage - cache.lastContentHeight = roundedContentHeight - cache.lastResult = result - ConfirmedImportLayoutDiagnostics.append( - event: "body-layout", - values: [ - "stage": String(describing: stage), - "contentHeight": roundedContentHeight, - "resultWidth": result.width, - "resultHeight": result.height, - "proposalWidth": proposal.width.map { $0 as Any } ?? NSNull(), - "proposalHeight": proposal.height.map { $0 as Any } ?? NSNull() - ] - ) - } - return result + return CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) } - func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout Cache) { + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { guard subviews.count == 2 else { return } subviews[0].place( at: bounds.origin, @@ -1070,29 +1026,3 @@ private struct ConfirmedImportCappedBodyLayout: Layout { ) } } - -enum ConfirmedImportLayoutDiagnostics { - private static let qaBundleIdentifier = "com.changfenhuang.weibei.qa.cursorcloseout20260926" - private static let outputURL = URL(fileURLWithPath: "/tmp/weibei-import-layout-diagnostics.jsonl") - - static func append(event: String, values: [String: Any]) { - guard Bundle.main.bundleIdentifier == qaBundleIdentifier else { return } - var record = values - record["event"] = event - record["timestamp"] = Date().timeIntervalSince1970 - guard let data = try? JSONSerialization.data(withJSONObject: record), - let lineBreak = "\n".data(using: .utf8) else { return } - if !FileManager.default.fileExists(atPath: outputURL.path) { - FileManager.default.createFile(atPath: outputURL.path, contents: nil) - } - guard let handle = try? FileHandle(forWritingTo: outputURL) else { return } - defer { try? handle.close() } - do { - try handle.seekToEnd() - try handle.write(contentsOf: data) - try handle.write(contentsOf: lineBreak) - } catch { - return - } - } -} diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 950b798cc..942899d5d 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -192,7 +192,7 @@ struct CourseManagementSheet: View { .fixedSize(horizontal: false, vertical: true) .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) + .background(CatalystIndependentSheetSizingProbe(color: WeiBeiNativePalette.paper())) #endif .background(WeiBeiTheme.paper) .foregroundStyle(WeiBeiTheme.ink) @@ -340,6 +340,22 @@ struct CourseProjectEntrySheet: View { title.trimmingCharacters(in: .whitespacesAndNewlines) } + private var contentSizeRevision: String { + [ + String(describing: intent), + title, + selectedFolder?.path ?? "", + selectedImportURLs.map(\.path).joined(separator: "|"), + String(configuredLibraryThisTime), + String(isWorking), + errorMessage ?? "", + String(reflecting: rebindProposal), + String(needsLibrary), + store.courseLibraryRootPath ?? "", + String(describing: store.interfaceLanguage) + ].joined(separator: "§") + } + var body: some View { VStack(alignment: .leading, spacing: 14) { VStack(alignment: .leading, spacing: 5) { @@ -383,8 +399,14 @@ struct CourseProjectEntrySheet: View { } .padding(22) .frame(width: 460) + .fixedSize(horizontal: false, vertical: true) + .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) + .background(CatalystIndependentSheetSizingProbe( + color: WeiBeiNativePalette.paper(), + followsContentSize: true, + contentSizeRevision: contentSizeRevision + )) #endif .background(WeiBeiTheme.paper) .foregroundStyle(WeiBeiTheme.ink) From 812cc6b2eacca057735b06384332755e7a9cf13b Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:28:37 +0800 Subject: [PATCH 24/50] =?UTF-8?q?=E7=B2=BE=E7=AE=80=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E4=B8=8E=E6=96=B0=E5=BB=BA=E8=AF=BE=E7=A8=8B=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=E5=B1=82=E7=BA=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 144 +++++++++++------- .../Views/CourseWorkspaceComponents.swift | 48 +++--- 2 files changed, 105 insertions(+), 87 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index d9a84c413..47789d0d0 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -642,10 +642,12 @@ struct ConfirmedFileImportView: View { private func heading(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 5) { Text(headingTitle(batch)) - .weiBeiBrandFont(language: store.interfaceLanguage, size: 22, weight: .semibold) - Text(headingDetail(batch)) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) + .weiBeiBrandFont(language: store.interfaceLanguage, size: 20, weight: .semibold) + if let detail = headingDetail(batch) { + Text(detail) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } } } @@ -657,14 +659,14 @@ struct ConfirmedFileImportView: View { } } - private func headingDetail(_ batch: ConfirmedFileImportBatch) -> String { + private func headingDetail(_ batch: ConfirmedFileImportBatch) -> String? { switch batch.stage { case .preparing, .reviewing: store.ui("导入副本,保留原文件。", "Import a copy and keep the original.") case .importing: destinationDescription(batch) case .finished: - store.ui("已完成的导入已经保留。", "Completed imports have been kept.") + nil } } @@ -688,12 +690,12 @@ struct ConfirmedFileImportView: View { "This batch · \(batch.candidates.count + batch.unsupportedNames.count) items" )) .weiBeiText(12, weight: .semibold) - if !batch.sourceFolderNames.isEmpty { + if batch.sourceFolderNames.count > 1 { Text(store.ui( "来源文件夹:\(batch.sourceFolderNames.joined(separator: "、"))", "Source folders: \(batch.sourceFolderNames.joined(separator: ", "))" )) - .weiBeiText(10.5) + .weiBeiText(12) .foregroundStyle(WeiBeiTheme.tertiaryInk) .lineLimit(2) } @@ -711,10 +713,10 @@ struct ConfirmedFileImportView: View { } if !batch.sourceFolderNames.isEmpty { Text(store.ui( - "文件夹内仅导入 PDF、Word、PPT、HTML、文本和 Markdown;隐藏文件与应用包会跳过。", - "Folders include PDF, Word, PPT, HTML, text, and Markdown only; hidden files and app bundles are skipped." + "文件夹内只导入支持的文稿;隐藏文件和应用会跳过。", + "Only supported documents are imported from folders; hidden files and apps are skipped." )) - .weiBeiText(10.5) + .weiBeiText(12) .foregroundStyle(WeiBeiTheme.tertiaryInk) } } @@ -729,20 +731,13 @@ struct ConfirmedFileImportView: View { .frame(width: 16) .padding(.top, 2) VStack(alignment: .leading, spacing: 3) { - HStack(alignment: .firstTextBaseline, spacing: 10) { - Text(candidate.sourceURL.lastPathComponent) - .weiBeiText(12) - .lineLimit(2) - .truncationMode(.middle) - Spacer(minLength: 6) - Text(kind.label(language: store.interfaceLanguage)) - .weiBeiText(10.5) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - .fixedSize() - } + Text(candidate.sourceURL.lastPathComponent) + .weiBeiText(13) + .lineLimit(2) + .truncationMode(.middle) if candidate.disposition != .ready { Text(candidateLabel(candidate)) - .weiBeiText(10.5, weight: .medium) + .weiBeiText(12, weight: .medium) .foregroundStyle(candidateColor(candidate)) .fixedSize(horizontal: false, vertical: true) } @@ -758,6 +753,7 @@ struct ConfirmedFileImportView: View { .frame(width: 16) VStack(alignment: .leading, spacing: 3) { Text(name) + .weiBeiText(13) .lineLimit(2) .truncationMode(.middle) Text( @@ -765,10 +761,9 @@ struct ConfirmedFileImportView: View { ? store.ui("仅支持 Markdown,已跳过", "Markdown only; skipped") : store.ui("不支持,已跳过", "Unsupported; skipped") ) - .weiBeiText(10.5, weight: .medium) + .weiBeiText(12, weight: .medium) } } - .weiBeiText(11) .foregroundStyle(WeiBeiTheme.cinnabar) .padding(.vertical, 6) .help(name) @@ -806,7 +801,7 @@ struct ConfirmedFileImportView: View { if !courseSearch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, matchingCourses.isEmpty { Text(store.ui("没有匹配的课程", "No matching courses")) - .weiBeiText(11) + .weiBeiText(12) .foregroundStyle(WeiBeiTheme.tertiaryInk) .padding(.vertical, 5) .padding(.horizontal, 8) @@ -847,39 +842,37 @@ struct ConfirmedFileImportView: View { private func progress(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 12) { if let current = batch.currentFileName { - Text(current).weiBeiText(12).lineLimit(2) + Text(current).weiBeiText(13).lineLimit(2) } ProgressView(value: Double(batch.completed), total: Double(max(1, batch.total))) .tint(WeiBeiTheme.cinnabar) Text("\(batch.completed) / \(batch.total)") - .weiBeiText(11, design: .monospaced) - .foregroundStyle(WeiBeiTheme.secondaryInk) - if !batch.pendingSourceURLs.isEmpty { - Text(store.ui( - "另有 \(batch.pendingSourceURLs.count) 个从 Dock 打开的文件等待本批完成。", - "\(batch.pendingSourceURLs.count) file(s) opened from the Dock are waiting for this batch." - )) - .weiBeiText(11) + .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) - } } } private func result(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 14) { - Text(store.ui( - "成功 \(batch.importedItems.count) 个 · 跳过 \(batch.skippedCount) 个 · 失败 \(batch.failures.count) 个", - "\(batch.importedItems.count) succeeded · \(batch.skippedCount) skipped · \(batch.failures.count) failed" - )) - .weiBeiText(15, weight: .semibold) - if batch.stopped { - Text(store.ui("已停止剩余任务;已完成的导入仍然保留。", "Remaining work stopped; completed imports were kept.")) + Text(resultSummary(batch)) + .weiBeiText(13, weight: .semibold) + if batch.stopped, !batch.pendingSourceURLs.isEmpty { + Text(store.ui( + "已停止;\(batch.pendingSourceURLs.count) 个文件未处理。已完成的导入已保留,原文件未变。", + "Stopped with \(batch.pendingSourceURLs.count) file(s) unprocessed. Completed imports were kept and originals are unchanged." + )) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) .fixedSize(horizontal: false, vertical: true) - } - if !batch.pendingSourceURLs.isEmpty { + } else if batch.stopped { + Text(store.ui( + "已停止;已完成的导入仍然保留。", + "Stopped. Completed imports were kept." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } else if !batch.pendingSourceURLs.isEmpty { Text(store.ui( "另有 \(batch.pendingSourceURLs.count) 个文件尚未处理,原文件仍保留。", "\(batch.pendingSourceURLs.count) file(s) are still waiting; their originals are unchanged." @@ -892,16 +885,24 @@ struct ConfirmedFileImportView: View { VStack(alignment: .leading, spacing: 8) { Text(store.ui("未导入", "Not imported")) .weiBeiText(12, weight: .semibold) + if let message = sharedFailureMessage(batch) { + Text(message) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } ForEach(batch.failures) { failure in VStack(alignment: .leading, spacing: 3) { Text(failure.sourceURL.lastPathComponent) - .weiBeiText(12, weight: .semibold) + .weiBeiText(13, weight: .semibold) .lineLimit(2) .truncationMode(.middle) - Text(failure.message) - .weiBeiText(11) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) + if sharedFailureMessage(batch) == nil { + Text(failure.message) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } } } } @@ -912,12 +913,12 @@ struct ConfirmedFileImportView: View { @ViewBuilder private func resultButtons(_ batch: ConfirmedFileImportBatch) -> some View { if !batch.pendingSourceURLs.isEmpty { - Button(store.ui("结束本次导入", "End This Import")) { store.dismissConfirmedFileImport() } + Button(store.ui("结束", "End")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) if batch.failures.isEmpty { Button(store.ui( - "处理待导入文件(\(batch.pendingSourceURLs.count))", - "Review Waiting Files (\(batch.pendingSourceURLs.count))" + "继续处理(\(batch.pendingSourceURLs.count))", + "Continue (\(batch.pendingSourceURLs.count))" )) { store.continuePendingConfirmedFileImport() } @@ -925,13 +926,13 @@ struct ConfirmedFileImportView: View { .keyboardShortcut(.defaultAction) } else { Button(store.ui( - "放弃失败项并继续(\(batch.pendingSourceURLs.count))", - "Leave Failures and Continue (\(batch.pendingSourceURLs.count))" + "放弃失败项,继续(\(batch.pendingSourceURLs.count))", + "Leave Failures, Continue (\(batch.pendingSourceURLs.count))" )) { store.continuePendingConfirmedFileImport(abandoningFailures: true) } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button(store.ui("只重试失败项", "Retry Failed Only")) { + Button(store.ui("重试失败项", "Retry Failed")) { store.retryFailedConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) @@ -940,7 +941,7 @@ struct ConfirmedFileImportView: View { } else if !batch.failures.isEmpty { Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button(store.ui("只重试失败项", "Retry Failed Only")) { + Button(store.ui("重试失败项", "Retry Failed")) { store.retryFailedConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) @@ -968,6 +969,33 @@ struct ConfirmedFileImportView: View { } } + private func resultSummary(_ batch: ConfirmedFileImportBatch) -> String { + var chinese: [String] = [] + var english: [String] = [] + if !batch.importedItems.isEmpty { + chinese.append("\(batch.importedItems.count)个已导入") + english.append("\(batch.importedItems.count) imported") + } + if batch.skippedCount > 0 { + chinese.append("\(batch.skippedCount)个已跳过") + english.append("\(batch.skippedCount) skipped") + } + if !batch.failures.isEmpty { + chinese.append("\(batch.failures.count)个失败") + english.append("\(batch.failures.count) failed") + } + if chinese.isEmpty { + return store.ui("没有导入文件", "No files imported") + } + return store.ui(chinese.joined(separator: " · "), english.joined(separator: " · ")) + } + + private func sharedFailureMessage(_ batch: ConfirmedFileImportBatch) -> String? { + guard let message = batch.failures.first?.message, + batch.failures.allSatisfy({ $0.message == message }) else { return nil } + return message + } + private func confirmTitle(_ batch: ConfirmedFileImportBatch) -> String { if let courseID = batch.courseID, let course = store.courses.first(where: { $0.id == courseID }) { diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 942899d5d..9f2a179b3 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -188,9 +188,7 @@ struct CourseManagementSheet: View { } } .padding(22) - .frame(width: 440) - .fixedSize(horizontal: false, vertical: true) - .modifier(WeiBeiFittedSheetPresentation()) + .frame(width: 460) #if targetEnvironment(macCatalyst) .background(CatalystIndependentSheetSizingProbe(color: WeiBeiNativePalette.paper())) #endif @@ -340,6 +338,10 @@ struct CourseProjectEntrySheet: View { title.trimmingCharacters(in: .whitespacesAndNewlines) } + private var selectedImportIncludesMarkdown: Bool { + selectedImportURLs.contains { StudyItemKind.detect(from: $0) == .markdown } + } + private var contentSizeRevision: String { [ String(describing: intent), @@ -398,7 +400,7 @@ struct CourseProjectEntrySheet: View { actionBar } .padding(22) - .frame(width: 460) + .frame(width: 440) .fixedSize(horizontal: false, vertical: true) .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) @@ -446,8 +448,8 @@ struct CourseProjectEntrySheet: View { if needsLibrary { if libraryNeedsReauthorization { return store.ui( - "魏碑记得原资料库,但当前无法访问。重新选择后魏碑会改用所选文件夹,课程文件不会被移动;要找回原课程,请选回原来的资料库。", - "WeiBei remembers the library but cannot access it. Re-selecting switches WeiBei to the chosen folder without moving any course files; to find your original courses, pick the original library." + "原资料库无法访问。选回原文件夹可恢复课程;选择其他文件夹会切换资料库,不移动文件。", + "The original library is unavailable. Choose it again to restore courses, or choose another folder to switch libraries without moving files." ) } return store.ui( @@ -475,23 +477,6 @@ struct CourseProjectEntrySheet: View { path: path ) } - Label( - store.ui( - "原资料库当前无法访问,课程记录仍保留。选择别的文件夹会改用那个文件夹,课程文件不会被移动。", - "The original library is currently unavailable, but course records are preserved. Choosing another folder switches to that folder; course files are not moved." - ), - systemImage: "exclamationmark.triangle" - ) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) - } else { - Label( - store.ui("建议选择或新建一个名为“魏碑”的总文件夹。", "Choose or create a top-level WeiBei folder."), - systemImage: "folder" - ) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) } Button( @@ -563,7 +548,7 @@ struct CourseProjectEntrySheet: View { VStack(alignment: .leading, spacing: 8) { Button( selectedImportURLs.isEmpty - ? store.ui("同时选择现有文稿或文件夹…", "Choose Existing Files or Folder…") + ? store.ui("添加初始资料…", "Add Initial Materials…") : store.ui("重新选择导入内容…", "Choose Different Content…"), action: chooseImportContent ) @@ -571,10 +556,15 @@ struct CourseProjectEntrySheet: View { .disabled(isWorking) if !selectedImportURLs.isEmpty { - Text(store.ui( - "已选择 \(selectedImportURLs.count) 项;课程创建后会直接导入。Markdown 会同时出现在文稿与笔记中。", - "Selected \(selectedImportURLs.count) item(s). Markdown will appear in both Materials and Notes." - )) + Text(selectedImportIncludesMarkdown + ? store.ui( + "已选 \(selectedImportURLs.count) 项;Markdown 同时加入文稿和笔记。", + "\(selectedImportURLs.count) selected; Markdown will be added to Materials and Notes." + ) + : store.ui( + "已选 \(selectedImportURLs.count) 项", + "\(selectedImportURLs.count) selected" + )) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) .fixedSize(horizontal: false, vertical: true) @@ -592,7 +582,7 @@ struct CourseProjectEntrySheet: View { private func pathLine(label: String, path: String) -> some View { VStack(alignment: .leading, spacing: 4) { Text(label) - .weiBeiText(10.5, weight: .semibold) + .weiBeiText(12, weight: .semibold) .foregroundStyle(WeiBeiTheme.tertiaryInk) Text(path) .weiBeiText(12) From 09204370677c2bd01d5cebb0c9953eb272cc4902 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:30:08 +0800 Subject: [PATCH 25/50] =?UTF-8?q?=E7=B2=BE=E7=AE=80=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E7=BB=93=E6=9E=9C=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Views/ConfirmedFileImportView.swift | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 47789d0d0..baa64c797 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -853,7 +853,8 @@ struct ConfirmedFileImportView: View { } private func result(_ batch: ConfirmedFileImportBatch) -> some View { - VStack(alignment: .leading, spacing: 14) { + let commonFailureMessage = sharedFailureMessage(batch) + return VStack(alignment: .leading, spacing: 14) { Text(resultSummary(batch)) .weiBeiText(13, weight: .semibold) if batch.stopped, !batch.pendingSourceURLs.isEmpty { @@ -883,9 +884,7 @@ struct ConfirmedFileImportView: View { } if !batch.failures.isEmpty { VStack(alignment: .leading, spacing: 8) { - Text(store.ui("未导入", "Not imported")) - .weiBeiText(12, weight: .semibold) - if let message = sharedFailureMessage(batch) { + if let message = commonFailureMessage { Text(message) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) @@ -897,7 +896,7 @@ struct ConfirmedFileImportView: View { .weiBeiText(13, weight: .semibold) .lineLimit(2) .truncationMode(.middle) - if sharedFailureMessage(batch) == nil { + if commonFailureMessage == nil { Text(failure.message) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) From ca05a4be5d1deb630e1834b7559f0813886eae74 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:30:34 +0800 Subject: [PATCH 26/50] =?UTF-8?q?=E6=8B=92=E7=BB=9D=E8=BF=87=E6=9C=9F?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=B0=BA=E5=AF=B8=E8=AF=B7=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index f64ace079..0530a9a93 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -594,7 +594,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { func updateUIView(_ view: Probe, context: Context) { view.color = color view.followsContentSize = followsContentSize - view.contentSizeRevision = contentSizeRevision view.configure() if followsContentSize { DispatchQueue.main.async { [weak view] in view?.configure() } @@ -604,7 +603,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { final class Probe: UIView { var color = UIColor.clear var followsContentSize = false - var contentSizeRevision = "" private var lastGeometryRequestSignature: String? override func didMoveToWindow() { super.didMoveToWindow(); configure() } @@ -660,6 +658,11 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { preferred: CGSize, signature: String ) { + guard let currentPreferred = window.rootViewController?.preferredContentSize, + Self.sameSize(currentPreferred, preferred) else { + clearGeometryRequest(signature) + return + } let sourceFrame = scene.effectiveGeometry.systemFrame let rootedWindows = scene.windows.filter { $0.rootViewController != nil } guard !Self.sameSize(window.bounds.size, preferred), @@ -691,7 +694,9 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let effectiveFrame = scene.effectiveGeometry.systemFrame let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) let rootedWindows = scene.windows.filter { $0.rootViewController != nil } - guard window.windowScene === scene, + guard let currentPreferred = window.rootViewController?.preferredContentSize, + Self.sameSize(currentPreferred, preferred), + window.windowScene === scene, rootedWindows.count == 1, rootedWindows[0] === window, Self.sameSize(effectiveFrame.size, preferred), From 953bcc41cffc7cb75625765b2e2b105d877947d1 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:32:30 +0800 Subject: [PATCH 27/50] =?UTF-8?q?=E6=81=A2=E5=A4=8D=E8=BF=9E=E7=BB=AD?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=B0=BA=E5=AF=B8=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 0530a9a93..3099401e8 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -694,16 +694,21 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let effectiveFrame = scene.effectiveGeometry.systemFrame let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) let rootedWindows = scene.windows.filter { $0.rootViewController != nil } - guard let currentPreferred = window.rootViewController?.preferredContentSize, - Self.sameSize(currentPreferred, preferred), - window.windowScene === scene, + guard window.windowScene === scene, rootedWindows.count == 1, rootedWindows[0] === window, - Self.sameSize(effectiveFrame.size, preferred), - !Self.sameSize(window.bounds.size, preferred) else { return } - window.frame = Self.sameSize(coordinateSpaceBounds.size, preferred) - ? coordinateSpaceBounds - : CGRect(origin: coordinateSpaceBounds.origin, size: preferred) + Self.sameSize(effectiveFrame.size, preferred) else { return } + if !Self.sameSize(window.bounds.size, preferred) { + window.frame = Self.sameSize(coordinateSpaceBounds.size, preferred) + ? coordinateSpaceBounds + : CGRect(origin: coordinateSpaceBounds.origin, size: preferred) + } + guard let currentPreferred = window.rootViewController?.preferredContentSize, + !Self.sameSize(currentPreferred, preferred) else { return } + DispatchQueue.main.async { [weak self, weak window] in + guard let self, let window, self.window === window else { return } + self.configure() + } } private func clearGeometryRequest(_ signature: String) { From 4aff33655585dcc68bc7fc99f25d470b763f468a Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:47:02 +0800 Subject: [PATCH 28/50] =?UTF-8?q?=E6=8C=89=E5=86=85=E5=AE=B9=E5=87=A0?= =?UTF-8?q?=E4=BD=95=E8=B0=83=E6=95=B4=E5=BC=B9=E7=AA=97=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 43 +++++++++++------------ 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 3099401e8..55a43263f 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -595,9 +595,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { view.color = color view.followsContentSize = followsContentSize view.configure() - if followsContentSize { - DispatchQueue.main.async { [weak view] in view?.configure() } - } } final class Probe: UIView { @@ -623,17 +620,17 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { } private func resizeSheetIfNeeded(window: UIWindow) { - guard let preferred = window.rootViewController?.preferredContentSize, - preferred.width.isFinite, preferred.height.isFinite, - preferred.width > 0, preferred.height > 0, - !Self.sameSize(window.bounds.size, preferred), + let targetSize = bounds.size + guard targetSize.width.isFinite, targetSize.height.isFinite, + targetSize.width > 0, targetSize.height > 0, + !Self.sameSize(window.bounds.size, targetSize), let scene = window.windowScene else { return } let sourceFrame = scene.effectiveGeometry.systemFrame let rootedWindows = scene.windows.filter { $0.rootViewController != nil } guard Self.sameSize(sourceFrame.size, window.bounds.size), rootedWindows.count == 1, rootedWindows[0] === window else { return } - let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) + let targetFrame = Self.centeredFrame(size: targetSize, in: sourceFrame) let signature = "\(sourceFrame)|\(targetFrame)" guard signature != lastGeometryRequestSignature else { return } lastGeometryRequestSignature = signature @@ -646,7 +643,7 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { self.requestGeometryUpdate( window: window, scene: scene, - preferred: preferred, + targetSize: targetSize, signature: signature ) } @@ -655,24 +652,24 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { private func requestGeometryUpdate( window: UIWindow, scene: UIWindowScene, - preferred: CGSize, + targetSize: CGSize, signature: String ) { - guard let currentPreferred = window.rootViewController?.preferredContentSize, - Self.sameSize(currentPreferred, preferred) else { + guard self.window === window, + Self.sameSize(bounds.size, targetSize) else { clearGeometryRequest(signature) return } let sourceFrame = scene.effectiveGeometry.systemFrame let rootedWindows = scene.windows.filter { $0.rootViewController != nil } - guard !Self.sameSize(window.bounds.size, preferred), + guard !Self.sameSize(window.bounds.size, targetSize), Self.sameSize(sourceFrame.size, window.bounds.size), rootedWindows.count == 1, rootedWindows[0] === window else { clearGeometryRequest(signature) return } - let targetFrame = Self.centeredFrame(size: preferred, in: sourceFrame) + let targetFrame = Self.centeredFrame(size: targetSize, in: sourceFrame) scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { [weak self] _ in self?.clearGeometryRequest(signature) } @@ -681,7 +678,7 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { self.synchronizeWindowWithSceneIfNeeded( window: window, scene: scene, - preferred: preferred + targetSize: targetSize ) } } @@ -689,22 +686,22 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { private func synchronizeWindowWithSceneIfNeeded( window: UIWindow, scene: UIWindowScene, - preferred: CGSize + targetSize: CGSize ) { let effectiveFrame = scene.effectiveGeometry.systemFrame let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) let rootedWindows = scene.windows.filter { $0.rootViewController != nil } - guard window.windowScene === scene, + guard self.window === window, + window.windowScene === scene, rootedWindows.count == 1, rootedWindows[0] === window, - Self.sameSize(effectiveFrame.size, preferred) else { return } - if !Self.sameSize(window.bounds.size, preferred) { - window.frame = Self.sameSize(coordinateSpaceBounds.size, preferred) + Self.sameSize(effectiveFrame.size, targetSize) else { return } + if !Self.sameSize(window.bounds.size, targetSize) { + window.frame = Self.sameSize(coordinateSpaceBounds.size, targetSize) ? coordinateSpaceBounds - : CGRect(origin: coordinateSpaceBounds.origin, size: preferred) + : CGRect(origin: coordinateSpaceBounds.origin, size: targetSize) } - guard let currentPreferred = window.rootViewController?.preferredContentSize, - !Self.sameSize(currentPreferred, preferred) else { return } + guard !Self.sameSize(bounds.size, targetSize) else { return } DispatchQueue.main.async { [weak self, weak window] in guard let self, let window, self.window === window else { return } self.configure() From 85de655b844b0ec3070117d099f376a3973d624a Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:50:16 +0800 Subject: [PATCH 29/50] =?UTF-8?q?=E6=94=B6=E6=8B=A2=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E7=AA=97=E5=8F=A3=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 229 +++++++----------- 1 file changed, 83 insertions(+), 146 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index baa64c797..7803c2d20 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -512,30 +512,16 @@ extension WorkspaceStore { struct ConfirmedFileImportView: View { @EnvironmentObject private var store: WorkspaceStore - @State private var courseSearch = "" @State private var creatingCourse = false - private static let bodyWidth: CGFloat = 456 - private static let maximumBodyHeight: CGFloat = 350 + private static let bodyWidth: CGFloat = 396 + private static let maximumBodyHeight: CGFloat = 300 private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } - private var contentSizeRevision: String { - "\(String(reflecting: batch))|\(courseSearch)|\(creatingCourse)" - } - private var matchingCourses: [Course] { - let query = courseSearch.trimmingCharacters(in: .whitespacesAndNewlines) - return query.isEmpty ? store.courses : store.courses.filter { - $0.title.localizedCaseInsensitiveContains(query) - } - } var body: some View { VStack(alignment: .leading, spacing: 0) { if let batch { - heading(batch) - .padding(.horizontal, 22) - .padding(.top, 20) - .padding(.bottom, 15) ConfirmedImportCappedBodyLayout( width: Self.bodyWidth, maximumHeight: Self.maximumBodyHeight @@ -554,19 +540,19 @@ struct ConfirmedFileImportView: View { } .clipped() .padding(.horizontal, 22) - .padding(.vertical, 16) + .padding(.top, 22) footer(batch) .padding(.horizontal, 22) - .padding(.vertical, 13) + .padding(.top, 12) + .padding(.bottom, 22) } } - .frame(width: 500, alignment: .topLeading) + .frame(width: 440, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true) #if targetEnvironment(macCatalyst) .background(CatalystIndependentSheetSizingProbe( color: WeiBeiNativePalette.paper(), - followsContentSize: true, - contentSizeRevision: contentSizeRevision + followsContentSize: true )) #endif .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) @@ -639,37 +625,6 @@ struct ConfirmedFileImportView: View { } } - private func heading(_ batch: ConfirmedFileImportBatch) -> some View { - VStack(alignment: .leading, spacing: 5) { - Text(headingTitle(batch)) - .weiBeiBrandFont(language: store.interfaceLanguage, size: 20, weight: .semibold) - if let detail = headingDetail(batch) { - Text(detail) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - } - } - } - - private func headingTitle(_ batch: ConfirmedFileImportBatch) -> String { - switch batch.stage { - case .preparing, .reviewing: store.ui("确认导入", "Confirm Import") - case .importing: store.ui("正在导入", "Importing") - case .finished: store.ui("导入结果", "Import Results") - } - } - - private func headingDetail(_ batch: ConfirmedFileImportBatch) -> String? { - switch batch.stage { - case .preparing, .reviewing: - store.ui("导入副本,保留原文件。", "Import a copy and keep the original.") - case .importing: - destinationDescription(batch) - case .finished: - nil - } - } - private func review(_ batch: ConfirmedFileImportBatch) -> some View { VStack(alignment: .leading, spacing: 14) { fileSummary(batch) @@ -684,20 +639,11 @@ struct ConfirmedFileImportView: View { } private func fileSummary(_ batch: ConfirmedFileImportBatch) -> some View { - VStack(alignment: .leading, spacing: 8) { - Text(store.ui( - "本批内容 · \(batch.candidates.count + batch.unsupportedNames.count) 个", - "This batch · \(batch.candidates.count + batch.unsupportedNames.count) items" - )) + let fileCount = batch.candidates.count + batch.unsupportedNames.count + return VStack(alignment: .leading, spacing: 8) { + if fileCount > 1 { + Text(store.ui("\(fileCount)个文件", "\(fileCount) files")) .weiBeiText(12, weight: .semibold) - if batch.sourceFolderNames.count > 1 { - Text(store.ui( - "来源文件夹:\(batch.sourceFolderNames.joined(separator: "、"))", - "Source folders: \(batch.sourceFolderNames.joined(separator: ", "))" - )) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - .lineLimit(2) } VStack(alignment: .leading, spacing: 0) { ForEach(Array(batch.candidates.enumerated()), id: \.element.id) { index, candidate in @@ -711,14 +657,6 @@ struct ConfirmedFileImportView: View { unsupportedRow(name, asNotes: batch.importsMarkdownAsNotes) } } - if !batch.sourceFolderNames.isEmpty { - Text(store.ui( - "文件夹内只导入支持的文稿;隐藏文件和应用会跳过。", - "Only supported documents are imported from folders; hidden files and apps are skipped." - )) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - } } } @@ -770,73 +708,54 @@ struct ConfirmedFileImportView: View { } private func destinationPicker(_ batch: ConfirmedFileImportBatch) -> some View { - VStack(alignment: .leading, spacing: 8) { + HStack(spacing: 12) { Text(store.ui("导入到", "Import to")) .weiBeiText(12, weight: .semibold) - if !store.courses.isEmpty { - WeiBeiSearchField( - text: $courseSearch, - prompt: store.ui("搜索课程", "Search courses"), - isFocused: .constant(false), - fontSize: 12, - focusesOnAppear: false, - chromeHeight: 30 - ) - } - VStack(alignment: .leading, spacing: 3) { - destinationButton( - title: batch.importsMarkdownAsNotes - ? store.ui("通用笔记", "Common Notes") - : store.ui("通用资料", "Common Materials"), - courseID: nil, - selected: batch.courseID == nil - ) - ForEach(matchingCourses) { course in - destinationButton( - title: course.title, - courseID: course.id, - selected: batch.courseID == course.id - ) + Spacer(minLength: 0) + Menu { + Button { + store.setConfirmedFileImportDestination(courseID: nil) + } label: { + if batch.courseID == nil { + Label(commonDestinationTitle(batch), systemImage: "checkmark") + } else { + Text(commonDestinationTitle(batch)) + } } - if !courseSearch.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, - matchingCourses.isEmpty { - Text(store.ui("没有匹配的课程", "No matching courses")) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.tertiaryInk) - .padding(.vertical, 5) - .padding(.horizontal, 8) + ForEach(store.courses) { course in + Button { + store.setConfirmedFileImportDestination(courseID: course.id) + } label: { + if batch.courseID == course.id { + Label(course.title, systemImage: "checkmark") + } else { + Text(course.title) + } + } } + Divider() + Button(store.ui("新建课程…", "Create Course…")) { creatingCourse = true } + } label: { + HStack(spacing: 6) { + Text(destinationTitle(batch)) + .weiBeiText(13) + .lineLimit(1) + .truncationMode(.tail) + Image(systemName: "chevron.down") + .weiBeiText(12, weight: .semibold) + } + .foregroundStyle(WeiBeiTheme.ink) + .padding(.horizontal, 10) + .frame(height: 30) + .weibeiEtchedBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.52), + stroke: WeiBeiTheme.hairline.opacity(0.3), + cornerRadius: 8 + ) } - Button(store.ui("新建课程…", "Create Course…")) { creatingCourse = true } - .buttonStyle(WeiBeiTextActionButtonStyle()) - } - } - - private func destinationButton(title: String, courseID: UUID?, selected: Bool) -> some View { - Button { store.setConfirmedFileImportDestination(courseID: courseID) } label: { - HStack(alignment: .top, spacing: 8) { - Image(systemName: courseID == nil ? "tray" : "folder") - .frame(width: 15) - .padding(.top, 2) - Text(title) - .multilineTextAlignment(.leading) - .fixedSize(horizontal: false, vertical: true) - Spacer(minLength: 8) - if selected { Image(systemName: "checkmark") } - } - .weiBeiText(12, weight: selected ? .semibold : .regular) - .foregroundStyle(selected ? WeiBeiTheme.cinnabar : WeiBeiTheme.ink) - .padding(.horizontal, 9) - .padding(.vertical, 6) - .frame(maxWidth: .infinity, alignment: .leading) - .background( - selected ? WeiBeiTheme.cinnabarSoft : Color.clear, - in: RoundedRectangle(cornerRadius: 8, style: .continuous) - ) - .contentShape(Rectangle()) + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) } - .buttonStyle(.plain) - .help(title) } private func progress(_ batch: ConfirmedFileImportBatch) -> some View { @@ -855,8 +774,20 @@ struct ConfirmedFileImportView: View { private func result(_ batch: ConfirmedFileImportBatch) -> some View { let commonFailureMessage = sharedFailureMessage(batch) return VStack(alignment: .leading, spacing: 14) { - Text(resultSummary(batch)) - .weiBeiText(13, weight: .semibold) + if isSimpleSingleSuccess(batch), let item = batch.importedItems.first { + VStack(alignment: .leading, spacing: 3) { + Text(item.subtitle) + .weiBeiText(13, weight: .semibold) + .lineLimit(2) + .truncationMode(.middle) + Text(store.ui("已导入", "Imported")) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + } else { + Text(resultSummary(batch)) + .weiBeiText(13, weight: .semibold) + } if batch.stopped, !batch.pendingSourceURLs.isEmpty { Text(store.ui( "已停止;\(batch.pendingSourceURLs.count) 个文件未处理。已完成的导入已保留,原文件未变。", @@ -909,6 +840,14 @@ struct ConfirmedFileImportView: View { } } + private func isSimpleSingleSuccess(_ batch: ConfirmedFileImportBatch) -> Bool { + batch.importedItems.count == 1 + && batch.skippedCount == 0 + && batch.failures.isEmpty + && !batch.stopped + && batch.pendingSourceURLs.isEmpty + } + @ViewBuilder private func resultButtons(_ batch: ConfirmedFileImportBatch) -> some View { if !batch.pendingSourceURLs.isEmpty { @@ -995,18 +934,16 @@ struct ConfirmedFileImportView: View { return message } - private func confirmTitle(_ batch: ConfirmedFileImportBatch) -> String { - if let courseID = batch.courseID, - let course = store.courses.first(where: { $0.id == courseID }) { - return store.ui("加入《\(course.title)》", "Add to \(course.title)") - } - return batch.importsMarkdownAsNotes - ? store.ui("加入通用笔记", "Add to Common Notes") - : store.ui("加入通用资料", "Add to Common Materials") + private func commonDestinationTitle(_ batch: ConfirmedFileImportBatch) -> String { + batch.importsMarkdownAsNotes + ? store.ui("通用笔记", "Common Notes") + : store.ui("通用资料", "Common Materials") } - private func destinationDescription(_ batch: ConfirmedFileImportBatch) -> String { - store.ui("正在\(confirmTitle(batch))", confirmTitle(batch)) + private func destinationTitle(_ batch: ConfirmedFileImportBatch) -> String { + guard let courseID = batch.courseID else { return commonDestinationTitle(batch) } + return store.courses.first(where: { $0.id == courseID })?.title + ?? store.ui("选择课程", "Choose Course") } private func candidateLabel(_ candidate: ConfirmedFileImportCandidate) -> String { From 741cf6ff1e791cb81b5e2f825bb4758468e9825c Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:52:56 +0800 Subject: [PATCH 30/50] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=B0=BA=E5=AF=B8=E7=9A=84=E5=86=97=E4=BD=99=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=A0=87=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 1 - .../Views/CourseWorkspaceComponents.swift | 19 +------------------ 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 55a43263f..90aaf424b 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -587,7 +587,6 @@ struct CatalystWindowChrome: UIViewRepresentable { struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let color: UIColor var followsContentSize = false - var contentSizeRevision = "" func makeUIView(context: Context) -> Probe { Probe() } diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 9f2a179b3..d90bd241d 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -342,22 +342,6 @@ struct CourseProjectEntrySheet: View { selectedImportURLs.contains { StudyItemKind.detect(from: $0) == .markdown } } - private var contentSizeRevision: String { - [ - String(describing: intent), - title, - selectedFolder?.path ?? "", - selectedImportURLs.map(\.path).joined(separator: "|"), - String(configuredLibraryThisTime), - String(isWorking), - errorMessage ?? "", - String(reflecting: rebindProposal), - String(needsLibrary), - store.courseLibraryRootPath ?? "", - String(describing: store.interfaceLanguage) - ].joined(separator: "§") - } - var body: some View { VStack(alignment: .leading, spacing: 14) { VStack(alignment: .leading, spacing: 5) { @@ -406,8 +390,7 @@ struct CourseProjectEntrySheet: View { #if targetEnvironment(macCatalyst) .background(CatalystIndependentSheetSizingProbe( color: WeiBeiNativePalette.paper(), - followsContentSize: true, - contentSizeRevision: contentSizeRevision + followsContentSize: true )) #endif .background(WeiBeiTheme.paper) From dc4a9dbbfd636ebf59fb048a600b9f7c05860a68 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 11:59:28 +0800 Subject: [PATCH 31/50] =?UTF-8?q?=E8=A1=A5=E5=85=A8=E5=AF=BC=E5=85=A5?= =?UTF-8?q?=E8=8C=83=E5=9B=B4=E4=B8=8E=E7=BB=93=E6=9E=9C=E5=8A=A8=E4=BD=9C?= =?UTF-8?q?=E8=AF=AD=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/ConfirmedFileImportView.swift | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 7803c2d20..b943f5796 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -641,7 +641,13 @@ struct ConfirmedFileImportView: View { private func fileSummary(_ batch: ConfirmedFileImportBatch) -> some View { let fileCount = batch.candidates.count + batch.unsupportedNames.count return VStack(alignment: .leading, spacing: 8) { - if fileCount > 1 { + if !batch.sourceFolderNames.isEmpty { + Text(store.ui( + "可导入文稿 · \(batch.candidates.count)个", + "Importable documents · \(batch.candidates.count)" + )) + .weiBeiText(12, weight: .semibold) + } else if fileCount > 1 { Text(store.ui("\(fileCount)个文件", "\(fileCount) files")) .weiBeiText(12, weight: .semibold) } @@ -887,7 +893,11 @@ struct ConfirmedFileImportView: View { } else if batch.importedItems.count == 1 { Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button(store.ui("打开文稿", "Open Document")) { + Button( + batch.importsMarkdownAsNotes + ? store.ui("打开笔记", "Open Note") + : store.ui("打开文稿", "Open Document") + ) { store.openSingleConfirmedImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) @@ -895,7 +905,11 @@ struct ConfirmedFileImportView: View { } else if batch.importedItems.count > 1 { Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button(store.ui("查看已导入资料", "View Imported Items")) { + Button( + batch.importsMarkdownAsNotes + ? store.ui("查看已导入笔记", "View Imported Notes") + : store.ui("查看已导入资料", "View Imported Items") + ) { store.showConfirmedImportBatch() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) From 4efbc81e25d4a81b33c48d0f864704fa1b191ac4 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 12:01:00 +0800 Subject: [PATCH 32/50] =?UTF-8?q?=E5=A4=8D=E7=94=A8=E6=96=87=E6=9C=AC?= =?UTF-8?q?=E7=88=B6=E7=B1=BB=E5=9E=8B=E8=A6=86=E7=9B=96=E8=B5=84=E6=96=99?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index b4211ff7e..5922a8606 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -5948,7 +5948,7 @@ final class WorkspaceStore: ObservableObject { Task { @MainActor in let types: [UTType] = markdownAsNotes ? [WorkspaceFileDialog.markdownType, .folder] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, WorkspaceFileDialog.markdownType, .folder] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, .folder] let urls = await WorkspaceFileDialog.pick( title: panelTitle ?? ui("选择学习资料或课程文件夹", "Choose study materials or a course folder"), types: types, multiple: true @@ -5970,7 +5970,7 @@ final class WorkspaceStore: ObservableObject { panel.canChooseFiles = true panel.allowedContentTypes = markdownAsNotes ? [WorkspaceFileDialog.markdownType] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, WorkspaceFileDialog.markdownType] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText] guard panel.runModal() == .OK else { return } prepareConfirmedFileImport( From f061bbbb9a22897d5892b0bc01b01b6085cab417 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 12:04:37 +0800 Subject: [PATCH 33/50] =?UTF-8?q?=E6=8C=89=E8=87=AA=E7=84=B6=E5=86=85?= =?UTF-8?q?=E5=AE=B9=E5=B0=BA=E5=AF=B8=E6=9B=B4=E6=96=B0=E5=BC=B9=E7=AA=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 42 +++++++++++++++---- .../Views/ConfirmedFileImportView.swift | 5 +-- .../Views/CourseWorkspaceComponents.swift | 8 +--- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 90aaf424b..c3dc431c0 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -584,21 +584,44 @@ struct CatalystWindowChrome: UIViewRepresentable { } // SwiftUI's Mac Catalyst sheet is hosted in a separate UIKit window. +struct CatalystIndependentSheetFitting: ViewModifier { + let color: UIColor + @State private var contentSize = CGSize.zero + + func body(content: Content) -> some View { + content + .onGeometryChange(for: CGSize.self) { proxy in + proxy.size + } action: { size in + contentSize = size + } + .background(CatalystIndependentSheetSizingProbe( + color: color, + contentSize: contentSize + )) + } +} + struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let color: UIColor - var followsContentSize = false + var contentSize: CGSize? + + init(color: UIColor, contentSize: CGSize? = nil) { + self.color = color + self.contentSize = contentSize + } func makeUIView(context: Context) -> Probe { Probe() } func updateUIView(_ view: Probe, context: Context) { view.color = color - view.followsContentSize = followsContentSize + view.contentSize = contentSize view.configure() } final class Probe: UIView { var color = UIColor.clear - var followsContentSize = false + var contentSize: CGSize? private var lastGeometryRequestSignature: String? override func didMoveToWindow() { super.didMoveToWindow(); configure() } @@ -614,12 +637,11 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { } responder = current.next } - guard followsContentSize else { return } - resizeSheetIfNeeded(window: window) + guard let contentSize else { return } + resizeSheetIfNeeded(window: window, targetSize: contentSize) } - private func resizeSheetIfNeeded(window: UIWindow) { - let targetSize = bounds.size + private func resizeSheetIfNeeded(window: UIWindow, targetSize: CGSize) { guard targetSize.width.isFinite, targetSize.height.isFinite, targetSize.width > 0, targetSize.height > 0, !Self.sameSize(window.bounds.size, targetSize), @@ -655,7 +677,8 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { signature: String ) { guard self.window === window, - Self.sameSize(bounds.size, targetSize) else { + let contentSize, + Self.sameSize(contentSize, targetSize) else { clearGeometryRequest(signature) return } @@ -700,7 +723,8 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { ? coordinateSpaceBounds : CGRect(origin: coordinateSpaceBounds.origin, size: targetSize) } - guard !Self.sameSize(bounds.size, targetSize) else { return } + guard let contentSize, + !Self.sameSize(contentSize, targetSize) else { return } DispatchQueue.main.async { [weak self, weak window] in guard let self, let window, self.window === window else { return } self.configure() diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index b943f5796..cfa0797ec 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -550,10 +550,7 @@ struct ConfirmedFileImportView: View { .frame(width: 440, alignment: .topLeading) .fixedSize(horizontal: false, vertical: true) #if targetEnvironment(macCatalyst) - .background(CatalystIndependentSheetSizingProbe( - color: WeiBeiNativePalette.paper(), - followsContentSize: true - )) + .modifier(CatalystIndependentSheetFitting(color: WeiBeiNativePalette.paper())) #endif .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index d90bd241d..2603dddd2 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -388,10 +388,7 @@ struct CourseProjectEntrySheet: View { .fixedSize(horizontal: false, vertical: true) .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) - .background(CatalystIndependentSheetSizingProbe( - color: WeiBeiNativePalette.paper(), - followsContentSize: true - )) + .modifier(CatalystIndependentSheetFitting(color: WeiBeiNativePalette.paper())) #endif .background(WeiBeiTheme.paper) .foregroundStyle(WeiBeiTheme.ink) @@ -714,7 +711,7 @@ struct CourseProjectEntrySheet: View { private func chooseImportContentWithPicker() async { #if targetEnvironment(macCatalyst) - let urls = await WorkspaceFileDialog.pick(title: store.ui("选择课程内容", "Choose Course Content"), types: [.folder, .pdf, .html, .plainText, WorkspaceFileDialog.markdownType, UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation")], multiple: true) + let urls = await WorkspaceFileDialog.pick(title: store.ui("选择课程内容", "Choose Course Content"), types: [.folder, .pdf, .html, .plainText, UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation")], multiple: true) #else let panel = NSOpenPanel() panel.title = store.ui("选择课程内容", "Choose Course Content") @@ -732,7 +729,6 @@ struct CourseProjectEntrySheet: View { .pdf, .html, .plainText, - WorkspaceFileDialog.markdownType, ] guard panel.runModal() == .OK else { return } let urls = panel.urls From 74d50927ca58115cc2d4ea2d94011327b91e0226 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 14:08:37 +0800 Subject: [PATCH 34/50] =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=B0=BA=E5=AF=B8=E8=AF=B7=E6=B1=82=E6=97=B6=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 96 +++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index c3dc431c0..1deaa7b4e 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -629,6 +629,12 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { func configure() { guard let window else { return } + logGeometry( + event: "configure", + window: window, + scene: window.windowScene, + targetSize: contentSize + ) window.backgroundColor = color var responder: UIResponder? = self while let current = responder { @@ -676,6 +682,12 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { targetSize: CGSize, signature: String ) { + logGeometry( + event: "request-before-guard", + window: window, + scene: scene, + targetSize: targetSize + ) guard self.window === window, let contentSize, Self.sameSize(contentSize, targetSize) else { @@ -710,6 +722,12 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { scene: UIWindowScene, targetSize: CGSize ) { + logGeometry( + event: "sync-before-guard", + window: window, + scene: scene, + targetSize: targetSize + ) let effectiveFrame = scene.effectiveGeometry.systemFrame let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) let rootedWindows = scene.windows.filter { $0.rootViewController != nil } @@ -731,6 +749,84 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { } } + private func logGeometry( + event: String, + window: UIWindow, + scene: UIWindowScene?, + targetSize: CGSize? + ) { + guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926" else { + return + } + let rootedWindows = scene?.windows.filter { $0.rootViewController != nil } ?? [] + let effectiveFrame = scene?.effectiveGeometry.systemFrame + let rootViewController = window.rootViewController + let windowSceneMatches = scene != nil && window.windowScene === scene + let singleRootedWindowMatches = rootedWindows.count == 1 && rootedWindows[0] === window + let effectiveMatchesTarget: Bool + if let effectiveFrame, let targetSize { + effectiveMatchesTarget = Self.sameSize(effectiveFrame.size, targetSize) + } else { + effectiveMatchesTarget = false + } + let effectiveMatchesWindow: Bool + if let effectiveFrame { + effectiveMatchesWindow = Self.sameSize(effectiveFrame.size, window.bounds.size) + } else { + effectiveMatchesWindow = false + } + let contentMatchesTarget: Bool + if let contentSize, let targetSize { + contentMatchesTarget = Self.sameSize(contentSize, targetSize) + } else { + contentMatchesTarget = false + } + let record: [String: Any] = [ + "event": event, + "uptime": ProcessInfo.processInfo.systemUptime, + "contentSize": Self.jsonSize(contentSize), + "targetSize": Self.jsonSize(targetSize), + "probeBounds": Self.jsonRect(bounds), + "windowBounds": Self.jsonRect(window.bounds), + "rootViewBounds": Self.jsonRect(rootViewController?.view.bounds), + "rootPreferredSize": Self.jsonSize(rootViewController?.preferredContentSize), + "effectiveFrame": Self.jsonRect(effectiveFrame), + "lastSignature": (lastGeometryRequestSignature as Any?) ?? NSNull(), + "probeWindowMatches": self.window === window, + "windowSceneMatches": windowSceneMatches, + "rootedWindowCount": rootedWindows.count, + "singleRootedWindowMatches": singleRootedWindowMatches, + "effectiveMatchesTarget": effectiveMatchesTarget, + "effectiveMatchesWindow": effectiveMatchesWindow, + "contentMatchesTarget": contentMatchesTarget + ] + guard let data = try? JSONSerialization.data(withJSONObject: record) else { return } + let url = URL(fileURLWithPath: "/private/tmp/weibei-dialog-geometry-0929.jsonl") + if !FileManager.default.fileExists(atPath: url.path) { + _ = FileManager.default.createFile(atPath: url.path, contents: nil) + } + guard let handle = try? FileHandle(forWritingTo: url) else { return } + defer { try? handle.close() } + handle.seekToEndOfFile() + handle.write(data) + handle.write(Data([0x0A])) + } + + private static func jsonSize(_ size: CGSize?) -> Any { + guard let size else { return NSNull() } + return ["width": size.width, "height": size.height] + } + + private static func jsonRect(_ rect: CGRect?) -> Any { + guard let rect else { return NSNull() } + return [ + "x": rect.origin.x, + "y": rect.origin.y, + "width": rect.size.width, + "height": rect.size.height + ] + } + private func clearGeometryRequest(_ signature: String) { if lastGeometryRequestSignature == signature { lastGeometryRequestSignature = nil From 778e7336922ad7e9234fb2e5c838efad3f12360b Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 14:14:42 +0800 Subject: [PATCH 35/50] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=86=85=E9=83=A8=E8=A7=86=E5=8F=A3=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 34 ++++++++++++++++++++--- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 1deaa7b4e..95fdcd9c8 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -741,10 +741,36 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { ? coordinateSpaceBounds : CGRect(origin: coordinateSpaceBounds.origin, size: targetSize) } - guard let contentSize, - !Self.sameSize(contentSize, targetSize) else { return } - DispatchQueue.main.async { [weak self, weak window] in - guard let self, let window, self.window === window else { return } + logGeometry( + event: "sync-after-frame", + window: window, + scene: scene, + targetSize: targetSize + ) + let acceptedSize = effectiveFrame.size + if !Self.sameSize(window.bounds.size, acceptedSize) { + window.bounds = CGRect(origin: window.bounds.origin, size: acceptedSize) + } + window.setNeedsLayout() + window.layoutIfNeeded() + logGeometry( + event: "sync-after-bounds", + window: window, + scene: scene, + targetSize: targetSize + ) + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self, let window, let scene, + self.window === window, + window.windowScene === scene else { return } + self.logGeometry( + event: "sync-next-runloop", + window: window, + scene: scene, + targetSize: targetSize + ) + guard let contentSize, + !Self.sameSize(contentSize, targetSize) else { return } self.configure() } } From 98635a24ef4ec568aae6cb205b2a4725058a43df Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 14:21:50 +0800 Subject: [PATCH 36/50] =?UTF-8?q?=E9=80=9A=E7=9F=A5=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E6=9B=B4=E6=96=B0=E5=86=85=E5=AE=B9=E5=B0=BA?= =?UTF-8?q?=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 49 +++++++++++++---------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 95fdcd9c8..5eb130e30 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -729,32 +729,30 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { targetSize: targetSize ) let effectiveFrame = scene.effectiveGeometry.systemFrame - let coordinateSpaceBounds = Self.coordinateSpaceBounds(for: scene) let rootedWindows = scene.windows.filter { $0.rootViewController != nil } guard self.window === window, window.windowScene === scene, rootedWindows.count == 1, rootedWindows[0] === window, - Self.sameSize(effectiveFrame.size, targetSize) else { return } - if !Self.sameSize(window.bounds.size, targetSize) { - window.frame = Self.sameSize(coordinateSpaceBounds.size, targetSize) - ? coordinateSpaceBounds - : CGRect(origin: coordinateSpaceBounds.origin, size: targetSize) - } + Self.sameSize(effectiveFrame.size, targetSize), + let rootViewController = window.rootViewController, + let presentationController = rootViewController.presentationController, + presentationController.presentedViewController === rootViewController, + let containerView = presentationController.containerView else { return } + rootViewController.preferredContentSize = targetSize logGeometry( - event: "sync-after-frame", + event: "notification-before", window: window, scene: scene, targetSize: targetSize ) - let acceptedSize = effectiveFrame.size - if !Self.sameSize(window.bounds.size, acceptedSize) { - window.bounds = CGRect(origin: window.bounds.origin, size: acceptedSize) - } - window.setNeedsLayout() - window.layoutIfNeeded() + presentationController.preferredContentSizeDidChange( + forChildContentContainer: rootViewController + ) + containerView.setNeedsLayout() + containerView.layoutIfNeeded() logGeometry( - event: "sync-after-bounds", + event: "notification-after", window: window, scene: scene, targetSize: targetSize @@ -764,7 +762,7 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { self.window === window, window.windowScene === scene else { return } self.logGeometry( - event: "sync-next-runloop", + event: "notification-next-runloop", window: window, scene: scene, targetSize: targetSize @@ -787,8 +785,18 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { let rootedWindows = scene?.windows.filter { $0.rootViewController != nil } ?? [] let effectiveFrame = scene?.effectiveGeometry.systemFrame let rootViewController = window.rootViewController + let presentationController = rootViewController?.presentationController + let presentationClassName = presentationController.map { + String(reflecting: type(of: $0)) + } let windowSceneMatches = scene != nil && window.windowScene === scene let singleRootedWindowMatches = rootedWindows.count == 1 && rootedWindows[0] === window + let presentedRootMatches: Bool + if let rootViewController, let presentationController { + presentedRootMatches = presentationController.presentedViewController === rootViewController + } else { + presentedRootMatches = false + } let effectiveMatchesTarget: Bool if let effectiveFrame, let targetSize { effectiveMatchesTarget = Self.sameSize(effectiveFrame.size, targetSize) @@ -816,6 +824,9 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { "windowBounds": Self.jsonRect(window.bounds), "rootViewBounds": Self.jsonRect(rootViewController?.view.bounds), "rootPreferredSize": Self.jsonSize(rootViewController?.preferredContentSize), + "presentationClass": (presentationClassName as Any?) ?? NSNull(), + "presentedRootMatches": presentedRootMatches, + "presentationContainerBounds": Self.jsonRect(presentationController?.containerView?.bounds), "effectiveFrame": Self.jsonRect(effectiveFrame), "lastSignature": (lastGeometryRequestSignature as Any?) ?? NSNull(), "probeWindowMatches": self.window === window, @@ -872,11 +883,5 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { ) } - private static func coordinateSpaceBounds(for scene: UIWindowScene) -> CGRect { - if #available(iOS 26.0, *) { - return scene.effectiveGeometry.coordinateSpace.bounds - } - return scene.coordinateSpace.bounds - } } } From 41f8bbd89cc8622b9e2a00e0d35a11d259aaa18e Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 14:22:45 +0800 Subject: [PATCH 37/50] =?UTF-8?q?=E9=87=87=E6=A0=B7=E9=AA=8C=E6=94=B6?= =?UTF-8?q?=E5=BC=B9=E7=AA=97=E5=A4=96=E5=B1=82=E5=8E=9F=E7=94=9F=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E5=B0=BA=E5=AF=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/WindowBridge/NativeWindowBridge.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index b70dff2a2..f379915f4 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -25,6 +25,19 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didUpdateNotification, object: nil, queue: .main) { [weak self] note in guard let self, let window = note.object as? NSWindow else { return } self.updateToolbarBackground(in: window) + if Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926", + window.isVisible, abs(window.frame.width - 440) < 1 { + let line = "uptime=\(ProcessInfo.processInfo.systemUptime) native=\(window.windowNumber) frame=\(window.frame) content=\(String(describing: window.contentView?.bounds)) parent=\(window.parent?.windowNumber ?? -1)\n" + let url = URL(fileURLWithPath: "/private/tmp/weibei-native-window-0929.log") + if !FileManager.default.fileExists(atPath: url.path) { + _ = FileManager.default.createFile(atPath: url.path, contents: nil) + } + if let handle = try? FileHandle(forWritingTo: url) { + handle.seekToEndOfFile() + handle.write(Data(line.utf8)) + try? handle.close() + } + } guard !window.acceptsMouseMovedEvents || (self.mode.hasPrefix("glass") && self.materials.object(forKey: window)?.superview == nil) else { return } self.apply(to: window) From b17b1cf21f1363dd5800d19c76dffef79c717dd7 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 14:35:57 +0800 Subject: [PATCH 38/50] =?UTF-8?q?=E6=B8=85=E7=90=86=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E5=B0=BA=E5=AF=B8=E4=B8=B4=E6=97=B6=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/Sources/CatalystWorkspaceChrome.swift | 127 ---------------------- App/WindowBridge/NativeWindowBridge.swift | 13 --- 2 files changed, 140 deletions(-) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 5eb130e30..ea7abd9ff 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -629,12 +629,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { func configure() { guard let window else { return } - logGeometry( - event: "configure", - window: window, - scene: window.windowScene, - targetSize: contentSize - ) window.backgroundColor = color var responder: UIResponder? = self while let current = responder { @@ -682,12 +676,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { targetSize: CGSize, signature: String ) { - logGeometry( - event: "request-before-guard", - window: window, - scene: scene, - targetSize: targetSize - ) guard self.window === window, let contentSize, Self.sameSize(contentSize, targetSize) else { @@ -722,12 +710,6 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { scene: UIWindowScene, targetSize: CGSize ) { - logGeometry( - event: "sync-before-guard", - window: window, - scene: scene, - targetSize: targetSize - ) let effectiveFrame = scene.effectiveGeometry.systemFrame let rootedWindows = scene.windows.filter { $0.rootViewController != nil } guard self.window === window, @@ -740,130 +722,21 @@ struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { presentationController.presentedViewController === rootViewController, let containerView = presentationController.containerView else { return } rootViewController.preferredContentSize = targetSize - logGeometry( - event: "notification-before", - window: window, - scene: scene, - targetSize: targetSize - ) presentationController.preferredContentSizeDidChange( forChildContentContainer: rootViewController ) containerView.setNeedsLayout() containerView.layoutIfNeeded() - logGeometry( - event: "notification-after", - window: window, - scene: scene, - targetSize: targetSize - ) DispatchQueue.main.async { [weak self, weak window, weak scene] in guard let self, let window, let scene, self.window === window, window.windowScene === scene else { return } - self.logGeometry( - event: "notification-next-runloop", - window: window, - scene: scene, - targetSize: targetSize - ) guard let contentSize, !Self.sameSize(contentSize, targetSize) else { return } self.configure() } } - private func logGeometry( - event: String, - window: UIWindow, - scene: UIWindowScene?, - targetSize: CGSize? - ) { - guard Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926" else { - return - } - let rootedWindows = scene?.windows.filter { $0.rootViewController != nil } ?? [] - let effectiveFrame = scene?.effectiveGeometry.systemFrame - let rootViewController = window.rootViewController - let presentationController = rootViewController?.presentationController - let presentationClassName = presentationController.map { - String(reflecting: type(of: $0)) - } - let windowSceneMatches = scene != nil && window.windowScene === scene - let singleRootedWindowMatches = rootedWindows.count == 1 && rootedWindows[0] === window - let presentedRootMatches: Bool - if let rootViewController, let presentationController { - presentedRootMatches = presentationController.presentedViewController === rootViewController - } else { - presentedRootMatches = false - } - let effectiveMatchesTarget: Bool - if let effectiveFrame, let targetSize { - effectiveMatchesTarget = Self.sameSize(effectiveFrame.size, targetSize) - } else { - effectiveMatchesTarget = false - } - let effectiveMatchesWindow: Bool - if let effectiveFrame { - effectiveMatchesWindow = Self.sameSize(effectiveFrame.size, window.bounds.size) - } else { - effectiveMatchesWindow = false - } - let contentMatchesTarget: Bool - if let contentSize, let targetSize { - contentMatchesTarget = Self.sameSize(contentSize, targetSize) - } else { - contentMatchesTarget = false - } - let record: [String: Any] = [ - "event": event, - "uptime": ProcessInfo.processInfo.systemUptime, - "contentSize": Self.jsonSize(contentSize), - "targetSize": Self.jsonSize(targetSize), - "probeBounds": Self.jsonRect(bounds), - "windowBounds": Self.jsonRect(window.bounds), - "rootViewBounds": Self.jsonRect(rootViewController?.view.bounds), - "rootPreferredSize": Self.jsonSize(rootViewController?.preferredContentSize), - "presentationClass": (presentationClassName as Any?) ?? NSNull(), - "presentedRootMatches": presentedRootMatches, - "presentationContainerBounds": Self.jsonRect(presentationController?.containerView?.bounds), - "effectiveFrame": Self.jsonRect(effectiveFrame), - "lastSignature": (lastGeometryRequestSignature as Any?) ?? NSNull(), - "probeWindowMatches": self.window === window, - "windowSceneMatches": windowSceneMatches, - "rootedWindowCount": rootedWindows.count, - "singleRootedWindowMatches": singleRootedWindowMatches, - "effectiveMatchesTarget": effectiveMatchesTarget, - "effectiveMatchesWindow": effectiveMatchesWindow, - "contentMatchesTarget": contentMatchesTarget - ] - guard let data = try? JSONSerialization.data(withJSONObject: record) else { return } - let url = URL(fileURLWithPath: "/private/tmp/weibei-dialog-geometry-0929.jsonl") - if !FileManager.default.fileExists(atPath: url.path) { - _ = FileManager.default.createFile(atPath: url.path, contents: nil) - } - guard let handle = try? FileHandle(forWritingTo: url) else { return } - defer { try? handle.close() } - handle.seekToEndOfFile() - handle.write(data) - handle.write(Data([0x0A])) - } - - private static func jsonSize(_ size: CGSize?) -> Any { - guard let size else { return NSNull() } - return ["width": size.width, "height": size.height] - } - - private static func jsonRect(_ rect: CGRect?) -> Any { - guard let rect else { return NSNull() } - return [ - "x": rect.origin.x, - "y": rect.origin.y, - "width": rect.size.width, - "height": rect.size.height - ] - } - private func clearGeometryRequest(_ signature: String) { if lastGeometryRequestSignature == signature { lastGeometryRequestSignature = nil diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index f379915f4..b70dff2a2 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -25,19 +25,6 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didUpdateNotification, object: nil, queue: .main) { [weak self] note in guard let self, let window = note.object as? NSWindow else { return } self.updateToolbarBackground(in: window) - if Bundle.main.bundleIdentifier == "com.changfenhuang.weibei.qa.cursorcloseout20260926", - window.isVisible, abs(window.frame.width - 440) < 1 { - let line = "uptime=\(ProcessInfo.processInfo.systemUptime) native=\(window.windowNumber) frame=\(window.frame) content=\(String(describing: window.contentView?.bounds)) parent=\(window.parent?.windowNumber ?? -1)\n" - let url = URL(fileURLWithPath: "/private/tmp/weibei-native-window-0929.log") - if !FileManager.default.fileExists(atPath: url.path) { - _ = FileManager.default.createFile(atPath: url.path, contents: nil) - } - if let handle = try? FileHandle(forWritingTo: url) { - handle.seekToEndOfFile() - handle.write(Data(line.utf8)) - try? handle.close() - } - } guard !window.acceptsMouseMovedEvents || (self.mode.hasPrefix("glass") && self.materials.object(forKey: window)?.superview == nil) else { return } self.apply(to: window) From fcef856f9a598cb13e315f5c9d6ecaa82af82937 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 15:09:46 +0800 Subject: [PATCH 39/50] refine confirmed import completion flow --- .../Stores/CourseProjectRootSupport.swift | 42 ++- .../Views/ConfirmedFileImportView.swift | 251 +++++++++---- .../ConfirmedFileImportTests.swift | 339 ++++++++++++++++-- 3 files changed, 531 insertions(+), 101 deletions(-) diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index 87bc78b60..87d7d7434 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -3153,23 +3153,42 @@ actor CourseProjectFileWorker { nonisolated static func expandedImportSelection( from urls: [URL], markdownOnly: Bool - ) -> (supported: [URL], unsupportedNames: [String]) { + ) -> ( + supported: [URL], + unsupportedNames: [String], + unavailableSourceURLs: [URL] + ) { let fileManager = FileManager.default var seenSupported = Set() var seenUnsupported = Set() + var seenUnavailable = Set() var supported: [URL] = [] var unsupportedNames: [String] = [] + var unavailableSourceURLs: [URL] = [] + func recordUnavailable(_ url: URL) { + let standardized = url.standardizedFileURL + if seenUnavailable.insert(standardized.path).inserted { + unavailableSourceURLs.append(standardized) + } + } for rawURL in urls { guard let rootValues = try? rawURL.resourceValues(forKeys: [ .isDirectoryKey, .isSymbolicLinkKey, .isAliasFileKey, - ]), - rootValues.isSymbolicLink != true, + ]) else { + recordUnavailable(rawURL) + continue + } + guard rootValues.isSymbolicLink != true, rootValues.isAliasFile != true else { continue } if rootValues.isDirectory != true { + guard fileManager.isReadableFile(atPath: rawURL.path) else { + recordUnavailable(rawURL) + continue + } appendImportSelection( rawURL, displayName: rawURL.lastPathComponent, @@ -3191,8 +3210,12 @@ actor CourseProjectFileWorker { .isAliasFileKey, ], options: [.skipsHiddenFiles, .skipsPackageDescendants], - errorHandler: { _, _ in false } + errorHandler: { failedURL, _ in + recordUnavailable(failedURL) + return true + } ) else { + recordUnavailable(rawURL) continue } for case let fileURL as URL in enumerator { @@ -3201,6 +3224,7 @@ actor CourseProjectFileWorker { .isSymbolicLinkKey, .isAliasFileKey, ]) else { + recordUnavailable(fileURL) enumerator.skipDescendants() continue } @@ -3213,6 +3237,11 @@ actor CourseProjectFileWorker { enumerator.skipDescendants() continue } + if values.isDirectory != true, + !fileManager.isReadableFile(atPath: fileURL.path) { + recordUnavailable(fileURL) + continue + } let rootPath = rawURL.standardizedFileURL.path let filePath = fileURL.standardizedFileURL.path let relativePath = filePath.hasPrefix(rootPath + "/") @@ -3231,7 +3260,10 @@ actor CourseProjectFileWorker { } return ( supported.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }, - unsupportedNames.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + unsupportedNames.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, + unavailableSourceURLs.sorted { + $0.path.localizedStandardCompare($1.path) == .orderedAscending + } ) } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index cfa0797ec..a5c587fb9 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -38,7 +38,8 @@ struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { var unsupportedNames: [String] = [] var importedItems: [StudyItem] = [] var failures: [ConfirmedFileImportFailure] = [] - var previousSkippedCount = 0 + var previousDuplicateCount = 0 + var previousUnsupportedCount = 0 var completed = 0 var total = 0 var currentFileName: String? @@ -51,10 +52,17 @@ struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { } var skippedCount: Int { - previousSkippedCount - + unsupportedNames.count + duplicateCount + unsupportedCount + } + + var duplicateCount: Int { + previousDuplicateCount + candidates.filter { $0.disposition == .duplicate }.count } + + var unsupportedCount: Int { + previousUnsupportedCount + unsupportedNames.count + } } extension WorkspaceStore { @@ -165,7 +173,8 @@ extension WorkspaceStore { courseID: batch.courseID, importsMarkdownAsNotes: batch.importsMarkdownAsNotes, importedItems: batch.importedItems, - previousSkippedCount: batch.skippedCount, + previousDuplicateCount: batch.duplicateCount, + previousUnsupportedCount: batch.unsupportedCount, pendingSourceURLs: batch.pendingSourceURLs ) refreshConfirmedFileImportPlan() @@ -177,6 +186,7 @@ extension WorkspaceStore { batch.confirmableCount > 0, batch.destinationError == nil else { return } batch.stage = .importing + let preflightFailures = batch.failures batch.failures = [] batch.completed = 0 batch.total = batch.candidates.count + batch.unsupportedNames.count @@ -190,7 +200,7 @@ extension WorkspaceStore { guard let self else { return } var batch = initialBatch var imported = batch.importedItems - var failures: [ConfirmedFileImportFailure] = [] + var failures = preflightFailures var completed = batch.unsupportedNames.count for candidate in batch.candidates { if confirmedFileImportStopRequested { @@ -238,7 +248,7 @@ extension WorkspaceStore { batch.stopped = batch.stopped || confirmedFileImportStopRequested confirmedFileImportStopRequested = false confirmedFileImportTask = nil - publishConfirmedFileImportProgress(batch) + settleConfirmedFileImport(batch) } } @@ -254,6 +264,96 @@ extension WorkspaceStore { confirmedFileImport = next } + private func settleConfirmedFileImport(_ batch: ConfirmedFileImportBatch) { + guard confirmedFileImport?.id == batch.id else { return } + publishConfirmedFileImportProgress(batch) + guard let settled = confirmedFileImport, settled.id == batch.id else { return } + if settled.stopped, + settled.failures.isEmpty, + settled.pendingSourceURLs.isEmpty { + let remaining = max(0, settled.total - settled.completed) + dismissConfirmedFileImport() + showTransientNoteStatus( + remaining > 0 + ? ui( + "导入已停止;\(remaining) 份未导入。", + "Import stopped; \(remaining) item(s) were not imported." + ) + : ui( + "导入已停止;已完成的导入仍然保留。", + "Import stopped. Completed imports were kept." + ) + ) + return + } + guard settled.failures.isEmpty, + !settled.stopped, + settled.pendingSourceURLs.isEmpty else { return } + + let feedback = confirmedImportCompletionFeedback(settled) + if settled.importedItems.count == 1 { + openSingleConfirmedImport() + } else if !settled.importedItems.isEmpty { + showConfirmedImportBatch() + } else { + dismissConfirmedFileImport() + } + if let feedback { + showTransientNoteStatus(feedback) + } + } + + private func confirmedImportCompletionFeedback(_ batch: ConfirmedFileImportBatch) -> String? { + let imported = batch.importedItems.count + let duplicates = batch.duplicateCount + let unsupported = batch.unsupportedCount + let chineseRole = batch.importsMarkdownAsNotes ? "笔记" : "资料" + let englishRole = batch.importsMarkdownAsNotes ? "notes" : "materials" + if imported == 0 { + if duplicates > 0, unsupported > 0 { + return ui( + "没有新增内容;\(duplicates) 个已存在,\(unsupported) 个格式不支持。", + "Nothing new was imported. \(duplicates) already existed and \(unsupported) had unsupported formats." + ) + } + if duplicates > 0 { + return ui( + "这 \(duplicates) 份\(chineseRole)已存在,未重复导入。", + "These \(duplicates) \(englishRole) already exist and were not imported again." + ) + } + if unsupported > 0 { + return ui( + "没有可导入的文件;\(unsupported) 个格式不支持。", + "No files could be imported; \(unsupported) had unsupported formats." + ) + } + return ui( + "所选内容没有可导入的文件。", + "The selected content has no importable files." + ) + } + if duplicates > 0, unsupported > 0 { + return ui( + "\(duplicates) 个已存在未重复导入,\(unsupported) 个格式不支持。", + "\(duplicates) already existed and were not imported again; \(unsupported) had unsupported formats." + ) + } + if duplicates > 0 { + return ui( + "\(duplicates) 个已存在,未重复导入。", + "\(duplicates) already existed and were not imported again." + ) + } + if unsupported > 0 { + return ui( + "\(unsupported) 个格式不支持,未导入。", + "\(unsupported) had unsupported formats and were not imported." + ) + } + return nil + } + func openSingleConfirmedImport() { guard let batch = confirmedFileImport, batch.importedItems.count == 1, let item = batch.importedItems.first else { return } @@ -337,31 +437,45 @@ extension WorkspaceStore { current.stage = .reviewing current.candidates = plan.candidates current.unsupportedNames = plan.unsupportedNames + current.failures = plan.unavailableSourceURLs.map { + ConfirmedFileImportFailure( + sourceURL: $0, + message: self.ui( + "文件已移动、删除或暂时无法访问。请恢复文件后重试。", + "The file was moved, deleted, or is temporarily unavailable. Restore it, then retry." + ) + ) + } confirmedFileImportTask = nil - confirmedFileImport = current + if current.candidates.isEmpty { + confirmedFileImport = current + if current.failures.isEmpty { + let feedback = confirmedImportCompletionFeedback(current) + dismissConfirmedFileImport() + if let feedback { showTransientNoteStatus(feedback) } + } else { + current.stage = .finished + confirmedFileImport = current + } + } else { + confirmedFileImport = current + } } } nonisolated static func makeConfirmedFileImportPlan( urls: [URL], destination: URL, markdownOnly: Bool - ) -> (candidates: [ConfirmedFileImportCandidate], unsupportedNames: [String]) { + ) -> ( + candidates: [ConfirmedFileImportCandidate], + unsupportedNames: [String], + unavailableSourceURLs: [URL] + ) { let expansion = CourseProjectFileWorker.expandedImportSelection( from: urls, markdownOnly: markdownOnly ) let expanded = expansion.supported - var unsupported = expansion.unsupportedNames - unsupported.append(contentsOf: urls.compactMap { url -> String? in - let values = try? url.resourceValues(forKeys: [.isDirectoryKey]) - guard values?.isDirectory == true else { return nil } - let nested = CourseProjectFileWorker.expandedImportSelection( - from: [url], - markdownOnly: markdownOnly - ) - return nested.supported.isEmpty && nested.unsupportedNames.isEmpty - ? url.lastPathComponent - : nil - }) + let unsupported = expansion.unsupportedNames var candidates: [ConfirmedFileImportCandidate] = [] var reservedTargetNames = Set() var reservedSourcesByOriginalName: [String: [URL]] = [:] @@ -399,7 +513,7 @@ extension WorkspaceStore { reservedSourcesByOriginalName[originalName, default: []].append(url) candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) } - return (candidates, unsupported.sorted()) + return (candidates, unsupported.sorted(), expansion.unavailableSourceURLs) } nonisolated private static func nextConfirmedImportTargetName( @@ -636,7 +750,7 @@ struct ConfirmedFileImportView: View { } private func fileSummary(_ batch: ConfirmedFileImportBatch) -> some View { - let fileCount = batch.candidates.count + batch.unsupportedNames.count + let fileCount = batch.candidates.count + batch.unsupportedNames.count + batch.failures.count return VStack(alignment: .leading, spacing: 8) { if !batch.sourceFolderNames.isEmpty { Text(store.ui( @@ -659,6 +773,12 @@ struct ConfirmedFileImportView: View { } unsupportedRow(name, asNotes: batch.importsMarkdownAsNotes) } + ForEach(Array(batch.failures.enumerated()), id: \.element.id) { index, failure in + if !batch.candidates.isEmpty || !batch.unsupportedNames.isEmpty || index > 0 { + Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) + } + unavailableSourceRow(failure) + } } } } @@ -699,8 +819,8 @@ struct ConfirmedFileImportView: View { .truncationMode(.middle) Text( asNotes - ? store.ui("仅支持 Markdown,已跳过", "Markdown only; skipped") - : store.ui("不支持,已跳过", "Unsupported; skipped") + ? store.ui("仅支持 Markdown", "Markdown only") + : store.ui("格式不支持", "Unsupported format") ) .weiBeiText(12, weight: .medium) } @@ -710,6 +830,25 @@ struct ConfirmedFileImportView: View { .help(name) } + private func unavailableSourceRow(_ failure: ConfirmedFileImportFailure) -> some View { + HStack(alignment: .top, spacing: 10) { + Image(systemName: "exclamationmark.triangle") + .frame(width: 16) + VStack(alignment: .leading, spacing: 3) { + Text(failure.sourceURL.lastPathComponent) + .weiBeiText(13) + .lineLimit(2) + .truncationMode(.middle) + Text(failure.message) + .weiBeiText(12, weight: .medium) + .fixedSize(horizontal: false, vertical: true) + } + } + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.vertical, 6) + .help(failure.sourceURL.lastPathComponent) + } + private func destinationPicker(_ batch: ConfirmedFileImportBatch) -> some View { HStack(spacing: 12) { Text(store.ui("导入到", "Import to")) @@ -777,20 +916,8 @@ struct ConfirmedFileImportView: View { private func result(_ batch: ConfirmedFileImportBatch) -> some View { let commonFailureMessage = sharedFailureMessage(batch) return VStack(alignment: .leading, spacing: 14) { - if isSimpleSingleSuccess(batch), let item = batch.importedItems.first { - VStack(alignment: .leading, spacing: 3) { - Text(item.subtitle) - .weiBeiText(13, weight: .semibold) - .lineLimit(2) - .truncationMode(.middle) - Text(store.ui("已导入", "Imported")) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - } - } else { - Text(resultSummary(batch)) - .weiBeiText(13, weight: .semibold) - } + Text(resultSummary(batch)) + .weiBeiText(13, weight: .semibold) if batch.stopped, !batch.pendingSourceURLs.isEmpty { Text(store.ui( "已停止;\(batch.pendingSourceURLs.count) 个文件未处理。已完成的导入已保留,原文件未变。", @@ -843,14 +970,6 @@ struct ConfirmedFileImportView: View { } } - private func isSimpleSingleSuccess(_ batch: ConfirmedFileImportBatch) -> Bool { - batch.importedItems.count == 1 - && batch.skippedCount == 0 - && batch.failures.isEmpty - && !batch.stopped - && batch.pendingSourceURLs.isEmpty - } - @ViewBuilder private func resultButtons(_ batch: ConfirmedFileImportBatch) -> some View { if !batch.pendingSourceURLs.isEmpty { @@ -880,39 +999,15 @@ struct ConfirmedFileImportView: View { .keyboardShortcut(.defaultAction) } } else if !batch.failures.isEmpty { - Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + Button(store.ui("关闭", "Close")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) Button(store.ui("重试失败项", "Retry Failed")) { store.retryFailedConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) - } else if batch.importedItems.count == 1 { - Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } - .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button( - batch.importsMarkdownAsNotes - ? store.ui("打开笔记", "Open Note") - : store.ui("打开文稿", "Open Document") - ) { - store.openSingleConfirmedImport() - } - .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) - .keyboardShortcut(.defaultAction) - } else if batch.importedItems.count > 1 { - Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } - .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) - Button( - batch.importsMarkdownAsNotes - ? store.ui("查看已导入笔记", "View Imported Notes") - : store.ui("查看已导入资料", "View Imported Items") - ) { - store.showConfirmedImportBatch() - } - .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) - .keyboardShortcut(.defaultAction) } else { - Button(store.ui("完成", "Done")) { store.dismissConfirmedFileImport() } + Button(store.ui("关闭", "Close")) { store.dismissConfirmedFileImport() } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) } @@ -925,9 +1020,13 @@ struct ConfirmedFileImportView: View { chinese.append("\(batch.importedItems.count)个已导入") english.append("\(batch.importedItems.count) imported") } - if batch.skippedCount > 0 { - chinese.append("\(batch.skippedCount)个已跳过") - english.append("\(batch.skippedCount) skipped") + if batch.duplicateCount > 0 { + chinese.append("\(batch.duplicateCount)个已存在") + english.append("\(batch.duplicateCount) already existed") + } + if batch.unsupportedCount > 0 { + chinese.append("\(batch.unsupportedCount)个格式不支持") + english.append("\(batch.unsupportedCount) unsupported") } if !batch.failures.isEmpty { chinese.append("\(batch.failures.count)个失败") @@ -960,7 +1059,7 @@ struct ConfirmedFileImportView: View { private func candidateLabel(_ candidate: ConfirmedFileImportCandidate) -> String { switch candidate.disposition { case .ready: return store.ui("可导入", "Ready") - case .duplicate: return store.ui("重复,跳过", "Duplicate, skip") + case .duplicate: return store.ui("已存在", "Already exists") case .conflict(let name): return store.ui("同名,另存为 \(name)", "Name conflict, save as \(name)") } } diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index 80ff13460..e691f4f18 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -47,7 +47,7 @@ final class ConfirmedFileImportTests: XCTestCase { fixture.store.confirmFileImport() waitForStage(.finished, in: fixture.store) - var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) XCTAssertEqual(batch.importedItems.map(\.subtitle), ["一.txt"]) XCTAssertEqual(batch.failures.map(\.sourceURL.lastPathComponent), ["二.txt"]) XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) @@ -60,11 +60,14 @@ final class ConfirmedFileImportTests: XCTestCase { waitForStage(.reviewing, in: fixture.store) XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [second]) fixture.store.confirmFileImport() - waitForStage(.finished, in: fixture.store) + waitForImportIdle(in: fixture.store) - batch = try XCTUnwrap(fixture.store.confirmedFileImport) - XCTAssertEqual(Set(batch.importedItems.map(\.subtitle)), Set(["一.txt", "二.txt"])) - XCTAssertTrue(batch.failures.isEmpty) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual( + Set(fixture.store.importedItems.map(\.subtitle)), + Set(["一.txt", "二.txt"]) + ) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) XCTAssertEqual( try String(contentsOf: fixture.library.appendingPathComponent("通用资料/一.txt")), "one" @@ -76,18 +79,32 @@ final class ConfirmedFileImportTests: XCTestCase { defer { try? FileManager.default.removeItem(at: fixture.root) } let first = fixture.outside.appendingPathComponent("一.txt") let second = fixture.outside.appendingPathComponent("二.txt") + let baseline = fixture.outside.appendingPathComponent("当前阅读.txt") try Data("one".utf8).write(to: first) try Data("two".utf8).write(to: second) + try Data("baseline".utf8).write(to: baseline) + + fixture.store.prepareConfirmedFileImport([baseline]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + fixture.store.readerPageIndex = 9 + fixture.store.readerLocationID = "停止前位置" fixture.store.prepareConfirmedFileImport([first, second]) waitForStage(.reviewing, in: fixture.store) fixture.store.confirmFileImport() fixture.store.stopConfirmedFileImport() - waitForStage(.finished, in: fixture.store) - - let batch = try XCTUnwrap(fixture.store.confirmedFileImport) - XCTAssertTrue(batch.stopped) - XCTAssertTrue(batch.importedItems.isEmpty) + waitForImportIdle(in: fixture.store) + + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.importedItems.map(\.subtitle), ["当前阅读.txt"]) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.readerPageIndex, 9) + XCTAssertEqual(fixture.store.readerLocationID, "停止前位置") + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("导入已停止") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("2 份未导入") == true) XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) XCTAssertTrue(FileManager.default.fileExists(atPath: second.path)) XCTAssertFalse(FileManager.default.fileExists( @@ -125,9 +142,11 @@ final class ConfirmedFileImportTests: XCTestCase { fixture.store.prepareConfirmedFileImport([source]) waitForStage(.reviewing, in: fixture.store) fixture.store.confirmFileImport() - waitForStage(.finished, in: fixture.store) + waitForImportIdle(in: fixture.store) - let imported = try XCTUnwrap(fixture.store.confirmedFileImport?.importedItems.first) + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "阅读材料.md" } + ) XCTAssertEqual(imported.kind, .markdown) XCTAssertFalse(imported.isNotebookNote) XCTAssertTrue(imported.isCourseMaterial) @@ -136,7 +155,6 @@ final class ConfirmedFileImportTests: XCTestCase { .common(relativePath: "通用资料/阅读材料.md") ) - fixture.store.openSingleConfirmedImport() XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) XCTAssertNotEqual(fixture.store.activeNoteItemID, imported.id) @@ -151,6 +169,270 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) } + func testSingleNoteSuccessOpensNoteWithoutResultModal() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("课堂笔记.md") + try Data("# 课堂笔记\n\n正文".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source], asNotes: true) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "课堂笔记.md" } + ) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertTrue(imported.isNotebookNote) + XCTAssertFalse(imported.isCourseMaterial) + XCTAssertEqual(imported.storage, .common(relativePath: "通用笔记/课堂笔记.md")) + XCTAssertEqual(fixture.store.activeNoteItemID, imported.id) + XCTAssertNil(fixture.store.transientNoteStatus) + } + + func testAllDuplicateImportPreservesReadingSelectionAndExplainsNoChange() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let existingSource = fixture.outside.appendingPathComponent("已存在资料.txt") + let currentSource = fixture.outside.appendingPathComponent("当前阅读资料.txt") + try Data("same".utf8).write(to: existingSource) + try Data("current".utf8).write(to: currentSource) + + fixture.store.prepareConfirmedFileImport([existingSource]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + fixture.store.prepareConfirmedFileImport([currentSource]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + fixture.store.readerPageIndex = 7 + fixture.store.readerLocationID = "保持这里" + + fixture.store.prepareConfirmedFileImport([existingSource]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.selectedMaterialItem?.subtitle, "当前阅读资料.txt") + XCTAssertEqual(fixture.store.readerPageIndex, 7) + XCTAssertEqual(fixture.store.readerLocationID, "保持这里") + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "已存在资料.txt" }.count, 1) + XCTAssertEqual( + Set(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + )), + Set(["已存在资料.txt", "当前阅读资料.txt"]) + ) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("已存在") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("未重复导入") == true) + } + + func testMixedSuccessAndUnsupportedAutoOpensAndExplainsUnsupportedFile() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let supported = fixture.outside.appendingPathComponent("可读.txt") + let unsupported = fixture.outside.appendingPathComponent("原件.zip") + try Data("text".utf8).write(to: supported) + try Data("zip".utf8).write(to: unsupported) + + fixture.store.prepareConfirmedFileImport([supported, unsupported]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "可读.txt" } + ) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个格式不支持") == true) + XCTAssertFalse(fixture.store.transientNoteStatus?.contains("已导入") == true) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/原件.zip").path + )) + XCTAssertTrue(FileManager.default.fileExists(atPath: unsupported.path)) + } + + func testUnsupportedOnlySelectionClosesWithoutWritingOrChangingReadingSelection() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let baseline = fixture.outside.appendingPathComponent("当前资料.txt") + let unsupported = fixture.outside.appendingPathComponent("原件.zip") + try Data("baseline".utf8).write(to: baseline) + try Data("zip".utf8).write(to: unsupported) + + fixture.store.prepareConfirmedFileImport([baseline]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + + fixture.store.prepareConfirmedFileImport([unsupported]) + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.importedItems.count, 1) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("没有可导入的文件") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个格式不支持") == true) + XCTAssertTrue(FileManager.default.fileExists(atPath: unsupported.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/原件.zip").path + )) + } + + func testEmptyFolderClosesWithLightFeedbackAndNoWrite() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let emptyFolder = fixture.outside.appendingPathComponent("空资料夹", isDirectory: true) + try FileManager.default.createDirectory(at: emptyFolder, withIntermediateDirectories: true) + + fixture.store.prepareConfirmedFileImport([emptyFolder]) + waitForImportIdle(in: fixture.store) + + XCTAssertTrue(fixture.store.importedItems.isEmpty) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("没有可导入的文件") == true) + XCTAssertTrue(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ).isEmpty) + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: emptyFolder.path).isEmpty) + } + + func testUnavailableDestinationKeepsReviewErrorEvenWithNoCandidates() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("无法导入.txt") + try Data("source".utf8).write(to: source) + fixture.store.courseLibraryRootURL = nil + + fixture.store.prepareConfirmedFileImport([source]) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.stage, .reviewing) + XCTAssertNotNil(batch.destinationError) + XCTAssertTrue(batch.candidates.isEmpty) + XCTAssertNil(fixture.store.transientNoteStatus) + XCTAssertTrue(FileManager.default.fileExists(atPath: source.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/无法导入.txt").path + )) + } + + func testMissingSourceStaysVisibleAsRetryableFailure() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let missing = fixture.outside.appendingPathComponent("已移走.txt") + + fixture.store.prepareConfirmedFileImport([missing]) + waitForStage(.finished, in: fixture.store) + + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertTrue(batch.candidates.isEmpty) + XCTAssertEqual(batch.failures.map(\.sourceURL), [missing]) + XCTAssertTrue(batch.failures.first?.message.contains("无法访问") == true) + XCTAssertNil(fixture.store.transientNoteStatus) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.finished, in: fixture.store) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.failures.map(\.sourceURL), [missing]) + XCTAssertNil(fixture.store.transientNoteStatus) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/已移走.txt").path + )) + } + + func testUnreadableFileIsOnlyAVisibleFailureAndNeverACandidate() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let unreadable = fixture.outside.appendingPathComponent("暂不可读.txt") + try Data("source".utf8).write(to: unreadable) + try FileManager.default.setAttributes( + [.posixPermissions: 0], + ofItemAtPath: unreadable.path + ) + defer { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o600], + ofItemAtPath: unreadable.path + ) + } + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [unreadable], + destination: fixture.library.appendingPathComponent("通用资料", isDirectory: true), + markdownOnly: false + ) + + XCTAssertTrue(plan.candidates.isEmpty) + XCTAssertEqual(plan.unavailableSourceURLs, [unreadable.standardizedFileURL]) + XCTAssertTrue(plan.unsupportedNames.isEmpty) + } + + func testNestedEnumerationFailureRetriesOnlyFailedSubtreeWithoutDuplicatePollution() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let folder = fixture.outside.appendingPathComponent("混合资料", isDirectory: true) + let locked = folder.appendingPathComponent("暂不可读", isDirectory: true) + try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true) + let readable = folder.appendingPathComponent("可读.txt") + try Data("readable".utf8).write(to: readable) + try Data("locked".utf8).write(to: locked.appendingPathComponent("内部.txt")) + try FileManager.default.setAttributes( + [.posixPermissions: 0], + ofItemAtPath: locked.path + ) + defer { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o700], + ofItemAtPath: locked.path + ) + } + + fixture.store.prepareConfirmedFileImport([folder]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.sourceURL), + [readable.standardizedFileURL] + ) + XCTAssertEqual( + fixture.store.confirmedFileImport?.failures.map(\.sourceURL), + [locked.standardizedFileURL] + ) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.map(\.subtitle), ["可读.txt"]) + XCTAssertEqual(batch.failures.map(\.sourceURL), [locked.standardizedFileURL]) + XCTAssertEqual(batch.duplicateCount, 0) + + try FileManager.default.setAttributes( + [.posixPermissions: 0o700], + ofItemAtPath: locked.path + ) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.candidates.map(\.sourceURL), [ + locked.appendingPathComponent("内部.txt").standardizedFileURL, + ]) + XCTAssertEqual(batch.duplicateCount, 0) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual( + Set(fixture.store.importedItems.map(\.subtitle)), + Set(["可读.txt", "内部.txt"]) + ) + XCTAssertNil(fixture.store.transientNoteStatus) + } + func testDockFileOpenedDuringImportWaitsForNextBatch() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } @@ -336,10 +618,10 @@ final class ConfirmedFileImportTests: XCTestCase { ) fixture.store.confirmFileImport() - waitForStage(.finished, in: fixture.store) - let batch = try XCTUnwrap(fixture.store.confirmedFileImport) - XCTAssertEqual(batch.importedItems.count, 1) - XCTAssertEqual(batch.skippedCount, 1) + waitForImportIdle(in: fixture.store) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "同名.txt" }.count, 1) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个已存在") == true) XCTAssertEqual( try FileManager.default.contentsOfDirectory( atPath: fixture.library.appendingPathComponent("通用资料").path @@ -370,9 +652,10 @@ final class ConfirmedFileImportTests: XCTestCase { [.ready, .conflict(suggestedFileName: "同名 2.txt"), .duplicate] ) fixture.store.confirmFileImport() - waitForStage(.finished, in: fixture.store) - XCTAssertEqual(fixture.store.confirmedFileImport?.importedItems.count, 2) - XCTAssertEqual(fixture.store.confirmedFileImport?.skippedCount, 1) + waitForImportIdle(in: fixture.store) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个已存在") == true) XCTAssertEqual( try Set(FileManager.default.contentsOfDirectory( atPath: fixture.library.appendingPathComponent("通用资料").path @@ -451,6 +734,7 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertTrue(expansion.supported.isEmpty) XCTAssertTrue(expansion.unsupportedNames.isEmpty) + XCTAssertTrue(expansion.unavailableSourceURLs.isEmpty) } func testNestedDirectorySymlinkIsNotTraversed() throws { @@ -475,6 +759,7 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(expansion.supported, [safe.standardizedFileURL]) XCTAssertTrue(expansion.unsupportedNames.isEmpty) + XCTAssertTrue(expansion.unavailableSourceURLs.isEmpty) } private func waitForStage( @@ -490,6 +775,20 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(store.confirmedFileImport?.stage, stage, file: file, line: line) } + private func waitForImportIdle( + in store: WorkspaceStore, + file: StaticString = #filePath, + line: UInt = #line + ) { + let deadline = Date().addingTimeInterval(10) + while (store.confirmedFileImport != nil || store.confirmedFileImportTask != nil), + Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.02)) + } + XCTAssertNil(store.confirmedFileImport, file: file, line: line) + XCTAssertNil(store.confirmedFileImportTask, file: file, line: line) + } + private func makeFixture() throws -> ( root: URL, library: URL, From 306bf1c434420afc9008213b8809e11e4e70229c Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 15:24:31 +0800 Subject: [PATCH 40/50] reveal imported batches in sidebar --- .../Views/ConfirmedFileImportView.swift | 12 +-- Sources/WeiBei/Views/CourseSidebarModel.swift | 29 +++++++ Sources/WeiBei/Views/SidebarView.swift | 80 ++++++++++++------- .../ConfirmedFileImportTests.swift | 29 +++++++ .../SidebarPerformanceTests.swift | 71 ++++++++++++++++ 5 files changed, 186 insertions(+), 35 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index a5c587fb9..fdbd5908d 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -372,6 +372,10 @@ extension WorkspaceStore { func showConfirmedImportBatch() { guard let batch = confirmedFileImport, !batch.importedItems.isEmpty else { return } + librarySearch = "" + if let courseID = batch.courseID { + activateCourse(courseID) + } recentlyImportedItemIDs = Set(batch.importedItems.map(\.id)) recentlyImportedClearTask?.cancel() recentlyImportedClearTask = Task { @MainActor [weak self] in @@ -379,12 +383,8 @@ extension WorkspaceStore { guard !Task.isCancelled else { return } self?.recentlyImportedItemIDs = [] } - if let courseID = batch.courseID { - presentCourseWorkspace(batch.importsMarkdownAsNotes ? .notes : .materials, courseID: courseID) - } else { - if courseWorkspacePresented { dismissCourseWorkspace() } - showLibrary = true - } + if courseWorkspacePresented { dismissCourseWorkspace(restoringFocus: false) } + revealLibrary() dismissConfirmedFileImport() } diff --git a/Sources/WeiBei/Views/CourseSidebarModel.swift b/Sources/WeiBei/Views/CourseSidebarModel.swift index c22249051..7a4509ba9 100644 --- a/Sources/WeiBei/Views/CourseSidebarModel.swift +++ b/Sources/WeiBei/Views/CourseSidebarModel.swift @@ -94,6 +94,9 @@ final class CourseSidebarModel: ObservableObject { var unassignedMaterials: [CourseSidebarItemRow] { projection.unassignedMaterials } var unassignedNotes: [CourseSidebarItemRow] { projection.unassignedNotes } var searchTagTaskID: String { "\(tagInputGeneration):\(query)" } + var recentlyImportedItemIDs: Set { + store?.recentlyImportedItemIDs ?? [] + } init(store: WorkspaceStore) { interfaceLanguage = store.interfaceLanguage @@ -155,6 +158,15 @@ final class CourseSidebarModel: ObservableObject { store.$notebookRenameDraft.dropFirst().sink { [weak self] draft in self?.notebookRenameDraft = draft }.store(in: &subscriptions) + store.$recentlyImportedItemIDs.dropFirst().sink { [weak self] itemIDs in + guard let self else { return } + if !itemIDs.isEmpty, + !self.query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + self.updateQuery("") + } else { + self.objectWillChange.send() + } + }.store(in: &subscriptions) store.$interfaceLanguage.dropFirst().sink { [weak self] language in self?.interfaceLanguage = language self?.scheduleRebuild() @@ -265,6 +277,23 @@ final class CourseSidebarModel: ObservableObject { scheduleRebuild() } + func firstVisibleItemID(in itemIDs: Set) -> String? { + guard !itemIDs.isEmpty else { return nil } + if let activeCourseID, + let activeCourse = projection.courses.first(where: { $0.id == activeCourseID }) { + if let material = activeCourse.materials.first(where: { itemIDs.contains($0.id) }) { + return material.id + } + if let note = activeCourse.notes.first(where: { itemIDs.contains($0.id) }) { + return note.id + } + } + if let material = projection.unassignedMaterials.first(where: { itemIDs.contains($0.id) }) { + return material.id + } + return projection.unassignedNotes.first(where: { itemIDs.contains($0.id) })?.id + } + private func itemMatches( _ row: CourseSidebarItemRow, query: String, diff --git a/Sources/WeiBei/Views/SidebarView.swift b/Sources/WeiBei/Views/SidebarView.swift index da29579d0..b60597260 100644 --- a/Sources/WeiBei/Views/SidebarView.swift +++ b/Sources/WeiBei/Views/SidebarView.swift @@ -158,46 +158,58 @@ struct CourseSidebarList: View { let onManageCourse: (UUID) -> Void var body: some View { - List { - Section { - if model.courses.isEmpty { - if store.courses.isEmpty { - SidebarEmptyRow( - title: ui("还没有课程", "No courses yet") - ) + ScrollViewReader { scrollProxy in + List { + Section { + if model.courses.isEmpty { + if store.courses.isEmpty { + SidebarEmptyRow( + title: ui("还没有课程", "No courses yet") + ) + } else { + SidebarEmptyRow(title: ui("还没有匹配课程", "No matching courses")) + } } else { - SidebarEmptyRow(title: ui("还没有匹配课程", "No matching courses")) - } - } else { - ForEach(model.courses) { row in - courseRow(row) + ForEach(model.courses) { row in + courseRow(row) + } } } - } - if !model.unassignedMaterials.isEmpty { - Section { - ForEach(model.unassignedMaterials) { row in - itemRow(row, compact: false, accent: nil, opensNotebook: false) + if !model.unassignedMaterials.isEmpty { + Section { + ForEach(model.unassignedMaterials) { row in + itemRow(row, compact: false, accent: nil, opensNotebook: false) + } + } header: { + SidebarSectionHeader(title: ui("通用资料", "General materials")) } - } header: { - SidebarSectionHeader(title: ui("通用资料", "General materials")) } - } - if !model.unassignedNotes.isEmpty { - Section { - ForEach(model.unassignedNotes) { row in - itemRow(row, compact: false, accent: nil, opensNotebook: true) + if !model.unassignedNotes.isEmpty { + Section { + ForEach(model.unassignedNotes) { row in + itemRow(row, compact: false, accent: nil, opensNotebook: true) + } + } header: { + SidebarSectionHeader(title: ui("独立笔记", "Unassigned Notes")) } - } header: { - SidebarSectionHeader(title: ui("独立笔记", "Unassigned Notes")) } } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .background(WeiBeiTheme.paper) + .onAppear { + scrollToRecentlyImported(using: scrollProxy) + } + .onChange(of: model.recentlyImportedItemIDs) { _, _ in + scrollToRecentlyImported(using: scrollProxy) + } + .onChange(of: recentlyImportedScrollTarget) { _, target in + guard let target else { return } + scrollProxy.scrollTo(target, anchor: .center) + } } - .listStyle(.plain) - .scrollContentBackground(.hidden) - .background(WeiBeiTheme.paper) .task(id: model.searchTagTaskID) { [weak store = store, weak model = model] in guard let requests = model?.missingTagRequestsForSearch(), !requests.isEmpty else { return } @@ -218,6 +230,15 @@ struct CourseSidebarList: View { } } + private var recentlyImportedScrollTarget: String? { + model.firstVisibleItemID(in: model.recentlyImportedItemIDs) + } + + private func scrollToRecentlyImported(using proxy: ScrollViewProxy) { + guard let target = recentlyImportedScrollTarget else { return } + proxy.scrollTo(target, anchor: .center) + } + @ViewBuilder private func courseRow(_ row: CourseSidebarCourseRow) -> some View { let course = row.course @@ -375,6 +396,7 @@ struct CourseSidebarList: View { : Color.clear ) .listRowSeparator(.hidden) + .id(item.id) // 显示名与标签共用同一条异步正文管线:compact 行(课程分组内)不展示标签, // 但展示解析后的笔记名,所以笔记行无论 compact 与否都要加载。 .task(id: row.tagRequest) { [weak store = store, weak model = model] in diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index e691f4f18..dcb88ac3e 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -533,6 +533,31 @@ final class ConfirmedFileImportTests: XCTestCase { )) } + func testCourseBatchRevealsItsExpandedSidebarGroup() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("第一讲.txt") + let second = fixture.outside.appendingPathComponent("第二讲.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + let courseID = try fixture.store.createCourseInLibrary(title: "批量课") + fixture.store.activateCourse(nil) + fixture.store.librarySearch = "旧搜索" + fixture.store.showLibrary = false + fixture.store.courseWorkspacePresented = true + + fixture.store.prepareConfirmedFileImport([first, second], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.activeCourseID, courseID) + XCTAssertEqual(fixture.store.librarySearch, "") + XCTAssertTrue(fixture.store.showLibrary) + XCTAssertFalse(fixture.store.courseWorkspacePresented) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + } + func testCollisionPlanUsesCopyKernelWithoutWriting() throws { let root = FileManager.default.temporaryDirectory .appendingPathComponent("weibei-confirmed-collision-\(UUID().uuidString)", isDirectory: true) @@ -644,6 +669,8 @@ final class ConfirmedFileImportTests: XCTestCase { try Data("B".utf8).write(to: files[1]) try Data("B".utf8).write(to: files[2]) + fixture.store.librarySearch = "旧搜索" + fixture.store.showLibrary = false fixture.store.prepareConfirmedFileImport(files) waitForStage(.reviewing, in: fixture.store) @@ -655,6 +682,8 @@ final class ConfirmedFileImportTests: XCTestCase { waitForImportIdle(in: fixture.store) XCTAssertNil(fixture.store.confirmedFileImport) XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + XCTAssertEqual(fixture.store.librarySearch, "") + XCTAssertTrue(fixture.store.showLibrary) XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个已存在") == true) XCTAssertEqual( try Set(FileManager.default.contentsOfDirectory( diff --git a/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift b/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift index 736a8935e..f156f7632 100644 --- a/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift +++ b/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift @@ -179,6 +179,77 @@ final class SidebarPerformanceTests: XCTestCase { withExtendedLifetime((workspaceObservation, drawerObservation, model)) {} } + @MainActor + func testRecentBatchClearsExistingSearchAndTargetsFirstVisibleRow() { + let fixture = makeStore(itemCount: 0) + defer { try? FileManager.default.removeItem(at: fixture.root) } + let course = Course(title: "批量课") + let courseMaterial = StudyItem( + id: "recent-course-material", + title: "课程文稿", + subtitle: "course.txt", + kind: .text, + urlPath: nil, + isSample: false + ) + let courseNote = StudyItem( + id: "recent-course-note", + title: "课程笔记", + subtitle: "course-note.md", + kind: .markdown, + urlPath: nil, + isSample: false, + isNotebookNote: true + ) + let commonMaterial = StudyItem( + id: "recent-common-material", + title: "通用资料", + subtitle: "common.txt", + kind: .text, + urlPath: nil, + isSample: false + ) + let commonNote = StudyItem( + id: "recent-common-note", + title: "独立笔记", + subtitle: "common-note.md", + kind: .markdown, + urlPath: nil, + isSample: false, + isNotebookNote: true + ) + fixture.store.courses = [course] + fixture.store.importedItems = [courseMaterial, courseNote, commonMaterial, commonNote] + fixture.store.courseItemMemberships = [ + CourseItemMembership(courseID: course.id, itemID: courseMaterial.id), + CourseItemMembership(courseID: course.id, itemID: courseNote.id), + ] + fixture.store.activeCourseID = course.id + let model = CourseSidebarModel(store: fixture.store) + + XCTAssertEqual( + model.firstVisibleItemID(in: [courseNote.id, courseMaterial.id]), + courseMaterial.id + ) + XCTAssertEqual( + model.firstVisibleItemID(in: [commonNote.id, commonMaterial.id]), + commonMaterial.id + ) + + model.updateQuery("不会匹配") + pumpMainRunLoop() + fixture.store.librarySearch = "" + fixture.store.recentlyImportedItemIDs = [commonMaterial.id, commonNote.id] + pumpMainRunLoop() + + XCTAssertEqual(model.query, "") + XCTAssertEqual(model.recentlyImportedItemIDs, [commonMaterial.id, commonNote.id]) + XCTAssertEqual( + model.firstVisibleItemID(in: model.recentlyImportedItemIDs), + commonMaterial.id + ) + } + @MainActor func testFourthActiveNoteTagRemainsSearchableAfterRealLoad() async throws { let fixture = makeStore(itemCount: 0) From d912835a8d6541e9262b022074dae9b2faa04b25 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 15:52:08 +0800 Subject: [PATCH 41/50] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=AF=BE=E7=A8=8B?= =?UTF-8?q?=E7=AC=94=E8=AE=B0=E5=8A=A0=E8=BD=BD=E5=AE=8C=E6=88=90=E5=90=8E?= =?UTF-8?q?=E4=BB=8D=E8=BD=AC=E5=9C=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 4 +- .../ContextualListReturnTests.swift | 53 +++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 5922a8606..c6e4756b3 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -744,7 +744,7 @@ final class WorkspaceStore: ObservableObject { /// 先登记、不动文件。内存态即可:重启丢基线只少一次自动改名,方向安全。 var headingSyncedNoteStemByItemID: [String: String] = [:] var loadedCourseNoteTextByItemID: [String: String] = [:] - var courseNoteLoadTasksByItemID: [String: Task] = [:] + @Published var courseNoteLoadTasksByItemID: [String: Task] = [:] var courseNoteLoadGenerationByItemID: [String: UInt64] = [:] var courseNoteWritesInFlight = Set() var courseNoteWriteTasksByItemID: [String: Task] = [:] @@ -1157,7 +1157,7 @@ final class WorkspaceStore: ObservableObject { } } - deinit { + isolated deinit { courseReconciliationTask?.cancel() courseNoteLoadTasksByItemID.values.forEach { $0.cancel() } courseNoteWriteTasksByItemID.values.forEach { $0.cancel() } diff --git a/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift b/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift index 47c6a611f..a20bf5d96 100644 --- a/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift +++ b/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift @@ -1,4 +1,5 @@ import AppKit +import Combine import SwiftUI import XCTest @testable import WeiBei @@ -382,4 +383,56 @@ final class ContextualListReturnTests: XCTestCase { store.setNoteCustomDisplayTitle("", for: noteID) XCTAssertEqual(store.agentNoteTitle, "普通首行也作为标题") } + + /// 课程笔记读盘结束必须再次发布状态,否则笔记栏会一直停在载入动画, + /// 直到用户另开一份文稿才被无关刷新带回正文。 + @MainActor + func testCourseNoteLoadPublishesCompletionWithoutOpeningAnotherDocument() throws { + let fixture = try Fixture(name: "course-note-load-publish") + defer { fixture.remove() } + let store = WorkspaceStore( + workspaceDirectory: fixture.workspaceDirectory, + selectionAskThreadDefaults: fixture.selectionAskThreadDefaults, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + try store.configureCourseLibrary(at: fixture.importsDirectory) + let courseID = try store.createCourseInLibrary(title: "直接打开课程笔记") + let expected = "# 课程笔记定位\n\n无需先打开另一份文稿。" + let createdID = try store.waitForCourseFileOperation { + await store.createCourseNotebookNote( + courseID: courseID, + title: "课程笔记定位", + markdown: expected + ) + } + let noteID = try XCTUnwrap(createdID) + + store.activeNotebookItemID = nil + store.noteText = "" + store.notesByItemID.removeValue(forKey: noteID) + store.loadedCourseNoteTextByItemID.removeValue(forKey: noteID) + + var publishedAfterBodyAdoption = false + let observation = store.objectWillChange.sink { + if store.noteText == expected, store.activeNoteIsLoading { + publishedAfterBodyAdoption = true + } + } + defer { observation.cancel() } + + XCTAssertTrue(store.openCourseNote(noteID, in: courseID)) + XCTAssertTrue(store.activeNoteIsLoading) + let deadline = Date().addingTimeInterval(2) + while store.activeNoteIsLoading, Date() < deadline { + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + } + + XCTAssertFalse(store.activeNoteIsLoading) + XCTAssertEqual(store.noteText, expected) + XCTAssertTrue( + publishedAfterBodyAdoption, + "正文采用后必须再发布加载结束,不能等另开文稿触发刷新" + ) + } } From 215bdcf843727beb0aad95d2708ccdae5e9e837c Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 18:32:01 +0800 Subject: [PATCH 42/50] =?UTF-8?q?fix:=20=E5=8F=91=E5=B8=83=E8=AF=BE?= =?UTF-8?q?=E7=A8=8B=E7=AC=94=E8=AE=B0=E8=AF=BB=E7=9B=98=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/WeiBei/Stores/WorkspaceStore.swift | 3 + .../WriteGateSafetyTests.swift | 63 +++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index c6e4756b3..a1857f3b2 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -11218,6 +11218,9 @@ final class WorkspaceStore: ObservableObject { defer { if courseNoteLoadGenerationByItemID[itemID] == generation { courseNoteLoadTasksByItemID[itemID] = nil + // @Published 在字典改动前发出通知;读盘结束后再发布一次, + // 让笔记栏按已经清空的任务状态退出载入分支并重新挂载编辑器。 + objectWillChange.send() } } do { diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index ddc7498cb..5c9029d46 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -1,3 +1,4 @@ +import Combine import Foundation @testable import WeiBei import WeiBeiCore @@ -429,6 +430,68 @@ final class WriteGateSafetyTests: XCTestCase { XCTAssertTrue(store.noteText.contains("磁盘上的新内容")) } + func testAtomicExternalEditAdoptsDiskAfterSwitchingAwayAndBack() throws { + let base = makeTempRoot("weibei-external-adopt-after-switch") + defer { try? FileManager.default.removeItem(at: base) } + let store = try makeStore( + base: base, + library: base.appendingPathComponent("资料库"), + backupRoot: base.appendingPathComponent("backups") + ) + let courseID = try store.createCourseInLibrary(title: "外部修改课") + let original = "# 合成笔记\n\n原始正文\n" + let external = original + "\n外部修改验收:正文已从磁盘更新,界面应自动采用。\n" + let target = try importNote( + store, base: base, courseID: courseID, + content: original, fileName: "合成笔记" + ) + let other = try importNote( + store, base: base, courseID: courseID, + content: "# 01\n\n另一份笔记\n", fileName: "01" + ) + + XCTAssertTrue(store.openCourseNote(target.item.id, in: courseID)) + waitForCourseNoteLoad(store, itemID: target.item.id) + store.noteEditingSession.replaceDocument(with: target.item.id) + XCTAssertEqual(store.noteText, original) + + var completionPublished = false + let observation = store.objectWillChange.sink { + if store.activeNoteItemID == target.item.id, + store.noteText == external, + !store.activeNoteIsLoading { + completionPublished = true + } + } + defer { observation.cancel() } + + try external.write(to: target.url, atomically: true, encoding: .utf8) + XCTAssertTrue(store.openCourseNote(other.item.id, in: courseID)) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + XCTAssertTrue(store.openCourseNote(target.item.id, in: courseID)) + waitForCourseNoteLoad(store, itemID: target.item.id) + + XCTAssertFalse(store.activeNoteIsLoading, "返回后不能一直停在无编辑器的载入态") + XCTAssertEqual(store.activeNoteItemID, target.item.id) + XCTAssertEqual(store.noteText, external) + XCTAssertTrue( + completionPublished, + "外部正文采用并结束读盘后必须再发布一次,否则笔记栏仍停在无编辑器的载入画面" + ) + } + + private func waitForCourseNoteLoad( + _ store: WorkspaceStore, + itemID: String, + timeout: TimeInterval = 2 + ) { + let deadline = Date().addingTimeInterval(timeout) + while store.courseNoteLoadTasksByItemID[itemID] != nil, + Date() < deadline { + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + } + } + func testUserNamedNoteKeepsFileNameAfterHeadingSave() throws { let base = makeTempRoot("weibei-named-note") defer { try? FileManager.default.removeItem(at: base) } From 41fea83ff23200d27db7c8f46f198cfc8e2d0b10 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 19:06:09 +0800 Subject: [PATCH 43/50] fix: avoid conflicts when note snapshot matches disk --- .../WorkspaceStore+NotesPersistence.swift | 11 +++++-- .../WriteGateSafetyTests.swift | 32 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift index 462b57a03..c974787a9 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift @@ -837,7 +837,8 @@ extension WorkspaceStore { /// 全仓唯一笔记写盘闸门(计划 §5 阶段1):所有写路径必须经此函数。 /// 文件在场时写前重读磁盘 digest:重读失败或无基线 ⇒ 拒写并保留待写内容; - /// 摘要不符 ⇒ 待写内容先入备份环再抛采用磁盘;一致才落盘并刷新双 digest。 + /// 待写内容已与磁盘一致 ⇒ 幂等采用并刷新双 digest; + /// 摘要不符 ⇒ 待写内容先入备份环再抛采用磁盘;基线一致才落盘并刷新双 digest。 /// 禁止绕过本函数直接调用 notebookMarkdownWriter(SelfCheck SAFETY 断言白名单)。 func writeNotebookMarkdownThroughGate( _ markdown: String, @@ -845,6 +846,7 @@ extension WorkspaceStore { url: URL, expectedBaseline: String? ) throws { + let intendedDigest = Self.noteContentDigest(Data(markdown.utf8)) var operationError: Error? var coordinationError: NSError? NSFileCoordinator().coordinate( @@ -861,6 +863,11 @@ extension WorkspaceStore { ) throw NoteWriteGateError.writeRefusedKeepContent } + if diskDigest == intendedDigest { + noteBackingContentDigestsByItemID[itemID] = diskDigest + lastSelfWrittenNoteDigestsByItemID[itemID] = diskDigest + return + } if diskDigest != expectedBaseline { WeiBeiLog.noteRepair.error( "code=note_write_external_conflict path=\(coordinatedURL.path, privacy: .private) expected_digest=\(expectedBaseline, privacy: .private) actual_digest=\(diskDigest, privacy: .private)" @@ -869,7 +876,7 @@ extension WorkspaceStore { } } try notebookMarkdownWriter(markdown, coordinatedURL) - let writtenDigest = Self.noteContentDigest(Data(markdown.utf8)) + let writtenDigest = intendedDigest let verifiedDigest = Self.noteContentDigest(at: coordinatedURL) guard verifiedDigest == writtenDigest else { WeiBeiLog.noteRepair.error( diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index 5c9029d46..ae0c133d6 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -233,6 +233,38 @@ final class WriteGateSafetyTests: XCTestCase { XCTAssertEqual(store.lastSelfWrittenNoteDigestsByItemID[item.id], Self.digest(of: "第二版")) } + func testGateAdoptsIdenticalExternalDiskContentWithoutConflict() throws { + let base = makeTempRoot("weibei-gate-identical-external-content") + defer { try? FileManager.default.removeItem(at: base) } + let backupRoot = base.appendingPathComponent("backups", isDirectory: true) + let store = WorkspaceStore( + workspaceDirectory: base.appendingPathComponent("workspace", isDirectory: true), + noteBackupRootURL: backupRoot, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + let original = "# 原文\n\n这是原始正文。\n" + let external = original + "\n这句来自应用外部。\n" + let itemID = "imported:identical-external-content" + let url = base.appendingPathComponent("合成笔记.md") + + try original.write(to: url, atomically: true, encoding: .utf8) + try external.write(to: url, atomically: true, encoding: .utf8) + + XCTAssertNoThrow( + try store.writeNotebookMarkdownThroughGate( + external, + itemID: itemID, + url: url, + expectedBaseline: Self.digest(of: original) + ), + "干净快照与当前磁盘正文完全一致时,旧基线不应制造外部修改冲突" + ) + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), external) + XCTAssertEqual(store.noteBackingContentDigestsByItemID[itemID], Self.digest(of: external)) + XCTAssertEqual(store.lastSelfWrittenNoteDigestsByItemID[itemID], Self.digest(of: external)) + } + func testRenameRewriteRoutesThroughGate() throws { let base = makeTempRoot("weibei-gate-rename") defer { try? FileManager.default.removeItem(at: base) } From a71f324595b56934913c30c4b9fd42bc13c4f2b3 Mon Sep 17 00:00:00 2001 From: taekchef Date: Tue, 29 Sep 2026 19:57:43 +0800 Subject: [PATCH 44/50] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8E=9F=E7=94=9F?= =?UTF-8?q?=E9=80=89=E6=8B=A9=E7=AA=97=E4=B8=AD=E6=96=87=E4=BB=B6=E4=B8=8E?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E6=B7=B7=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App/WindowBridge/NativeWindowBridge.swift | 76 +++++++++++++++++++ App/WindowBridge/WindowBridgeContract.swift | 9 +++ .../WeiBei/Support/WorkspaceFileDialog.swift | 57 ++++++++++++++ 3 files changed, 142 insertions(+) diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index b70dff2a2..d94e5b78f 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -1,5 +1,6 @@ import AppKit import Combine +import UniformTypeIdentifiers /// Native window services and Sparkle use this bridge; content stays in Catalyst. @objc(WeiBeiCatalystWindowBridge) @@ -8,6 +9,7 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { private var intensity = 1.0 private let materials = NSMapTable.weakToStrongObjects() private var observers: [NSObjectProtocol] = [] + private var activeOpenPanel: NSOpenPanel? @MainActor private lazy var updateService = WeiBeiUpdateService() @MainActor private var updateObservation: AnyCancellable? @@ -115,6 +117,80 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { func open(_ url: URL) -> Bool { NSWorkspace.shared.open(url) } func reveal(_ url: URL) { NSWorkspace.shared.activateFileViewerSelecting([url]) } func materialWindowCount() -> Int { materials.count } + @MainActor func presentOpenPanel( + title: String, + contentTypeIdentifiers: [String], + allowsMultipleSelection: Bool, + canChooseDirectories: Bool, + canChooseFiles: Bool, + presentationToolbar: NSObject?, + completion: @MainActor @escaping ([URL], NSError?) -> Void + ) { + guard activeOpenPanel == nil else { + completeOpenPanelFailure( + code: 1, + completion: completion + ) + return + } + let owner: NSWindow + if let toolbar = presentationToolbar as? NSToolbar { + let roots = NSApp.windows.filter { $0.toolbar === toolbar } + guard roots.count == 1, let root = roots.first, root.isVisible else { + completeOpenPanelFailure( + code: 2, + completion: completion + ) + return + } + var presentationWindow = root + while let sheet = presentationWindow.attachedSheet { presentationWindow = sheet } + owner = presentationWindow + } else { + guard let keyWindow = NSApp.keyWindow, + keyWindow.isVisible, + !keyWindow.isMiniaturized, + keyWindow.attachedSheet == nil else { + completeOpenPanelFailure( + code: 3, + completion: completion + ) + return + } + owner = keyWindow + } + guard !(owner is NSOpenPanel) else { + completeOpenPanelFailure( + code: 4, + completion: completion + ) + return + } + + let panel = NSOpenPanel() + panel.title = title + panel.canChooseDirectories = canChooseDirectories + panel.canChooseFiles = canChooseFiles + panel.allowsMultipleSelection = allowsMultipleSelection + panel.allowedContentTypes = contentTypeIdentifiers.map { UTType($0) ?? UTType(importedAs: $0) } + activeOpenPanel = panel + panel.beginSheetModal(for: owner) { [weak self] response in + let urls = response == .OK ? panel.urls : [] + self?.activeOpenPanel = nil + // Resume Catalyst on the next main-loop turn, after AppKit has detached the sheet. + DispatchQueue.main.async { completion(urls, nil) } + } + } + @MainActor private func completeOpenPanelFailure( + code: Int, + completion: @MainActor ([URL], NSError?) -> Void + ) { + WeiBeiLog.workspace.error("code=native_open_panel_failed reason=\(code, privacy: .public)") + completion([], NSError( + domain: "WeiBei.NativeOpenPanel", + code: code + )) + } @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) { updateObservation = updateService.$status.combineLatest(updateService.$availableUpdate) .sink { status, update in diff --git a/App/WindowBridge/WindowBridgeContract.swift b/App/WindowBridge/WindowBridgeContract.swift index da39141c2..0009609dd 100644 --- a/App/WindowBridge/WindowBridgeContract.swift +++ b/App/WindowBridge/WindowBridgeContract.swift @@ -10,6 +10,15 @@ import Foundation func open(_ url: URL) -> Bool func reveal(_ url: URL) func materialWindowCount() -> Int + @MainActor func presentOpenPanel( + title: String, + contentTypeIdentifiers: [String], + allowsMultipleSelection: Bool, + canChooseDirectories: Bool, + canChooseFiles: Bool, + presentationToolbar: NSObject?, + completion: @MainActor @escaping ([URL], NSError?) -> Void + ) @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) @MainActor func checkForUpdates() @MainActor func installAvailableUpdate() diff --git a/Sources/WeiBei/Support/WorkspaceFileDialog.swift b/Sources/WeiBei/Support/WorkspaceFileDialog.swift index 61067598a..dfa3b1c89 100644 --- a/Sources/WeiBei/Support/WorkspaceFileDialog.swift +++ b/Sources/WeiBei/Support/WorkspaceFileDialog.swift @@ -57,6 +57,36 @@ enum WorkspaceFileDialog { #if targetEnvironment(macCatalyst) static func pick(title: String, types: [UTType], multiple: Bool) async -> [URL] { guard let presenter else { return [] } + let canChooseDirectories = types.contains(.folder) + let fileTypes = types.filter { $0 != .folder } + if canChooseDirectories, !fileTypes.isEmpty { + let sourceWindow = presenter.view.window + let toolbar = sourceWindow?.windowScene?.titlebar?.toolbar + if toolbar == nil, sourceWindow?.isKeyWindow != true { + await showNativeOpenPanelFailure(NSError( + domain: "WeiBei.NativeOpenPanel", + code: 5 + ), from: presenter) + return [] + } + let result: ([URL], NSError?) = await withCheckedContinuation { continuation in + CatalystDesktopWindow.shared.presentOpenPanel( + title: title, + contentTypeIdentifiers: fileTypes.map(\.identifier), + allowsMultipleSelection: multiple, + canChooseDirectories: true, + canChooseFiles: true, + presentationToolbar: toolbar + ) { urls, error in + continuation.resume(returning: (urls, error)) + } + } + if let error = result.1 { + await showNativeOpenPanelFailure(error, from: presenter) + return [] + } + return result.0 + } let picker = Picker(forOpeningContentTypes: types, asCopy: false) picker.title = title picker.allowsMultipleSelection = multiple @@ -94,6 +124,33 @@ enum WorkspaceFileDialog { return controller } + private static func showNativeOpenPanelFailure( + _ error: NSError, + from presenter: UIViewController + ) async { + let store = AppDelegate.workspace + let busy = error.code == 1 || error.code == 4 + let alert = UIAlertController( + title: store.ui("无法打开文件选择器", "File Picker Unavailable"), + message: busy + ? store.ui( + "当前窗口正在显示另一个文件选择器,请先关闭后重试。", + "Another file picker is already open. Close it and try again." + ) + : store.ui( + "当前窗口暂时无法打开文件选择器,请关闭其他弹窗后重试。", + "The file picker cannot open in this window right now. Close other dialogs and try again." + ), + preferredStyle: .alert + ) + await withCheckedContinuation { continuation in + alert.addAction(UIAlertAction(title: store.ui("好", "OK"), style: .default) { _ in + continuation.resume() + }) + presenter.present(alert, animated: true) + } + } + final class Picker: UIDocumentPickerViewController, UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate { var completion: CheckedContinuation<[URL], Never>? func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { finish(urls) } From ab1a01f66173489a407db054b59e9b18b3bbeec2 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 30 Sep 2026 21:05:03 -1000 Subject: [PATCH 45/50] test: cover confirmed import duplicate recovery boundaries Add synthetic regressions for vanished representatives, failed course transactions, vanished destinations, and the initial Markdown material role. Retain the accepted explicit Chinese fixture locale without copying the temporary acceptance workflow. --- .../ConfirmedFileImportTests.swift | 129 +++++++++++++++++- 1 file changed, 128 insertions(+), 1 deletion(-) diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index dcb88ac3e..bcd092fb4 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -655,6 +655,128 @@ final class ConfirmedFileImportTests: XCTestCase { ) } + func testDuplicateSourceImportsWhenEarlierSourceDisappearsAfterReview() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = directories[0].appendingPathComponent("同名.txt") + let second = directories[1].appendingPathComponent("同名.txt") + let content = Data("same".utf8) + try content.write(to: first) + try content.write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready, .duplicate]) + try FileManager.default.removeItem(at: first) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.count, 1) + XCTAssertEqual(batch.failures.map(\.sourceURL), [first]) + XCTAssertEqual(batch.duplicateCount, 0) + XCTAssertEqual(batch.candidates[1].disposition, .ready) + XCTAssertEqual(try Data(contentsOf: fixture.library.appendingPathComponent("通用资料/同名.txt")), content) + XCTAssertEqual(try Data(contentsOf: second), content) + + try content.write(to: first) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [first]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "同名.txt" }.count, 1) + } + + func testCourseDuplicateSourceImportsAfterRepresentativeTransactionFails() throws { + var failNextStaging = false + let fixture = try makeFixture { stage in + if failNextStaging, stage == .beforeCourseFileStagingCopy { + failNextStaging = false + throw CocoaError(.fileWriteUnknown) + } + } + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "重复项恢复") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready, .duplicate]) + failNextStaging = true + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertFalse(failNextStaging) + XCTAssertEqual(batch.importedItems.count, 1) + XCTAssertEqual(batch.failures.map(\.sourceURL), [files[0]]) + XCTAssertEqual(batch.duplicateCount, 0) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名.txt")), content) + XCTAssertEqual(fixture.store.courseMaterials(in: courseID).count, 1) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + + func testReviewedDuplicateImportsWhenDestinationDisappears() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("已存在.txt") + let destination = fixture.library.appendingPathComponent("通用资料/已存在.txt") + let content = Data("same".utf8) + try content.write(to: source) + try content.write(to: destination) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + try FileManager.default.removeItem(at: destination) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "已存在.txt" }.count, 1) + XCTAssertEqual(try Data(contentsOf: destination), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + + func testInitialCourseMarkdownImportsAsMaterialOnly() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("初始文稿.md") + let content = Data("# 初始文稿\n\n正文".utf8) + try content.write(to: source) + let courseID = try fixture.store.createCourseInLibrary(title: "初始资料") + + fixture.store.prepareInitialCourseImportAfterEntryDismissal([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertFalse(try XCTUnwrap(fixture.store.confirmedFileImport).importsMarkdownAsNotes) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let item = try XCTUnwrap(fixture.store.courseMaterials(in: courseID).first) + XCTAssertFalse(item.isNotebookNote) + XCTAssertTrue(item.isCourseMaterial) + XCTAssertEqual(item.storage, .courseOwned(ownerCourseID: courseID, relativePath: "文稿/初始文稿.md")) + XCTAssertTrue(fixture.store.courseNotes(in: courseID).isEmpty) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(fixture.store.resolvedLibraryURL(for: item))), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + func testSameNameCollisionGroupComparesEveryEarlierContent() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } @@ -818,7 +940,9 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertNil(store.confirmedFileImportTask, file: file, line: line) } - private func makeFixture() throws -> ( + private func makeFixture( + mutationHook: @escaping (CourseProjectMutationStage) throws -> Void = { _ in } + ) throws -> ( root: URL, library: URL, outside: URL, @@ -844,9 +968,12 @@ final class ConfirmedFileImportTests: XCTestCase { }, courseSecurityScopeStarter: { _ in true }, courseSecurityScopeStopper: { _ in }, + courseProjectMutationHook: mutationHook, startsAtBlankEntries: true, startsCourseFileMaintenance: false ) + // These fixture assertions deliberately inspect Chinese localized feedback. + store.interfaceLanguage = .chinese try store.configureCourseLibrary(at: library) return (root, library, outside, store) } From ead5649c6ee21b25b540006f225da39969199c6b Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 30 Sep 2026 21:15:40 -1000 Subject: [PATCH 46/50] fix: recover confirmed import duplicates after representative failures Revalidate preview duplicates against current destination content and successful copies scoped to that destination. Retain same-batch successful copy evidence across retry, compare prepared source HTML to raw imported bytes, and preserve course keep-both behavior. Align initial-course Markdown copy with its material-only placement. Add targeted synthetic recovery, retry, changed-destination, conflict, and HTML regressions. --- .../Views/ConfirmedFileImportView.swift | 104 ++++++++++- .../Views/CourseWorkspaceComponents.swift | 8 +- Sources/WeiBeiCore/ImportFileCopy.swift | 34 +++- .../ConfirmedFileImportTests.swift | 165 +++++++++++++++++- 4 files changed, 294 insertions(+), 17 deletions(-) diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index fdbd5908d..6b1ca88c9 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -37,6 +37,7 @@ struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { var candidates: [ConfirmedFileImportCandidate] = [] var unsupportedNames: [String] = [] var importedItems: [StudyItem] = [] + var successfulCopiesByOriginalName: [String: [URL]] = [:] var failures: [ConfirmedFileImportFailure] = [] var previousDuplicateCount = 0 var previousUnsupportedCount = 0 @@ -173,6 +174,7 @@ extension WorkspaceStore { courseID: batch.courseID, importsMarkdownAsNotes: batch.importsMarkdownAsNotes, importedItems: batch.importedItems, + successfulCopiesByOriginalName: batch.successfulCopiesByOriginalName, previousDuplicateCount: batch.duplicateCount, previousUnsupportedCount: batch.unsupportedCount, pendingSourceURLs: batch.pendingSourceURLs @@ -202,7 +204,8 @@ extension WorkspaceStore { var imported = batch.importedItems var failures = preflightFailures var completed = batch.unsupportedNames.count - for candidate in batch.candidates { + for (candidateIndex, plannedCandidate) in batch.candidates.enumerated() { + var candidate = plannedCandidate if confirmedFileImportStopRequested { batch.stopped = true break @@ -215,12 +218,34 @@ extension WorkspaceStore { batch.completed = completed publishConfirmedFileImportProgress(batch) } - if candidate.disposition == .duplicate { continue } do { + let successfulCopies = batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ] + if candidate.disposition == .duplicate || !successfulCopies.isEmpty { + // A preview may refer to an earlier source whose copy failed, + // or to destination content that changed before confirmation. + candidate.disposition = .ready + batch.candidates[candidateIndex] = candidate + candidate.disposition = try await revalidatedDuplicateDisposition( + candidate.sourceURL, + batch: batch, + successfulCopies: successfulCopies + ) + batch.candidates[candidateIndex] = candidate + if candidate.disposition == .duplicate { continue } + } let item = try await importConfirmedFile(candidate, batch: batch) if !imported.contains(where: { $0.id == item.id }) { imported.append(item) } + if let copiedURL = resolvedLibraryURL(for: item) { + batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ].append(copiedURL) + } } catch { if let recovered = await recoverConfirmedCourseImport( candidate, @@ -229,6 +254,12 @@ extension WorkspaceStore { if !imported.contains(where: { $0.id == recovered.id }) { imported.append(recovered) } + if let copiedURL = resolvedLibraryURL(for: recovered) { + batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ].append(copiedURL) + } continue } WeiBeiLog.workspace.error( @@ -401,6 +432,7 @@ extension WorkspaceStore { let urls = batch.sourceURLs let asNotes = batch.importsMarkdownAsNotes let courseID = batch.courseID + let successfulCopies = batch.successfulCopiesByOriginalName let destination: URL? if let courseID { destination = courseRootURL(for: courseID)?.appendingPathComponent( @@ -428,7 +460,8 @@ extension WorkspaceStore { Self.makeConfirmedFileImportPlan( urls: urls, destination: destination, - markdownOnly: asNotes + markdownOnly: asNotes, + successfulCopiesByOriginalName: successfulCopies ) }.value guard let self, !Task.isCancelled, @@ -464,7 +497,8 @@ extension WorkspaceStore { } nonisolated static func makeConfirmedFileImportPlan( - urls: [URL], destination: URL, markdownOnly: Bool + urls: [URL], destination: URL, markdownOnly: Bool, + successfulCopiesByOriginalName: [String: [URL]] = [:] ) -> ( candidates: [ConfirmedFileImportCandidate], unsupportedNames: [String], @@ -490,6 +524,14 @@ extension WorkspaceStore { } } catch {} let originalName = url.lastPathComponent + let duplicatesSuccessfulCopy = successfulCopiesByOriginalName[originalName, default: []] + .contains { copiedURL in + guard CourseProjectPathPolicy.isSame( + copiedURL.deletingLastPathComponent().resolvingSymlinksInPath(), + destination.resolvingSymlinksInPath() + ) else { return false } + return (try? ImportFileCopy.sourceHasIdenticalImportedContents(url, at: copiedURL)) == true + } let duplicatesReservedSource = reservedSourcesByOriginalName[originalName, default: []] .contains { reservedSource in (try? ImportFileCopy.sourcesHaveIdenticalImportedContents( @@ -497,7 +539,7 @@ extension WorkspaceStore { url )) == true } - if duplicatesReservedSource { + if duplicatesSuccessfulCopy || duplicatesReservedSource { candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) continue } @@ -542,6 +584,58 @@ extension WorkspaceStore { : "\(stem) \(UUID().uuidString.lowercased()).\(pathExtension)" } + private func revalidatedDuplicateDisposition( + _ sourceURL: URL, + batch: ConfirmedFileImportBatch, + successfulCopies: [URL] + ) async throws -> ConfirmedFileImportDisposition { + let destination: URL + if let courseID = batch.courseID { + guard let root = courseRootURL(for: courseID) else { + throw CocoaError(.fileNoSuchFile) + } + destination = root.appendingPathComponent( + batch.importsMarkdownAsNotes + ? CourseOwnedFileRole.note.directoryName + : CourseOwnedFileRole.material.directoryName, + isDirectory: true + ) + } else { + guard let root = courseLibraryRootURL else { + throw CocoaError(.fileNoSuchFile) + } + destination = root.appendingPathComponent( + batch.importsMarkdownAsNotes + ? CourseOwnedFileRole.note.commonDirectoryName + : CourseOwnedFileRole.material.commonDirectoryName, + isDirectory: true + ) + } + return try await Task.detached(priority: .userInitiated) { + () throws -> ConfirmedFileImportDisposition in + // A same-name representative may have been safely renamed by an + // earlier conflict. Compare its actual copy, never just its source. + for copiedURL in successfulCopies { + guard CourseProjectPathPolicy.isSame( + copiedURL.deletingLastPathComponent().resolvingSymlinksInPath(), + destination.resolvingSymlinksInPath() + ) else { continue } + if (try? ImportFileCopy.sourceHasIdenticalImportedContents( + sourceURL, + at: copiedURL + )) == true { + return .duplicate + } + } + let collision = try ImportFileCopy.collision(from: sourceURL, into: destination) + switch collision { + case .available: return .ready + case .duplicate: return .duplicate + case .conflict(let suggested): return .conflict(suggestedFileName: suggested) + } + }.value + } + private func importConfirmedFile( _ candidate: ConfirmedFileImportCandidate, batch: ConfirmedFileImportBatch diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 2603dddd2..00162c08e 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -538,8 +538,8 @@ struct CourseProjectEntrySheet: View { if !selectedImportURLs.isEmpty { Text(selectedImportIncludesMarkdown ? store.ui( - "已选 \(selectedImportURLs.count) 项;Markdown 同时加入文稿和笔记。", - "\(selectedImportURLs.count) selected; Markdown will be added to Materials and Notes." + "已选 \(selectedImportURLs.count) 项;Markdown 作为课程文稿导入。", + "\(selectedImportURLs.count) selected; Markdown will be imported as course materials." ) : store.ui( "已选 \(selectedImportURLs.count) 项", @@ -716,8 +716,8 @@ struct CourseProjectEntrySheet: View { let panel = NSOpenPanel() panel.title = store.ui("选择课程内容", "Choose Course Content") panel.message = store.ui( - "可以选择多个文件或一个文件夹。Markdown 会作为同一个文件同时用于阅读和笔记。", - "Choose files or a folder. Markdown stays one file and appears in both reading and notes." + "可以选择多个文件或一个文件夹。Markdown 作为课程文稿导入。", + "Choose files or a folder. Markdown will be imported as course materials." ) panel.prompt = store.ui("选择", "Choose") panel.allowsMultipleSelection = true diff --git a/Sources/WeiBeiCore/ImportFileCopy.swift b/Sources/WeiBeiCore/ImportFileCopy.swift index b49ad9945..f3c06f771 100644 --- a/Sources/WeiBeiCore/ImportFileCopy.swift +++ b/Sources/WeiBeiCore/ImportFileCopy.swift @@ -68,6 +68,19 @@ public enum ImportFileCopy { } } + /// Compare the bytes a source would import with an already imported file. + /// Do not re-embed HTML resources relative to the copy's new directory. + public static func sourceHasIdenticalImportedContents( + _ sourceURL: URL, + at importedURL: URL + ) throws -> Bool { + try importedContentsMatch( + from: sourceURL, + at: importedURL, + preparedHTML: HTMLResourceImport.dataIfHTML(at: sourceURL) + ) + } + private static func collision( from sourceURL: URL, into directory: URL, @@ -77,17 +90,26 @@ public enum ImportFileCopy { guard FileManager.default.fileExists(atPath: preferred.path) else { return .available } - if let html = preparedHTML { - if try preferred.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count, - try Data(contentsOf: preferred) == html { - return .duplicate - } - } else if try filesHaveIdenticalContents(sourceURL, preferred) { + if try importedContentsMatch(from: sourceURL, at: preferred, preparedHTML: preparedHTML) { return .duplicate } return .conflict(suggestedFileName: uniqueCopyURL(in: directory, preferred: preferred).lastPathComponent) } + private static func importedContentsMatch( + from sourceURL: URL, + at importedURL: URL, + preparedHTML: Data? + ) throws -> Bool { + if let html = preparedHTML { + guard try importedURL.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count else { + return false + } + return try Data(contentsOf: importedURL) == html + } + return try filesHaveIdenticalContents(sourceURL, importedURL) + } + static func filesHaveIdenticalContents(_ lhs: URL, _ rhs: URL) throws -> Bool { let lhsSize = try lhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 let rhsSize = try rhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index bcd092fb4..558dfedba 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -706,6 +706,9 @@ final class ConfirmedFileImportTests: XCTestCase { defer { try? FileManager.default.removeItem(at: fixture.root) } let courseID = try fixture.store.createCourseInLibrary(title: "重复项恢复") let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let existing = courseRoot.appendingPathComponent("文稿/同名.txt") + let existingContent = Data("different existing content".utf8) + try existingContent.write(to: existing) let directories = ["a", "b"].map { fixture.outside.appendingPathComponent($0, isDirectory: true) } @@ -718,7 +721,9 @@ final class ConfirmedFileImportTests: XCTestCase { fixture.store.prepareConfirmedFileImport(files, courseID: courseID) waitForStage(.reviewing, in: fixture.store) - XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready, .duplicate]) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "同名 2.txt"), .duplicate + ]) failNextStaging = true fixture.store.confirmFileImport() waitForStage(.finished, in: fixture.store) @@ -728,9 +733,71 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(batch.importedItems.count, 1) XCTAssertEqual(batch.failures.map(\.sourceURL), [files[0]]) XCTAssertEqual(batch.duplicateCount, 0) - XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名.txt")), content) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) XCTAssertEqual(fixture.store.courseMaterials(in: courseID).count, 1) for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [files[0]]) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertEqual(fixture.store.courseMaterials(in: courseID).count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent("文稿/同名 3.txt").path)) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) + } + + func testRetryInAnotherCourseDoesNotSkipCopyFromPreviousDestination() throws { + var failNextStaging = false + let fixture = try makeFixture { stage in + if failNextStaging, stage == .beforeCourseFileStagingCopy { + failNextStaging = false + throw CocoaError(.fileWriteUnknown) + } + } + defer { try? FileManager.default.removeItem(at: fixture.root) } + let firstCourseID = try fixture.store.createCourseInLibrary(title: "第一目标") + let nextCourseID = try fixture.store.createCourseInLibrary(title: "第二目标") + let firstRoot = try XCTUnwrap(fixture.store.courseRootURL(for: firstCourseID)) + let nextRoot = try XCTUnwrap(fixture.store.courseRootURL(for: nextCourseID)) + let existing = firstRoot.appendingPathComponent("文稿/同名.txt") + let existingContent = Data("different existing content".utf8) + try existingContent.write(to: existing) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: firstCourseID) + waitForStage(.reviewing, in: fixture.store) + failNextStaging = true + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [files[0]]) + XCTAssertEqual(try Data(contentsOf: firstRoot.appendingPathComponent("文稿/同名 2.txt")), content) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.setConfirmedFileImportDestination(courseID: nextCourseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: nextRoot.appendingPathComponent("文稿/同名.txt")), content) + XCTAssertEqual(try Data(contentsOf: firstRoot.appendingPathComponent("文稿/同名 2.txt")), content) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(fixture.store.courseMaterials(in: nextCourseID).count, 1) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } } func testReviewedDuplicateImportsWhenDestinationDisappears() throws { @@ -754,6 +821,100 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertEqual(try Data(contentsOf: source), content) } + func testReviewedCourseDuplicateKeepsBothWhenDestinationChanges() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "确认后变更") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let source = fixture.outside.appendingPathComponent("讲义.txt") + let destination = courseRoot.appendingPathComponent("文稿/讲义.txt") + let content = Data("original".utf8) + let changed = Data("external edit".utf8) + try content.write(to: source) + try content.write(to: destination) + + fixture.store.prepareConfirmedFileImport([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + try changed.write(to: destination) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: destination), changed) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/讲义 2.txt")), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + + func testCourseDuplicateUsesSuccessfulRenamedRepresentative() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "同名另存恢复") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let original = courseRoot.appendingPathComponent("文稿/同名.txt") + let originalContent = Data("existing".utf8) + try originalContent.write(to: original) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same new content".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "同名 2.txt"), .duplicate + ]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: original), originalContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) + XCTAssertFalse(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent("文稿/同名 3.txt").path)) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + + func testHTMLDuplicateUsesStoredRenamedCopyWithoutReembeddingLibraryResources() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("页面.html") } + let content = Data("".utf8) + for file in files { try content.write(to: file) } + let destination = fixture.library.appendingPathComponent("通用资料", isDirectory: true) + let original = destination.appendingPathComponent("页面.html") + let originalContent = Data("different existing page".utf8) + try originalContent.write(to: original) + let neighboringFrame = destination.appendingPathComponent("frame.html") + let frameContent = Data("unrelated library frame".utf8) + try frameContent.write(to: neighboringFrame) + let expectedImportedBytes = try XCTUnwrap(HTMLResourceImport.dataIfHTML(at: files[0])) + + fixture.store.prepareConfirmedFileImport(files) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "页面 2.html"), .duplicate + ]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let copied = destination.appendingPathComponent("页面 2.html") + XCTAssertEqual(try Data(contentsOf: copied), expectedImportedBytes) + XCTAssertNotEqual(try HTMLResourceImport.dataIfHTML(at: copied), expectedImportedBytes) + XCTAssertFalse(FileManager.default.fileExists(atPath: destination.appendingPathComponent("页面 3.html").path)) + XCTAssertEqual(try Data(contentsOf: original), originalContent) + XCTAssertEqual(try Data(contentsOf: neighboringFrame), frameContent) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + func testInitialCourseMarkdownImportsAsMaterialOnly() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } From fa106706dab735051000b1a2158fa17bee65657c Mon Sep 17 00:00:00 2001 From: Codex Acceptance Date: Thu, 1 Oct 2026 00:22:10 -1000 Subject: [PATCH 47/50] test: await initial Mermaid preview before measuring typing debounce --- Sources/WeiBeiWebEditorCheck/main.swift | 39 ++++++++++++++++--------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/Sources/WeiBeiWebEditorCheck/main.swift b/Sources/WeiBeiWebEditorCheck/main.swift index 14b92e30b..d606cb28f 100644 --- a/Sources/WeiBeiWebEditorCheck/main.swift +++ b/Sources/WeiBeiWebEditorCheck/main.swift @@ -1585,7 +1585,7 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { let imageMarkdown = "![failed alt](missing.png)\n\n![success alt](data:image/svg+xml;base64,PHN2Zy8+)" let mermaidMarkdown = "```mermaid\ngraph TD\nA --> B\n```\n\nafter" let script = """ - (() => { + return await (async () => { const editor = window.WeiBeiEditor; editor.setDocumentID('work-package-e-metrics'); editor.setMarkdown(\(json(ordinaryMarkdown))); @@ -1626,7 +1626,13 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { document.querySelector('.ProseMirror')?.dispatchEvent(new FocusEvent('focus')); if (!editor.selectFirstCodeBlockEndForCheck()) throw new Error('Mermaid selection helper unavailable'); window.WeiBeiMermaidPreviewForE = document.querySelector('.weibei-mermaid-render'); - window.WeiBeiMermaidHTMLForE = window.WeiBeiMermaidPreviewForE?.innerHTML || ''; + // Isolate the debounce contract from lazy engine loading and the initial SVG render. + const initialDeadline = performance.now() + 5000; + while (window.WeiBeiMermaidPreviewForE?.dataset.rendered !== 'true' && performance.now() < initialDeadline) { + await new Promise(resolve => window.setTimeout(resolve, 25)); + } + if (window.WeiBeiMermaidPreviewForE?.dataset.rendered !== 'true') throw new Error('initial Mermaid preview did not become ready'); + window.WeiBeiMermaidHTMLForE = window.WeiBeiMermaidPreviewForE.innerHTML; editor.resetCheckMetrics(); if (!editor.typeTextForCheck('x')) throw new Error('Mermaid typing helper unavailable'); window.WeiBeiMermaidBeforeForE = new Promise((resolve) => window.setTimeout(() => resolve({ @@ -1648,9 +1654,9 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { }; })(); """ - webView.evaluateJavaScript(script) { [weak self] value, error in + webView.callAsyncJavaScript(script, arguments: [:], in: nil, in: .page) { [weak self] outcome in guard let self else { return } - guard error == nil, + guard case let .success(value) = outcome, let result = value as? [String: Any], result["selectionDecorationNodes"] as? Int == 0, result["inputImageScans"] as? Int == 0, @@ -1662,7 +1668,7 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { result["successSelectable"] as? Bool == true, result["mermaidPreviewExists"] as? Bool == true, result["mermaidDOMReused"] as? Bool == true else { - self.fail("work package E structural metrics or image identity failed: \(String(describing: error)); \(String(describing: value))") + self.fail("work package E structural metrics or image identity failed: \(String(describing: outcome))") return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { @@ -1688,12 +1694,12 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { - self.validateMermaidDebounceAfterDeadline() + self.validateMermaidDebounceAfterDeadline(deadline: Date().addingTimeInterval(5)) } } } - private func validateMermaidDebounceAfterDeadline() { + private func validateMermaidDebounceAfterDeadline(deadline: Date) { webView.evaluateJavaScript(""" ({ sameDOM: document.querySelector('.weibei-mermaid-render') === window.WeiBeiMermaidPreviewForE, @@ -1702,15 +1708,22 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { }) """) { [weak self] value, error in guard let self else { return } - guard error == nil, - let result = value as? [String: Any], - result["sameDOM"] as? Bool == true, - result["changedHTML"] as? Bool == true, - (result["renders"] as? Int ?? 0) >= 1 else { + guard error == nil, let result = value as? [String: Any], + result["sameDOM"] as? Bool == true else { + self.fail("focused Mermaid preview replaced its DOM or failed: \(String(describing: error)); \(String(describing: value))") + return + } + if result["changedHTML"] as? Bool == true && (result["renders"] as? Int ?? 0) >= 1 { + self.validateOutlineInitialEvent() + return + } + guard Date() < deadline else { self.fail("focused Mermaid preview did not update in place after its 300ms debounce: \(String(describing: value))") return } - self.validateOutlineInitialEvent() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { + self.validateMermaidDebounceAfterDeadline(deadline: deadline) + } } } From 28da939a2497216741866fa976e3b6b9a1648443 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 2 Oct 2026 23:08:05 +0800 Subject: [PATCH 48/50] test: verify confirmed import through the real Catalyst sheet --- App/Sources/CatalystBusinessCheck.swift | 43 ++++++++++++++++++++++--- App/script/check-ci.sh | 4 ++- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/App/Sources/CatalystBusinessCheck.swift b/App/Sources/CatalystBusinessCheck.swift index a1780811d..d83eccc40 100644 --- a/App/Sources/CatalystBusinessCheck.swift +++ b/App/Sources/CatalystBusinessCheck.swift @@ -354,12 +354,45 @@ enum CatalystBusinessCheck { try "# 阅读位置\n\n候选独立合成资料:内容增长时保留同一处文字。材料标记 WB452_SOURCE。\n".write(to: materialURL, atomically: true, encoding: .utf8) let noteURL = inputs.appendingPathComponent("候选验证笔记.md") try "# 候选验证笔记\n\n这是独立测试资料,不是用户笔记。\n".write(to: noteURL, atomically: true, encoding: .utf8) - let materials: [StudyItem] = await withCheckedContinuation { done in - store.importFiles([materialURL]) { done.resume(returning: $0) } - } - let notes: [StudyItem] = await withCheckedContinuation { done in - store.importFiles([noteURL], markdownAsNotes: true) { done.resume(returning: $0) } + var confirmedItems: [StudyItem] = [] + let importSheet = { + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + .flatMap(\.windows).flatMap(descendants) + .compactMap { $0 as? CatalystIndependentSheetSizingProbe.Probe } + .first { $0.window != nil && !$0.isHidden && $0.contentSize != nil } + } + for (url, asNotes) in [(materialURL, false), (noteURL, true)] { + let previousIDs = Set(store.importedItems.map(\.id)) + store.prepareConfirmedFileImport([url], asNotes: asNotes) + try await until("confirmed import review and fitted native sheet") { + guard store.confirmedFileImport?.stage == .reviewing, + let sheet = importSheet(), let size = sheet.contentSize, + let window = sheet.window, !window.isHidden else { return false } + return abs(window.bounds.width - size.width) < 1 + && abs(window.bounds.height - size.height) < 1 + && size.width > 100 && size.height > 100 + } + if !asNotes, let window = importSheet()?.window { + let snapshot = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try snapshot.pngData()?.write(to: LabMetrics.directory.appendingPathComponent("confirmed-import.png")) + } + store.confirmFileImport() + try await until("confirmed import completes and dismisses") { + store.confirmedFileImport == nil && importSheet() == nil + } + let added = store.importedItems.filter { !previousIDs.contains($0.id) } + guard added.count == 1, let imported = added.first, + let copiedURL = store.resolvedLibraryURL(for: imported), + try Data(contentsOf: copiedURL) == Data(contentsOf: url) else { + throw Failure("confirmed import did not preserve the material/note") + } + confirmedItems.append(imported) } + let materials = Array(confirmedItems.prefix(1)) + let notes = Array(confirmedItems.suffix(1)) + try check("confirmed_import_review_copy_and_dismiss", confirmedItems.count == 2) guard let material = materials.first, let note = notes.first, let persistedNote = store.resolvedLibraryURL(for: note) else { throw Failure("original import returned no material/note") } store.openCourseNote(note.id) diff --git a/App/script/check-ci.sh b/App/script/check-ci.sh index ab22c6a78..79721a6f0 100755 --- a/App/script/check-ci.sh +++ b/App/script/check-ci.sh @@ -15,6 +15,7 @@ save_evidence() { "${CHECK_SUPPORT:-$CHECK_DIR}/Workspace/business-failure.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-composers.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-discussion.png" \ + "${CHECK_SUPPORT:-$CHECK_DIR}/Results/confirmed-import.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/reasoning-composer.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Workspace/quit-save.json"; do [[ ! -f "$file" ]] || cp "$file" "App/Evidence/ci-$(basename "$file")" @@ -67,6 +68,7 @@ verify(business_path, 'source', 'awaiting_reopen') launch('--exit-after-check') business = verify(business_path, 'source', 'passed') expected_business_checks = { + 'confirmed_import_review_copy_and_dismiss', 'conversation_appearance_and_scale_after_resize', 'divider_batches_widths_and_reflows_during_drag', 'divider_interface_language_updates', @@ -94,7 +96,7 @@ assert set(business['checks']) == expected_business_checks, business assert business['checks'].get('divider_interface_language_updates') == 'passed', business shutil.copy2(business_path, evidence / 'ci-business.json') shutil.copy2(support / 'Results/workspace.png', evidence / 'ci-business-window.png') -for filename in ['selection-composers.png', 'selection-discussion.png', 'reasoning-composer.png']: +for filename in ['selection-composers.png', 'selection-discussion.png', 'confirmed-import.png', 'reasoning-composer.png']: shutil.copy2(support / 'Results' / filename, evidence / ('ci-' + filename)) print('14 项会话检查与 22 项业务保存重开检查通过;含原生工具栏、选区双输入框与引用定位,不替代鼠标、输入法及触控板体验验收。') From f9d637e6d5a2a536a20d3e6b5b0dcdfe18f08496 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 2 Oct 2026 23:12:24 +0800 Subject: [PATCH 49/50] fix(import): secure confirmed import queue and copying --- .../Stores/CourseProjectRootSupport.swift | 147 ++++++++++++++++++ .../Stores/WorkspaceStore+LibraryRoot.swift | 51 ++---- Sources/WeiBei/Stores/WorkspaceStore.swift | 8 +- .../Views/ConfirmedFileImportView.swift | 125 ++++++++++++--- Sources/WeiBeiCore/ImportFileCopy.swift | 2 +- .../ConfirmedFileImportTests.swift | 103 +++++++++++- .../LibraryRelativeOnlyTests.swift | 49 ++++-- 7 files changed, 411 insertions(+), 74 deletions(-) diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index 87d7d7434..d4cc7bc92 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -1904,6 +1904,153 @@ actor CourseProjectFileWorker { return identity } + func copyImportedFilePreservingOriginal( + from rawSourceURL: URL, + into rawDestinationDirectory: URL, + libraryRoot rawLibraryRoot: URL, + expectedLibraryRootIdentity: ImportedFileIdentity + ) throws -> URL { + let source = try validatedRegularSource(rawSourceURL) + let sourceSnapshot = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity + ) + let rawLibraryRoot = rawLibraryRoot.standardizedFileURL + let libraryRoot = try CourseProjectPathPolicy.existingDirectory(rawLibraryRoot) + guard CourseProjectPathPolicy.isSame(rawLibraryRoot, libraryRoot), + Self.identity(at: libraryRoot) == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let destinationDirectory = try ensureRealDirectory( + rawDestinationDirectory, + inside: libraryRoot + ) + guard let destinationDirectoryIdentity = Self.identity(at: destinationDirectory), + Self.identity(at: libraryRoot) == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let preparedHTML = try prepareHTMLImport(at: source.url) + let payloadSnapshot = preparedHTML.map { snapshot(of: $0) } + ?? sourceSnapshot + let preferredURL = destinationDirectory.appendingPathComponent( + source.url.lastPathComponent + ) + let targetURL: URL + if !fileManager.fileExists(atPath: preferredURL.path) { + targetURL = preferredURL + } else { + let existingSource = try validatedRegularSource(preferredURL) + let existingSnapshot = try stableSnapshot( + at: preferredURL, + expectedIdentity: existingSource.identity + ) + let existing = try stableMetadata( + at: preferredURL, + expectedIdentity: existingSource.identity, + expectedSnapshot: existingSnapshot + ) + if existingSnapshot == payloadSnapshot { + _ = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity, + expectedSnapshot: sourceSnapshot + ) + let currentDirectory = try ensureRealDirectory( + rawDestinationDirectory, + inside: libraryRoot + ) + guard CourseProjectPathPolicy.isSame( + currentDirectory, + destinationDirectory + ), Self.identity(at: currentDirectory) + == destinationDirectoryIdentity, + Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + _ = try stableMetadata( + at: existing.url, + expectedIdentity: existing.identity, + expectedSnapshot: existingSnapshot + ) + return existing.url + } + targetURL = ImportFileCopy.uniqueCopyURL( + in: destinationDirectory, + preferred: preferredURL + ) + } + + let rawStagingDirectory = try fileManager.url( + for: .itemReplacementDirectory, + in: .userDomainMask, + appropriateFor: destinationDirectory, + create: true + ) + defer { try? fileManager.removeItem(at: rawStagingDirectory) } + let stagingValues = try rawStagingDirectory.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]) + let stagingDirectory = try CourseProjectPathPolicy.existingDirectory( + rawStagingDirectory + ) + guard stagingValues.isDirectory == true, + stagingValues.isSymbolicLink != true, + stagingValues.isAliasFile != true, + CourseProjectPathPolicy.isSame( + rawStagingDirectory, + stagingDirectory + ), + Self.identity(at: stagingDirectory)?.volumeID + == destinationDirectoryIdentity.volumeID else { + throw CourseProjectFileWorkerError.unsafePath + } + let payloadURL = stagingDirectory.appendingPathComponent("payload") + let stagedIdentity = try copyAndVerify( + from: preparedHTML == nil ? source.url : nil, + generatedData: preparedHTML, + to: payloadURL, + expectedSnapshot: payloadSnapshot + ) + _ = try stableMetadata( + at: payloadURL, + expectedIdentity: stagedIdentity, + expectedSnapshot: payloadSnapshot + ) + _ = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity, + expectedSnapshot: sourceSnapshot + ) + guard Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let placedIdentity = try placeWithoutReplacement( + from: payloadURL, + to: targetURL, + courseRoot: libraryRoot, + destinationDirectory: destinationDirectory, + expectedDestinationIdentity: destinationDirectoryIdentity, + expectedSnapshot: payloadSnapshot + ) + guard placedIdentity == stagedIdentity else { + throw CourseProjectFileWorkerError.verificationFailed + } + _ = try stableMetadata( + at: targetURL, + expectedIdentity: placedIdentity, + expectedSnapshot: payloadSnapshot + ) + guard Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + return targetURL + } + func write(_ data: Data, to url: URL) throws { try data.write(to: url, options: [.atomic]) } diff --git a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift index 8950f1e6b..82f445af6 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift @@ -59,40 +59,17 @@ extension WorkspaceStore { bootstrapDefaultLibraryIfNeeded() } - func copyExternalFileIntoCourse( - _ sourceURL: URL, - courseID: UUID, - isNote: Bool - ) throws -> URL { - guard let courseRoot = courseRootURL(for: courseID) else { - throw CourseProjectRootError.unavailableLibrary - } - let directoryName = isNote - ? CourseLibraryLayout.courseNotesDirectoryName - : CourseLibraryLayout.courseMaterialsDirectoryName - let directory = courseRoot.appendingPathComponent( - directoryName, - isDirectory: true - ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) - return try Self.copyPreservingOriginal(from: sourceURL, into: directory) - } - - /// Kernel-side copy with the original dedupe semantics: identical content - /// resolves to the existing file, real conflicts get a unique name. Size is - /// compared before any byte read, so large imports never enter memory whole. - nonisolated static func copyPreservingOriginal(from sourceURL: URL, into directory: URL) throws -> URL { - try ImportFileCopy.copyPreservingOriginal(from: sourceURL, into: directory) - } - - nonisolated static func copyExternalFileIntoLibrary( + func copyExternalFileIntoLibrary( root: URL, sourceURL: URL, isNote: Bool - ) throws -> URL { + ) async throws -> URL { + guard let expectedLibraryRootIdentity = courseLibraryRootIdentity, + courseLibraryRootURL.map({ + CourseProjectPathPolicy.isSame($0, root) + }) == true else { + throw CourseProjectRootError.unavailableLibrary + } let directoryName = isNote ? CourseLibraryLayout.commonNotesDirectoryName : CourseLibraryLayout.commonMaterialsDirectoryName @@ -100,11 +77,13 @@ extension WorkspaceStore { directoryName, isDirectory: true ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) - return try ImportFileCopy.copyPreservingOriginal(from: sourceURL, into: directory) + return try await courseProjectFileWorker + .copyImportedFilePreservingOriginal( + from: sourceURL, + into: directory, + libraryRoot: root, + expectedLibraryRootIdentity: expectedLibraryRootIdentity + ) } func libraryRelativePath(of url: URL) -> String? { diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index e298bce58..7febe62c0 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -703,6 +703,7 @@ final class WorkspaceStore: ObservableObject { var confirmedFileImportTask: Task? var confirmedFileImportStopRequested = false var confirmedFileImportSecurityScopes: [URL] = [] + var pendingConfirmedFileImports: [PendingConfirmedFileImport] = [] var recentlyImportedClearTask: Task? @Published var notebookCreationDraft: NotebookCreationDraft? @Published var notebookRenameDraft: NotebookRenameDraft? @@ -5944,7 +5945,7 @@ final class WorkspaceStore: ObservableObject { types: types, multiple: true ) guard !urls.isEmpty else { return } - let scoped = urls.filter { $0.startAccessingSecurityScopedResource() } + let scoped = urls.filter(courseSecurityScopeStarter) prepareConfirmedFileImport( urls, courseID: assigningToCourseID, @@ -6008,7 +6009,10 @@ final class WorkspaceStore: ObservableObject { let importsIntoNotes = Self.isMarkdownFile(rawURL) && (markdownNotePaths?.contains(rawURL.path) ?? markdownAsNotes) do { - let url = try Self.copyExternalFileIntoLibrary( + guard let self else { + throw CancellationError() + } + let url = try await self.copyExternalFileIntoLibrary( root: libraryRoot, sourceURL: rawURL, isNote: importsIntoNotes diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 6b1ca88c9..6e8b7dd6b 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -27,6 +27,13 @@ struct ConfirmedFileImportFailure: Identifiable, Equatable, Sendable { var id: String { sourceURL.path } } +struct PendingConfirmedFileImport: Sendable { + var sourceURLs: [URL] + var courseID: UUID? + var importsMarkdownAsNotes: Bool + var securityScopedURLs: [URL] +} + struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { let id: UUID var sourceURLs: [URL] @@ -73,8 +80,19 @@ extension WorkspaceStore { asNotes: Bool = false, securityScopedURLs: [URL] = [] ) { - guard !urls.isEmpty else { return } - guard confirmedFileImport?.stage != .importing else { return } + guard !urls.isEmpty else { + releaseConfirmedFileImportSecurityScopes(securityScopedURLs) + return + } + if confirmedFileImport?.stage == .importing { + enqueuePendingConfirmedFileImport( + urls, + courseID: courseID, + asNotes: asNotes, + securityScopedURLs: securityScopedURLs + ) + return + } dismissConfirmedFileImport() confirmedFileImportSecurityScopes = securityScopedURLs let folders = urls.filter { @@ -91,14 +109,8 @@ extension WorkspaceStore { } func receiveExternalFileForConfirmedImport(_ url: URL) { - if var batch = confirmedFileImport, batch.stage == .importing { - let knownURLs = batch.sourceURLs + batch.pendingSourceURLs - if !knownURLs.contains(where: { - $0.standardizedFileURL == url.standardizedFileURL - }) { - batch.pendingSourceURLs.append(url) - confirmedFileImport = batch - } + if confirmedFileImport?.stage == .importing { + enqueuePendingConfirmedFileImport([url]) return } if var batch = confirmedFileImport, @@ -132,8 +144,12 @@ extension WorkspaceStore { func dismissConfirmedFileImport() { confirmedFileImportTask?.cancel() confirmedFileImportTask = nil - confirmedFileImportSecurityScopes.forEach { $0.stopAccessingSecurityScopedResource() } + releaseConfirmedFileImportSecurityScopes(confirmedFileImportSecurityScopes) + for request in pendingConfirmedFileImports { + releaseConfirmedFileImportSecurityScopes(request.securityScopedURLs) + } confirmedFileImportSecurityScopes = [] + pendingConfirmedFileImports = [] confirmedFileImportStopRequested = false confirmedFileImport = nil } @@ -148,7 +164,78 @@ extension WorkspaceStore { batch.stage == .finished, !batch.pendingSourceURLs.isEmpty, batch.failures.isEmpty || abandoningFailures else { return } - prepareConfirmedFileImport(batch.pendingSourceURLs) + let request: PendingConfirmedFileImport + if pendingConfirmedFileImports.isEmpty { + request = PendingConfirmedFileImport( + sourceURLs: batch.pendingSourceURLs, + courseID: nil, + importsMarkdownAsNotes: false, + securityScopedURLs: [] + ) + } else { + request = pendingConfirmedFileImports.removeFirst() + } + releaseConfirmedFileImportSecurityScopes(confirmedFileImportSecurityScopes) + confirmedFileImportSecurityScopes = request.securityScopedURLs + let remainingURLs = pendingConfirmedFileImports.flatMap(\.sourceURLs) + let folders = request.sourceURLs.filter { + (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + }.map(\.lastPathComponent) + confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: request.sourceURLs, + sourceFolderNames: folders, + courseID: request.courseID, + importsMarkdownAsNotes: request.importsMarkdownAsNotes, + pendingSourceURLs: remainingURLs + ) + refreshConfirmedFileImportPlan() + } + + private func enqueuePendingConfirmedFileImport( + _ urls: [URL], + courseID: UUID? = nil, + asNotes: Bool = false, + securityScopedURLs: [URL] = [] + ) { + guard var batch = confirmedFileImport, batch.stage == .importing else { + releaseConfirmedFileImportSecurityScopes(securityScopedURLs) + return + } + var knownPaths = Set() + if batch.courseID == courseID, batch.importsMarkdownAsNotes == asNotes { + knownPaths.formUnion(batch.sourceURLs.map { $0.standardizedFileURL.path }) + } + for request in pendingConfirmedFileImports + where request.courseID == courseID + && request.importsMarkdownAsNotes == asNotes { + knownPaths.formUnion(request.sourceURLs.map { $0.standardizedFileURL.path }) + } + let acceptedURLs = urls.filter { + knownPaths.insert($0.standardizedFileURL.path).inserted + } + let acceptedPaths = Set(acceptedURLs.map { $0.standardizedFileURL.path }) + let acceptedScopes = securityScopedURLs.filter { + acceptedPaths.contains($0.standardizedFileURL.path) + } + releaseConfirmedFileImportSecurityScopes( + securityScopedURLs.filter { + !acceptedPaths.contains($0.standardizedFileURL.path) + } + ) + guard !acceptedURLs.isEmpty else { return } + pendingConfirmedFileImports.append(PendingConfirmedFileImport( + sourceURLs: acceptedURLs, + courseID: courseID, + importsMarkdownAsNotes: asNotes, + securityScopedURLs: acceptedScopes + )) + batch.pendingSourceURLs = pendingConfirmedFileImports.flatMap(\.sourceURLs) + confirmedFileImport = batch + } + + private func releaseConfirmedFileImportSecurityScopes(_ urls: [URL]) { + urls.forEach(courseSecurityScopeStopper) } func prepareInitialCourseImportAfterEntryDismissal( @@ -482,7 +569,7 @@ extension WorkspaceStore { confirmedFileImportTask = nil if current.candidates.isEmpty { confirmedFileImport = current - if current.failures.isEmpty { + if current.failures.isEmpty, current.pendingSourceURLs.isEmpty { let feedback = confirmedImportCompletionFeedback(current) dismissConfirmedFileImport() if let feedback { showTransientNoteStatus(feedback) } @@ -659,13 +746,11 @@ extension WorkspaceStore { guard let root = courseLibraryRootURL else { throw CocoaError(.fileNoSuchFile) } - let copiedURL = try await Task.detached(priority: .userInitiated) { - try Self.copyExternalFileIntoLibrary( - root: root, - sourceURL: candidate.sourceURL, - isNote: batch.importsMarkdownAsNotes - ) - }.value + let copiedURL = try await copyExternalFileIntoLibrary( + root: root, + sourceURL: candidate.sourceURL, + isNote: batch.importsMarkdownAsNotes + ) guard let item = applyImportedCommonFiles( [(copiedURL, batch.importsMarkdownAsNotes)], selectsFirstImportedItem: false, diff --git a/Sources/WeiBeiCore/ImportFileCopy.swift b/Sources/WeiBeiCore/ImportFileCopy.swift index f3c06f771..483a9be77 100644 --- a/Sources/WeiBeiCore/ImportFileCopy.swift +++ b/Sources/WeiBeiCore/ImportFileCopy.swift @@ -130,7 +130,7 @@ public enum ImportFileCopy { } } - static func uniqueCopyURL(in directory: URL, preferred: URL) -> URL { + public static func uniqueCopyURL(in directory: URL, preferred: URL) -> URL { let stem = preferred.deletingPathExtension().lastPathComponent let ext = preferred.pathExtension var index = 2 diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index 558dfedba..af51416b2 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -516,6 +516,56 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertTrue(fixture.store.confirmedFileImport?.failures.isEmpty == true) } + func testFilePickerBatchDuringImportKeepsDestinationAndSecurityScope() throws { + var stoppedScopes: [URL] = [] + let fixture = try makeFixture( + securityScopeStopper: { stoppedScopes.append($0.standardizedFileURL) } + ) + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "稍后导入") + let current = fixture.outside.appendingPathComponent("当前.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.md") + try Data("current".utf8).write(to: current) + try Data("waiting".utf8).write(to: waiting) + + fixture.store.prepareConfirmedFileImport([current]) + waitForStage(.reviewing, in: fixture.store) + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + batch.stage = .importing + fixture.store.confirmedFileImport = batch + + fixture.store.prepareConfirmedFileImport( + [waiting], + courseID: courseID, + asNotes: true, + securityScopedURLs: [waiting] + ) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.pendingSourceURLs, [waiting]) + XCTAssertTrue(stoppedScopes.isEmpty) + + batch.stage = .finished + fixture.store.confirmedFileImport = batch + fixture.store.continuePendingConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + XCTAssertEqual(fixture.store.confirmedFileImport?.courseID, courseID) + XCTAssertEqual(fixture.store.confirmedFileImport?.importsMarkdownAsNotes, true) + XCTAssertTrue(stoppedScopes.isEmpty) + + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "稍后.md" } + ) + XCTAssertEqual( + imported.storage, + .courseOwned(ownerCourseID: courseID, relativePath: "笔记/稍后.md") + ) + XCTAssertEqual(stoppedScopes, [waiting.standardizedFileURL]) + } + func testInitialCourseFilesWaitForUnifiedConfirmation() throws { let fixture = try makeFixture() defer { try? FileManager.default.removeItem(at: fixture.root) } @@ -1074,6 +1124,54 @@ final class ConfirmedFileImportTests: XCTestCase { XCTAssertTrue(expansion.unavailableSourceURLs.isEmpty) } + func testConfirmationRejectsSourceReplacedBySymbolicLink() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + let outside = fixture.root.appendingPathComponent("边界外.txt") + try Data("preview".utf8).write(to: source) + try Data("outside".utf8).write(to: outside) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: source) + try FileManager.default.createSymbolicLink(at: source, withDestinationURL: outside) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [source]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/讲义.txt").path + )) + } + + func testConfirmationRejectsCommonDirectoryReplacedBySymbolicLink() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + let commonMaterials = fixture.library.appendingPathComponent("通用资料", isDirectory: true) + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try Data("source".utf8).write(to: source) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: commonMaterials) + try FileManager.default.createSymbolicLink( + at: commonMaterials, + withDestinationURL: outsideDirectory + ) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [source]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: outsideDirectory.appendingPathComponent("讲义.txt").path + )) + } + private func waitForStage( _ stage: ConfirmedFileImportStage, in store: WorkspaceStore, @@ -1102,7 +1200,8 @@ final class ConfirmedFileImportTests: XCTestCase { } private func makeFixture( - mutationHook: @escaping (CourseProjectMutationStage) throws -> Void = { _ in } + mutationHook: @escaping (CourseProjectMutationStage) throws -> Void = { _ in }, + securityScopeStopper: @escaping (URL) -> Void = { _ in } ) throws -> ( root: URL, library: URL, @@ -1128,7 +1227,7 @@ final class ConfirmedFileImportTests: XCTestCase { ) }, courseSecurityScopeStarter: { _ in true }, - courseSecurityScopeStopper: { _ in }, + courseSecurityScopeStopper: securityScopeStopper, courseProjectMutationHook: mutationHook, startsAtBlankEntries: true, startsCourseFileMaintenance: false diff --git a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift index 219bfe12e..be8a29132 100644 --- a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift +++ b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift @@ -84,15 +84,32 @@ enum LibraryRelativeOnlyCheck { let source = outside.appendingPathComponent("讲义.txt") let sourceBytes = Data("hello-library\n".utf8) try sourceBytes.write(to: source) - let copiedCommon = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: source, isNote: false) + let copiedCommon = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: source, + isNote: false + ) + } XCTAssertEqual(FileManager.default.contents(atPath: source.path), sourceBytes) XCTAssertEqual(copiedCommon.deletingLastPathComponent().lastPathComponent, "通用资料") - let copiedCourse = try store.copyExternalFileIntoCourse(source, courseID: originalCourseID, isNote: false) + let courseImport = try store.importFileIntoCourseForSelfCheck( + source, + courseID: originalCourseID, + role: .material + ) + let copiedCourse = try XCTUnwrap(courseImport.item.url) XCTAssertEqual(FileManager.default.contents(atPath: source.path), sourceBytes) XCTAssertEqual(copiedCourse.deletingLastPathComponent().lastPathComponent, "文稿") XCTAssertNotEqual(copiedCommon.path, copiedCourse.path) - let same = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: source, isNote: false) + let same = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: source, + isNote: false + ) + } XCTAssertEqual(same.path, copiedCommon.path) let other = outside.appendingPathComponent("讲义-2.txt") try Data("different-content\n".utf8).write(to: other) @@ -101,7 +118,13 @@ enum LibraryRelativeOnlyCheck { let renamedSource = outside.appendingPathComponent("讲义.txt") try? FileManager.default.removeItem(at: renamedSource) try FileManager.default.moveItem(at: colliding, to: renamedSource) - let second = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: renamedSource, isNote: false) + let second = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: renamedSource, + isNote: false + ) + } XCTAssertNotEqual(second.lastPathComponent, copiedCommon.lastPathComponent) XCTAssertEqual(FileManager.default.contents(atPath: copiedCommon.path), sourceBytes) @@ -208,15 +231,15 @@ enum LibraryInsideOnlyCheck { XCTAssertNil(store.resolvedLibraryURL(for: escapeItem)) let sharedBytes = Data("shared-in-library\n".utf8) - let commonURL = try WorkspaceStore.copyExternalFileIntoLibrary( - root: library, - sourceURL: { - let source = outside.appendingPathComponent("共享讲义.txt") - try sharedBytes.write(to: source) - return source - }(), - isNote: false - ) + let sharedSource = outside.appendingPathComponent("共享讲义.txt") + try sharedBytes.write(to: sharedSource) + let commonURL = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: sharedSource, + isNote: false + ) + } let courseA = try store.createCourseInLibrary(title: "共享甲") let courseB = try store.createCourseInLibrary(title: "共享乙") let imported = importFilesAndWait(store, [commonURL], markdownAsNotes: false) From dcf663918933d4f5ccc3d1e31a802c5e98f593c5 Mon Sep 17 00:00:00 2001 From: taekchef Date: Fri, 2 Oct 2026 23:37:18 +0800 Subject: [PATCH 50/50] Keep queued import metadata and verify reopened editor content --- App/Sources/CatalystBusinessCheck.swift | 5 +++++ Sources/WeiBei/Views/ConfirmedFileImportView.swift | 14 ++------------ .../ConfirmedFileImportTests.swift | 14 ++++++++------ 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/App/Sources/CatalystBusinessCheck.swift b/App/Sources/CatalystBusinessCheck.swift index 34abcb976..6f7f34975 100644 --- a/App/Sources/CatalystBusinessCheck.swift +++ b/App/Sources/CatalystBusinessCheck.swift @@ -381,6 +381,11 @@ enum CatalystBusinessCheck { store.continueLastWork() store.ensureAllStudySessionMessagesLoaded() try await until("reopened note editor") { !store.activeNoteIsLoading && store.noteText.contains(noteMarker) } + let renderedMarker = String(decoding: try JSONEncoder().encode(finalMarker), as: UTF8.self) + try await until("reopened note editor content") { + guard let webView = await editor(documentID: store.activeNoteEditorDocumentID) else { return false } + return (try? await webView.evaluateJavaScript("document.querySelector('.ProseMirror')?.textContent?.includes(\(renderedMarker)) === true") as? Bool) == true + } let history = store.studySessions.flatMap(\.messages) try check("reopen_original_note_and_session_files", store.noteText.contains(finalMarker) && history.contains { $0.text.contains(finalMarker) && $0.completionState == .completed } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift index 6e8b7dd6b..76be97a9b 100644 --- a/Sources/WeiBei/Views/ConfirmedFileImportView.swift +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -162,19 +162,9 @@ extension WorkspaceStore { func continuePendingConfirmedFileImport(abandoningFailures: Bool = false) { guard let batch = confirmedFileImport, batch.stage == .finished, - !batch.pendingSourceURLs.isEmpty, + !pendingConfirmedFileImports.isEmpty, batch.failures.isEmpty || abandoningFailures else { return } - let request: PendingConfirmedFileImport - if pendingConfirmedFileImports.isEmpty { - request = PendingConfirmedFileImport( - sourceURLs: batch.pendingSourceURLs, - courseID: nil, - importsMarkdownAsNotes: false, - securityScopedURLs: [] - ) - } else { - request = pendingConfirmedFileImports.removeFirst() - } + let request = pendingConfirmedFileImports.removeFirst() releaseConfirmedFileImportSecurityScopes(confirmedFileImportSecurityScopes) confirmedFileImportSecurityScopes = request.securityScopedURLs let remainingURLs = pendingConfirmedFileImports.flatMap(\.sourceURLs) diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift index af51416b2..d11a6e8ac 100644 --- a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -477,10 +477,11 @@ final class ConfirmedFileImportTests: XCTestCase { sourceFolderNames: [], courseID: nil, importsMarkdownAsNotes: false, - stage: .finished, - failures: [failure], - pendingSourceURLs: [waiting] + stage: .importing, + failures: [failure] ) + fixture.store.prepareConfirmedFileImport([waiting]) + fixture.store.confirmedFileImport?.stage = .finished fixture.store.continuePendingConfirmedFileImport() XCTAssertEqual(fixture.store.confirmedFileImport?.failures, [failure]) @@ -505,10 +506,11 @@ final class ConfirmedFileImportTests: XCTestCase { sourceFolderNames: [], courseID: nil, importsMarkdownAsNotes: false, - stage: .finished, - failures: [ConfirmedFileImportFailure(sourceURL: failed, message: "失败")], - pendingSourceURLs: [waiting] + stage: .importing, + failures: [ConfirmedFileImportFailure(sourceURL: failed, message: "失败")] ) + fixture.store.prepareConfirmedFileImport([waiting]) + fixture.store.confirmedFileImport?.stage = .finished fixture.store.continuePendingConfirmedFileImport(abandoningFailures: true) waitForStage(.reviewing, in: fixture.store)