feat(share): dup-aware interactive save card with AI tag suggestions
All checks were successful
CI / build-and-deploy (push) Successful in 20s

Replace the fire-and-forget share toast with an interactive SwiftUI card.
On open it checks linkding's /api/bookmarks/check/ so an already-saved URL
routes to an Update (no more silent duplicates) and a new URL shows a save
form with title, tags, notes, and a read-later toggle.

Tag suggestions are hybrid: fetch the user's existing tag vocabulary
(/api/tags/) and AI tag ideas (/v1/marks/enrich via anonymous device auth),
auto-fill known-vocabulary matches into the field and surface net-new ideas
as tappable chips. Best-effort and non-blocking — failures never block save.

Also:
- Refresh bookmarks when the app returns to the foreground (scenePhase).
- Render bookmark dates as a static relative label instead of the live
  ticking RelativeDateTime timer.
- Share LinkdingAPI/Bookmark/ServerConfig/MarksAuth into the ShareExtension
  target via project.yml (durable across xcodegen regen) and regenerate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krishna Kumar
2026-06-23 20:36:46 -05:00
parent a3059f25fc
commit e82e69c5f3
10 changed files with 454 additions and 88 deletions

View File

@@ -0,0 +1,307 @@
import SwiftUI
/// Interactive save card shown by the share extension. On open it checks whether
/// the URL is already bookmarked, then lets the user set/edit tags, notes, and a
/// read-later flag before saving (new) or updating (existing) never a duplicate.
struct ShareView: View {
let url: String
/// Called when the extension should dismiss. `saved` is true after a successful
/// write, false on cancel.
let onClose: (_ saved: Bool) -> Void
@State private var phase: Phase = .loading
@State private var existing: Bookmark?
@State private var title = ""
@State private var tagText = ""
@State private var notes = ""
@State private var readLater = false
@State private var suggestedTags: [String] = [] // linkding auto_tags
@State private var knownTags: Set<String> = [] // user's existing vocabulary (lowercased)
@State private var aiSuggestions: [String] = [] // net-new AI ideas (not in vocabulary)
@State private var suggesting = false
@State private var errorMessage = ""
@FocusState private var tagsFocused: Bool
private let api: LinkdingAPI?
init(url: String, onClose: @escaping (_ saved: Bool) -> Void) {
self.url = url
self.onClose = onClose
self.api = ServerConfig.loadShared().map(LinkdingAPI.init)
}
private enum Phase { case loading, editing, saving, done, failed }
private static let relativeFormatter: RelativeDateTimeFormatter = {
let f = RelativeDateTimeFormatter()
f.unitsStyle = .abbreviated
f.dateTimeStyle = .named
return f
}()
var body: some View {
VStack {
Spacer()
card
.frame(maxWidth: 460)
.padding(.horizontal, 20)
Spacer()
}
.task { await check() }
}
@ViewBuilder
private var card: some View {
VStack(alignment: .leading, spacing: 16) {
switch phase {
case .loading:
HStack(spacing: 12) {
ProgressView()
Text("Checking…").foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .center)
.padding(.vertical, 24)
case .editing, .saving:
header
editor
actions
case .done:
statusCard(icon: "checkmark.circle.fill", tint: .green,
text: existing != nil ? "Updated" : "Saved")
case .failed:
statusCard(icon: "xmark.circle.fill", tint: .red,
text: errorMessage.isEmpty ? "Something went wrong" : errorMessage)
}
}
.padding(20)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.shadow(color: .black.opacity(0.15), radius: 24, y: 8)
}
// MARK: - Sections
private var header: some View {
VStack(alignment: .leading, spacing: 4) {
if let existing {
Label {
Text(existing.dateAdded == .distantPast
? "Already saved"
: "Already saved · \(Self.relativeFormatter.localizedString(for: existing.dateAdded, relativeTo: Date()))")
} icon: {
Image(systemName: "checkmark.circle.fill").foregroundStyle(.green)
}
.font(.subheadline.weight(.semibold))
} else {
Text("Save bookmark").font(.headline)
}
Text(title.isEmpty ? url : title)
.font(.subheadline.weight(.medium))
.lineLimit(2)
Text(domain)
.font(.caption)
.foregroundStyle(.secondary)
}
}
private var editor: some View {
VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 6) {
TextField("Tags (space separated)", text: $tagText)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.focused($tagsFocused)
.textFieldStyle(.roundedBorder)
if suggesting && aiSuggestions.isEmpty {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text("Suggesting tags…")
.font(.caption)
.foregroundStyle(.secondary)
}
}
if !suggestionChips.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 6) {
ForEach(suggestionChips, id: \.tag) { item in
Button { addTag(item.tag) } label: {
Text(item.isAI ? "\(item.tag)" : "+ \(item.tag)")
.font(.caption.weight(.medium))
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background((item.isAI ? Color.purple : .blue).opacity(0.12), in: Capsule())
.foregroundStyle(item.isAI ? Color.purple : .blue)
}
.buttonStyle(.plain)
}
}
}
}
}
TextField("Notes", text: $notes, axis: .vertical)
.lineLimit(1...3)
.textFieldStyle(.roundedBorder)
Toggle("Read later", isOn: $readLater)
.font(.subheadline)
}
}
private var actions: some View {
HStack(spacing: 12) {
Button("Cancel") { onClose(false) }
.buttonStyle(.bordered)
.frame(maxWidth: .infinity)
Button {
Task { await commit() }
} label: {
Group {
if phase == .saving { ProgressView().tint(.white) }
else { Text(existing != nil ? "Update" : "Save") }
}
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.disabled(phase == .saving)
}
.padding(.top, 2)
}
private func statusCard(icon: String, tint: Color, text: String) -> some View {
HStack(spacing: 10) {
Image(systemName: icon).font(.title3).foregroundStyle(tint)
Text(text).font(.headline)
}
.frame(maxWidth: .infinity, alignment: .center)
.padding(.vertical, 16)
}
// MARK: - Derived
private var domain: String { URL(string: url)?.host ?? url }
/// Tappable suggestion chips: net-new AI ideas () followed by linkding's
/// auto_tags (+), excluding anything already in the field, de-duplicated.
private var suggestionChips: [(tag: String, isAI: Bool)] {
let current = Set(parsedTags.map { $0.lowercased() })
var seen = Set<String>()
var out: [(tag: String, isAI: Bool)] = []
for tag in aiSuggestions + suggestedTags {
let key = tag.lowercased()
let isAI = aiSuggestions.contains { $0.lowercased() == key }
if !current.contains(key) && seen.insert(key).inserted {
out.append((tag, isAI))
}
}
return out
}
private var parsedTags: [String] {
tagText.split(whereSeparator: { $0 == " " || $0 == "," })
.map { String($0) }
.filter { !$0.isEmpty }
}
private func addTag(_ tag: String) {
let trimmed = tagText.trimmingCharacters(in: .whitespaces)
tagText = trimmed.isEmpty ? tag : trimmed + " " + tag
tagText += " "
}
// MARK: - Networking
private func check() async {
guard let api else {
errorMessage = "Open Marks first"
phase = .failed
return
}
do {
let result = try await api.checkBookmark(url: url)
if let bookmark = result.bookmark {
existing = bookmark
title = bookmark.displayTitle
tagText = bookmark.tagNames.joined(separator: " ")
notes = bookmark.description
readLater = bookmark.unread
} else {
title = result.metadata?.title ?? ""
suggestedTags = result.autoTags ?? []
}
phase = .editing
await loadSuggestions()
} catch {
errorMessage = error.localizedDescription
phase = .failed
}
}
/// Fetches the user's existing tag vocabulary and AI tag ideas in parallel,
/// then applies the hybrid behavior: auto-fill suggestions that match the
/// existing vocabulary (new bookmarks only), surface the rest as chips.
/// Best-effort never throws, never blocks saving.
private func loadSuggestions() async {
guard let api else { return }
suggesting = true
defer { suggesting = false }
async let vocabTask = api.fetchTags()
let ai = await TagSuggester.suggest(url: url, title: title)
let vocab = (try? await vocabTask) ?? []
knownTags = Set(vocab.map { $0.lowercased() })
if existing == nil {
// Auto-fill AI tags the user already uses; high confidence, low surprise.
let current = Set(parsedTags.map { $0.lowercased() })
for tag in ai where knownTags.contains(tag.lowercased()) && !current.contains(tag.lowercased()) {
addTag(tag)
}
}
// Everything not in the vocabulary becomes a tappable chip.
aiSuggestions = ai.filter { !knownTags.contains($0.lowercased()) }
}
private func commit() async {
guard let api else { return }
phase = .saving
do {
if let existing {
let update = BookmarkUpdate(
url: existing.url,
title: existing.title,
description: notes,
tagNames: parsedTags,
unread: readLater,
shared: existing.shared
)
_ = try await api.updateBookmark(id: existing.id, update: update)
} else {
let create = BookmarkCreate(
url: url,
title: "",
tagNames: parsedTags,
isArchived: false,
unread: readLater,
shared: false
)
_ = try await api.createBookmark(create)
}
phase = .done
try? await Task.sleep(nanoseconds: 700_000_000)
onClose(true)
} catch {
errorMessage = error.localizedDescription
phase = .failed
try? await Task.sleep(nanoseconds: 1_600_000_000)
onClose(false)
}
}
}

