Branchwell

Inkspring / app · inkspring.ai / native-mac / Tests / InkspringTests / WorkContextTests.swift

Raw 6.5 KB on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import Foundation
2import Testing
3@testable import Inkspring
4
5@Test @MainActor func workSourceRefreshImportsOnlyApprovedRecentNotes() async throws {
6 let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
7 let notes = root.appending(path: "notes")
8 try FileManager.default.createDirectory(at: notes, withIntermediateDirectories: true)
9 defer { try? FileManager.default.removeItem(at: root) }
10 let current = notes.appending(path: "Recent.md")
11 let old = notes.appending(path: "Old.md")
12 try "---\ninternal: metadata\n---\nA fresh reference".write(to: current, atomically: true, encoding: .utf8)
13 try "An old reference".write(to: old, atomically: true, encoding: .utf8)
14 try FileManager.default.setAttributes([.modificationDate: Date.now.addingTimeInterval(-72 * 3600)], ofItemAtPath: old.path)
15 try FileManager.default.createSymbolicLink(at: notes.appending(path: "Linked.md"), withDestinationURL: current)
16
17 let workspace = Workspace(directory: root.appending(path: "workspace"))
18 let project = try #require(workspace.projects.first)
19 try workspace.updateWorkSourceSchedule(project.id, fields: ["enabled": true, "hours": 6, "notesFolder": notes.path])
20 await workspace.refreshScheduledWork()
21 #expect(!workspace.records.contains { $0["origin"] == "Obsidian notes" })
22 try workspace.updateWorkSourceSchedule(project.id, fields: ["nativeApproved": true])
23 await workspace.refreshScheduledWork()
24 let imported = workspace.records.filter { $0["origin"] == "Obsidian notes" }
25 #expect(imported.count == 1)
26 #expect(imported.first?.title == "Recent")
27 #expect(imported.first?.body == "A fresh reference")
28 #expect(workspace.workSourceSchedule(project.id)["lastCount"] as? Int == 1)
29 try workspace.updateWorkSourceSchedule(project.id, fields: [:])
30 await workspace.refreshScheduledWork()
31 #expect(workspace.records.filter { $0["origin"] == "Obsidian notes" }.count == 1)
32 #expect(workspace.workSourceSchedule(project.id)["lastCount"] as? Int == 0)
33}
34
35@Test func workContextReadsOnlyRecapsForTheSelectedFolder() throws {
36 let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
37 let project = root.appending(path: "project")
38 let claude = root.appending(path: "Library/Application Support/Claude/claude-code-sessions")
39 let codex = root.appending(path: ".codex")
40 for folder in [project, claude, codex] { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) }
41 defer { try? FileManager.default.removeItem(at: root) }
42 let now = Date.now
43 for (name, folder) in [("In scope", project.path + "/feature"), ("Sibling", project.path + "-other")] {
44 let data = try JSONSerialization.data(withJSONObject: [
45 "title": name, "cwd": folder, "lastActivityAt": now.timeIntervalSince1970 * 1000,
46 "turnWrapUp": ["description": "The local recap."]
47 ])
48 try data.write(to: claude.appending(path: "local_\(name).json"))
49 }
50 let rollout = codex.appending(path: "recent.jsonl")
51 try #"{"type":"event_msg","payload":{"type":"task_complete","last_agent_message":"Completed local work."}}"#
52 .write(to: rollout, atomically: true, encoding: .utf8)
53 try runFixtureProcess("/usr/bin/sqlite3", [codex.appending(path: "state_5.sqlite").path, """
54 CREATE TABLE threads(title TEXT, cwd TEXT, rollout_path TEXT, updated_at INTEGER);
55 INSERT INTO threads VALUES ('Codex fixture','\(project.path)','\(rollout.path)',\(Int(now.timeIntervalSince1970)));
56 INSERT INTO threads VALUES ('Outside rollout','\(project.path)','\(claude.path)/local_In scope.json',\(Int(now.timeIntervalSince1970)));
57 """])
58 let git = ["-C", project.path, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid",
59 "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgSign=false"]
60 try runFixtureProcess("/usr/bin/git", git + ["init", "-q"])
61 try "Fixture".write(to: project.appending(path: "draft.md"), atomically: true, encoding: .utf8)
62 try runFixtureProcess("/usr/bin/git", git + ["add", "draft.md"])
63 try runFixtureProcess("/usr/bin/git", git + ["commit", "-qm", "Write a local draft"])
64 let result = WorkContext(now: now, home: root).collect(code: project, notes: nil)
65 #expect(Set(result.items.map(\.title)) == ["In scope", "Codex fixture", "Write a local draft"])
66 #expect(result.items.first { $0.origin == .codex }?.text == "Completed local work.")
67 #expect(result.unavailable.isEmpty)
68}
69
70private func runFixtureProcess(_ executable: String, _ arguments: [String]) throws {
71 let process = Process()
72 process.executableURL = URL(fileURLWithPath: executable)
73 process.arguments = arguments
74 process.environment = ["PATH": "/usr/bin:/bin", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"]
75 try process.run()
76 process.waitUntilExit()
77 try #require(process.terminationStatus == 0)
78}
79
80@Test @MainActor func legacyJSONRestorePreservesTextAndPausesDelivery() throws {
81 let root = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)
82 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
83 defer { try? FileManager.default.removeItem(at: root) }
84 let file = root.appending(path: "legacy.json")
85 let data = try JSONSerialization.data(withJSONObject: [
86 "app": "inkspring-desktop", "version": 1,
87 "projects": [["id": "project", "name": "Legacy"]],
88 "drafts": [["id": "draft", "projectId": "project", "title": "Older post", "content": "Keep this text.",
89 "format": "image", "platform": "x", "image": ["file": "old.png"],
90 "schedule": ["status": "queued", "slotAt": "2027-01-01T12:00:00Z"]]],
91 "sources": [],
92 "newsletters": [["id": "news", "projectId": "project", "title": "Newsletter", "body": "Old issue",
93 "remoteId": "123", "sendEmail": true]]
94 ])
95 try data.write(to: file)
96 let workspace = Workspace(directory: root.appending(path: "workspace"))
97 let (backup, files) = try WorkspaceBackup.stage(file, in: root)
98 #expect(backup.isLegacy)
99 #expect(files.isEmpty)
100 try workspace.apply(backup, files: files)
101 let draft = try #require(workspace.records.first { $0.id == "draft" })
102 #expect(draft.body == "Keep this text.")
103 #expect(draft.scheduleStatus == "ready")
104 #expect(draft.fields["image"] == nil)
105 let newsletter = try #require(workspace.records.first { $0.id == "news" })
106 #expect(newsletter["remoteId"].isEmpty)
107 #expect(newsletter.fields["sendEmail"] as? Bool == false)
108}