Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ResearchView.swift

Raw 25.2 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import SwiftUI
2
3struct ResearchView: View {
4 private struct SearchRequest: Equatable {
5 let tab: String
6 var refresh: UUID?
7 }
8
9 let workspace: Workspace
10 let add: () -> Void
11 let edit: (WorkspaceRecord) -> Void
12 let editProject: () -> Void
13 let openDraft: (WorkspaceRecord) -> Void
14 let openSettings: (String) -> Void
15 let openConnections: () -> Void
16 @State private var request = SearchRequest(tab: RecentResearch.platform)
17 @State private var destination = "x"
18 @State private var searching = false
19 @State private var searchError: String?
20 @State private var showsReferenceHelp = false
21 @State private var referenceSearch = ""
22 @State private var recentTopic = ""
23 @State private var selectedBriefID: String?
24
25 private var tab: String { request.tab }
26 private var platform: ResearchPlatform { ResearchPlatform(rawValue: tab) ?? .x }
27 private var isRecent: Bool { tab == RecentResearch.platform }
28 private var hasApify: Bool { ProviderKey.apify.isSaved }
29 private var hasX: Bool { ProviderKey.x.isSaved || workspace.socialAccounts.hasSavedAccount(.x) }
30 private var canSearch: Bool {
31 switch ResearchPlatform(rawValue: tab) {
32 case .x: hasX || hasApify
33 case .instagram, .linkedin: hasApify
34 case .news, nil: true
35 }
36 }
37 private var canSynthesize: Bool {
38 switch StudioWritingConnection(settings: workspace.settings) {
39 case .agent: workspace.agentConnected
40 case .api: WritingProviders(settings: workspace.settings).writingProvider.isSaved
41 }
42 }
43 private var topicKey: String { "researchTopic:" + workspace.projectID }
44 private var feed: WorkspaceRecord? { workspace.items("discovery").first { $0["platform"] == platform.rawValue } }
45 private var items: [[String: Any]] { feed?.fields["items"] as? [[String: Any]] ?? [] }
46 private var recentBriefs: [WorkspaceRecord] {
47 workspace.items("discovery").filter { $0["platform"] == RecentResearch.platform }
48 .sorted { $0["searchedAt"] > $1["searchedAt"] }
49 }
50 private var recentBrief: WorkspaceRecord? { recentBriefs.first { $0.id == selectedBriefID } ?? recentBriefs.first }
51 private var savedTopic: String? {
52 (workspace.settings[topicKey] as? String) ?? recentBriefs.first?.title
53 }
54 private var topics: [String] {
55 var seen = Set<String>()
56 return ((feed?.fields["topics"] as? [String] ?? []) + items.compactMap { $0["topic"] as? String })
57 .filter { !$0.isEmpty && seen.insert($0).inserted }
58 }
59 private var references: [WorkspaceRecord] {
60 let query = referenceSearch.trimmingCharacters(in: .whitespacesAndNewlines)
61 return workspace.sources.filter {
62 query.isEmpty || $0.title.localizedStandardContains(query) || $0.body.localizedStandardContains(query)
63 }
64 }
65
66 var body: some View {
67 StudioScrollView {
68 VStack(alignment: .leading, spacing: 18) {
69 HStack {
70 PageHeading(title: "Worth your attention.",
71 subtitle: "Find relevant posts and news, and save sources for your drafts.")
72 Spacer()
73 }
74 StudioTabs(selection: Binding(get: { tab }, set: { if tab != $0 { request = SearchRequest(tab: $0) } }),
75 tabs: [RecentResearch.platform] + ResearchPlatform.allCases.map(\.rawValue),
76 label: { ResearchPlatform(rawValue: $0)?.title ?? RecentResearch.title }, platform: { $0 })
77 .onChange(of: tab) { _, tab in destination = ["instagram", "linkedin"].contains(tab) ? tab : "x" }
78 if searching {
79 HStack(spacing: 8) {
80 ProgressView().controlSize(.small)
81 Text("Looking for recent sources…").foregroundStyle(.secondary)
82 }
83 }
84 if let searchError {
85 Label(searchError, systemImage: "exclamationmark.circle")
86 .foregroundStyle(.secondary)
87 }
88 if isRecent { recentResearch }
89 else { platformResearch }
90 StudioRule()
91 savedReferences
92 }
93 .studioPage()
94 }
95 .task(id: request) { [request] in await load(request) }
96 }
97
98 @ViewBuilder private var recentResearch: some View {
99 HStack {
100 StudioSearchField(title: "Research a topic", text: $recentTopic)
101 .onSubmit { if !searching { refresh() } }
102 .disabled(searching)
103 refreshButton
104 }
105 recentSetup
106 if let brief = recentBrief {
107 let evidence = brief.fields["items"] as? [[String: Any]] ?? []
108 let findings = brief.fields["findings"] as? [[String: Any]] ?? []
109 HStack(alignment: .firstTextBaseline) {
110 Text(brief.title).font(InkspringTypography.editorial(25, relativeTo: .title2))
111 .accessibilityAddTraits(.isHeader)
112 Spacer()
113 if recentBriefs.count > 1 {
114 Menu("Saved briefs") {
115 ForEach(recentBriefs) { report in
116 Button(report.title) {
117 selectedBriefID = report.id
118 recentTopic = report.title
119 workspace.perform { try workspace.set(topicKey, to: report.title) }
120 }
121 }
122 }
123 .fixedSize()
124 }
125 }
126 if let start = scheduleDate(brief["windowStart"]), let end = scheduleDate(brief["searchedAt"]) {
127 Text("\(start.formatted(date: .abbreviated, time: .omitted)) – \(end.formatted(date: .abbreviated, time: .omitted))")
128 .font(.caption).foregroundStyle(.secondary)
129 }
130 recentCoverage(brief)
131 if !brief["focus"].isEmpty { Text(brief["focus"]).foregroundStyle(.secondary) }
132 if evidence.isEmpty {
133 Text("No dated sources matched this topic. Try a shorter or broader topic, then select Refresh topics.")
134 .foregroundStyle(.secondary)
135 recentFallback
136 } else {
137 ForEach(Array(findings.enumerated()), id: \.offset) { _, finding in
138 recentFinding(finding, evidence: evidence)
139 }
140 HStack {
141 Text("Sources (\(evidence.count))").font(.headline).accessibilityAddTraits(.isHeader)
142 Spacer()
143 writeDestination
144 }
145 recommendations(evidence, feed: brief)
146 }
147 } else {
148 recentFallback
149 }
150 }
151
152 @ViewBuilder private var recentFallback: some View {
153 if let cached = workspace.items("discovery").filter({ $0.id != recentBrief?.id })
154 .sorted(by: { $0["searchedAt"] > $1["searchedAt"] })
155 .first(where: { !datedItems($0).isEmpty }) {
156 let platform = cached["platform"]
157 let label = ResearchPlatform(rawValue: platform)?.title ?? cached.title
158 Text(platform == RecentResearch.starterPlatform ? "Browse recent technology sources" : "Previous results · " + label)
159 .font(.headline)
160 recommendations(Array(datedItems(cached).prefix(3)), feed: cached)
161 }
162 }
163
164 private func datedItems(_ record: WorkspaceRecord) -> [[String: Any]] {
165 let now = Date.now
166 return (record.fields["items"] as? [[String: Any]] ?? []).filter { item in
167 guard let source = item["source"] as? [String: Any],
168 let published = (source["postedAt"] as? String).flatMap(scheduleDate) else { return false }
169 return (0...RecentResearch.duration).contains(now.timeIntervalSince(published))
170 }
171 }
172
173 private var refreshButton: some View {
174 Button("Refresh topics", systemImage: "arrow.clockwise", action: refresh)
175 .modifier(PrimaryActionStyle())
176 .disabled(searching || !canSearch || workspace.project == nil)
177 }
178
179 private var recentSetup: some View {
180 DisclosureGroup("Research sources and setup") {
181 VStack(alignment: .leading, spacing: 8) {
182 Text("Google News, Hacker News and GitHub load automatically without API keys. Refresh topics includes your connected sources.")
183 Text("For Reddit and YouTube, add an Apify token. X works with Apify, a connected X account, or an X Bearer Token with Recent Search access.")
184 setupActions(includeX: true)
185 }
186 .font(.callout)
187 .foregroundStyle(.secondary)
188 .padding(.top, 5)
189 }
190 }
191
192 private var platformSetup: some View {
193 VStack(alignment: .leading, spacing: 8) {
194 Text(platform == .x ? "Connect X to load posts" : "Add an Apify token to load \(platform.title) posts")
195 .font(.headline)
196 Text(platform == .x
197 ? "In Connections, connect your X account. You can also save an X Bearer Token with Recent Search access or an Apify token in Settings → API keys."
198 : "Create an API token in Apify, then paste it into the Apify field in Settings → API keys and select Save key. Return here to load topics.")
199 .foregroundStyle(.secondary)
200 setupActions(includeX: platform == .x)
201 }
202 }
203
204 @ViewBuilder private func setupActions(includeX: Bool) -> some View {
205 HStack {
206 Button("Open API keys") { openSettings("API keys") }
207 SetupHelpLink("Apify setup", topic: "key-apify")
208 if includeX {
209 Button("Open Connections", action: openConnections)
210 SetupHelpLink("X token setup", topic: "key-x")
211 }
212 }
213 }
214
215 private func recentCoverage(_ brief: WorkspaceRecord) -> some View {
216 let rows = brief.fields["coverage"] as? [[String: Any]] ?? []
217 let labels = rows.compactMap { row -> String? in
218 guard let platform = row["platform"] as? String, let status = row["status"] as? String else { return nil }
219 let count = row["count"] as? Int ?? 0
220 return switch status {
221 case "searched": "\(platform) (\(count))"
222 case "imported": "\(platform) (\(count) imported)"
223 case "7-day search": "\(platform) (\(count) · 7-day search)"
224 case "unavailable": "\(platform) (setup needed)"
225 case "failed": "\(platform) (couldn’t load)"
226 default: "\(platform) (\(status))"
227 }
228 }
229 let failed = rows.filter { $0["status"] as? String == "failed" }.compactMap { $0["platform"] as? String }
230 return VStack(alignment: .leading, spacing: 5) {
231 Text(labels.joined(separator: " · ")).font(.caption)
232 if !failed.isEmpty {
233 Text("Couldn’t load \(failed.joined(separator: ", ")). If a connected source keeps failing, check its token and access in Settings → API keys, then refresh.")
234 .font(.callout)
235 }
236 }
237 .foregroundStyle(.secondary)
238 }
239
240 private func recentFinding(_ finding: [String: Any], evidence: [[String: Any]]) -> some View {
241 let addresses = finding["sourceURLs"] as? [String] ?? []
242 return VStack(alignment: .leading, spacing: 5) {
243 Text(finding["title"] as? String ?? "").font(.headline)
244 Text(finding["text"] as? String ?? "").textSelection(.enabled)
245 ForEach(addresses, id: \.self) { address in
246 if let url = sourceURL(address), let item = evidence.first(where: { $0["id"] as? String == address }),
247 let source = item["source"] as? [String: Any], let title = source["title"] as? String {
248 StudioExternalLink("\(source["origin"] as? String ?? "Source") · \(title)", destination: url)
249 .lineLimit(1)
250 }
251 }
252 }
253 }
254
255 private var writeDestination: some View {
256 StudioChoicePicker(title: "Write for", selection: $destination,
257 options: ["x", "linkedin", "instagram", "reddit"], label: platformName, icon: PlatformMark.image)
258 }
259
260 @ViewBuilder private var platformResearch: some View {
261 HStack {
262 if let project = workspace.project {
263 Button("Edit research focus", action: editProject)
264 if let updated = feed?["profileUpdatedAt"], !updated.isEmpty, updated != project["updatedAt"] {
265 Text("Refresh to use the updated project focus.").font(.caption).foregroundStyle(.secondary)
266 }
267 }
268 Spacer()
269 if !items.isEmpty { writeDestination }
270 refreshButton
271 }
272 if !canSearch || searchError != nil && platform != .news { platformSetup }
273 if let feed {
274 if !feed["focus"].isEmpty { Text(feed["focus"]).foregroundStyle(.secondary) }
275 if let date = scheduleDate(feed["searchedAt"]) {
276 Text("Last searched \(date.formatted(date: .abbreviated, time: .shortened))")
277 .font(.caption).foregroundStyle(.secondary)
278 }
279 ForEach(feed.fields["warnings"] as? [String] ?? [], id: \.self) { Text($0).foregroundStyle(.secondary) }
280 if items.isEmpty && !searching {
281 Text("No matching sources. Edit your research focus for a broader topic, then select Refresh topics.")
282 .foregroundStyle(.secondary)
283 }
284 ForEach(topics, id: \.self) { topic in
285 let matching = items.filter { $0["topic"] as? String == topic }
286 if !matching.isEmpty {
287 Text(topic).font(.headline)
288 recommendations(matching, feed: feed)
289 }
290 }
291 recommendations(items.filter { ($0["topic"] as? String ?? "").isEmpty }, feed: feed)
292 }
293 }
294
295 @ViewBuilder private var savedReferences: some View {
296 HStack {
297 Text("Saved references").font(InkspringTypography.editorial(25, relativeTo: .title2))
298 .accessibilityAddTraits(.isHeader)
299 Button { showsReferenceHelp.toggle() } label: {
300 Image(systemName: "questionmark.circle")
301 }
302 .buttonStyle(StudioIconButtonStyle())
303 .accessibilityLabel("What are saved references?")
304 .help("Keep a source in this project to reopen it or start a draft from it.")
305 .popover(isPresented: $showsReferenceHelp, arrowEdge: .bottom) {
306 Text("Select Save reference on a research result to keep it in this project, or select Add reference to save your own link or note. Use Write from reference to start a draft with the source attached.")
307 .frame(width: 285, alignment: .leading)
308 .fixedSize(horizontal: false, vertical: true)
309 .padding(14)
310 }
311 Spacer()
312 StudioSearchField(title: "Search saved references", text: $referenceSearch)
313 .frame(maxWidth: 240)
314 Button("Add reference", systemImage: "plus", action: add)
315 }
316 if references.isEmpty {
317 Text(referenceSearch.isEmpty ? "Save a result you want to use later, or add your own link or note." : "No matching references.")
318 .foregroundStyle(.secondary)
319 } else {
320 LazyVGrid(columns: [GridItem(.adaptive(minimum: 250), spacing: 12)], spacing: 12) {
321 ForEach(references) { source in
322 VStack(alignment: .leading, spacing: 8) {
323 Button { edit(source) } label: { RecordCard(record: source) }.buttonStyle(.plain)
324 ViewThatFits(in: .horizontal) {
325 HStack(spacing: 6) { referenceActions(source) }
326 VStack(alignment: .leading, spacing: 6) { referenceActions(source) }
327 }
328 }
329 }
330 }
331 }
332 }
333
334 @ViewBuilder private func referenceActions(_ source: WorkspaceRecord) -> some View {
335 Button("Write from reference") { openDraft(ResearchDraft.post(from: source, platform: "x")) }
336 .modifier(PrimaryActionStyle())
337 if let url = sourceURL(source["url"]) { StudioExternalLink("Open source", destination: url) }
338 }
339
340 private func recommendations(_ items: [[String: Any]], feed: WorkspaceRecord) -> some View {
341 ForEach(Array(items.enumerated()), id: \.offset) { _, item in recommendation(item, feed: feed) }
342 }
343
344 private func recommendation(_ item: [String: Any], feed: WorkspaceRecord) -> some View {
345 let source = item["source"] as? [String: Any] ?? [:]
346 let address = source["url"] as? String ?? ""
347 let saved = !address.isEmpty && workspace.sources.contains { $0["url"] == address }
348 let canReply = (isRecent || platform == .x) && XQuoteComposer.postURL(address) != nil
349 let angle = item["angle"] as? String ?? ""
350 return GroupBox(item["headline"] as? String ?? "Research idea") {
351 VStack(alignment: .leading, spacing: 7) {
352 if let hook = item["hook"] as? String, !hook.isEmpty { Text(hook).font(.headline) }
353 if !angle.isEmpty { Text(angle).textSelection(.enabled) }
354 if let fit = item["whyItFits"] as? String, !fit.isEmpty { Text(fit).foregroundStyle(.secondary) }
355 if let evidence = source["text"] as? String {
356 DisclosureGroup(isRecent ? "Read source excerpt" : platform == .news ? "Read headline" : "Read source post") {
357 Text(evidence).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
358 }
359 }
360 sourceDetails(source)
361 HStack {
362 if let url = sourceURL(address) { StudioExternalLink("Open source", destination: url) }
363 if canReply {
364 Button("Reply to source") {
365 workspace.perform { openDraft(try ResearchDraft.reply(to: source, projectID: workspace.projectID)) }
366 }
367 }
368 Spacer()
369 Button(saved ? "Saved" : "Save reference") { save(source) }
370 .disabled(saved)
371 Button(angle.isEmpty ? "Write from source" : "Write from this angle") { save(source, recommendation: item) }
372 if !isRecent {
373 Button("Dismiss") {
374 workspace.perform { try workspace.dismissResearch(item["id"] as? String ?? "", from: feed.id) }
375 }
376 }
377 }
378 }
379 .frame(maxWidth: .infinity, alignment: .leading)
380 }
381 }
382
383 private func sourceDetails(_ source: [String: Any]) -> some View {
384 HStack(spacing: 10) {
385 if isRecent, let origin = source["origin"] as? String { Text(origin) }
386 if let author = source["author"] as? String, !author.isEmpty { Text(author) }
387 if let day = source["publishedDay"] as? String {
388 Text(day)
389 } else if let date = (source["postedAt"] as? String).flatMap(scheduleDate) {
390 Text(date.formatted(date: .abbreviated, time: .shortened))
391 }
392 if isRecent || platform != .news {
393 if let likes = source["likes"] as? Int {
394 let metric = switch (source["origin"] as? String ?? "").lowercased() {
395 case "reddit": "upvotes"
396 case "hacker news": "points"
397 case "github": "reactions"
398 default: "likes"
399 }
400 Text("\(likes.formatted()) \(metric)")
401 }
402 if let reposts = source["reposts"] as? Int { Text("\(reposts.formatted()) reposts") }
403 if let replies = source["replies"] as? Int {
404 Text("\(replies.formatted()) replies")
405 }
406 if let views = source["views"] as? Int { Text("\(views.formatted()) views") }
407 }
408 }
409 .font(.caption)
410 .foregroundStyle(.secondary)
411 }
412
413 private func refresh() {
414 request.refresh = UUID()
415 }
416
417 private func load(_ action: SearchRequest) async {
418 guard !Task.isCancelled, request == action else { return }
419 searching = false
420 searchError = nil
421 guard let project = workspace.project, canSearch else { return }
422 let refresh = action.refresh != nil
423 if action.tab == RecentResearch.platform {
424 let entered = recentTopic.trimmingCharacters(in: .whitespacesAndNewlines)
425 let topic = (refresh && !entered.isEmpty ? entered : savedTopic) ?? RecentResearch.topic(in: project["researchFocus"])
426 recentTopic = topic
427 let cached = recentBriefs.first { $0.title.localizedCaseInsensitiveCompare(topic) == .orderedSame }
428 selectedBriefID = cached?.id
429 if !refresh, RecentResearch.fresh(cached), let cached, !datedItems(cached).isEmpty { return }
430 await loadRecent(action, topic: topic, projectID: project.id, cached: cached, refresh: refresh)
431 } else if let platform = ResearchPlatform(rawValue: action.tab) {
432 if !refresh, RecentResearch.fresh(feed), feed?["profileUpdatedAt"] == project["updatedAt"], !items.isEmpty { return }
433 await loadPlatform(action, platform: platform, project: project)
434 }
435 }
436
437 private func loadRecent(_ action: SearchRequest, topic: String, projectID: String, cached: WorkspaceRecord?, refresh: Bool) async {
438 searching = true
439 defer { if request == action { searching = false } }
440 do {
441 if refresh, (1...180).contains(topic.utf16.count) { try workspace.set(topicKey, to: topic) }
442 let research = RecentResearch(studio: ContentStudio(workspace: workspace))
443 let coverage = cached?.fields["coverage"] as? [[String: Any]] ?? []
444 let includedConnectedSources = coverage.contains {
445 ["X", "Reddit", "YouTube"].contains($0["platform"] as? String ?? "")
446 }
447 let sources = refresh || includedConnectedSources ? Set(RecentResearchSource.allCases) : RecentResearch.publicSources
448 let brief = try await research.run(topic: topic, projectID: projectID, sources: sources,
449 synthesize: refresh && canSynthesize)
450 guard !Task.isCancelled, request == action else { return }
451 selectedBriefID = brief.id
452 if datedItems(brief).isEmpty, !refresh, topic != RecentResearch.starterTopic {
453 let starter = workspace.items("discovery").first { $0["platform"] == RecentResearch.starterPlatform }
454 if !RecentResearch.fresh(starter) {
455 _ = try await research.run(topic: RecentResearch.starterTopic, projectID: projectID,
456 sources: RecentResearch.publicSources, synthesize: false, starter: true)
457 }
458 }
459 } catch {
460 if !Task.isCancelled, request == action { searchError = error.localizedDescription }
461 }
462 }
463
464 private func loadPlatform(_ action: SearchRequest, platform: ResearchPlatform, project: WorkspaceRecord) async {
465 searching = true
466 defer { if request == action { searching = false } }
467 let discovery = ResearchDiscovery(studio: ContentStudio(workspace: workspace))
468 let topic = RecentResearch.topic(in: savedTopic ?? project["researchFocus"])
469 do {
470 if canSynthesize {
471 do {
472 _ = try await discovery.discover(platform, projectID: project.id, includeUnrankedSources: true)
473 return
474 } catch {
475 try Task.checkCancellation()
476 _ = try await discovery.browse(platform, projectID: project.id, topic: topic,
477 note: "Showing recent sources. Writing suggestions couldn’t load. Check your writing connection in Settings.")
478 }
479 } else {
480 _ = try await discovery.browse(platform, projectID: project.id, topic: topic)
481 }
482 } catch {
483 if !Task.isCancelled, request == action {
484 searchError = "Couldn’t refresh \(platform.title). \(error.localizedDescription) Try Refresh topics again."
485 }
486 }
487 }
488
489 private func save(_ evidence: [String: Any], recommendation: [String: Any]? = nil) {
490 workspace.perform {
491 let source = try workspace.saveResearchReference(evidence, projectID: workspace.projectID)
492 if let recommendation {
493 openDraft(ResearchDraft.post(from: source, platform: destination, hook: recommendation["hook"] as? String ?? "",
494 angle: recommendation["angle"] as? String ?? ""))
495 } else {
496 workspace.notice = "Reference saved"
497 }
498 }
499 }
500
501 private func sourceURL(_ value: String) -> URL? {
502 guard let url = URL(string: value), url.scheme == "https", url.host != nil,
503 url.user == nil, url.password == nil else { return nil }
504 return url
505 }
506}