Skip to content
254 changes: 254 additions & 0 deletions Docs/plans/2026-08-22-file-model-convergence-and-library-relocation.md

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions Sources/WeiBei/Stores/CourseProjectRootSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5363,6 +5363,11 @@ enum CourseProjectRootError: LocalizedError {
case metadataConflict
case manifestMismatch
case workspaceSaveFailed
case destinationInsideLibrary
case destinationContainsLibrary
case destinationIsLibrary
case destinationNotEmpty
case migrationFailed(String)

var errorDescription: String? {
switch self {
Expand Down Expand Up @@ -5406,6 +5411,18 @@ enum CourseProjectRootError: LocalizedError {
return "课程 manifest 与当前课程记录冲突。"
case .workspaceSaveFailed:
return "课程状态没有成功保存。魏碑只撤销能确认属于本次操作的内容;如果磁盘内容已经变化,会原样保留。"
case .destinationInsideLibrary:
return "所选位置在当前资料库内部,请选择资料库之外的位置。"
case .destinationContainsLibrary:
return "所选位置是当前资料库的上级目录,请选择其他位置。"
case .destinationIsLibrary:
return "所选位置已经是一个魏碑资料库,可以直接认领。"
case .destinationNotEmpty:
return "所选文件夹不是空的,迁移需要一个空文件夹。"
case .migrationFailed(let detail):
return detail.isEmpty
? "资料库迁移未完成,原资料库保持不变。"
: "资料库迁移未完成:\(detail)。原资料库保持不变。"
}
}
}
Expand Down
145 changes: 145 additions & 0 deletions Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,151 @@ extension WorkspaceStore {
}
}

struct LibraryMigrationResult {
let destination: URL
let movedItemCount: Int
}

func migrateLibrary(to destination: URL) async throws -> LibraryMigrationResult {
guard let libraryRoot = courseLibraryRootURL else {
throw CourseProjectRootError.missingLibrary
}
try validateMigrationDestinationRelationship(
destination,
libraryRoot: libraryRoot
)
let canonicalDestination: URL
if FileManager.default.fileExists(atPath: destination.path) {
canonicalDestination = try CourseProjectPathPolicy.existingDirectory(destination)
try validateMigrationDestinationContent(canonicalDestination)
} else {
let parent = try CourseProjectPathPolicy.existingDirectory(
destination.deletingLastPathComponent()
)
canonicalDestination = parent.appendingPathComponent(
destination.lastPathComponent,
isDirectory: true
)
}

flushPendingNotePersistence()
libraryMigrationInFlight = true
defer { libraryMigrationInFlight = false }

let fileManager = FileManager.default
let sameVolume = Self.volumeDeviceID(of: libraryRoot)
== Self.volumeDeviceID(of: canonicalDestination.deletingLastPathComponent())
var movedBack: [URL] = []
do {
if sameVolume {
if fileManager.fileExists(atPath: canonicalDestination.path) {
try fileManager.removeItem(at: canonicalDestination)
}
try fileManager.moveItem(at: libraryRoot, to: canonicalDestination)
} else {
let staging = canonicalDestination.deletingLastPathComponent()
.appendingPathComponent(
canonicalDestination.lastPathComponent + "-weibei-migrating",
isDirectory: true
)
try? fileManager.removeItem(at: staging)
try fileManager.createDirectory(at: staging, withIntermediateDirectories: true)
let entries = try fileManager.contentsOfDirectory(
at: libraryRoot,
includingPropertiesForKeys: nil
)
for entry in entries {
let target = staging.appendingPathComponent(entry.lastPathComponent)
try fileManager.moveItem(at: entry, to: target)
movedBack.append(target)
}
if fileManager.fileExists(atPath: canonicalDestination.path) {
try fileManager.removeItem(at: canonicalDestination)
}
try fileManager.moveItem(at: staging, to: canonicalDestination)
}
} catch {
for staged in movedBack.reversed() {
try? fileManager.moveItem(
at: staged,
to: libraryRoot.appendingPathComponent(staged.lastPathComponent)
)
}
throw CourseProjectRootError.migrationFailed(error.localizedDescription)
}

guard let identity = importedFileIdentityResolver(canonicalDestination),
let bookmark = courseRootBookmarkMaker(canonicalDestination) else {
applyBoundLibraryRoot(libraryRoot, identity: courseLibraryRootIdentity, bookmark: courseLibraryRootBookmarkData)
throw CourseProjectRootError.rootIdentityUnavailable
}
applyBoundLibraryRoot(canonicalDestination, identity: identity, bookmark: bookmark)
for course in courses {
guard let relativePath = course.sourceRootRelativePath,
let folder = CourseProjectPathPolicy.resolvedRelativePath(
relativePath,
inside: canonicalDestination
) else {
continue
}
resolvedCourseRootURLs[course.id] = folder
courseRootUnavailableReasons.removeValue(forKey: course.id)
_ = resolveCourseOwnedItems(for: course.id)
}
refreshRuntimeItemURLs()
for course in courses {
guard let relativePath = course.sourceRootRelativePath,
let folder = CourseProjectPathPolicy.resolvedRelativePath(
relativePath,
inside: canonicalDestination
),
courseManifestCourseID(at: folder) == course.id else {
throw CourseProjectRootError.migrationFailed(
ui("课程 \(course.title) 的清单校验未通过", "Course manifest check failed for \(course.title)")
)
}
}
courseDocumentSearchIndex.synchronize(allItems)
invalidateAgentContext()
libraryMigrationInFlight = false
flushPendingNotePersistence(flushWorkspace: false)
_ = await persistWorkspaceNow()
WeiBeiLog.workspace.notice("library_migration_completed")
return LibraryMigrationResult(
destination: canonicalDestination,
movedItemCount: (try? fileManager.contentsOfDirectory(at: canonicalDestination, includingPropertiesForKeys: nil))?.count ?? 0
)
}