View File

@@ -1,25 +1,23 @@
import UIKit
import SwiftUI
import UniformTypeIdentifiers
@objc(ShareViewController)
class ShareViewController: UIViewController {
private let appGroupId = "group.com.magicive.marks"
private let configKey = "serverConfig"
override func viewDidLoad() {
super.viewDidLoad()
let blur = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial))
blur.frame = view.bounds
blur.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blur)
extractURLAndSave()
extractURL()
}
private func extractURLAndSave() {
private func extractURL() {
guard let item = extensionContext?.inputItems.first as? NSExtensionItem,
let attachments = item.attachments else {
showResult(success: false, message: "Nothing to save")
present(url: nil)
return
}
@@ -31,99 +29,36 @@ class ShareViewController: UIViewController {
let urlString = typeId == UTType.url.identifier
? ((item as? URL)?.absoluteString ?? (item as? String))
: (item as? String)
DispatchQueue.main.async {
if let url = urlString { self?.save(url: url) }
else { self?.showResult(success: false, message: "No URL found") }
}
DispatchQueue.main.async { self?.present(url: urlString) }
}
return true
}
if !load(typeId: UTType.url.identifier) && !load(typeId: UTType.plainText.identifier) {
showResult(success: false, message: "No URL found")
present(url: nil)
}
}
private func save(url: String) {
guard let groupDefaults = UserDefaults(suiteName: appGroupId),
let data = groupDefaults.data(forKey: configKey),
let config = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let host = config["host"] as? String,
let token = config["token"] as? String,
let useHttps = config["useHttps"] as? Bool else {
showResult(success: false, message: "Open Marks first")
return
/// Hosts the SwiftUI save card. A nil URL surfaces an error state in the card.
private func present(url: String?) {
let root = ShareView(url: url ?? "") { [weak self] _ in
self?.close()
}
let host = UIHostingController(rootView: root)
host.view.backgroundColor = .clear
addChild(host)
host.view.frame = view.bounds
host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(host.view)
host.didMove(toParent: self)
var base = (useHttps ? "https" : "http") + "://" + host
if let port = config["port"] as? Int { base += ":\(port)" }
if let path = config["path"] as? String, !path.isEmpty { base += path }
guard let apiUrl = URL(string: "\(base)/api/bookmarks/") else {
showResult(success: false, message: "Bad server URL")
return
if url == nil {
// No URL to work with let the card render its failure state briefly.
DispatchQueue.main.asyncAfter(deadline: .now() + 1.6) { [weak self] in self?.close() }
}
var req = URLRequest(url: apiUrl)
req.httpMethod = "POST"
req.setValue("Token \(token)", forHTTPHeaderField: "Authorization")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try? JSONSerialization.data(withJSONObject: [
"url": url, "is_archived": false, "unread": false, "shared": false
])
URLSession.shared.dataTask(with: req) { [weak self] _, response, error in
DispatchQueue.main.async {
let code = (response as? HTTPURLResponse)?.statusCode ?? 0
let ok = error == nil && (code == 200 || code == 201)
self?.showResult(success: ok, message: ok ? "Bookmarked" : "Failed to save")
}
}.resume()
}
private func showResult(success: Bool, message: String) {
let card = UIView()
card.backgroundColor = success ? .systemGreen : .systemRed
card.layer.cornerRadius = 16
card.layer.cornerCurve = .continuous
card.translatesAutoresizingMaskIntoConstraints = false
card.alpha = 0
let stack = UIStackView()
stack.axis = .horizontal
stack.spacing = 10
stack.alignment = .center
stack.translatesAutoresizingMaskIntoConstraints = false
let icon = UIImageView(image: UIImage(systemName: success ? "checkmark.circle.fill" : "xmark.circle.fill"))
icon.tintColor = .white
icon.preferredSymbolConfiguration = .init(pointSize: 22, weight: .semibold)
let label = UILabel()
label.text = message
label.textColor = .white
label.font = .systemFont(ofSize: 17, weight: .semibold)
stack.addArrangedSubview(icon)
stack.addArrangedSubview(label)
card.addSubview(stack)
view.addSubview(card)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: card.centerXAnchor),
stack.centerYAnchor.constraint(equalTo: card.centerYAnchor),
stack.leadingAnchor.constraint(greaterThanOrEqualTo: card.leadingAnchor, constant: 24),
card.centerXAnchor.constraint(equalTo: view.centerXAnchor),
card.centerYAnchor.constraint(equalTo: view.centerYAnchor),
card.heightAnchor.constraint(equalToConstant: 56),
card.widthAnchor.constraint(greaterThanOrEqualToConstant: 180),
])
UIView.animate(withDuration: 0.2) { card.alpha = 1 }
DispatchQueue.main.asyncAfter(deadline: .now() + (success ? 0.8 : 2.0)) { [weak self] in
UIView.animate(withDuration: 0.15, animations: { card.alpha = 0 }) { _ in
self?.extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
}
}
private func close() {
extensionContext?.completeRequest(returningItems: [], completionHandler: nil)
}
}

View File

@@ -0,0 +1,30 @@
import Foundation
/// Lightweight, extension-local client for AI tag suggestions. Reuses the same
/// backend + anonymous device auth as the main app's `ClaudeService.enrich`, but
/// without pulling the whole service (and its podcast/collection deps) into the
/// extension. The backend fetches the page itself, so suggestions reflect the
/// actual web page content not just the URL.
enum TagSuggester {
/// Asks the backend for tags for `url`. Returns [] on any failure tag
/// suggestion is best-effort and must never block saving.
static func suggest(url: String, title: String) async -> [String] {
struct Response: Decodable { let tags: [String] }
do {
let token = try await MarksAuth.validToken()
guard let endpoint = URL(string: MarksAuth.baseURL + "/v1/marks/enrich") else { return [] }
var req = URLRequest(url: endpoint)
req.httpMethod = "POST"
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"url": url, "title": title, "tags": [String](),
])
let (data, response) = try await URLSession.shared.data(for: req)
guard (200...299).contains((response as? HTTPURLResponse)?.statusCode ?? 0) else { return [] }
return try JSONDecoder().decode(Response.self, from: data).tags
} catch {
return []
}
}
}