Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatUI/Sources/Features/Settings/SyncPane.swift3// Description: Sync pane: local-only by default; setup of an encrypted folder or Mac-node destination with a passphrase; status and "Sync now".4import SwiftUI5import UniformTypeIdentifiers6import LocalChatCore7import LocalChatSync8import RemoteInference910struct SyncPane: View {11 @Environment(AppModel.self) private var app12 @State private var choice: SyncController.Mode = .folder13 @State private var passphrase = ""14 @State private var generated = false15 @State private var folder: URL?16 @State private var pickingFolder = false17 @State private var nodeID: UUID?18 @State private var nodeURL = ""19 @State private var nodeKey = ""20 @State private var allowInsecure = false21 @State private var confirmDisable = false2223 var body: some View {24 let sync = app.sync25 InlineNotice(.privacy, "End-to-end encrypted: records are encrypted on this device with a key derived from your passphrase. The folder or the Mac that stores them cannot read them.")26 SettingsGroup("What is synchronized", symbol: "checklist") {27 bullet("checkmark.circle.fill", DS.C.ok, "Conversations and their messages, folders, prompt templates, preferences, workspaces, agent configurations, knowledge collection names and settings.")28 bullet("xmark.circle.fill", DS.C.muted, "Never: model weights, documents and vectors of knowledge collections, attachments, API keys, granted folders.")29 }30 if sync.isEnabled { enabledView(sync) } else { setupView(sync) }31 }3233 private func bullet(_ symbol: String, _ color: Color, _ text: String) -> some View {34 HStack(alignment: .firstTextBaseline, spacing: 8) {35 Image(systemName: symbol).foregroundStyle(color).font(.system(size: 12))36 Text(text).font(DS.F.callout).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true)37 }38 }3940 // MARK: Enabled4142 @ViewBuilder private func enabledView(_ sync: SyncController) -> some View {43 SettingsGroup("Status", symbol: "arrow.triangle.2.circlepath") {44 HStack(spacing: 10) {45 statusPill(sync)46 Text(sync.mode == .folder ? "Folder" : "Mac node").font(DS.F.body.weight(.medium)).foregroundStyle(DS.C.text)47 Spacer(minLength: 8)48 if sync.status == .syncing { ProgressView().controlSize(.small) }49 Button("Sync now") { Task { await sync.syncNow() } }.buttonStyle(.lcPrimaryCompact).disabled(sync.status == .syncing || sync.isBusy)50 }51 if let d = sync.destination { Text(d).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted).lineLimit(2).truncationMode(.middle).textSelection(.enabled) }52 if let error = sync.lastError { InlineNotice(.error, error) }53 if let s = sync.lastSummary {54 TileGrid(minimum: 130) {55 MetricTile("Last sync", value: s.finishedAt.formatted(date: .omitted, time: .shortened), footnote: s.finishedAt.formatted(date: .abbreviated, time: .omitted))56 MetricTile("Received", value: "\(s.appliedRecords)", unit: "records", symbol: "arrow.down", tint: DS.C.accent3)57 MetricTile("Sent", value: "\(s.pushedRecords)", unit: "records", symbol: "arrow.up", tint: DS.C.accent2)58 }59 if !s.skippedBatches.isEmpty { InlineNotice(.warning, "\(s.skippedBatches.count) damaged batch\(s.skippedBatches.count == 1 ? " was" : "es were") ignored.") }60 } else { Text("No synchronization yet.").font(DS.F.caption).foregroundStyle(DS.C.muted) }61 }62 SettingsGroup("Turn off", symbol: "power", footer: "Turning sync off deletes nothing, here or at the destination. The sync key is removed from this device's Keychain.") {63 HStack { Spacer(); Button("Turn off sync…") { confirmDisable = true }.buttonStyle(.lcDestructive) }64 }65 .confirmationDialog("Turn off sync on this device?", isPresented: $confirmDisable, titleVisibility: .visible) {66 Button("Turn off, remember what was synchronized") { Task { await sync.disable(forgetProgress: false) } }67 Button("Turn off and forget progress", role: .destructive) { Task { await sync.disable(forgetProgress: true) } }68 } message: { Text("\"Forget progress\" makes a later setup exchange everything again.") }69 }7071 private func statusPill(_ sync: SyncController) -> Pill {72 switch sync.status {73 case .syncing: Pill("Syncing", symbol: "arrow.triangle.2.circlepath", tone: .accent)74 case .failed: Pill("Failed", symbol: "exclamationmark.triangle.fill", tone: .danger)75 case .idle, .localOnly: sync.lastError == nil ? Pill("On", symbol: "checkmark.circle.fill", tone: .ok) : Pill("Needs attention", symbol: "exclamationmark.triangle.fill", tone: .warn)76 }77 }7879 // MARK: Setup8081 @ViewBuilder private func setupView(_ sync: SyncController) -> some View {82 SettingsGroup("Sync is off", symbol: "iphone.and.arrow.forward", footer: "Local-only is the default: nothing leaves this device.") {83 Picker("Destination", selection: $choice) { Text("Folder").tag(SyncController.Mode.folder); Text("Mac node").tag(SyncController.Mode.node) }84 .pickerStyle(.segmented).labelsHidden()85 if choice == .folder {86 Text("Pick a folder every device can reach, for example in iCloud Drive. Each device uses the same folder and the same passphrase.").font(DS.F.caption).foregroundStyle(DS.C.text2)87 HStack(spacing: 8) {88 Button { pickingFolder = true } label: { Label(folder == nil ? "Choose folder…" : "Change…", systemImage: "folder") }.buttonStyle(.lcSecondaryCompact)89 if let folder { Text(folder.path).font(DS.F.mono(11.5)).foregroundStyle(DS.C.muted).lineLimit(1).truncationMode(.head) }90 }91 } else {92 Text("A Mac running Local Chat with its Local API server started stores the encrypted records. It never has the passphrase.").font(DS.F.caption).foregroundStyle(DS.C.text2)93 let nodes = app.nodeStatuses.filter { $0.node.kind == .localChat }94 if !nodes.isEmpty {95 Picker("Node", selection: $nodeID) {96 Text("Enter an address").tag(UUID?.none)97 ForEach(nodes) { Text($0.node.name).tag(UUID?.some($0.node.id)) }98 }99 .onChange(of: nodeID) { _, id in100 if let n = nodes.first(where: { $0.node.id == id })?.node { nodeURL = SyncController.serverRoot(of: n.baseURL); allowInsecure = n.allowInsecureHTTP; nodeKey = "" }101 }102 }103 TextField("http://studio.local:8765", text: $nodeURL).textFieldStyle(.roundedBorder).autocorrectionDisabled().disabled(nodeID != nil)104 #if os(iOS)105 .textInputAutocapitalization(.never).keyboardType(.URL)106 #endif107 if nodeID == nil {108 SecureField("API key of the Mac", text: $nodeKey).textFieldStyle(.roundedBorder)109 Toggle("Allow plain HTTP to a public address", isOn: $allowInsecure).font(DS.F.callout)110 } else { Text("Uses the API key saved for this node.").font(DS.F.caption).foregroundStyle(DS.C.muted) }111 }112 RowDivider()113 VStack(alignment: .leading, spacing: 6) {114 Text("Passphrase").font(DS.F.caption.weight(.semibold)).foregroundStyle(DS.C.text2)115 HStack(spacing: 8) {116 Group { if generated { TextField("Passphrase", text: $passphrase) } else { SecureField("Enter the passphrase of your other devices, or generate one", text: $passphrase) } }117 .textFieldStyle(.roundedBorder).font(DS.F.mono(12.5)).autocorrectionDisabled()118 #if os(iOS)119 .textInputAutocapitalization(.characters)120 #endif121 Button("Generate") { passphrase = sync.generatePassphrase(); generated = true }.buttonStyle(.lcSecondaryCompact)122 if generated { IconButton("doc.on.doc", label: "Copy passphrase") { Pasteboard.copy(passphrase) } }123 }124 if generated { InlineNotice(.warning, "Write this code down. You need it on every other device, and it cannot be recovered: without it the synchronized data is unreadable.") }125 if !passphrase.isEmpty, let p = sync.passphraseProblem(passphrase) { InlineNotice(.error, p) }126 }127 if let error = sync.lastError { InlineNotice(.error, error) }128 HStack {129 Spacer()130 if sync.isBusy { ProgressView().controlSize(.small) }131 Button("Turn on sync") { enable(sync) }.buttonStyle(.lcPrimaryCompact).disabled(!canEnable(sync) || sync.isBusy)132 }133 }134 .fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in if case .success(let url) = result { folder = url } }135 }136137 private func canEnable(_ sync: SyncController) -> Bool {138 guard sync.passphraseProblem(passphrase) == nil else { return false }139 if choice == .folder { return folder != nil }140 return !nodeURL.trimmingCharacters(in: .whitespaces).isEmpty && (nodeID != nil || !nodeKey.isEmpty)141 }142143 private func enable(_ sync: SyncController) {144 let secret = passphrase145 Task {146 if choice == .folder, let folder { await sync.enableFolder(folder, passphrase: secret) }147 else if choice == .node {148 var key = nodeKey; var name: String?149 if let node = app.nodeStatuses.first(where: { $0.node.id == nodeID })?.node {150 key = ((try? app.keychain.string(for: node.keychainAccount)) ?? nil) ?? ""; name = node.name151 }152 await sync.enableNode(baseURL: nodeURL, name: name, apiKey: key, allowInsecureHTTP: allowInsecure, passphrase: secret)153 }154 if sync.isEnabled { passphrase = ""; generated = false; nodeKey = "" }155 }156 }157}158