private func validateMigrationDestinationRelationship(_ destination: URL, libraryRoot: URL) throws {
let rootPath = libraryRoot.standardizedFileURL.path
let destinationPath = destination.standardizedFileURL.path
if destinationPath == rootPath {
throw CourseProjectRootError.destinationIsLibrary
}
if destinationPath.hasPrefix(rootPath + "/") {
throw CourseProjectRootError.destinationInsideLibrary
}
if rootPath.hasPrefix(destinationPath + "/") {
throw CourseProjectRootError.destinationContainsLibrary
}
}

private func validateMigrationDestinationContent(_ destination: URL) throws {
let entries = try FileManager.default.contentsOfDirectory(atPath: destination.path)
guard !entries.isEmpty else { return }
if courseManifestCourseID(at: destination) != nil {
throw CourseProjectRootError.destinationIsLibrary
}
throw CourseProjectRootError.destinationNotEmpty
}

private static func volumeDeviceID(of url: URL) -> dev_t? {
var statBuffer = stat()
guard stat(url.path, &statBuffer) == 0 else { return nil }
return statBuffer.st_dev
}

/// Applies already-copied common-library files to the item model in one
/// MainActor transaction after the background copy loop finishes.
func applyImportedCommonFiles(
Expand Down
2 changes: 2 additions & 0 deletions Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,7 @@ extension WorkspaceStore {
}

func persistCurrentNote() {
guard !libraryMigrationInFlight else { return }
guard let item = activeNoteItem else { return }
if pendingNotePersistenceByItemID[item.id] != nil {
flushPendingNotePersistence(for: item.id)
Expand Down Expand Up @@ -676,6 +677,7 @@ extension WorkspaceStore {
}

func flushPendingNotePersistence(for itemID: String) {
guard !libraryMigrationInFlight else { return }
cancelPendingNotePersistence(for: itemID)
guard let pending = pendingNotePersistenceByItemID.removeValue(forKey: itemID) else { return }
WeiBeiPerf.measure("note.persist.flush", extra: "item=\(itemID)") {
Expand Down
10 changes: 7 additions & 3 deletions Sources/WeiBei/Stores/WorkspaceStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ final class WorkspaceStore: ObservableObject {
var courseLibraryRootBookmarkData: Data?
var courseLibraryRootURL: URL?
var courseLibraryUnavailableReason: String?
/// 资料库迁移进行中:写回、3 秒对账、课程笔记加载全部挂起(计划 §4.2)。
@Published var libraryMigrationInFlight = false
@Published private(set) var courseItemMemberships: [CourseItemMembership] = [] {
didSet {
courseMembershipIndex = CourseItemMemberships(values: courseItemMemberships)
Expand Down Expand Up @@ -747,8 +749,8 @@ final class WorkspaceStore: ObservableObject {
#if DEBUG
private var usesBackgroundWorkspacePersistenceForSelfCheck = false
#endif
private var resolvedCourseRootURLs: [UUID: URL] = [:]
private var courseRootUnavailableReasons: [UUID: String] = [:]
var resolvedCourseRootURLs: [UUID: URL] = [:]
var courseRootUnavailableReasons: [UUID: String] = [:]
private let courseProjectFileWorker = CourseProjectFileWorker()
private var courseReconciliationTask: Task<Void, Never>?
private var courseReconciliationInFlight = false
Expand Down Expand Up @@ -17150,7 +17152,7 @@ final class WorkspaceStore: ObservableObject {
}

@discardableResult
private func resolveCourseOwnedItems(for courseID: UUID) -> Bool {
func resolveCourseOwnedItems(for courseID: UUID) -> Bool {
var changed = false
let itemIDs = importedItems.compactMap { item -> String? in
guard case .courseOwned(let ownerCourseID, _) = item.storage,
Expand All @@ -17175,6 +17177,7 @@ final class WorkspaceStore: ObservableObject {

func reconcileCourseFilesNow(courseID requestedCourseID: UUID? = nil) async {
guard !courseReconciliationInFlight else { return }
guard !libraryMigrationInFlight else { return }
courseReconciliationInFlight = true
defer { courseReconciliationInFlight = false }
if let libraryRoot = courseLibraryRootURL {
Expand Down Expand Up @@ -18554,6 +18557,7 @@ final class WorkspaceStore: ObservableObject {
}

private func scheduleCourseNoteLoad(_ item: StudyItem) {
guard !libraryMigrationInFlight else { return }
guard let access = verifiedCourseOwnedNoteAccess(
item
) else {
Expand Down
135 changes: 135 additions & 0 deletions Sources/WeiBei/Views/Settings/SettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ struct SettingsView: View {
@State private var feedbackBody = ""
@State private var feedbackBusy = false
@State private var feedbackStatus: String?
// 资料库位置迁移(计划 §4.1)。
@State private var pendingMigrationDestination: URL?
@State private var migrationErrorText: String?
@State private var migrationSuccessText: String?
@State private var isMigratingLibrary = false

private var buildInfo: WeiBeiAppBuildInfo { .current() }

Expand Down Expand Up @@ -278,7 +283,137 @@ struct SettingsView: View {
)
}
}

libraryLocationSettings
}
}

private var libraryLocationSettings: some View {
settingsGroup(store.ui("资料库", "Library")) {
settingsRow(
title: store.ui("资料库位置", "Library location"),
detail: store.courseLibraryRootPath ?? CourseLibraryLayout.defaultRootURL().path,
showsBottomDivider: false
) {
Button(store.ui("更改…", "Change…")) {
pickMigrationDestination()
}
.disabled(isMigratingLibrary)
}
if let destination = pendingMigrationDestination {
migrationConfirmation(destination)
}
if isMigratingLibrary {
VStack(alignment: .leading, spacing: 6) {
ProgressView()
.progressViewStyle(.linear)
Text(store.ui(
"正在迁移资料库,请勿操作魏碑…",
"Migrating the library. Please do not use WeiBei during the move…"
))
.font(SettingsType.detail)
.foregroundStyle(WeiBeiTheme.secondaryInk)
}
.padding(.horizontal, 14)
.padding(.bottom, 12)
}
if let migrationErrorText {
Text(migrationErrorText)
.font(SettingsType.detail)
.foregroundStyle(.red)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 14)
.padding(.bottom, 12)
}
if let migrationSuccessText {
Text(migrationSuccessText)
.font(SettingsType.detail)
.foregroundStyle(WeiBeiTheme.cinnabar)
.padding(.horizontal, 14)
.padding(.bottom, 12)
}
}
.disabled(isMigratingLibrary)
}

@ViewBuilder
private func migrationConfirmation(_ destination: URL) -> some View {
VStack(alignment: .leading, spacing: 8) {
Text(store.ui(
"从 \(store.courseLibraryRootPath ?? "—") 迁移到 \(destination.path)",
"Move from \(store.courseLibraryRootPath ?? "—") to \(destination.path)"
))
.font(SettingsType.detail)
.foregroundStyle(WeiBeiTheme.ink)
.fixedSize(horizontal: false, vertical: true)
if Self.isCloudSyncPath(destination) {
Text(store.ui(
"目标位于 iCloud 或网盘同步目录,可能出现文件未下载或同步冲突。",
"The destination is inside an iCloud or cloud-sync folder; files may be evicted or conflict."
))
.font(SettingsType.detail)
.foregroundStyle(.orange)
.fixedSize(horizontal: false, vertical: true)
}
HStack(spacing: 10) {
Button(store.ui("开始迁移", "Start Migration")) {
confirmMigration(to: destination)
}
.buttonStyle(.borderedProminent)
Button(store.ui("取消", "Cancel")) {
pendingMigrationDestination = nil
}
}
}
.padding(.horizontal, 14)
.padding(.vertical, 4)
.padding(.bottom, 8)
}

private func pickMigrationDestination() {
migrationErrorText = nil
migrationSuccessText = nil
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.allowsMultipleSelection = false
panel.prompt = store.ui("选择", "Choose")
guard panel.runModal() == .OK, let url = panel.url else { return }
pendingMigrationDestination = url.standardizedFileURL
}

private func confirmMigration(to destination: URL) {
pendingMigrationDestination = nil
isMigratingLibrary = true
migrationErrorText = nil
migrationSuccessText = nil
Task { @MainActor in
do {
let result = try await store.migrateLibrary(to: destination)
migrationSuccessText = store.ui(
"已迁移到 \(result.destination.path)",
"Moved to \(result.destination.path)"
)
} catch CourseProjectRootError.destinationIsLibrary {
migrationErrorText = store.ui(
"所选位置已经是一个魏碑资料库,请在对话中打开它或选择其他空文件夹。",
"That location is already a WeiBei library. Open it instead, or choose an empty folder."
)
} catch {
migrationErrorText = error.localizedDescription
}
isMigratingLibrary = false
}
}

static func isCloudSyncPath(_ url: URL) -> Bool {
let path = url.path
if path.contains("Library/Mobile Documents") || path.contains("com~apple~CloudDocs") {
return true
}
let cloudNames = ["Dropbox", "Google Drive", "OneDrive", "坚果云", "iCloud"]
return cloudNames.contains { path.contains($0) }
}

/// Theme gallery modeled on AionUI `ThemeLayoutPreview` cards:
Expand Down
Loading