Branchwell

Jobley / app · jobley.ai / commits / 31b31c09

App source: current code new

written by Branchwell · 31b31c099e453aea6c2ecdc8181ae49a445ca531

66 files changed

.gitignore added

1+ .DS_Store
2+ .build/
3+ DerivedData/
4+ *.xcodeproj/
5+ .swiftpm/
6+ build/

Apps/Mac/Assets.xcassets/AccentColor.colorset/Contents.json added

1+ { "colors": [
2+ { "idiom": "universal", "color": { "color-space": "srgb", "components": { "red": "0x17", "green": "0x60", "blue": "0x3F", "alpha": "1.000" } } },
3+ { "idiom": "universal", "appearances": [ { "appearance": "luminosity", "value": "dark" } ], "color": { "color-space": "srgb", "components": { "red": "0x7F", "green": "0xD6", "blue": "0xA6", "alpha": "1.000" } } }
4+ ], "info": { "author": "xcode", "version": 1 } }

Apps/Mac/Assets.xcassets/AppIcon.appiconset/Contents.json added

1+ {
2+ "images": [
3+ {
4+ "idiom": "mac",
5+ "size": "16x16",
6+ "scale": "1x",
7+ "filename": "icon-16@1x.png"
8+ },
9+ {
10+ "idiom": "mac",
11+ "size": "16x16",
12+ "scale": "2x",
13+ "filename": "icon-16@2x.png"
14+ },
15+ {
16+ "idiom": "mac",
17+ "size": "32x32",
18+ "scale": "1x",
19+ "filename": "icon-32@1x.png"
20+ },
21+ {
22+ "idiom": "mac",
23+ "size": "32x32",
24+ "scale": "2x",
25+ "filename": "icon-32@2x.png"
26+ },
27+ {
28+ "idiom": "mac",
29+ "size": "128x128",
30+ "scale": "1x",
31+ "filename": "icon-128@1x.png"
32+ },
33+ {
34+ "idiom": "mac",
35+ "size": "128x128",
36+ "scale": "2x",
37+ "filename": "icon-128@2x.png"
38+ },
39+ {
40+ "idiom": "mac",
41+ "size": "256x256",
42+ "scale": "1x",
43+ "filename": "icon-256@1x.png"
44+ },
45+ {
46+ "idiom": "mac",
47+ "size": "256x256",
48+ "scale": "2x",
49+ "filename": "icon-256@2x.png"
50+ },
51+ {
52+ "idiom": "mac",
53+ "size": "512x512",
54+ "scale": "1x",
55+ "filename": "icon-512@1x.png"
56+ },
57+ {
58+ "idiom": "mac",
59+ "size": "512x512",
60+ "scale": "2x",
61+ "filename": "icon-512@2x.png"
62+ }
63+ ],
64+ "info": {
65+ "author": "xcode",
66+ "version": 1
67+ }
68+ }

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-128@1x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-128@2x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-16@1x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-16@2x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-256@1x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-256@2x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-32@1x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-32@2x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-512@1x.png added

Not a text file.

Apps/Mac/Assets.xcassets/AppIcon.appiconset/icon-512@2x.png added

Not a text file.

Apps/Mac/Assets.xcassets/Contents.json added

1+ { "info": { "author": "xcode", "version": 1 } }

Apps/Mac/DeskView.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ struct DeskView: View {
6+ @EnvironmentObject var desk: DeskModel
7+ var body: some View { DeskColumns(desk: desk, curator: desk.curator, board: desk.board) }
8+ }
9+
10+ struct DeskColumns: View {
11+ @ObservedObject var desk: DeskModel
12+ @ObservedObject var curator: CuratorModel
13+ @ObservedObject var board: BoardModel
14+
15+ var body: some View {
16+ NavigationSplitView {
17+ sidebar
18+ .navigationSplitViewColumnWidth(min: 210, ideal: 230)
19+ } content: {
20+ content
21+ .navigationSplitViewColumnWidth(min: 300, ideal: 360)
22+ } detail: {
23+ detail
24+ }
25+ .task {
26+ #if DEBUG
27+ Snapshot.runIfRequested()
28+ #endif
29+ await desk.start()
30+ }
31+ .onChange(of: desk.section) {
32+ desk.selectedJobID = nil; desk.selectedCandidateID = nil
33+ desk.candidates.scope = .everyone
34+ Task { await desk.refreshSection() }
35+ }
36+ .onChange(of: desk.selectedJobID) { Task { await curator.open(desk.selectedJobID) } }
37+ .alert("Something went wrong", isPresented: Binding(get: { curator.error != nil }, set: { if !$0 { curator.error = nil } })) {
38+ Button("OK") { curator.error = nil }
39+ } message: { Text(curator.error ?? "") }
40+ }
41+
42+ // MARK: Sidebar
43+
44+ var sidebar: some View {
45+ List(selection: $desk.section) {
46+ Section("Review") {
47+ ForEach(CuratorModel.Queue.allCases) { queue in
48+ Label(queue.title, systemImage: queue.systemImage)
49+ .badge(count(queue))
50+ .tag(DeskModel.Section.queue(queue))
51+ }
52+ }
53+ if curator.canSeeCandidates || curator.me?.isCurator == true {
54+ Section("People") {
55+ if curator.canSeeCandidates {
56+ Label("Candidates", systemImage: "person.2").badge(curator.stats?.candidates?["new"] ?? 0).tag(DeskModel.Section.candidates)
57+ }
58+ if curator.me?.isCurator == true {
59+ Label("Moderators", systemImage: "person.badge.shield.checkmark")
60+ .badge(curator.stats?.moderatorApplications?.new ?? 0).tag(DeskModel.Section.moderators)
61+ }
62+ }
63+ }
64+ Section("The board") {
65+ Label("Browse jobs", systemImage: "list.bullet.rectangle").tag(DeskModel.Section.board)
66+ Label("Post a job", systemImage: "square.and.pencil").tag(DeskModel.Section.post)
67+ }
68+ }
69+ .scrollContentBackground(.hidden)
70+ .background(Theme.surface2)
71+ .safeAreaInset(edge: .bottom) { signedInFooter }
72+ .navigationTitle("Jobley")
73+ }
74+
75+ func count(_ queue: CuratorModel.Queue) -> Int {
76+ guard let stats = curator.stats, let status = JobStatus(rawValue: queue.rawValue) else { return 0 }
77+ return queue == .published ? 0 : stats.jobs(status)
78+ }
79+
80+ var signedInFooter: some View {
81+ HStack(spacing: 8) {
82+ JobleyMark(size: 22)
83+ VStack(alignment: .leading, spacing: 0) {
84+ Text(curator.me.map { $0.isCurator ? "Curator" : "Moderator · \($0.name)" } ?? "Not signed in")
85+ .font(.caption.weight(.semibold))
86+ if let stats = curator.stats {
87+ Text("\(stats.jobs(.published)) on the board · \(stats.jobs(.pending)) waiting").font(.caption2).foregroundStyle(.secondary)
88+ }
89+ }
90+ Spacer()
91+ SettingsLink { Image(systemName: "gearshape") }.buttonStyle(.borderless)
92+ }
93+ .padding(12)
94+ }
95+
96+ // MARK: Content column
97+
98+ @ViewBuilder var content: some View {
99+ switch desk.section {
100+ case .queue(let queue):
101+ if curator.isSignedIn { QueueList(desk: desk, curator: curator, queue: queue, labels: board.labels) }
102+ else { SignInPanel(curator: curator) }
103+ case .candidates: CandidateList(desk: desk, model: desk.candidates, jobs: curator.jobs(.published))
104+ case .moderators: ModeratorsView(model: desk.moderators)
105+ case .board: BoardList(desk: desk, board: board)
106+ case .post: PostJobForm(api: board.api) { desk.section = .board }.navigationTitle("Post a job")
107+ }
108+ }
109+
110+ // MARK: Detail column
111+
112+ @ViewBuilder var detail: some View {
113+ switch desk.section {
114+ case .queue:
115+ if let item = curator.item, item.job.id == desk.selectedJobID {
116+ ReviewDetail(model: curator, item: item, labels: board.labels).id(item.job.id + (item.job.updatedAt ?? ""))
117+ } else if curator.isSignedIn {
118+ StateMessage("Pick a post", detail: "The oldest post is at the top. A person reads every one.", systemImage: "tray")
119+ } else {
120+ Color.clear
121+ }
122+ case .candidates:
123+ CandidateDetailColumn(model: desk.candidates, selectedID: desk.selectedCandidateID, jobs: curator.jobs(.published), curator: curator)
124+ case .board:
125+ if let job = board.jobs.first(where: { $0.id == desk.selectedJobID }) {
126+ ScrollView { JobBody(job: job, labels: board.labels).padding(28).frame(maxWidth: 760, alignment: .leading) }
127+ .frame(maxWidth: .infinity, alignment: .leading).background(Theme.background)
128+ } else {
129+ StateMessage("Pick a job", detail: "This is the board exactly as everyone sees it.", systemImage: "list.bullet.rectangle")
130+ }
131+ case .moderators:
132+ StateMessage("Moderators read posts against the rules", detail: "Approving an application shows a one-time passkey setup link to hand them. Only you can see candidates unless you switch it on for them.", systemImage: "person.badge.shield.checkmark")
133+ case .post:
134+ Color.clear
135+ }
136+ }
137+ }
138+
139+ struct CandidateDetailColumn: View {
140+ @ObservedObject var model: CandidatesModel
141+ let selectedID: String?
142+ let jobs: [Job]
143+ @ObservedObject var curator: CuratorModel
144+
145+ var body: some View {
146+ if let detail = model.detail, detail.candidate.id == selectedID {
147+ CandidateDetailView(model: model, detail: detail, jobs: jobs, curator: curator)
148+ } else {
149+ StateMessage("Pick a person", detail: "Listed oldest first. Nothing here ranks or scores anyone.", systemImage: "person.2")
150+ }
151+ }
152+ }
153+
154+ struct QueueList: View {
155+ @ObservedObject var desk: DeskModel
156+ @ObservedObject var curator: CuratorModel
157+ let queue: CuratorModel.Queue
158+ let labels: Labels
159+
160+ var body: some View {
161+ let jobs = curator.jobs(queue)
162+ Group {
163+ if jobs.isEmpty {
164+ StateMessage(queue == .pending ? "Nothing waiting" : "Nothing here",
165+ detail: queue == .pending ? "Every post has been read. New posts appear here, oldest first." : "Posts move here as people decide.",
166+ systemImage: queue.systemImage) { Task { await desk.refresh() } }
167+ } else {
168+ List(jobs, selection: $desk.selectedJobID) { job in
169+ JobRow(job: job, labels: labels, showStatus: queue != .pending).tag(job.id)
170+ }
171+ }
172+ }
173+ .navigationTitle(queue.title)
174+ .navigationSubtitle(queue == .pending || queue == .approved ? "Oldest first" : "")
175+ .toolbar { Button { Task { await desk.refresh() } } label: { Label("Refresh", systemImage: "arrow.clockwise") } }
176+ }
177+ }
178+
179+ struct BoardList: View {
180+ @ObservedObject var desk: DeskModel
181+ @ObservedObject var board: BoardModel
182+
183+ var body: some View {
184+ VStack(spacing: 0) {
185+ BoardFilters(board: board).padding(10)
186+ if let error = board.error, board.jobs.isEmpty {
187+ StateMessage("Couldn't load the board", detail: error, systemImage: "wifi.slash") { Task { await board.reload() } }
188+ } else if board.jobs.isEmpty && !board.loading {
189+ StateMessage(board.hasFilters ? "Nothing matches" : "No jobs yet", detail: board.hasFilters ? "Try fewer filters." : "Published jobs appear here.",
190+ systemImage: "magnifyingglass")
191+ } else {
192+ List(selection: $desk.selectedJobID) {
193+ ForEach(board.jobs) { JobRow(job: $0, labels: board.labels).tag($0.id) }
194+ if board.nextCursor != nil {
195+ Button("Load more") { Task { await board.loadMore() } }.frame(maxWidth: .infinity)
196+ }
197+ }
198+ }
199+ }
200+ .searchable(text: $board.query, prompt: "Title, company or place")
201+ .onSubmit(of: .search) { Task { await board.reload() } }
202+ .navigationTitle("The board")
203+ .navigationSubtitle("Newest first")
204+ }
205+ }
206+
207+ struct SignInPanel: View {
208+ @ObservedObject var curator: CuratorModel
209+
210+ var body: some View {
211+ VStack(alignment: .leading, spacing: 14) {
212+ JobleyMark(size: 48)
213+ Text("The curator's desk").font(Theme.display(26))
214+ Text("Curators and moderators sign in with a passkey to read the review queue.")
215+ .foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)
216+ PasskeySignIn(curator: curator).frame(maxWidth: 420, alignment: .leading)
217+ Text("Moderators get a one-time setup link when the curator approves their application. Add a second passkey in Settings so you can always get back in.")
218+ .font(.caption).foregroundStyle(Theme.muted).fixedSize(horizontal: false, vertical: true)
219+ Spacer()
220+ }
221+ .padding(24)
222+ .navigationTitle("Sign in")
223+ }
224+ }

Apps/Mac/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Jobley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleVersion</key>
22+ <string>$(CURRENT_PROJECT_VERSION)</string>
23+ <key>ITSAppUsesNonExemptEncryption</key>
24+ <false/>
25+ <key>LSApplicationCategoryType</key>
26+ <string>public.app-category.business</string>
27+ <key>NSAppTransportSecurity</key>
28+ <dict>
29+ <key>NSAllowsLocalNetworking</key>
30+ <true/>
31+ </dict>
32+ <key>NSHumanReadableCopyright</key>
33+ <string>Free and open source, public domain (Unlicense).</string>
34+ <key>SUFeedURL</key>
35+ <string>$(JOBLEY_UPDATE_FEED)</string>
36+ <key>SUPublicEDKey</key>
37+ <string>$(JOBLEY_UPDATE_PUBLIC_KEY)</string>
38+ </dict>
39+ </plist>

Apps/Mac/JobleyMac.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>com.apple.developer.associated-domains</key>
6+ <array>
7+ <string>webcredentials:jobley.ai</string>
8+ </array>
9+ <key>com.apple.security.network.client</key>
10+ <true/>
11+ </dict>
12+ </plist>

Apps/Mac/MacApp.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ /// `Jobley --mcp` runs the MCP server on stdin/stdout instead of the app.
6+ @main
7+ enum Launcher {
8+ static func main() {
9+ if CommandLine.arguments.contains("--mcp") {
10+ let done = DispatchSemaphore(value: 0)
11+ Task.detached { await MCPServer.live().run(); done.signal() }
12+ done.wait()
13+ return
14+ }
15+ JobleyMacApp.main()
16+ }
17+ }
18+
19+ struct JobleyMacApp: App {
20+ @StateObject private var desk = DeskModel()
21+ @StateObject private var updates = AppUpdates()
22+
23+ var body: some Scene {
24+ Window("Jobley", id: "desk") {
25+ DeskView()
26+ .environmentObject(desk)
27+ .frame(minWidth: 1080, minHeight: 680)
28+ .tint(Theme.accent)
29+ }
30+ .defaultSize(width: 1320, height: 840)
31+ .commands {
32+ CommandGroup(after: .appInfo) { CheckForUpdatesButton(updates: updates) }
33+ CommandGroup(after: .toolbar) {
34+ Button("Refresh") { Task { await desk.refresh() } }.keyboardShortcut("r")
35+ }
36+ }
37+
38+ Settings {
39+ MacSettings(updates: updates)
40+ .environmentObject(desk)
41+ .tint(Theme.accent)
42+ }
43+ }
44+ }
45+
46+ /// Everything the desk shows. The passkey sign-in (a session) comes from the Keychain.
47+ @MainActor
48+ final class DeskModel: ObservableObject {
49+ enum Section: Hashable {
50+ case queue(CuratorModel.Queue)
51+ case candidates, moderators, board, post
52+ }
53+
54+ let curator: CuratorModel
55+ let board: BoardModel
56+ let candidates: CandidatesModel
57+ let moderators: ModeratorsModel
58+ @Published var section: Section = .queue(.pending)
59+ @Published var selectedJobID: String?
60+ @Published var selectedCandidateID: String?
61+ private var purged = false
62+
63+ init() {
64+ let api = APIClient(client: .mac, token: TokenStore.load())
65+ let curator = CuratorModel(api: api)
66+ self.curator = curator
67+ board = BoardModel(api: APIClient(client: .mac))
68+ candidates = CandidatesModel { curator.api }
69+ moderators = ModeratorsModel { curator.api }
70+ #if DEBUG
71+ if let start = ProcessInfo.processInfo.environment["JOBLEY_SECTION"] { section = Self.section(named: start) }
72+ selectedJobID = ProcessInfo.processInfo.environment["JOBLEY_JOB"]
73+ selectedCandidateID = ProcessInfo.processInfo.environment["JOBLEY_CANDIDATE"]
74+ #endif
75+ }
76+
77+ static func section(named name: String) -> Section {
78+ switch name {
79+ case "candidates": .candidates
80+ case "moderators": .moderators
81+ case "board": .board
82+ case "post": .post
83+ default: .queue(CuratorModel.Queue(rawValue: name) ?? .pending)
84+ }
85+ }
86+
87+ func start() async {
88+ await board.loadMeta()
89+ await curator.start()
90+ await purgeOnce()
91+ await refreshSection()
92+ }
93+
94+ func refresh() async {
95+ await curator.refreshAll()
96+ await refreshSection()
97+ }
98+
99+ func refreshSection() async {
100+ switch section {
101+ case .board:
102+ await board.reload()
103+ #if DEBUG
104+ if ProcessInfo.processInfo.environment["JOBLEY_JOB"] == "first" { selectedJobID = board.jobs.first?.id }
105+ #endif
106+ case .candidates where curator.canSeeCandidates:
107+ await candidates.reload()
108+ await candidates.open(selectedCandidateID)
109+ case .moderators where curator.me?.isCurator == true: await moderators.reload()
110+ case .queue:
111+ if selectedJobID == nil, case .queue(let queue) = section { selectedJobID = curator.jobs(queue).first?.id }
112+ await curator.open(selectedJobID)
113+ default: break
114+ }
115+ }
116+
117+ /// The privacy promise: posts off the board, candidates and applications are deleted
118+ /// 12 months after their last change. The curator's desk runs it when it opens.
119+ private func purgeOnce() async {
120+ guard !purged, curator.me?.isCurator == true else { return }
121+ purged = true
122+ _ = try? await curator.api.purge()
123+ }
124+ }

Apps/Mac/MacSettings.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ struct MacSettings: View {
6+ @ObservedObject var updates: AppUpdates
7+
8+ var body: some View {
9+ TabView {
10+ AccountSettings().tabItem { Label("Account", systemImage: "person.crop.circle") }
11+ AgentSettingsTab().tabItem { Label("Agents", systemImage: "cpu") }
12+ AboutSettings(updates: updates).tabItem { Label("About", systemImage: "info.circle") }
13+ }
14+ .frame(width: 560, height: 520)
15+ }
16+ }
17+
18+ struct AccountSettings: View {
19+ @EnvironmentObject var desk: DeskModel
20+ @AppStorage(APIClient.serverDefaultsKey) private var server = ""
21+
22+ var body: some View {
23+ AccountForm(curator: desk.curator, server: $server)
24+ }
25+ }
26+
27+ struct AccountForm: View {
28+ @ObservedObject var curator: CuratorModel
29+ @Binding var server: String
30+
31+ var body: some View {
32+ Form {
33+ Section {
34+ if let me = curator.me {
35+ LabeledContent("Signed in as", value: me.isCurator ? "Curator" : "Moderator · \(me.name)")
36+ LabeledContent("Candidates", value: curator.canSeeCandidates ? "Can see" : "Hidden")
37+ Button("Sign out", role: .destructive) { curator.signOut() }
38+ } else {
39+ PasskeySignIn(curator: curator)
40+ }
41+ } header: { Text("Sign in") } footer: { Text("Curators and moderators sign in with a passkey. Your sign-in is kept in your Mac's Keychain, never in a file or sent to an agent.") }
42+ if curator.me != nil {
43+ Section {
44+ PasskeyList(curator: curator)
45+ } header: { Text("Passkeys") } footer: { Text("Add a second passkey, on another device or a security key, so you can always get back in. The last one can't be removed.") }
46+ }
47+ Section {
48+ TextField("Server", text: $server, prompt: Text(APIClient.productionBase.absoluteString))
49+ } header: { Text("Server") } footer: { Text("Leave empty for Jobley. Restart the app after changing it.") }
50+ }
51+ .formStyle(.grouped)
52+ }
53+ }
54+
55+ /// "Let agents make changes" and the log of what agents changed (the house MCP pattern).
56+ struct AgentSettingsTab: View {
57+ @AppStorage(AgentSettings.allowWritesKey) private var allowWrites = false
58+ @State private var log: [AgentLogEntry] = []
59+
60+ var command: String { (Bundle.main.executablePath ?? "/Applications/Jobley.app/Contents/MacOS/Jobley") + " --mcp" }
61+
62+ var body: some View {
63+ Form {
64+ Section {
65+ Toggle("Let agents make changes", isOn: $allowWrites)
66+ } footer: {
67+ Text("Agents can read the board and the review queue. With this on they can also tidy a post's wording and leave notes. They can never publish, send back or unpublish a post, and never see candidates.")
68+ }
69+ Section("Connect an agent") {
70+ Text(command).font(Theme.mono(11)).textSelection(.enabled)
71+ Button("Copy command") { Clipboard.copy(command) }
72+ Link("How to set it up", destination: URL(string: "https://jobley.ai/mcp/")!)
73+ }
74+ Section("What agents changed") {
75+ if log.isEmpty { Text("Nothing yet.").foregroundStyle(.secondary) }
76+ ForEach(log.prefix(50)) { entry in
77+ VStack(alignment: .leading, spacing: 2) {
78+ Text(entry.summary).font(.callout)
79+ Text("\(entry.agent) · \(entry.tool) · \(entry.at.formatted(date: .abbreviated, time: .shortened))").font(.caption).foregroundStyle(.secondary)
80+ }
81+ }
82+ }
83+ }
84+ .formStyle(.grouped)
85+ .onAppear { log = AgentLog.entries() }
86+ }
87+ }
88+
89+ struct AboutSettings: View {
90+ @ObservedObject var updates: AppUpdates
91+
92+ var body: some View {
93+ Form {
94+ Section("About") {
95+ LabeledContent("Version", value: "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? ""))")
96+ Link("Source code (public domain, Unlicense)", destination: AppLinks.source)
97+ if updates.isAvailable { CheckForUpdatesButton(updates: updates) }
98+ }
99+ }
100+ .formStyle(.grouped)
101+ }
102+ }

Apps/Mac/PeopleViews.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ /// Candidates: per job or "any job", oldest first. People mark them reviewed or declined and make
6+ /// introductions themselves. There is no score, rank or match anywhere.
7+ struct CandidateList: View {
8+ @ObservedObject var desk: DeskModel
9+ @ObservedObject var model: CandidatesModel
10+ let jobs: [Job]
11+
12+ var body: some View {
13+ VStack(spacing: 0) {
14+ HStack {
15+ Picker("Who", selection: $model.scope) {
16+ Text("Everyone").tag(CandidatesModel.Scope.everyone)
17+ Text("Any job (asked about a kind of job)").tag(CandidatesModel.Scope.anyJob)
18+ if !jobs.isEmpty { Divider() }
19+ ForEach(jobs) { Text("\($0.title) · \($0.company)").tag(CandidatesModel.Scope.job($0.id)) }
20+ }
21+ Picker("Status", selection: $model.status) {
22+ Text("Any status").tag("")
23+ ForEach(["new", "reviewed", "introduced", "declined", "withdrawn"], id: \.self) { Text($0.capitalized).tag($0) }
24+ }
25+ .frame(width: 150)
26+ }
27+ .labelsHidden()
28+ .padding(10)
29+ if model.candidates.isEmpty {
30+ StateMessage("No one here yet", detail: "When someone asks to be put forward they appear here, oldest first.", systemImage: "person.2")
31+ } else {
32+ List(model.candidates, selection: $desk.selectedCandidateID) { person in
33+ VStack(alignment: .leading, spacing: 4) {
34+ HStack {
35+ Text(person.name).font(.headline)
36+ Spacer()
37+ StatusPill(person.status)
38+ }
39+ Text(person.headline).font(.subheadline).foregroundStyle(Theme.ink2)
40+ Text(person.jobID.flatMap { id in jobs.first { $0.id == id }?.title } ?? (person.jobID == nil ? "Any job" : "A job no longer on the board"))
41+ .font(.caption).foregroundStyle(Theme.muted)
42+ Text("Asked \(APIDate.short(person.createdAt))").font(.caption2).foregroundStyle(Theme.muted)
43+ }
44+ .padding(.vertical, 4)
45+ .tag(person.id)
46+ }
47+ }
48+ }
49+ .navigationTitle("Candidates")
50+ .navigationSubtitle("Oldest first")
51+ .onChange(of: model.scope) { Task { await model.reload() } }
52+ .onChange(of: model.status) { Task { await model.reload() } }
53+ .onChange(of: desk.selectedCandidateID) { Task { await model.open(desk.selectedCandidateID) } }
54+ .alert("Something went wrong", isPresented: Binding(get: { model.error != nil }, set: { if !$0 { model.error = nil } })) {
55+ Button("OK") { model.error = nil }
56+ } message: { Text(model.error ?? "") }
57+ }
58+ }
59+
60+ struct CandidateDetailView: View {
61+ @ObservedObject var model: CandidatesModel
62+ let detail: CandidateDetail
63+ let jobs: [Job]
64+ @ObservedObject var curator: CuratorModel
65+ @State private var introducing = false
66+
67+ var person: Candidate { detail.candidate }
68+
69+ var body: some View {
70+ ScrollView {
71+ VStack(alignment: .leading, spacing: 18) {
72+ HStack {
73+ StatusPill(person.status)
74+ Text("Asked \(APIDate.full(person.createdAt))").font(.caption).foregroundStyle(Theme.muted)
75+ }
76+ Text(person.name).font(Theme.display(28))
77+ Text(person.headline).font(.title3).foregroundStyle(Theme.ink2)
78+ HStack(spacing: 10) {
79+ Button { introducing = true } label: { Label("Introduce", systemImage: "envelope.badge.person.crop") }
80+ .buttonStyle(PrimaryButtonStyle()).disabled(jobs.isEmpty)
81+ Button("Mark reviewed") { Task { await model.setStatus(person, "reviewed") } }.buttonStyle(SecondaryButtonStyle())
82+ Button("Decline") { Task { await model.setStatus(person, "declined") } }.buttonStyle(SecondaryButtonStyle())
83+ }
84+ GroupBox {
85+ VStack(alignment: .leading, spacing: 6) {
86+ Text(person.email).textSelection(.enabled)
87+ if let location = person.location { Text(location).foregroundStyle(Theme.ink2) }
88+ }.frame(maxWidth: .infinity, alignment: .leading)
89+ } label: { Label("Private", systemImage: "lock").font(.caption.weight(.semibold)).foregroundStyle(Theme.muted) }
90+ if let looking = person.lookingFor { section("Looking for", looking) }
91+ if let about = person.about { section("About their work", about) }
92+ if !person.links.isEmpty || person.resumeURL != nil {
93+ VStack(alignment: .leading, spacing: 6) {
94+ Text("Links").font(Theme.display(18))
95+ ForEach(person.links, id: \.self) { link in if let url = URL(string: link) { Link(link, destination: url) } }
96+ if let resume = person.resumeURL, let url = URL(string: resume) { Link("Resume", destination: url) }
97+ }
98+ }
99+ if !detail.introductions.isEmpty {
100+ VStack(alignment: .leading, spacing: 6) {
101+ Text("Introductions").font(Theme.display(18))
102+ ForEach(detail.introductions) { intro in
103+ Text("\(jobs.first { $0.id == intro.jobID }?.title ?? intro.jobID) · by \(intro.introducedBy) · \(APIDate.short(intro.createdAt))")
104+ .font(.callout)
105+ }
106+ }
107+ }
108+ }
109+ .padding(28)
110+ .frame(maxWidth: 760, alignment: .leading)
111+ .frame(maxWidth: .infinity, alignment: .leading)
112+ }
113+ .background(Theme.background)
114+ .sheet(isPresented: $introducing) { IntroduceSheet(model: model, person: person, jobs: jobs, curator: curator) }
115+ }
116+
117+ func section(_ title: String, _ text: String) -> some View {
118+ VStack(alignment: .leading, spacing: 6) {
119+ Text(title).font(Theme.display(18))
120+ Text(text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
121+ }
122+ }
123+ }
124+
125+ /// A person writes the introduction: pick the job, write the note, send the mail draft to both
126+ /// sides from Mail, then record that it happened.
127+ struct IntroduceSheet: View {
128+ @ObservedObject var model: CandidatesModel
129+ let person: Candidate
130+ let jobs: [Job]
131+ @ObservedObject var curator: CuratorModel
132+ @State private var jobID = ""
133+ @State private var note = ""
134+ @State private var drafted = false
135+ @Environment(\.dismiss) private var dismiss
136+ @Environment(\.openURL) private var openURL
137+
138+ var body: some View {
139+ VStack(alignment: .leading, spacing: 14) {
140+ Text("Introduce \(person.name)").font(Theme.display(22))
141+ Picker("Job", selection: $jobID) {
142+ Text("Choose a job…").tag("")
143+ ForEach(jobs) { Text("\($0.title) · \($0.company)").tag($0.id) }
144+ }
145+ Text("A few words for both of them").font(.callout).foregroundStyle(Theme.ink2)
146+ TextEditor(text: $note).frame(minHeight: 120).scrollContentBackground(.hidden)
147+ .padding(6).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8))
148+ Text("First open the mail draft and send it from Mail. Then record the introduction here.")
149+ .font(.caption).foregroundStyle(Theme.muted)
150+ HStack {
151+ Button("Cancel") { dismiss() }
152+ Spacer()
153+ Button("Open mail draft") {
154+ Task {
155+ // The poster's contact is on the admin copy of the job.
156+ guard let item = try? await curator.api.reviewItem(jobID),
157+ let mail = MailDraft.introduction(candidate: person, job: item.job, note: note) else { return }
158+ openURL(mail); drafted = true
159+ }
160+ }
161+ .disabled(jobID.isEmpty)
162+ Button("Record introduction") {
163+ Task { if await model.introduce(person, jobID: jobID, note: note) { dismiss() } }
164+ }
165+ .buttonStyle(PrimaryButtonStyle())
166+ .disabled(jobID.isEmpty || !drafted)
167+ }
168+ }
169+ .padding(22)
170+ .frame(width: 520)
171+ .onAppear { jobID = person.jobID.flatMap { id in jobs.contains { $0.id == id } ? id : nil } ?? "" }
172+ }
173+ }
174+
175+ /// Moderator applications and moderators (curator only).
176+ struct ModeratorsView: View {
177+ @ObservedObject var model: ModeratorsModel
178+ @State private var grantCandidates: Set<String> = []
179+
180+ var body: some View {
181+ List {
182+ Section("Applications") {
183+ if model.applications.isEmpty { Text("No new applications.").foregroundStyle(.secondary) }
184+ ForEach(model.applications) { app in
185+ VStack(alignment: .leading, spacing: 6) {
186+ HStack {
187+ Text(app.name).font(.headline)
188+ Text(app.email).foregroundStyle(.secondary).textSelection(.enabled)
189+ Spacer()
190+ Text(APIDate.short(app.createdAt)).font(.caption).foregroundStyle(.secondary)
191+ }
192+ if let hours = app.hoursPerWeek { Text("\(hours) hours a week\(app.timezone.map { " · \($0)" } ?? "")").font(.caption) }
193+ Text(app.why).font(.callout).fixedSize(horizontal: false, vertical: true)
194+ if let experience = app.experience { Text(experience).font(.caption).foregroundStyle(Theme.ink2) }
195+ HStack {
196+ Toggle("Can see candidates", isOn: Binding(get: { grantCandidates.contains(app.id) },
197+ set: { if $0 { grantCandidates.insert(app.id) } else { grantCandidates.remove(app.id) } }))
198+ Spacer()
199+ Button("Decline") { Task { await model.decline(app) } }
200+ Button("Approve") { Task { await model.approve(app, canSeeCandidates: grantCandidates.contains(app.id)) } }
201+ .buttonStyle(.borderedProminent)
202+ }
203+ }
204+ .padding(.vertical, 6)
205+ }
206+ }
207+ Section("Moderators") {
208+ if model.moderators.isEmpty { Text("No moderators yet.").foregroundStyle(.secondary) }
209+ ForEach(model.moderators) { moderator in
210+ HStack {
211+ VStack(alignment: .leading) {
212+ Text(moderator.name).font(.headline)
213+ Text(moderator.email).font(.caption).foregroundStyle(.secondary)
214+ Text(moderator.lastSeenAt.map { "Last seen \(APIDate.short($0))" } ?? "Not seen yet").font(.caption2).foregroundStyle(.secondary)
215+ }
216+ Spacer()
217+ if moderator.active {
218+ Toggle("Candidates", isOn: Binding(get: { moderator.canSeeCandidates }, set: { value in Task { await model.setAccess(moderator, value) } }))
219+ Button("Setup link") { Task { await model.makeSetupLink(moderator) } }
220+ .help("A new one-time link to add a passkey, for a moderator setting up or one who lost theirs")
221+ Button("Revoke", role: .destructive) { Task { await model.revoke(moderator) } }
222+ } else {
223+ Text("Revoked").foregroundStyle(.secondary)
224+ }
225+ }
226+ }
227+ }
228+ }
229+ .navigationTitle("Moderators")
230+ .task { await model.reload() }
231+ .sheet(item: $model.newSetupLink) { made in
232+ VStack(alignment: .leading, spacing: 14) {
233+ Text("A passkey setup link for \(made.name)").font(Theme.display(22))
234+ Text("Send it to them yourself. They open Jobley, choose Add a passkey and paste it. It works once, until \(APIDate.full(made.link.expiresAt)), and we show it only now.")
235+ .foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)
236+ Text(made.link.url).font(Theme.mono(12)).textSelection(.enabled).padding(10)
237+ .background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8))
238+ HStack {
239+ Button("Copy") { Clipboard.copy(made.link.url) }
240+ Spacer()
241+ Button("Done") { model.newSetupLink = nil }.buttonStyle(PrimaryButtonStyle())
242+ }
243+ }
244+ .padding(22).frame(width: 480)
245+ }
246+ }
247+ }

Apps/Mac/Snapshot.swift added

1+ #if DEBUG
2+ import AppKit
3+
4+ /// Debug-only proof capture that works while the Mac is locked: draws the real desk window (or the
5+ /// sheet in front of it) into a PNG. `JOBLEY_SNAPSHOT=/path/shot.png` captures once the window has
6+ /// loaded, then quits. The glass sidebar is drawn by the window server, so it needs a live capture.
7+ @MainActor
8+ enum Snapshot {
9+ static func runIfRequested() {
10+ guard let path = ProcessInfo.processInfo.environment["JOBLEY_SNAPSHOT"] else { return }
11+ let delay = Double(ProcessInfo.processInfo.environment["JOBLEY_SNAPSHOT_DELAY"] ?? "") ?? 5
12+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
13+ let main = NSApp.windows.first { $0.isVisible && $0.contentView != nil && $0.sheetParent == nil }
14+ let window = main?.sheets.first ?? main
15+ guard let window, let view = window.contentView?.superview ?? window.contentView,
16+ let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { exit(2) }
17+ view.cacheDisplay(in: view.bounds, to: rep)
18+ try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path))
19+ exit(0)
20+ }
21+ }
22+ }
23+ #endif

Apps/Mac/Updates.swift added

1+ import Combine
2+ import Sparkle
3+ import SwiftUI
4+
5+ /// Sparkle updates for the Mac build downloaded from the Jobley site.
6+ /// Debug builds and builds without a feed or signing key leave the updater off.
7+ @MainActor
8+ final class AppUpdates: ObservableObject {
9+ @Published private(set) var canCheck = false
10+ private let controller: SPUStandardUpdaterController?
11+
12+ init() {
13+ #if DEBUG
14+ controller = nil
15+ #else
16+ guard Self.configured("SUFeedURL"), Self.configured("SUPublicEDKey") else {
17+ controller = nil
18+ return
19+ }
20+ let controller = SPUStandardUpdaterController(startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil)
21+ self.controller = controller
22+ controller.updater.publisher(for: \.canCheckForUpdates).assign(to: &$canCheck)
23+ #endif
24+ }
25+
26+ var isAvailable: Bool { controller != nil }
27+
28+ func check() { controller?.checkForUpdates(nil) }
29+
30+ private static func configured(_ key: String) -> Bool {
31+ !((Bundle.main.object(forInfoDictionaryKey: key) as? String) ?? "").isEmpty
32+ }
33+ }
34+
35+ struct CheckForUpdatesButton: View {
36+ @ObservedObject var updates: AppUpdates
37+
38+ var body: some View {
39+ Button("Check for Updates…") { updates.check() }
40+ .disabled(!updates.canCheck)
41+ }
42+ }

Apps/Mac/installer-background.tiff added

Not a text file.

Apps/iPhone/Assets.xcassets/AccentColor.colorset/Contents.json added

1+ { "colors": [
2+ { "idiom": "universal", "color": { "color-space": "srgb", "components": { "red": "0x17", "green": "0x60", "blue": "0x3F", "alpha": "1.000" } } },
3+ { "idiom": "universal", "appearances": [ { "appearance": "luminosity", "value": "dark" } ], "color": { "color-space": "srgb", "components": { "red": "0x7F", "green": "0xD6", "blue": "0xA6", "alpha": "1.000" } } }
4+ ], "info": { "author": "xcode", "version": 1 } }

Apps/iPhone/Assets.xcassets/AppIcon.appiconset/Contents.json added

1+ { "images": [ { "idiom": "universal", "platform": "ios", "size": "1024x1024", "filename": "icon-1024.png" } ], "info": { "author": "xcode", "version": 1 } }

Apps/iPhone/Assets.xcassets/AppIcon.appiconset/icon-1024.png added

Not a text file.

Apps/iPhone/Assets.xcassets/Contents.json added

1+ { "info": { "author": "xcode", "version": 1 } }

Apps/iPhone/Info.plist added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>CFBundleDevelopmentRegion</key>
6+ <string>$(DEVELOPMENT_LANGUAGE)</string>
7+ <key>CFBundleDisplayName</key>
8+ <string>Jobley</string>
9+ <key>CFBundleExecutable</key>
10+ <string>$(EXECUTABLE_NAME)</string>
11+ <key>CFBundleIdentifier</key>
12+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13+ <key>CFBundleInfoDictionaryVersion</key>
14+ <string>6.0</string>
15+ <key>CFBundleName</key>
16+ <string>$(PRODUCT_NAME)</string>
17+ <key>CFBundlePackageType</key>
18+ <string>APPL</string>
19+ <key>CFBundleShortVersionString</key>
20+ <string>$(MARKETING_VERSION)</string>
21+ <key>CFBundleVersion</key>
22+ <string>$(CURRENT_PROJECT_VERSION)</string>
23+ <key>ITSAppUsesNonExemptEncryption</key>
24+ <false/>
25+ <key>LSApplicationCategoryType</key>
26+ <string>public.app-category.business</string>
27+ <key>NSAppTransportSecurity</key>
28+ <dict>
29+ <key>NSAllowsLocalNetworking</key>
30+ <true/>
31+ </dict>
32+ <key>UILaunchScreen</key>
33+ <dict/>
34+ <key>UISupportedInterfaceOrientations</key>
35+ <array>
36+ <string>UIInterfaceOrientationPortrait</string>
37+ </array>
38+ <key>UISupportedInterfaceOrientations~ipad</key>
39+ <array>
40+ <string>UIInterfaceOrientationPortrait</string>
41+ <string>UIInterfaceOrientationPortraitUpsideDown</string>
42+ <string>UIInterfaceOrientationLandscapeLeft</string>
43+ <string>UIInterfaceOrientationLandscapeRight</string>
44+ </array>
45+ </dict>
46+ </plist>

Apps/iPhone/JobleyPhone.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0">
4+ <dict>
5+ <key>com.apple.developer.associated-domains</key>
6+ <array>
7+ <string>webcredentials:jobley.ai</string>
8+ </array>
9+ </dict>
10+ </plist>

Apps/iPhone/PhoneApp.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ @main
6+ struct JobleyPhoneApp: App {
7+ @StateObject private var app = PhoneModel()
8+
9+ var body: some Scene {
10+ WindowGroup {
11+ PhoneRoot(app: app, curator: app.curator, board: app.board)
12+ .tint(Theme.accent)
13+ }
14+ }
15+ }
16+
17+ /// Everyone gets the board, saved jobs, "Put me forward" and "Post a job". Curators and moderators
18+ /// sign in with a passkey in Settings to get the Review tab: the same queue as the Mac desk.
19+ @MainActor
20+ final class PhoneModel: ObservableObject {
21+ enum Tab: String { case jobs, saved, post, review, settings }
22+
23+ let board: BoardModel
24+ let curator: CuratorModel
25+ let saved = SavedJobs()
26+ @Published var tab: Tab = .jobs
27+
28+ init() {
29+ board = BoardModel(api: APIClient(client: .iphone))
30+ curator = CuratorModel(api: APIClient(client: .iphone, token: TokenStore.load()))
31+ #if DEBUG
32+ if let start = ProcessInfo.processInfo.environment["JOBLEY_TAB"], let tab = Tab(rawValue: start) { self.tab = tab }
33+ #endif
34+ }
35+ }
36+
37+ struct PhoneRoot: View {
38+ @ObservedObject var app: PhoneModel
39+ @ObservedObject var curator: CuratorModel
40+ @ObservedObject var board: BoardModel
41+
42+ var body: some View {
43+ TabView(selection: $app.tab) {
44+ Tab("Jobs", systemImage: "list.bullet.rectangle", value: PhoneModel.Tab.jobs) {
45+ NavigationStack { BoardScreen(board: board, saved: app.saved) }
46+ }
47+ Tab("Saved", systemImage: "bookmark", value: PhoneModel.Tab.saved) {
48+ NavigationStack { SavedScreen(board: board, saved: app.saved) }
49+ }
50+ Tab("Post", systemImage: "square.and.pencil", value: PhoneModel.Tab.post) {
51+ NavigationStack { PostJobForm(api: board.api) { app.tab = .jobs }.navigationTitle("Post a job") }
52+ }
53+ if curator.isSignedIn {
54+ Tab("Review", systemImage: "tray.full", value: PhoneModel.Tab.review) {
55+ NavigationStack { ReviewScreen(curator: curator, labels: board.labels) }
56+ }
57+ .badge(curator.stats?.jobs(.pending) ?? 0)
58+ }
59+ Tab("Settings", systemImage: "gearshape", value: PhoneModel.Tab.settings) {
60+ NavigationStack { PhoneSettings(curator: curator) }
61+ }
62+ }
63+ .task {
64+ await board.loadMeta()
65+ await board.reload()
66+ await curator.start()
67+ }
68+ }
69+ }
70+
71+ struct BoardScreen: View {
72+ @ObservedObject var board: BoardModel
73+ @ObservedObject var saved: SavedJobs
74+
75+ var body: some View {
76+ List {
77+ Section {
78+ ScrollView(.horizontal, showsIndicators: false) { BoardFilters(board: board) }
79+ .listRowInsets(EdgeInsets(top: 4, leading: 16, bottom: 4, trailing: 16))
80+ .listRowBackground(Color.clear)
81+ }
82+ if let error = board.error, board.jobs.isEmpty {
83+ StateMessage("Couldn't load the board", detail: error, systemImage: "wifi.slash") { Task { await board.reload() } }
84+ .listRowBackground(Color.clear)
85+ } else if board.jobs.isEmpty && !board.loading {
86+ StateMessage(board.hasFilters ? "Nothing matches" : "No jobs yet",
87+ detail: board.hasFilters ? "Try fewer filters." : "Every job here is read by a person first. Check back soon.",
88+ systemImage: "magnifyingglass")
89+ .listRowBackground(Color.clear)
90+ } else {
91+ Section {
92+ ForEach(board.jobs) { job in
93+ NavigationLink(value: job) { JobRow(job: job, labels: board.labels, saved: saved.contains(job)) }
94+ }
95+ if board.nextCursor != nil {
96+ Button("Load more") { Task { await board.loadMore() } }.frame(maxWidth: .infinity)
97+ }
98+ } header: {
99+ Text("\(board.jobs.count) on the board · newest first").font(Theme.mono(11))
100+ }
101+ }
102+ }
103+ .listStyle(.insetGrouped)
104+ .scrollContentBackground(.hidden)
105+ .background(Theme.background)
106+ .navigationTitle("Good jobs")
107+ .searchable(text: $board.query, prompt: "Title, company or place")
108+ .onSubmit(of: .search) { Task { await board.reload() } }
109+ .onChange(of: board.query) { if board.query.isEmpty { Task { await board.reload() } } }
110+ .refreshable { await board.reload() }
111+ .navigationDestination(for: Job.self) { JobScreen(job: $0, board: board, saved: saved) }
112+ .overlay { if board.loading && board.jobs.isEmpty { ProgressView() } }
113+ #if DEBUG
114+ .task {
115+ // Screenshot hooks: open the first job, or its "Put me forward" form.
116+ guard let mode = ProcessInfo.processInfo.environment["JOBLEY_OPEN"] else { return }
117+ while board.jobs.isEmpty { try? await Task.sleep(for: .milliseconds(200)) }
118+ DebugOpen.shared.mode = mode
119+ debugJob = board.jobs.first
120+ }
121+ .navigationDestination(item: $debugJob) { JobScreen(job: $0, board: board, saved: saved) }
122+ #endif
123+ }
124+
125+ #if DEBUG
126+ @State private var debugJob: Job?
127+ #endif
128+ }
129+
130+ #if DEBUG
131+ @MainActor
132+ final class DebugOpen {
133+ static let shared = DebugOpen()
134+ var mode = ""
135+ }
136+ #endif
137+
138+ struct JobScreen: View {
139+ let job: Job
140+ @ObservedObject var board: BoardModel
141+ @ObservedObject var saved: SavedJobs
142+ @State private var puttingForward = false
143+
144+ var body: some View {
145+ ScrollView {
146+ VStack(alignment: .leading, spacing: 20) {
147+ JobBody(job: job, labels: board.labels)
148+ }
149+ .padding(20)
150+ }
151+ .background(Theme.background)
152+ .safeAreaInset(edge: .bottom) {
153+ HStack(spacing: 12) {
154+ Button { saved.toggle(job) } label: {
155+ Label(saved.contains(job) ? "Saved" : "Save", systemImage: saved.contains(job) ? "bookmark.fill" : "bookmark")
156+ }
157+ .buttonStyle(SecondaryButtonStyle())
158+ Button { puttingForward = true } label: { Text("Put me forward").frame(maxWidth: .infinity) }
159+ .buttonStyle(PrimaryButtonStyle())
160+ .accessibilityIdentifier("putMeForward")
161+ }
162+ .padding(.horizontal, 20).padding(.vertical, 12)
163+ .background(.bar)
164+ }
165+ .toolbar { ShareLink(item: URL(string: job.url) ?? AppLinks.website) }
166+ .navigationBarTitleDisplayMode(.inline)
167+ .sheet(isPresented: $puttingForward) {
168+ NavigationStack {
169+ PutMeForwardForm(api: board.api, job: job) { puttingForward = false }
170+ .navigationTitle("Put me forward")
171+ .navigationBarTitleDisplayMode(.inline)
172+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { puttingForward = false } } }
173+ }
174+ }
175+ #if DEBUG
176+ .onAppear { if DebugOpen.shared.mode == "forward" { DebugOpen.shared.mode = ""; puttingForward = true } }
177+ #endif
178+ }
179+ }
180+
181+ struct SavedScreen: View {
182+ @ObservedObject var board: BoardModel
183+ @ObservedObject var saved: SavedJobs
184+ @State private var askingAnyJob = false
185+
186+ var body: some View {
187+ List {
188+ if saved.jobs.isEmpty {
189+ StateMessage("Nothing saved", detail: "Tap Save on a job to keep it here, on this iPhone.", systemImage: "bookmark")
190+ .listRowBackground(Color.clear)
191+ }
192+ ForEach(saved.jobs) { job in
193+ NavigationLink(value: job) { JobRow(job: job, labels: board.labels, saved: true) }
194+ }
195+ Section {
196+ Button { askingAnyJob = true } label: { Label("Put me forward for a kind of job", systemImage: "person.crop.circle.badge.plus") }
197+ } footer: {
198+ Text("Tell us what you're looking for. When a good job fits, a person introduces you.")
199+ }
200+ }
201+ .scrollContentBackground(.hidden)
202+ .background(Theme.background)
203+ .navigationTitle("Saved")
204+ .navigationDestination(for: Job.self) { JobScreen(job: $0, board: board, saved: saved) }
205+ .sheet(isPresented: $askingAnyJob) {
206+ NavigationStack {
207+ PutMeForwardForm(api: board.api, job: nil) { askingAnyJob = false }
208+ .navigationTitle("Put me forward")
209+ .navigationBarTitleDisplayMode(.inline)
210+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { askingAnyJob = false } } }
211+ }
212+ }
213+ }
214+ }
215+
216+ /// The same review queue as the Mac desk, to decide on the go.
217+ struct ReviewScreen: View {
218+ @ObservedObject var curator: CuratorModel
219+ let labels: Labels
220+ @State private var queue: CuratorModel.Queue = .pending
221+
222+ var body: some View {
223+ List {
224+ Picker("Queue", selection: $queue) {
225+ Text("Waiting").tag(CuratorModel.Queue.pending)
226+ Text("Approved").tag(CuratorModel.Queue.approved)
227+ Text("Published").tag(CuratorModel.Queue.published)
228+ Text("Sent back").tag(CuratorModel.Queue.rejected)
229+ }
230+ .pickerStyle(.segmented)
231+ .listRowBackground(Color.clear)
232+ let jobs = curator.jobs(queue)
233+ if jobs.isEmpty {
234+ StateMessage("Nothing here", detail: queue == .pending ? "Every post has been read." : "Posts move here as people decide.", systemImage: queue.systemImage)
235+ .listRowBackground(Color.clear)
236+ }
237+ Section {
238+ ForEach(jobs) { job in
239+ NavigationLink(value: job.id) { JobRow(job: job, labels: labels, showStatus: queue != .pending) }
240+ }
241+ } footer: {
242+ if queue == .pending && !jobs.isEmpty { Text("Oldest first. A person reads every one.") }
243+ }
244+ }
245+ .scrollContentBackground(.hidden)
246+ .background(Theme.background)
247+ .navigationTitle("Review")
248+ .refreshable { await curator.refreshAll() }
249+ .navigationDestination(for: String.self) { id in ReviewItemScreen(curator: curator, id: id, labels: labels) }
250+ #if DEBUG
251+ .task {
252+ guard ProcessInfo.processInfo.environment["JOBLEY_OPEN"] == "review" else { return }
253+ while curator.jobs(.pending).isEmpty { try? await Task.sleep(for: .milliseconds(200)) }
254+ reviewDebugID = curator.jobs(.pending).first?.id
255+ }
256+ .navigationDestination(item: $reviewDebugID) { id in ReviewItemScreen(curator: curator, id: id, labels: labels) }
257+ #endif
258+ }
259+
260+ #if DEBUG
261+ @State private var reviewDebugID: String?
262+ #endif
263+ }
264+
265+ struct ReviewItemScreen: View {
266+ @ObservedObject var curator: CuratorModel
267+ let id: String
268+ let labels: Labels
269+
270+ var body: some View {
271+ Group {
272+ if let item = curator.item, item.job.id == id {
273+ ReviewDetail(model: curator, item: item, labels: labels, allowsEdit: false)
274+ } else {
275+ ProgressView()
276+ }
277+ }
278+ .navigationBarTitleDisplayMode(.inline)
279+ .task { await curator.open(id) }
280+ }
281+ }

Apps/iPhone/PhoneSettings.swift added

1+ import SwiftUI
2+ import JobleyKit
3+ import JobleyUI
4+
5+ struct PhoneSettings: View {
6+ @ObservedObject var curator: CuratorModel
7+
8+ var body: some View {
9+ Form {
10+ Section {
11+ if let me = curator.me {
12+ LabeledContent("Signed in as", value: me.isCurator ? "Curator" : "Moderator · \(me.name)")
13+ Button("Sign out", role: .destructive) { curator.signOut() }
14+ } else {
15+ PasskeySignIn(curator: curator).padding(.vertical, 4)
16+ }
17+ } header: {
18+ Text("Curators and moderators")
19+ } footer: {
20+ Text("Sign in with your passkey to add the Review tab. Moderators get a one-time setup link when their application is approved.")
21+ }
22+ if curator.me != nil {
23+ Section {
24+ PasskeyList(curator: curator)
25+ } header: {
26+ Text("Passkeys")
27+ } footer: {
28+ Text("Add a second passkey so you can always get back in. The last one can't be removed.")
29+ }
30+ }
31+ Section("About") {
32+ LabeledContent("Version", value: "\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? ""))")
33+ Link("Source code (public domain, Unlicense)", destination: AppLinks.source)
34+ Link("Privacy", destination: URL(string: "https://jobley.ai/privacy/")!)
35+ Link("What counts as a good job", destination: URL(string: "https://jobley.ai/help/#rules")!)
36+ }
37+ }
38+ .navigationTitle("Settings")
39+ }
40+ }

LICENSE added

1+ This is free and unencumbered software released into the public domain.
2+
3+ Anyone is free to copy, modify, publish, use, compile, sell, or
4+ distribute this software, either in source code form or as a compiled
5+ binary, for any purpose, commercial or non-commercial, and by any
6+ means.
7+
8+ In jurisdictions that recognize copyright laws, the author or authors
9+ of this software dedicate any and all copyright interest in the
10+ software to the public domain. We make this dedication for the benefit
11+ of the public at large and to the detriment of our heirs and
12+ successors. We intend this dedication to be an overt act of
13+ relinquishment in perpetuity of all present and future rights to this
14+ software under copyright law.
15+
16+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22+ OTHER DEALINGS IN THE SOFTWARE.
23+
24+ For more information, please refer to <https://unlicense.org>

Package.swift added

1+ // swift-tools-version: 6.0
2+ // Jobley: a curated job board. The Mac app is the curator's desk; the iPhone app is the board
3+ // for everyone plus the same review queue for curators and moderators. Both talk to the Jobley API.
4+ import PackageDescription
5+
6+ let package = Package(
7+ name: "Jobley",
8+ platforms: [.macOS(.v15), .iOS(.v18)],
9+ products: [
10+ .library(name: "JobleyKit", targets: ["JobleyKit"]),
11+ .library(name: "JobleyUI", targets: ["JobleyUI"])
12+ ],
13+ targets: [
14+ // Models, the API client, Keychain, agent settings, the MCP server and the support-prompt rules.
15+ .target(name: "JobleyKit"),
16+ // The Noticeboard theme, shared models for the board and the review queue, and shared views.
17+ .target(name: "JobleyUI", dependencies: ["JobleyKit"]),
18+ .testTarget(name: "JobleyKitTests", dependencies: ["JobleyKit"])
19+ ],
20+ swiftLanguageModes: [.v5]
21+ )

README.md added

1+ # Jobley
2+
3+ A curated job board. Anyone can post a job. We read every one and only publish good jobs. Then we bring qualified people to them.
4+
5+ This repository holds the two apps. The website and API live at [jobley.ai](https://jobley.ai/).
6+
7+ - **Mac: the curator's desk.** The review queue (oldest first), each post in full with the rules as a checklist a person ticks by hand, Publish, Send back with a reason (then a mail draft to the poster), Approve, Unpublish, Edit wording, notes and history. Candidates per job or for any job, introductions a person makes, moderator applications and moderators. The board as everyone sees it, and Post a job.
8+ - **iPhone and iPad.** Everyone: browse and search the board, save jobs on the device, Put me forward, Post a job. Curators and moderators sign in with a passkey in Settings to get the Review tab: the same queue, to decide on the go.
9+ - **MCP.** `Jobley.app/Contents/MacOS/Jobley --mcp` is a STDIO MCP server. Agents can read the board and the queue, read the rules, tidy a post's wording and leave notes, only after "Let agents make changes" is on, and every change is logged. Agents can never approve, send back, publish or unpublish a post, and never see candidates (the API also answers `403 people_only`).
10+
11+ People decide everything. Nothing in Jobley ranks, scores, filters or decides on a job or a person. Lists of people are oldest first.
12+
13+ Free and open source, public domain under [The Unlicense](LICENSE). No ads, no paid posts, no purchases. Help is free through the [feedback form](https://projectatom.ai/apps?app=jobley#feedback). A [Project ATOM](https://projectatom.ai/) project.
14+
15+ ## Build
16+
17+ ```sh
18+ brew install xcodegen
19+ xcodegen # creates Jobley.xcodeproj
20+ open Jobley.xcodeproj # schemes JobleyMac and JobleyPhone
21+ ```
22+
23+ Layout: `Sources/JobleyKit` (models, the API client, Keychain, the MCP server, the reminder rules), `Sources/JobleyUI` (the Noticeboard theme, shared models and views), `Apps/Mac`, `Apps/iPhone`.
24+
25+ ## Test
26+
27+ The tests run the API client against the real API code: jobley-site's dev server on a fresh database with five sample jobs from made-up companies.
28+
29+ ```sh
30+ SITE=../jobley-site scripts/test-api.sh
31+ ```
32+
33+ Point the apps at a local server with `JOBLEY_API_BASE=http://localhost:8788` (and `JOBLEY_TOKEN` for the dev server's curator session), or set Server in Settings.
34+
35+ ## Signing in: passkeys only
36+
37+ The curator and moderators sign in with a passkey (relying party `jobley.ai`, `webcredentials:jobley.ai` in both apps' entitlements, the association file served by jobley-site). No passwords, pasted tokens, email links or codes; recovery is a second passkey, added in Settings. A first passkey comes from a one-time setup link: the curator's from jobley-site's secret-guarded setup endpoint, a moderator's when the curator approves them (or Moderators → Setup link). Open Jobley, choose Add a passkey and paste the link. The session the sign-in returns stays in the Keychain, and the MCP server uses it.

RELEASING.md added

1+ # Releasing Jobley
2+
3+ Two pipelines, both scripted, both also runnable from GitHub Actions.
4+
5+ | What | Script | GitHub workflow | Where it lands |
6+ |---|---|---|---|
7+ | Mac app (direct download + auto-update) | `scripts/release-mac.sh <version> --notes "…" [--publish]` | **Mac release** (`mac-release.yml`, run manually) | `jobley.ai/downloads/Jobley-<version>.dmg` (R2 bucket `jobley-downloads`) and the Sparkle feed `jobley.ai/appcast.xml`, via `projectatomai/jobley-site` main → Cloudflare Pages |
8+ | iPhone app (TestFlight) | `scripts/release-ios.sh [--build N]` | **TestFlight** (`testflight.yml`, run manually) | App Store Connect app 6840041303, internal group "Jobley Internal" |
9+
10+ Every push to main also runs **Checks** (`checks.yml`): package tests plus unsigned Mac and iPhone builds.
11+
12+ App Store listing content (description, screenshots, review submission) is not part of this pipeline. Never
13+ submit for review from these scripts.
14+
15+ ## Mac release
16+
17+ 1. `scripts/release-mac.sh 0.1.1 --notes "What changed"` regenerates the Xcode project, archives `JobleyMac`,
18+ exports with Developer ID and the "Jobley Developer ID" profile, notarizes and staples the app, builds the
19+ house drag installer (`installer/`, artwork in `Apps/Mac/installer-background.tiff`), signs and notarizes the
20+ DMG, signs the update with Sparkle's EdDSA key and writes `appcast.xml`.
21+ 2. It copies the DMG to `../jobley-site/downloads/` (gitignored there), the feed to `../jobley-site/appcast.xml`,
22+ runs the site's `tools/set-release.sh` (download links, version, size, JSON-LD) and bumps the version and
23+ build in `project.yml`.
24+ 3. Without `--publish` it stops so you can review both repos. With `--publish` it uploads the DMG to the R2
25+ bucket `jobley-downloads`, commits and pushes jobley-site and this repo to main, then waits until jobley.ai
26+ serves the new feed and a byte-identical DMG.
27+
28+ Work files go to `/Volumes/Expand/Projects/Jobley/release/<version>-<build>/` (`JOBLEY_RELEASE_DIR` overrides,
29+ `JOBLEY_SITE_DIR` points at another site checkout).
30+
31+ Credentials on this Mac: the Developer ID certificate in the login Keychain, the Sparkle private key in the login
32+ Keychain (account `com.protomota.jobley`, made by Sparkle's `generate_keys`), and the notarization key from
33+ Bitwarden Secrets Manager (`APP_STORE_CONNECT_API_KEY`, `APP_STORE_CONNECT_KEY_ID`, `APP_STORE_CONNECT_ISSUER_ID`).
34+
35+ The app checks `https://jobley.ai/appcast.xml` (Sparkle 2, public key in `project.yml`). Debug builds never
36+ check. **Jobley → Check for Updates…** checks by hand.
37+
38+ ## TestFlight
39+
40+ `scripts/release-ios.sh` reads the version from `project.yml`, picks the next build number from App Store
41+ Connect, archives `JobleyPhone` with Apple Distribution and the "Jobley App Store" profile, uploads with
42+ `altool`, waits for processing and makes the build available to the internal group. Testers must accept the
43+ TestFlight invitation email before they get build notifications.
44+
45+ Credentials on this Mac: the Apple Distribution certificate in the login Keychain and the upload key from
46+ Secrets Manager (`INKSPRING_ASC_UPLOAD_KEY_ID`, `_ISSUER_ID`, `_PRIVATE_KEY`; override the prefix with
47+ `JOBLEY_ASC_SECRET_PREFIX`).
48+
49+ ## GitHub secrets
50+
51+ | Secret | Used by | Value |
52+ |---|---|---|
53+ | `APPLE_API_KEY`, `APPLE_API_KEY_ID`, `APPLE_API_ISSUER` | Mac release | Notarization key (.p8 text), key ID, issuer ID |
54+ | `JOBLEY_SPARKLE_EDDSA_PRIVATE_KEY` | Mac release | `generate_keys --account com.protomota.jobley -x key.txt` |
55+ | `SITE_REPO_TOKEN` | Mac release | Fine-grained token with Contents read/write on projectatomai/jobley-site |
56+ | `DEVELOPER_ID_P12_BASE64`, `DEVELOPER_ID_P12_PASSWORD` | Mac release | Developer ID Application certificate + key exported as .p12 |
57+ | `ASC_UPLOAD_KEY`, `ASC_UPLOAD_KEY_ID`, `ASC_UPLOAD_ISSUER` | TestFlight | App Store Connect upload key (Admin or App Manager) |
58+ | `DISTRIBUTION_P12_BASE64`, `DISTRIBUTION_P12_PASSWORD` | TestFlight | Apple Distribution certificate + key exported as .p12 |
59+
60+ The provisioning profiles are checked in under `signing/` (they hold no secrets) and the scripts install them.
61+
62+ ## Apple setup
63+
64+ - Bundle ID `com.protomota.jobley` (team 22HV69L32T, universal): registered 2026-11-27 through the App Store
65+ Connect API. Jobley keeps no data in iCloud, so there is no container.
66+ - App Store Connect app "Jobley: Curated Jobs" (SKU jobley, Apple ID 6840041303): created 2026-11-27.
67+ `scripts/asc.py app-id` finds its ID by bundle ID.
68+ - Profiles "Jobley Developer ID" (Mac, Developer ID, cert V3D25LB5M4) and "Jobley App Store" (iOS, Apple
69+ Distribution, cert WH27C9B5PQ) are in `signing/` (created 2026-11-27 through the App Store Connect API).

Sources/JobleyKit/APIClient.swift added

1+ import Foundation
2+
3+ /// Which app is calling. The API records it in the audit log, and refuses people-only actions
4+ /// (approve, reject, publish, unpublish, anything about candidates) from `mcp`.
5+ public enum ClientKind: String, Sendable {
6+ case mac, iphone, mcp
7+ }
8+
9+ /// Every error the API sends: `{ok:false, error, message, fields?, status?}`.
10+ public struct APIError: Error, LocalizedError, Equatable, Sendable {
11+ public var code: String
12+ public var message: String
13+ public var fields: [String: String]
14+ public var status: String?
15+ public var httpStatus: Int
16+
17+ public init(code: String, message: String, fields: [String: String] = [:], status: String? = nil, httpStatus: Int = 0) {
18+ self.code = code; self.message = message; self.fields = fields; self.status = status; self.httpStatus = httpStatus
19+ }
20+
21+ public var errorDescription: String? {
22+ if fields.isEmpty { return message }
23+ return message + " " + fields.sorted { $0.key < $1.key }.map(\.value).joined(separator: " ")
24+ }
25+
26+ public static let signedOut = APIError(code: "unauthorized", message: "Sign in with your passkey in Settings first.", httpStatus: 401)
27+ }
28+
29+ /// A job post from the "Post a job" form (`POST /api/jobs`).
30+ public struct JobDraft: Equatable, Sendable {
31+ public var title = "", company = "", companyURL = "", location = ""
32+ public var workplace = "", employmentType = "", category = ""
33+ public var payMin = "", payMax = "", payPeriod = "hour", payCurrency = "USD"
34+ public var description = "", applyURL = "", contactName = "", contactEmail = ""
35+
36+ public init() {}
37+
38+ func body(turnstileToken: String?) -> [String: Any] {
39+ var body: [String: Any] = [
40+ "title": title, "company": company, "location": location, "workplace": workplace,
41+ "employment_type": employmentType, "category": category, "pay_period": payPeriod,
42+ "pay_currency": payCurrency.uppercased(), "description": description,
43+ "contact_name": contactName, "contact_email": contactEmail,
44+ "pay_min": Int(payMin.filter(\.isNumber)) ?? payMin, "pay_max": Int(payMax.filter(\.isNumber)) ?? payMax
45+ ]
46+ if !companyURL.isEmpty { body["company_url"] = companyURL }
47+ if !applyURL.isEmpty { body["apply_url"] = applyURL }
48+ if let turnstileToken { body["turnstile_token"] = turnstileToken }
49+ return body
50+ }
51+ }
52+
53+ /// "Put me forward" (`POST /api/candidates`), for one job or for a kind of job.
54+ public struct CandidateDraft: Equatable, Sendable {
55+ public var jobID: String?
56+ public var name = "", email = "", headline = "", location = "", lookingFor = "", about = ""
57+ public var links = "", resumeURL = ""
58+ public var consent = false
59+
60+ public init(jobID: String? = nil) { self.jobID = jobID }
61+
62+ func body(turnstileToken: String?) -> [String: Any] {
63+ var body: [String: Any] = ["name": name, "email": email, "headline": headline, "consent": consent]
64+ if let jobID { body["job_id"] = jobID }
65+ if !location.isEmpty { body["location"] = location }
66+ if !lookingFor.isEmpty { body["looking_for"] = lookingFor }
67+ if !about.isEmpty { body["about"] = about }
68+ if !resumeURL.isEmpty { body["resume_url"] = resumeURL }
69+ let list = links.split(whereSeparator: { $0.isNewline || $0 == " " || $0 == "," }).map(String.init).filter { !$0.isEmpty }
70+ if !list.isEmpty { body["links"] = list }
71+ if let turnstileToken { body["turnstile_token"] = turnstileToken }
72+ return body
73+ }
74+ }
75+
76+ /// The fields an edit may change (`PATCH /api/admin/jobs/:id`). Contact and status never change here.
77+ public struct JobEdit: Equatable, Sendable {
78+ public var title: String, company: String, companyURL: String, location: String
79+ public var workplace: String, employmentType: String, category: String
80+ public var payMin: Int, payMax: Int, payPeriod: String, payCurrency: String
81+ public var description: String, applyURL: String
82+
83+ public init(_ job: Job) {
84+ title = job.title; company = job.company; companyURL = job.companyURL ?? ""; location = job.location
85+ workplace = job.workplace; employmentType = job.employmentType; category = job.category
86+ payMin = job.pay.min; payMax = job.pay.max; payPeriod = job.pay.period; payCurrency = job.pay.currency
87+ description = job.description; applyURL = job.applyURL ?? ""
88+ }
89+
90+ /// Only the fields that differ from the job, so the audit log shows what really changed.
91+ public func changes(from job: Job) -> [String: Any] {
92+ let before = JobEdit(job)
93+ var out: [String: Any] = [:]
94+ if title != before.title { out["title"] = title }
95+ if company != before.company { out["company"] = company }
96+ if companyURL != before.companyURL { out["company_url"] = companyURL }
97+ if location != before.location { out["location"] = location }
98+ if workplace != before.workplace { out["workplace"] = workplace }
99+ if employmentType != before.employmentType { out["employment_type"] = employmentType }
100+ if category != before.category { out["category"] = category }
101+ if payMin != before.payMin || payMax != before.payMax { out["pay_min"] = payMin; out["pay_max"] = payMax }
102+ if payPeriod != before.payPeriod { out["pay_period"] = payPeriod }
103+ if payCurrency != before.payCurrency { out["pay_currency"] = payCurrency }
104+ if description != before.description { out["description"] = description }
105+ if applyURL != before.applyURL { out["apply_url"] = applyURL }
106+ return out
107+ }
108+ }
109+
110+ /// The Jobley API (PRD section 7). Public calls need no token; admin calls send
111+ /// `Authorization: Bearer <session token from a passkey sign-in>` and `X-Client`.
112+ public struct APIClient: Sendable {
113+ public let base: URL
114+ public let client: ClientKind
115+ public let token: String?
116+ let session: URLSession
117+
118+ /// Production until jobley.ai is connected. `JOBLEY_API_BASE` (tests, local work) and the
119+ /// "Server" setting override it.
120+ public static let productionBase = URL(string: "https://jobley.ai")!
121+ public static let serverDefaultsKey = "jobley.server"
122+
123+ public static var configuredBase: URL {
124+ if let env = ProcessInfo.processInfo.environment["JOBLEY_API_BASE"], let url = URL(string: env) { return url }
125+ if let saved = UserDefaults.standard.string(forKey: serverDefaultsKey), let url = URL(string: saved), url.scheme != nil { return url }
126+ return productionBase
127+ }
128+
129+ public init(base: URL = APIClient.configuredBase, client: ClientKind, token: String? = nil, session: URLSession = .shared) {
130+ self.base = base; self.client = client; self.token = token?.trimmingCharacters(in: .whitespacesAndNewlines); self.session = session
131+ }
132+
133+ public var hasToken: Bool { !(token ?? "").isEmpty }
134+ public var turnstilePage: URL { base.appending(path: "app/turnstile/") }
135+ public func withToken(_ token: String?) -> APIClient { APIClient(base: base, client: client, token: token, session: session) }
136+
137+ // MARK: Public
138+
139+ public func meta() async throws -> Meta { try await get("api/meta") }
140+
141+ public func jobs(query: String = "", workplace: String = "", type: String = "", category: String = "",
142+ limit: Int = 30, cursor: String? = nil) async throws -> JobPage {
143+ var items = [URLQueryItem(name: "limit", value: String(limit))]
144+ if !query.isEmpty { items.append(.init(name: "q", value: String(query.prefix(80)))) }
145+ if !workplace.isEmpty { items.append(.init(name: "workplace", value: workplace)) }
146+ if !type.isEmpty { items.append(.init(name: "type", value: type)) }
147+ if !category.isEmpty { items.append(.init(name: "category", value: category)) }
148+ if let cursor { items.append(.init(name: "cursor", value: cursor)) }
149+ return try await get("api/jobs", query: items)
150+ }
151+
152+ public func job(_ id: String) async throws -> Job {
153+ let reply: JobReply = try await get("api/jobs/\(id)")
154+ return reply.job
155+ }
156+
157+ public func post(_ draft: JobDraft, turnstileToken: String?) async throws -> PostedJob {
158+ try await send("POST", "api/jobs", body: draft.body(turnstileToken: turnstileToken), admin: false)
159+ }
160+
161+ public func close(job id: String, manageToken: String) async throws {
162+ let _: Received = try await send("POST", "api/jobs/\(id)/close", body: ["manage_token": manageToken], admin: false)
163+ }
164+
165+ public func putForward(_ draft: CandidateDraft, turnstileToken: String?) async throws -> Received {
166+ try await send("POST", "api/candidates", body: draft.body(turnstileToken: turnstileToken), admin: false)
167+ }
168+
169+ // MARK: Admin: jobs
170+
171+ public func me() async throws -> Me { try await get("api/admin/me", admin: true) }
172+ public func stats() async throws -> Stats { try await get("api/admin/stats", admin: true) }
173+
174+ public func adminJobs(status: String, limit: Int = 100) async throws -> [Job] {
175+ let reply: JobsReply = try await get("api/admin/jobs", query: [.init(name: "status", value: status), .init(name: "limit", value: String(limit))], admin: true)
176+ return reply.jobs
177+ }
178+
179+ public func reviewItem(_ id: String) async throws -> JobReviewItem { try await get("api/admin/jobs/\(id)", admin: true) }
180+
181+ public func edit(job id: String, changes: [String: Any]) async throws -> Job {
182+ let reply: JobReply = try await send("PATCH", "api/admin/jobs/\(id)", body: changes)
183+ return reply.job
184+ }
185+
186+ @discardableResult
187+ public func addNote(job id: String, note: String) async throws -> String {
188+ let reply: IDReply = try await send("POST", "api/admin/jobs/\(id)/notes", body: ["note": note])
189+ return reply.id
190+ }
191+
192+ /// The normal one-step "Publish" is `approve(publish: true)`.
193+ public func approve(job id: String, publish: Bool, reason: String? = nil) async throws -> Job {
194+ var body: [String: Any] = ["publish": publish]
195+ if let reason, !reason.isEmpty { body["reason"] = reason }
196+ let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/approve", body: body)
197+ return reply.job
198+ }
199+
200+ /// "Send back": the reason is required and goes to the poster.
201+ public func reject(job id: String, reason: String) async throws -> Job {
202+ let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/reject", body: ["reason": reason])
203+ return reply.job
204+ }
205+
206+ public func publish(job id: String) async throws -> Job {
207+ let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/publish", body: [:])
208+ return reply.job
209+ }
210+
211+ public func unpublish(job id: String, reason: String? = nil) async throws -> Job {
212+ var body: [String: Any] = [:]
213+ if let reason, !reason.isEmpty { body["reason"] = reason }
214+ let reply: JobReply = try await send("POST", "api/admin/jobs/\(id)/unpublish", body: body)
215+ return reply.job
216+ }
217+
218+ // MARK: Admin: candidates (people only, never agents)
219+
220+ /// `jobID` nil lists everyone; "none" lists people who asked about a kind of job. Oldest first.
221+ public func candidates(jobID: String? = nil, status: String? = nil, limit: Int = 200) async throws -> [Candidate] {
222+ var items = [URLQueryItem(name: "limit", value: String(limit))]
223+ if let jobID { items.append(.init(name: "job_id", value: jobID)) }
224+ if let status, !status.isEmpty { items.append(.init(name: "status", value: status)) }
225+ let reply: CandidatesReply = try await get("api/admin/candidates", query: items, admin: true)
226+ return reply.candidates
227+ }
228+
229+ public func candidate(_ id: String) async throws -> CandidateDetail { try await get("api/admin/candidates/\(id)", admin: true) }
230+
231+ public func introduce(candidate id: String, jobID: String?, note: String?) async throws -> IntroductionResult {
232+ var body: [String: Any] = [:]
233+ if let jobID { body["job_id"] = jobID }
234+ if let note, !note.isEmpty { body["note"] = note }
235+ return try await send("POST", "api/admin/candidates/\(id)/introduce", body: body)
236+ }
237+
238+ public func setStatus(candidate id: String, status: String, note: String? = nil) async throws -> Candidate {
239+ var body: [String: Any] = ["status": status]
240+ if let note, !note.isEmpty { body["note"] = note }
241+ let reply: CandidateReply = try await send("POST", "api/admin/candidates/\(id)/status", body: body)
242+ return reply.candidate
243+ }
244+
245+ // MARK: Admin: moderators (curator only)
246+
247+ public func moderatorApplications(status: String = "new") async throws -> [ModeratorApplication] {
248+ let reply: ApplicationsReply = try await get("api/admin/moderator-applications", query: [.init(name: "status", value: status)], admin: true)
249+ return reply.applications
250+ }
251+
252+ public func approve(application id: String, canSeeCandidates: Bool) async throws -> NewModerator {
253+ try await send("POST", "api/admin/moderator-applications/\(id)/approve", body: ["can_see_candidates": canSeeCandidates])
254+ }
255+
256+ public func decline(application id: String, note: String? = nil) async throws {
257+ var body: [String: Any] = [:]
258+ if let note, !note.isEmpty { body["note"] = note }
259+ let _: IDReply = try await send("POST", "api/admin/moderator-applications/\(id)/decline", body: body)
260+ }
261+
262+ public func moderators() async throws -> [Moderator] {
263+ let reply: ModeratorsReply = try await get("api/admin/moderators", admin: true)
264+ return reply.moderators
265+ }
266+
267+ public func setAccess(moderator id: String, canSeeCandidates: Bool) async throws {
268+ let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/access", body: ["can_see_candidates": canSeeCandidates])
269+ }
270+
271+ public func revoke(moderator id: String) async throws {
272+ let _: IDReply = try await send("POST", "api/admin/moderators/\(id)/revoke", body: [:])
273+ }
274+
275+ /// Deletes what is past the retention period. The Mac app calls it when the curator opens it.
276+ public func purge() async throws -> PurgeResult { try await send("POST", "api/admin/purge", body: [:]) }
277+
278+ // MARK: Transport
279+
280+ func get<T: Decodable>(_ path: String, query: [URLQueryItem] = [], admin: Bool = false) async throws -> T {
281+ try await perform(request("GET", path, query: query, admin: admin))
282+ }
283+
284+ func send<T: Decodable>(_ method: String, _ path: String, body: [String: Any], admin: Bool = true) async throws -> T {
285+ var request = try request(method, path, admin: admin)
286+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
287+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
288+ return try await perform(request)
289+ }
290+
291+ func request(_ method: String, _ path: String, query: [URLQueryItem] = [], admin: Bool) throws -> URLRequest {
292+ var components = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false)!
293+ if !query.isEmpty { components.queryItems = query }
294+ // Always fresh: the board answers with cache-control max-age=60, and a curator must see a
295+ // post disappear the moment it is unpublished.
296+ var request = URLRequest(url: components.url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30)
297+ request.httpMethod = method
298+ request.setValue("application/json", forHTTPHeaderField: "Accept")
299+ request.setValue(client.rawValue, forHTTPHeaderField: "X-Client")
300+ if admin {
301+ guard let token, !token.isEmpty else { throw APIError.signedOut }
302+ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
303+ }
304+ return request
305+ }
306+
307+ func perform<T: Decodable>(_ request: URLRequest) async throws -> T {
308+ let data: Data, response: URLResponse
309+ do { (data, response) = try await session.data(for: request) }
310+ catch { throw APIError(code: "offline", message: "We couldn't reach Jobley. Check your connection and try again.") }
311+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
312+ guard (200..<300).contains(status) else { throw Self.error(from: data, status: status) }
313+ do { return try JSONDecoder().decode(T.self, from: data) }
314+ catch { throw APIError(code: "bad_reply", message: "Jobley sent a reply we couldn't read.", httpStatus: status) }
315+ }
316+
317+ static func error(from data: Data, status: Int) -> APIError {
318+ guard let reply = try? JSONDecoder().decode(ErrorReply.self, from: data) else {
319+ return APIError(code: "http_\(status)", message: "Jobley answered with an error (\(status)). Please try again.", httpStatus: status)
320+ }
321+ return APIError(code: reply.error, message: reply.message, fields: reply.fields ?? [:], status: reply.status, httpStatus: status)
322+ }
323+ }
324+
325+ struct ErrorReply: Decodable {
326+ var error: String
327+ var message: String
328+ var fields: [String: String]?
329+ var status: String?
330+ }
331+ struct JobReply: Decodable { var job: Job }
332+ struct JobsReply: Decodable { var jobs: [Job] }
333+ struct IDReply: Decodable { var id: String }
334+ struct CandidatesReply: Decodable { var candidates: [Candidate] }
335+ struct CandidateReply: Decodable { var candidate: Candidate }
336+ struct ApplicationsReply: Decodable { var applications: [ModeratorApplication] }
337+ struct ModeratorsReply: Decodable { var moderators: [Moderator] }

Sources/JobleyKit/AgentSettings.swift added

1+ import Foundation
2+
3+ /// "Let agents make changes" and the log of every change an agent made. The app and the MCP process
4+ /// (the same executable run with --mcp) share the standard defaults and this log file.
5+ public enum AgentSettings {
6+ public static let allowWritesKey = "jobley.agents.allowWrites"
7+
8+ public static func allowsWrites(_ defaults: UserDefaults = .standard) -> Bool { defaults.bool(forKey: allowWritesKey) }
9+ public static func setAllowsWrites(_ value: Bool, _ defaults: UserDefaults = .standard) { defaults.set(value, forKey: allowWritesKey) }
10+ }
11+
12+ public struct AgentLogEntry: Codable, Hashable, Identifiable, Sendable {
13+ public var id = UUID()
14+ public var at: Date
15+ public var agent: String
16+ public var tool: String
17+ public var jobID: String
18+ public var summary: String
19+ }
20+
21+ public enum AgentLog {
22+ public static var fileURL: URL {
23+ if let path = ProcessInfo.processInfo.environment["JOBLEY_AGENT_LOG"] { return URL(fileURLWithPath: path) }
24+ let folder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appending(path: "Jobley")
25+ return folder.appending(path: "agent-log.json")
26+ }
27+
28+ public static func entries(at url: URL = fileURL) -> [AgentLogEntry] {
29+ guard let data = try? Data(contentsOf: url) else { return [] }
30+ let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601
31+ return (try? decoder.decode([AgentLogEntry].self, from: data)) ?? []
32+ }
33+
34+ /// Newest first, at most 500 entries.
35+ public static func append(_ entry: AgentLogEntry, at url: URL = fileURL) {
36+ var all = entries(at: url)
37+ all.insert(entry, at: 0)
38+ if all.count > 500 { all.removeLast(all.count - 500) }
39+ let encoder = JSONEncoder(); encoder.dateEncodingStrategy = .iso8601
40+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
41+ if let data = try? encoder.encode(all) { try? data.write(to: url, options: .atomic) }
42+ }
43+ }

Sources/JobleyKit/AppLinks.swift added

1+ import Foundation
2+
3+ /// The app's own web addresses.
4+ public enum AppLinks {
5+ public static let website = URL(string: "https://jobley.ai/")!
6+ public static let source = URL(string: "https://github.com/projectatomai/jobley")!
7+ }

Sources/JobleyKit/HouseRules.swift added

1+ import Foundation
2+
3+ /// What counts as a good job (PRD section 4, the same list as jobley.ai/help/#rules). A person
4+ /// reads every post against it and ticks each rule by hand; nothing here checks a post automatically.
5+ public enum HouseRules {
6+ public struct Rule: Identifiable, Hashable, Sendable {
7+ public let title: String
8+ public let detail: String
9+ public var id: String { title }
10+ }
11+
12+ public static let all: [Rule] = [
13+ Rule(title: "A real company, named.", detail: "We can find it: a working website or a public record. A recruiter posting for someone else names who the job is with."),
14+ Rule(title: "Fair pay, shown.", detail: "\(payRule) We show a lowest and a highest figure, and whether it is by the year, month, week, day or hour. “Competitive” is not a number."),
15+ Rule(title: "Honest, paid work.", detail: "No commission-only roles, no multi-level marketing, no unpaid trials, no “pay to apply” and no fees for training, kits or equipment."),
16+ Rule(title: "A clear description.", detail: "It says what you would do, who you would work with, where and when. Not a list of buzzwords."),
17+ Rule(title: "One job per post.", detail: "A real opening that exists today, not a talent pool, an advertisement or a course."),
18+ Rule(title: "Legal and fair.", detail: "Nothing that asks for a photo, age, religion or anything else it is not fair or lawful to ask, and nothing that asks for bank or ID details up front."),
19+ Rule(title: "Reachable.", detail: "A real person’s name and email with the post, so we can introduce candidates. We keep those private.")
20+ ]
21+
22+ /// The pay floor, in step with MIN_HOURLY_USD and PAY_FLOOR in jobley-site's src/config.js. The server
23+ /// enforces it; the apps only warn early with the same message. A full-time year is 2,080 hours.
24+ public static let minHourlyUSD = 100
25+ public static let hoursAYear = 2080
26+ static let periodsAYear: [String: Int] = ["hour": 2080, "day": 260, "week": 52, "month": 12, "year": 1]
27+ public static var payFloorShort: String { "$\(minHourlyUSD) an hour or more, or $\((minHourlyUSD * hoursAYear).formatted()) a year full time" }
28+ public static var payRule: String {
29+ "At least $\(minHourlyUSD) an hour, or $\((minHourlyUSD * hoursAYear).formatted()) a year full time, or the same in local currency. By the hour or salaried, full or part time, with or without benefits."
30+ }
31+ public static var payFloorMessage: String {
32+ "Pay must be at least $\(minHourlyUSD) an hour, or $\((minHourlyUSD * hoursAYear).formatted()) a year full time."
33+ }
34+ /// True when a USD job's lowest pay is under the floor. Other currencies are judged by the person reviewing.
35+ public static func belowPayFloor(min: Int?, period: String, currency: String) -> Bool {
36+ guard let min, currency.uppercased() == "USD", let perYear = periodsAYear[period] else { return false }
37+ return min * perYear < minHourlyUSD * hoursAYear
38+ }
39+
40+ /// The promise every place that takes a post makes. Only a person's token can publish a job.
41+ public static let guarantee = "Every job you post is reviewed by a real person before it goes live. No AI decides."
42+
43+ public static let neverPublished = "Never published: scams, adult services, anything unlawful, or a copy of another company's listing without their say."
44+
45+ public static var text: String {
46+ guarantee + "\n\n" + all.enumerated().map { "\($0.offset + 1). \($0.element.title) \($0.element.detail)" }.joined(separator: "\n") + "\n\n" + neverPublished
47+ }
48+ }

Sources/JobleyKit/Keychain.swift added

1+ import Foundation
2+ import Security
3+
4+ /// The session token a passkey sign-in returns, for the curator or a moderator. It lives only in the
5+ /// Keychain, never in defaults, files or MCP arguments. The MCP process (the same executable) reads it
6+ /// from here too. Nobody types or pastes it: people sign in with a passkey.
7+ public enum TokenStore {
8+ public static let service = "com.protomota.jobley"
9+ static let account = "api-token"
10+
11+ /// Tests, screenshots and unsigned dev builds can pass a dev server session in the environment instead.
12+ public static var environmentToken: String? {
13+ let value = ProcessInfo.processInfo.environment["JOBLEY_TOKEN"]
14+ return (value?.isEmpty ?? true) ? nil : value
15+ }
16+
17+ public static func load() -> String? {
18+ if let environmentToken { return environmentToken }
19+ var query = base
20+ query[kSecReturnData as String] = true
21+ query[kSecMatchLimit as String] = kSecMatchLimitOne
22+ var out: AnyObject?
23+ guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }
24+ return String(data: data, encoding: .utf8)
25+ }
26+
27+ public static func save(_ token: String) throws {
28+ let data = Data(token.trimmingCharacters(in: .whitespacesAndNewlines).utf8)
29+ let status = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary)
30+ if status == errSecItemNotFound {
31+ var add = base
32+ add[kSecValueData as String] = data
33+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
34+ let added = SecItemAdd(add as CFDictionary, nil)
35+ guard added == errSecSuccess else { throw KeychainError(status: added) }
36+ } else if status != errSecSuccess {
37+ throw KeychainError(status: status)
38+ }
39+ }
40+
41+ public static func remove() { SecItemDelete(base as CFDictionary) }
42+
43+ private static var base: [String: Any] {
44+ [kSecClass as String: kSecClassGenericPassword,
45+ kSecAttrService as String: service,
46+ kSecAttrAccount as String: account]
47+ }
48+ }
49+
50+ public struct KeychainError: Error, LocalizedError {
51+ public let status: OSStatus
52+ public var errorDescription: String? { "The Keychain refused to save your sign-in (\(status))." }
53+ }

Sources/JobleyKit/MCPServer.swift added

1+ import Foundation
2+
3+ /// STDIO MCP server, run as `Jobley --mcp`. Every request carries `X-Client: mcp`.
4+ ///
5+ /// Agents may read the board and the review queue, read the house rules, tidy a post's wording and
6+ /// leave a review note. That is all. There is no tool to approve, send back, publish or unpublish,
7+ /// and none that touches candidates; the API also answers `403 people_only` if an agent client tries.
8+ /// Write tools need "Let agents make changes" in Settings → Agents, and every agent write is logged.
9+ /// It uses the Mac app's passkey sign-in (the session in the Keychain), never a token in tool arguments,
10+ /// and it can never sign in or add a passkey itself. Queue tools strip the poster's
11+ /// private contact details before anything reaches the agent.
12+ public final class MCPServer: @unchecked Sendable {
13+ let api: APIClient
14+ let defaults: UserDefaults
15+ let logURL: URL
16+ var clientName = "Agent"
17+
18+ public init(api: APIClient, defaults: UserDefaults = .standard, logURL: URL = AgentLog.fileURL) {
19+ self.api = api; self.defaults = defaults; self.logURL = logURL
20+ }
21+
22+ /// The server the Mac app's `--mcp` mode runs.
23+ public static func live() -> MCPServer {
24+ MCPServer(api: APIClient(client: .mcp, token: TokenStore.load()))
25+ }
26+
27+ struct Tool {
28+ let name: String, summary: String
29+ var fields: [String: [String: Any]] = [:]
30+ var required: [String] = []
31+ var writes = false
32+ var json: [String: Any] {
33+ ["name": name, "description": summary,
34+ "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false],
35+ "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "idempotentHint": !writes, "openWorldHint": true]]
36+ }
37+ }
38+
39+ static var str: [String: Any] { ["type": "string"] }
40+
41+ static var tools: [Tool] { [
42+ .init(name: "get_status", summary: "Who the Mac app is signed in as, how many posts are in each state, and whether agents may make changes. Call this first."),
43+ .init(name: "list_jobs", summary: "Search the public board (published jobs only), newest first.",
44+ fields: ["query": str, "workplace": str, "type": str, "category": str, "limit": ["type": "integer", "minimum": 1, "maximum": 100]]),
45+ .init(name: "get_job", summary: "One published job from the public board.", fields: ["job_id": str], required: ["job_id"]),
46+ .init(name: "list_review_queue", summary: "Posts waiting for a person to review, oldest first. Contact details are removed.",
47+ fields: ["status": ["type": "string", "enum": ["pending", "approved", "rejected", "unpublished"]]]),
48+ .init(name: "get_review_item", summary: "One post in the queue with its review history. Contact details are removed.", fields: ["job_id": str], required: ["job_id"]),
49+ .init(name: "get_house_rules", summary: "The rules for what counts as a good job, so you can point at the one a post may miss. A person decides."),
50+ .init(name: "tidy_job_post", summary: "Fix the wording of a post's title or description: typos, spacing, formatting. Never change pay, company, location or meaning.",
51+ fields: ["job_id": str, "title": str, "description": str], required: ["job_id"], writes: true),
52+ .init(name: "add_review_note", summary: "Leave a note on a post for the person reviewing it.",
53+ fields: ["job_id": str, "note": str], required: ["job_id", "note"], writes: true)
54+ ] }
55+
56+ public static var toolNames: [String] { tools.map(\.name) }
57+
58+ // MARK: Transport
59+
60+ public func run() async {
61+ let input = FileHandle.standardInput, output = FileHandle.standardOutput
62+ var line = Data()
63+ while true {
64+ let chunk = input.availableData
65+ if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return }
66+ for byte in chunk {
67+ if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) }
68+ else if line.count < 1_048_576 { line.append(byte) }
69+ }
70+ }
71+ }
72+
73+ private func respond(_ data: Data, _ output: FileHandle) async {
74+ let reply: [String: Any]?
75+ if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) }
76+ else { reply = failure(NSNull(), -32700, "Parse error.") }
77+ if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) }
78+ }
79+
80+ public func handle(_ request: [String: Any]) async -> [String: Any]? {
81+ let id = request["id"] ?? NSNull()
82+ guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") }
83+ guard request["id"] != nil else { return nil }
84+ let params = request["params"] as? [String: Any] ?? [:]
85+ switch method {
86+ case "initialize":
87+ if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name }
88+ let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
89+ let asked = params["protocolVersion"] as? String ?? ""
90+ return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0],
91+ "capabilities": ["tools": ["listChanged": false]],
92+ "serverInfo": ["name": "jobley", "version": "0.1.0"],
93+ "instructions": "Jobley is a job board where people decide. You can read the board and the review queue, tidy a post's wording and leave notes. You cannot approve, send back, publish or unpublish a post, and you never see candidates. Never rank, score or filter jobs or people."])
94+ case "ping": return success(id, [:])
95+ case "tools/list": return success(id, ["tools": Self.tools.map(\.json)])
96+ case "tools/call":
97+ let name = params["name"] as? String ?? ""
98+ let args = params["arguments"] as? [String: Any] ?? [:]
99+ guard let tool = Self.tools.first(where: { $0.name == name }) else { return failure(id, -32602, "Unknown tool \(name).") }
100+ if tool.writes && !AgentSettings.allowsWrites(defaults) {
101+ return success(id, text("Changes by agents are off. Ask the person to turn on “Let agents make changes” in Jobley Settings → Agents.", isError: true))
102+ }
103+ do { return success(id, text(try await call(name, args))) }
104+ catch let error as APIError { return success(id, text(error.errorDescription ?? error.message, isError: true)) }
105+ catch { return success(id, text(error.localizedDescription, isError: true)) }
106+ default: return failure(id, -32601, "Method not found.")
107+ }
108+ }
109+
110+ func call(_ name: String, _ args: [String: Any]) async throws -> String {
111+ func string(_ key: String) -> String { (args[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }
112+ func required(_ key: String) throws -> String {
113+ let value = string(key)
114+ guard !value.isEmpty else { throw APIError(code: "invalid", message: "\(key) is required.") }
115+ return value
116+ }
117+ switch name {
118+ case "get_status":
119+ let me = try await api.me(), stats = try await api.stats()
120+ return encode(["role": me.role, "name": me.name, "jobs": stats.jobs, "agents_may_make_changes": AgentSettings.allowsWrites(defaults)] as [String: any Encodable])
121+ case "list_jobs":
122+ let page = try await api.jobs(query: string("query"), workplace: string("workplace"), type: string("type"),
123+ category: string("category"), limit: args["limit"] as? Int ?? 30)
124+ return encode(page.jobs)
125+ case "get_job":
126+ return encode(try await api.job(try required("job_id")))
127+ case "list_review_queue":
128+ let status = string("status").isEmpty ? "pending" : string("status")
129+ guard ["pending", "approved", "rejected", "unpublished"].contains(status) else { throw APIError(code: "invalid", message: "Unknown status.") }
130+ return encode(try await api.adminJobs(status: status).map(\.withoutContact))
131+ case "get_review_item":
132+ let item = try await api.reviewItem(try required("job_id"))
133+ return encode(["job": item.job.withoutContact, "activity": item.activity] as [String: any Encodable])
134+ case "get_house_rules":
135+ return HouseRules.text
136+ case "tidy_job_post":
137+ let jobID = try required("job_id")
138+ var changes: [String: Any] = [:]
139+ if !string("title").isEmpty { changes["title"] = string("title") }
140+ if !string("description").isEmpty { changes["description"] = string("description") }
141+ guard !changes.isEmpty else { throw APIError(code: "invalid", message: "Pass a new title or description. Only wording can be tidied.") }
142+ let job = try await api.edit(job: jobID, changes: changes)
143+ log("tidy_job_post", jobID, "Tidied the " + changes.keys.sorted().joined(separator: " and ") + " of “\(job.title)”")
144+ return "Tidied. A person still decides whether it is published.\n" + encode(job.withoutContact)
145+ case "add_review_note":
146+ let jobID = try required("job_id"), note = try required("note")
147+ try await api.addNote(job: jobID, note: String(note.prefix(2000)))
148+ log("add_review_note", jobID, "Added a note: " + String(note.prefix(120)))
149+ return "Note added for the reviewer."
150+ default:
151+ throw APIError(code: "not_found", message: "Unknown tool.")
152+ }
153+ }
154+
155+ func log(_ tool: String, _ jobID: String, _ summary: String) {
156+ AgentLog.append(AgentLogEntry(at: .now, agent: clientName, tool: tool, jobID: jobID, summary: summary), at: logURL)
157+ }
158+
159+ func encode(_ value: any Encodable) -> String {
160+ let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
161+ return (try? encoder.encode(AnyEncodable(value))).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
162+ }
163+
164+ func encode(_ dictionary: [String: any Encodable]) -> String {
165+ encode(dictionary.mapValues(AnyEncodable.init))
166+ }
167+
168+ private func text(_ body: String, isError: Bool = false) -> [String: Any] {
169+ ["content": [["type": "text", "text": body]], "isError": isError]
170+ }
171+ private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] }
172+ private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] {
173+ ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]]
174+ }
175+ }
176+
177+ struct AnyEncodable: Encodable {
178+ let value: any Encodable
179+ init(_ value: any Encodable) { self.value = value }
180+ func encode(to encoder: Encoder) throws { try value.encode(to: encoder) }
181+ }

Sources/JobleyKit/Models.swift added

1+ import Foundation
2+
3+ // The shapes of the Jobley API (PRD section 7). Keys are mapped by hand: the API's value → label
4+ // maps (workplaces, categories) must keep their snake_case keys, so no automatic key strategy is used.
5+
6+ public struct Pay: Codable, Hashable, Sendable {
7+ public var min: Int
8+ public var max: Int
9+ public var currency: String
10+ public var period: String
11+
12+ public init(min: Int, max: Int, currency: String, period: String) {
13+ self.min = min; self.max = max; self.currency = currency; self.period = period
14+ }
15+
16+ /// "$82,000 to $98,000 a year", "£41,000 to £48,000 a year", "$70 to $85 an hour".
17+ public var text: String {
18+ let formatter = NumberFormatter()
19+ formatter.numberStyle = .currency
20+ formatter.currencyCode = currency
21+ formatter.maximumFractionDigits = 0
22+ let low = formatter.string(from: NSNumber(value: min)) ?? "\(min)"
23+ let high = formatter.string(from: NSNumber(value: max)) ?? "\(max)"
24+ let range = min == max ? low : "\(low) to \(high)"
25+ let article = period == "hour" ? "an" : "a"
26+ return "\(range) \(article) \(period)"
27+ }
28+ }
29+
30+ public struct Contact: Codable, Hashable, Sendable {
31+ public var name: String
32+ public var email: String
33+ }
34+
35+ public struct Review: Codable, Hashable, Sendable {
36+ public var reason: String?
37+ public var by: String?
38+ public var at: String?
39+ }
40+
41+ /// A job. The public shape, plus status, contact and review when it comes from the admin API.
42+ public struct Job: Codable, Hashable, Identifiable, Sendable {
43+ public var id: String
44+ public var url: String
45+ public var title: String
46+ public var company: String
47+ public var companyURL: String?
48+ public var location: String
49+ public var workplace: String
50+ public var employmentType: String
51+ public var category: String
52+ public var pay: Pay
53+ public var description: String
54+ public var applyURL: String?
55+ public var publishedAt: String?
56+ public var expiresAt: String?
57+ public var status: String?
58+ public var contact: Contact?
59+ public var review: Review?
60+ public var createdAt: String?
61+ public var updatedAt: String?
62+
63+ enum CodingKeys: String, CodingKey {
64+ case id, url, title, company, location, workplace, category, pay, description, status, contact, review
65+ case companyURL = "company_url", employmentType = "employment_type", applyURL = "apply_url"
66+ case publishedAt = "published_at", expiresAt = "expires_at", createdAt = "created_at", updatedAt = "updated_at"
67+ }
68+
69+ /// The same job without the poster's private contact details (what an agent may see).
70+ public var withoutContact: Job { var copy = self; copy.contact = nil; return copy }
71+ }
72+
73+ public enum JobStatus: String, CaseIterable, Sendable {
74+ case pending, approved, published, rejected, unpublished, closed
75+
76+ public var label: String {
77+ switch self {
78+ case .pending: "Waiting for review"
79+ case .approved: "Approved"
80+ case .published: "Published"
81+ case .rejected: "Sent back"
82+ case .unpublished: "Unpublished"
83+ case .closed: "Closed by the poster"
84+ }
85+ }
86+ }
87+
88+ public struct Meta: Codable, Sendable {
89+ public var name: String
90+ public var site: String
91+ public var turnstileSiteKey: String?
92+ public var workplaces: [String: String]
93+ public var employmentTypes: [String: String]
94+ public var categories: [String: String]
95+ public var payPeriods: [String: String]
96+ public var jobDaysLive: Int?
97+
98+ enum CodingKeys: String, CodingKey {
99+ case name, site, workplaces, categories
100+ case turnstileSiteKey = "turnstile_site_key", employmentTypes = "employment_types"
101+ case payPeriods = "pay_periods", jobDaysLive = "job_days_live"
102+ }
103+
104+ /// Labels used before /api/meta has loaded, and by the MCP server. They match src/config.js.
105+ public static let fallback = Meta(
106+ name: "Jobley", site: "https://jobley.ai", turnstileSiteKey: nil,
107+ workplaces: ["remote": "Remote", "hybrid": "Hybrid", "onsite": "On site"],
108+ employmentTypes: ["full_time": "Full time", "part_time": "Part time", "contract": "Contract", "temporary": "Temporary", "internship": "Internship"],
109+ categories: ["engineering": "Engineering", "design": "Design", "product": "Product", "data": "Data", "marketing": "Marketing",
110+ "sales": "Sales", "support": "Customer support", "operations": "Operations", "finance": "Finance",
111+ "people": "People and HR", "writing": "Writing and editing", "education": "Education",
112+ "healthcare": "Healthcare", "trades": "Skilled trades", "other": "Other"],
113+ payPeriods: ["year": "a year", "month": "a month", "week": "a week", "day": "a day", "hour": "an hour"],
114+ jobDaysLive: 45)
115+
116+ public init(from decoder: Decoder) throws {
117+ let c = try decoder.container(keyedBy: CodingKeys.self)
118+ name = try c.decode(String.self, forKey: .name)
119+ site = try c.decode(String.self, forKey: .site)
120+ turnstileSiteKey = try c.decodeIfPresent(String.self, forKey: .turnstileSiteKey)
121+ workplaces = try c.decode([String: String].self, forKey: .workplaces)
122+ employmentTypes = try c.decode([String: String].self, forKey: .employmentTypes)
123+ categories = try c.decode([String: String].self, forKey: .categories)
124+ // The API sends pay periods as a plain list; older drafts used a value → label map.
125+ if let map = try? c.decode([String: String].self, forKey: .payPeriods) { payPeriods = map }
126+ else {
127+ let list = (try? c.decode([String].self, forKey: .payPeriods)) ?? Meta.payPeriodOrder
128+ payPeriods = Dictionary(uniqueKeysWithValues: list.map { ($0, Meta.fallback.payPeriods[$0] ?? $0) })
129+ }
130+ jobDaysLive = try c.decodeIfPresent(Int.self, forKey: .jobDaysLive)
131+ }
132+
133+ public init(name: String, site: String, turnstileSiteKey: String?, workplaces: [String: String], employmentTypes: [String: String],
134+ categories: [String: String], payPeriods: [String: String], jobDaysLive: Int?) {
135+ self.name = name; self.site = site; self.turnstileSiteKey = turnstileSiteKey; self.workplaces = workplaces
136+ self.employmentTypes = employmentTypes; self.categories = categories; self.payPeriods = payPeriods; self.jobDaysLive = jobDaysLive
137+ }
138+
139+ public static let workplaceOrder = ["remote", "hybrid", "onsite"]
140+ public static let employmentTypeOrder = ["full_time", "part_time", "contract", "temporary", "internship"]
141+ public static let categoryOrder = ["engineering", "design", "product", "data", "marketing", "sales", "support", "operations",
142+ "finance", "people", "writing", "education", "healthcare", "trades", "other"]
143+ public static let payPeriodOrder = ["year", "month", "week", "day", "hour"]
144+ }
145+
146+ public struct JobPage: Codable, Sendable {
147+ public var jobs: [Job]
148+ public var nextCursor: String?
149+ enum CodingKeys: String, CodingKey { case jobs, nextCursor = "next_cursor" }
150+ }
151+
152+ public struct PostedJob: Codable, Sendable {
153+ public var id: String
154+ public var status: String
155+ public var manageToken: String
156+ enum CodingKeys: String, CodingKey { case id, status, manageToken = "manage_token" }
157+ }
158+
159+ public struct Received: Codable, Sendable {
160+ public var id: String
161+ public var status: String
162+ public var already: Bool?
163+ }
164+
165+ public struct Me: Codable, Sendable, Equatable {
166+ public var role: String
167+ public var id: String
168+ public var name: String
169+ public var canSeeCandidates: Bool
170+ enum CodingKeys: String, CodingKey { case role, id, name, canSeeCandidates = "can_see_candidates" }
171+ public var isCurator: Bool { role == "curator" }
172+ }
173+
174+ public struct Stats: Codable, Sendable, Equatable {
175+ public struct Applications: Codable, Sendable, Equatable { public var new: Int }
176+ public var jobs: [String: Int]
177+ public var candidates: [String: Int]?
178+ public var moderatorApplications: Applications?
179+ enum CodingKeys: String, CodingKey { case jobs, candidates, moderatorApplications = "moderator_applications" }
180+
181+ public func jobs(_ status: JobStatus) -> Int { jobs[status.rawValue] ?? 0 }
182+ }
183+
184+ public struct ActivityEntry: Codable, Hashable, Sendable, Identifiable {
185+ public var actor: String
186+ public var client: String?
187+ public var action: String
188+ public var detail: String?
189+ public var createdAt: String
190+ enum CodingKeys: String, CodingKey { case actor, client, action, detail, createdAt = "created_at" }
191+ public var id: String { "\(createdAt)-\(action)-\(actor)" }
192+ }
193+
194+ public struct JobReviewItem: Codable, Sendable {
195+ public var job: Job
196+ public var activity: [ActivityEntry]
197+ public var candidateCount: Int
198+ enum CodingKeys: String, CodingKey { case job, activity, candidateCount = "candidate_count" }
199+ }
200+
201+ public struct Candidate: Codable, Hashable, Identifiable, Sendable {
202+ public var id: String
203+ public var jobID: String?
204+ public var status: String
205+ public var name: String
206+ public var email: String
207+ public var location: String?
208+ public var headline: String
209+ public var lookingFor: String?
210+ public var about: String?
211+ public var links: [String]
212+ public var resumeURL: String?
213+ public var note: String?
214+ public var createdAt: String
215+ public var updatedAt: String
216+ enum CodingKeys: String, CodingKey {
217+ case id, status, name, email, location, headline, about, links, note
218+ case jobID = "job_id", lookingFor = "looking_for", resumeURL = "resume_url", createdAt = "created_at", updatedAt = "updated_at"
219+ }
220+ }
221+
222+ public struct Introduction: Codable, Hashable, Identifiable, Sendable {
223+ public var id: String
224+ public var jobID: String
225+ public var introducedBy: String
226+ public var note: String?
227+ public var createdAt: String
228+ enum CodingKeys: String, CodingKey { case id, note, jobID = "job_id", introducedBy = "introduced_by", createdAt = "created_at" }
229+ }
230+
231+ public struct CandidateDetail: Codable, Sendable {
232+ public var candidate: Candidate
233+ public var introductions: [Introduction]
234+ }
235+
236+ public struct IntroductionResult: Codable, Sendable {
237+ public var id: String
238+ public var candidateID: String
239+ public var jobID: String
240+ public var status: String
241+ public var already: Bool?
242+ enum CodingKeys: String, CodingKey { case id, status, already, candidateID = "candidate_id", jobID = "job_id" }
243+ }
244+
245+ public struct ModeratorApplication: Codable, Hashable, Identifiable, Sendable {
246+ public var id: String
247+ public var status: String
248+ public var name: String
249+ public var email: String
250+ public var timezone: String?
251+ public var hoursPerWeek: Int?
252+ public var why: String
253+ public var experience: String?
254+ public var links: [String]
255+ public var note: String?
256+ public var createdAt: String
257+ enum CodingKeys: String, CodingKey {
258+ case id, status, name, email, timezone, why, experience, links, note
259+ case hoursPerWeek = "hours_per_week", createdAt = "created_at"
260+ }
261+ }
262+
263+ public struct Moderator: Codable, Hashable, Identifiable, Sendable {
264+ public var id: String
265+ public var name: String
266+ public var email: String
267+ public var canSeeCandidates: Bool
268+ public var active: Bool
269+ public var createdAt: String?
270+ public var lastSeenAt: String?
271+ enum CodingKeys: String, CodingKey {
272+ case id, name, email, active
273+ case canSeeCandidates = "can_see_candidates", createdAt = "created_at", lastSeenAt = "last_seen_at"
274+ }
275+
276+ public init(from decoder: Decoder) throws {
277+ let c = try decoder.container(keyedBy: CodingKeys.self)
278+ id = try c.decode(String.self, forKey: .id)
279+ name = try c.decode(String.self, forKey: .name)
280+ email = try c.decode(String.self, forKey: .email)
281+ canSeeCandidates = try c.decodeFlexibleBool(.canSeeCandidates)
282+ active = (try? c.decodeFlexibleBool(.active)) ?? true
283+ createdAt = try c.decodeIfPresent(String.self, forKey: .createdAt)
284+ lastSeenAt = try c.decodeIfPresent(String.self, forKey: .lastSeenAt)
285+ }
286+ }
287+
288+ public struct NewModerator: Codable, Sendable {
289+ public var moderator: Moderator
290+ /// Shown once: the one-time link the new moderator opens in Jobley to add their passkey.
291+ public var setup: SetupLink
292+ }
293+
294+ public struct PurgeResult: Codable, Sendable {
295+ public var olderThan: String
296+ enum CodingKeys: String, CodingKey { case olderThan = "older_than" }
297+ }
298+
299+ extension KeyedDecodingContainer {
300+ /// SQLite booleans come back as 0/1.
301+ func decodeFlexibleBool(_ key: Key) throws -> Bool {
302+ if let value = try? decode(Bool.self, forKey: key) { return value }
303+ return try decode(Int.self, forKey: key) != 0
304+ }
305+ }
306+
307+ /// When a time from the API is shown to a person: "Nov 27, 2026".
308+ public enum APIDate {
309+ nonisolated(unsafe) private static let iso: ISO8601DateFormatter = {
310+ let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]; return f
311+ }()
312+ nonisolated(unsafe) private static let isoPlain = ISO8601DateFormatter()
313+
314+ public static func date(_ text: String?) -> Date? {
315+ guard let text else { return nil }
316+ return iso.date(from: text) ?? isoPlain.date(from: text)
317+ }
318+
319+ public static func short(_ text: String?) -> String {
320+ guard let date = date(text) else { return text ?? "" }
321+ return date.formatted(date: .abbreviated, time: .omitted)
322+ }
323+
324+ public static func full(_ text: String?) -> String {
325+ guard let date = date(text) else { return text ?? "" }
326+ return date.formatted(date: .abbreviated, time: .shortened)
327+ }
328+ }

Sources/JobleyKit/Passkeys.swift added

1+ import Foundation
2+
3+ /// Passkeys are the only way the curator and moderators sign in: no passwords, pasted tokens,
4+ /// email links or codes. Recovery is a second passkey. The relying party is jobley.ai, which serves
5+ /// the apple-app-site-association file the apps' `webcredentials:jobley.ai` entitlement points at.
6+ /// A passkey sign-in returns a session token, which the apps keep in the Keychain (`TokenStore`).
7+
8+ /// What the server sends to start a sign-in or to add a passkey.
9+ public struct PasskeyChallenge: Decodable, Sendable {
10+ public var challengeID: String
11+ public var options: Options
12+
13+ public struct Options: Decodable, Sendable {
14+ /// base64url
15+ public var challenge: String
16+ /// Sign-in options name the relying party here…
17+ public var rpId: String?
18+ /// …registration options here, with the person and the passkeys they already have.
19+ public var rp: RelyingParty?
20+ public var user: User?
21+ public var excludeCredentials: [Credential]?
22+ }
23+ public struct RelyingParty: Decodable, Sendable { public var id: String }
24+ public struct User: Decodable, Sendable { public var id: String, name: String, displayName: String? }
25+ public struct Credential: Decodable, Sendable { public var id: String }
26+
27+ enum CodingKeys: String, CodingKey { case challengeID = "challenge_id", options }
28+
29+ public var relyingParty: String { options.rp?.id ?? options.rpId ?? "jobley.ai" }
30+ public var challenge: Data? { Data(base64URL: options.challenge) }
31+ public var userID: Data? { options.user.flatMap { Data(base64URL: $0.id) } }
32+ public var excludedCredentialIDs: [Data] { (options.excludeCredentials ?? []).compactMap { Data(base64URL: $0.id) } }
33+ }
34+
35+ /// A signed-in session, from a passkey sign-in or from adding a passkey with a setup link.
36+ public struct PasskeySession: Decodable, Sendable {
37+ public var token: String
38+ public var role: String
39+ public var id: String
40+ public var name: String
41+ public var canSeeCandidates: Bool
42+ enum CodingKeys: String, CodingKey { case token, role, id, name, canSeeCandidates = "can_see_candidates" }
43+ }
44+
45+ /// One of the signed-in person's passkeys.
46+ public struct Passkey: Decodable, Identifiable, Sendable, Equatable {
47+ public var id: String
48+ public var name: String?
49+ public var createdAt: String?
50+ public var lastUsedAt: String?
51+ enum CodingKeys: String, CodingKey { case id, name, createdAt = "created_at", lastUsedAt = "last_used_at" }
52+ }
53+
54+ /// A one-time link that adds a person's first passkey. It works once, within 15 minutes.
55+ public struct SetupLink: Codable, Sendable, Equatable {
56+ public var url: String
57+ public var expiresAt: String
58+ enum CodingKeys: String, CodingKey { case url, expiresAt = "expires_at" }
59+ }
60+
61+ /// The WebAuthn JSON the server's verifier reads, built from what AuthenticationServices returns.
62+ public enum PasskeyResponse {
63+ public static func registration(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> [String: Any] {
64+ ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key",
65+ "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](),
66+ "response": ["clientDataJSON": clientDataJSON.base64URL, "attestationObject": attestationObject.base64URL, "transports": ["internal", "hybrid"]]]
67+ }
68+
69+ public static func assertion(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) -> [String: Any] {
70+ var response: [String: Any] = ["clientDataJSON": clientDataJSON.base64URL, "authenticatorData": authenticatorData.base64URL, "signature": signature.base64URL]
71+ if let userID { response["userHandle"] = userID.base64URL }
72+ return ["id": credentialID.base64URL, "rawId": credentialID.base64URL, "type": "public-key",
73+ "authenticatorAttachment": "platform", "clientExtensionResults": [String: Any](), "response": response]
74+ }
75+
76+ /// The code in a setup link ("https://jobley.ai/passkey/#jl_enroll_…"), or the code on its own.
77+ public static func setupCode(from text: String) -> String? {
78+ let code = text.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: "#").last.map(String.init) ?? ""
79+ return code.range(of: #"^[a-z]+_enroll_[0-9a-f]{64}$"#, options: .regularExpression) != nil ? code : nil
80+ }
81+ }
82+
83+ extension APIClient {
84+ // MARK: Passkeys
85+
86+ public func passkeySignInOptions() async throws -> PasskeyChallenge {
87+ try await send("POST", "api/passkeys/login/options", body: [:], admin: false)
88+ }
89+
90+ public func signIn(challengeID: String, assertion: [String: Any]) async throws -> PasskeySession {
91+ try await send("POST", "api/passkeys/login", body: ["challenge_id": challengeID, "response": assertion], admin: false)
92+ }
93+
94+ /// Options to add a first passkey with a setup link.
95+ public func passkeyOptions(setupCode: String) async throws -> PasskeyChallenge {
96+ try await send("POST", "api/passkeys/register/options", body: ["code": setupCode], admin: false)
97+ }
98+
99+ /// Saves the first passkey and signs in.
100+ public func addPasskey(challengeID: String, registration: [String: Any], name: String) async throws -> PasskeySession {
101+ try await send("POST", "api/passkeys/register", body: ["challenge_id": challengeID, "response": registration, "name": name], admin: false)
102+ }
103+
104+ /// Options to add another passkey while signed in.
105+ public func anotherPasskeyOptions() async throws -> PasskeyChallenge {
106+ try await send("POST", "api/admin/passkeys/options", body: [:])
107+ }
108+
109+ public func addAnotherPasskey(challengeID: String, registration: [String: Any], name: String) async throws {
110+ let _: IDReply = try await send("POST", "api/admin/passkeys", body: ["challenge_id": challengeID, "response": registration, "name": name])
111+ }
112+
113+ public func passkeys() async throws -> [Passkey] {
114+ let reply: PasskeysReply = try await get("api/admin/passkeys", admin: true)
115+ return reply.passkeys
116+ }
117+
118+ /// The server refuses to remove the last one.
119+ public func removePasskey(_ id: String) async throws {
120+ let _: IDReply = try await perform(request("DELETE", "api/admin/passkeys/\(id)", admin: true))
121+ }
122+
123+ public func signOut() async throws {
124+ let _: OKReply = try await send("POST", "api/admin/sign-out", body: [:])
125+ }
126+
127+ /// A new one-time setup link for a moderator (curator only).
128+ public func setupLink(moderator id: String) async throws -> SetupLink {
129+ let reply: SetupLinkReply = try await send("POST", "api/admin/moderators/\(id)/setup-link", body: [:])
130+ return reply.setup
131+ }
132+ }
133+
134+ struct PasskeysReply: Decodable { var passkeys: [Passkey] }
135+ struct SetupLinkReply: Decodable { var setup: SetupLink }
136+ struct OKReply: Decodable { var ok: Bool }
137+
138+ extension Data {
139+ public var base64URL: String {
140+ base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
141+ }
142+
143+ public init?(base64URL: String) {
144+ var text = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
145+ text += String(repeating: "=", count: (4 - text.count % 4) % 4)
146+ self.init(base64Encoded: text)
147+ }
148+ }

Sources/JobleyUI/Components.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// Labels for the API's enum values, from /api/meta (or the built-in copy until it loads).
5+ public struct Labels: Sendable {
6+ public var meta: Meta
7+ public init(_ meta: Meta = .fallback) { self.meta = meta }
8+ public func workplace(_ v: String) -> String { meta.workplaces[v] ?? Meta.fallback.workplaces[v] ?? v }
9+ public func type(_ v: String) -> String { meta.employmentTypes[v] ?? Meta.fallback.employmentTypes[v] ?? v }
10+ public func category(_ v: String) -> String { meta.categories[v] ?? Meta.fallback.categories[v] ?? v }
11+ }
12+
13+ public struct Chip: View {
14+ let text: String
15+ public init(_ text: String) { self.text = text }
16+ public var body: some View {
17+ Text(text)
18+ .font(.caption)
19+ .foregroundStyle(Theme.ink2)
20+ .padding(.horizontal, 9).padding(.vertical, 4)
21+ .overlay(Capsule().strokeBorder(Theme.line))
22+ }
23+ }
24+
25+ public struct StatusPill: View {
26+ let status: String
27+ public init(_ status: String) { self.status = status }
28+ var color: Color {
29+ switch status {
30+ case "published", "introduced": Theme.accent
31+ case "pending", "new": Theme.sealText
32+ case "rejected", "declined", "unpublished": Theme.danger
33+ default: Theme.muted
34+ }
35+ }
36+ public var body: some View {
37+ Text(JobStatus(rawValue: status)?.label ?? status.capitalized)
38+ .font(.caption.weight(.semibold))
39+ .foregroundStyle(color)
40+ .padding(.horizontal, 8).padding(.vertical, 3)
41+ .background(color.opacity(0.12), in: Capsule())
42+ }
43+ }
44+
45+ /// The "Reviewed by a person" seal shown on published jobs.
46+ public struct ReviewedSeal: View {
47+ public init() {}
48+ public var body: some View {
49+ Label("Reviewed by a person", systemImage: "checkmark.seal.fill")
50+ .font(.caption.weight(.semibold))
51+ .foregroundStyle(Theme.sealText)
52+ .symbolRenderingMode(.hierarchical)
53+ }
54+ }
55+
56+ /// One job in a list: title, company, pay, the facts as chips.
57+ public struct JobRow: View {
58+ let job: Job
59+ let labels: Labels
60+ var showStatus = false
61+ var saved = false
62+
63+ public init(job: Job, labels: Labels, showStatus: Bool = false, saved: Bool = false) {
64+ self.job = job; self.labels = labels; self.showStatus = showStatus; self.saved = saved
65+ }
66+
67+ public var body: some View {
68+ VStack(alignment: .leading, spacing: 6) {
69+ HStack(alignment: .firstTextBaseline) {
70+ Text(job.title).font(Theme.display(17)).foregroundStyle(Theme.ink).lineLimit(2)
71+ Spacer(minLength: 8)
72+ if saved { Image(systemName: "bookmark.fill").foregroundStyle(Theme.accent).font(.caption) }
73+ if showStatus, let status = job.status { StatusPill(status) }
74+ }
75+ Text(job.company).font(.subheadline).foregroundStyle(Theme.ink2)
76+ Text(job.pay.text).font(Theme.mono(12)).foregroundStyle(Theme.accent)
77+ HStack(spacing: 6) {
78+ Chip(labels.workplace(job.workplace))
79+ Chip(job.location).lineLimit(1)
80+ Chip(labels.type(job.employmentType))
81+ }
82+ if showStatus {
83+ Text("Posted \(APIDate.short(job.createdAt))").font(.caption2).foregroundStyle(Theme.muted)
84+ }
85+ }
86+ .padding(.vertical, 6)
87+ .accessibilityElement(children: .combine)
88+ }
89+ }
90+
91+ /// The body of a job as people read it: facts, pay, description, links.
92+ public struct JobBody: View {
93+ let job: Job
94+ let labels: Labels
95+ public init(job: Job, labels: Labels) { self.job = job; self.labels = labels }
96+
97+ public var body: some View {
98+ VStack(alignment: .leading, spacing: 14) {
99+ VStack(alignment: .leading, spacing: 6) {
100+ Text(job.title).font(Theme.display(28)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)
101+ HStack(spacing: 6) {
102+ Text(job.company).font(.title3).foregroundStyle(Theme.ink2)
103+ if let link = job.companyURL.flatMap(URL.init(string:)) {
104+ Link(destination: link) { Image(systemName: "arrow.up.right.square") }.foregroundStyle(Theme.accent)
105+ }
106+ }
107+ }
108+ Text(job.pay.text).font(Theme.mono(15).weight(.semibold)).foregroundStyle(Theme.accent)
109+ FlowChips(items: [labels.workplace(job.workplace), job.location, labels.type(job.employmentType), labels.category(job.category)])
110+ if job.status == nil || job.status == "published" {
111+ HStack(spacing: 10) {
112+ ReviewedSeal()
113+ if let published = job.publishedAt { Text("Published \(APIDate.short(published))").font(.caption).foregroundStyle(Theme.muted) }
114+ }
115+ }
116+ Divider()
117+ Text(job.description)
118+ .font(.body).foregroundStyle(Theme.ink)
119+ .lineSpacing(3)
120+ .textSelection(.enabled)
121+ .fixedSize(horizontal: false, vertical: true)
122+ if let apply = job.applyURL.flatMap(URL.init(string:)) {
123+ Link(destination: apply) { Label("The company's own job page", systemImage: "arrow.up.right") }
124+ .font(.subheadline).foregroundStyle(Theme.accent)
125+ }
126+ }
127+ }
128+ }
129+
130+ /// Chips that wrap onto more lines.
131+ public struct FlowChips: View {
132+ let items: [String]
133+ public init(items: [String]) { self.items = items }
134+ public var body: some View {
135+ FlowLayout(spacing: 6) { ForEach(items, id: \.self) { Chip($0) } }
136+ }
137+ }
138+
139+ public struct FlowLayout: Layout {
140+ var spacing: CGFloat
141+ public init(spacing: CGFloat = 6) { self.spacing = spacing }
142+
143+ public func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
144+ let width = proposal.width ?? .infinity
145+ var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, widest: CGFloat = 0
146+ for view in subviews {
147+ let size = view.sizeThatFits(.unspecified)
148+ if x > 0 && x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }
149+ x += size.width + spacing; rowHeight = max(rowHeight, size.height); widest = max(widest, x - spacing)
150+ }
151+ return CGSize(width: min(widest, width), height: y + rowHeight)
152+ }
153+
154+ public func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
155+ var x = bounds.minX, y = bounds.minY, rowHeight: CGFloat = 0
156+ for view in subviews {
157+ let size = view.sizeThatFits(.unspecified)
158+ if x > bounds.minX && x + size.width > bounds.maxX { x = bounds.minX; y += rowHeight + spacing; rowHeight = 0 }
159+ view.place(at: CGPoint(x: x, y: y), proposal: .unspecified)
160+ x += size.width + spacing; rowHeight = max(rowHeight, size.height)
161+ }
162+ }
163+ }
164+
165+ /// A plain message for empty, loading and error states.
166+ public struct StateMessage: View {
167+ let title: String, detail: String, systemImage: String
168+ var retry: (() -> Void)?
169+ public init(_ title: String, detail: String, systemImage: String, retry: (() -> Void)? = nil) {
170+ self.title = title; self.detail = detail; self.systemImage = systemImage; self.retry = retry
171+ }
172+ public var body: some View {
173+ ContentUnavailableView {
174+ Label(title, systemImage: systemImage)
175+ } description: {
176+ Text(detail)
177+ } actions: {
178+ if let retry { Button("Try again", action: retry).buttonStyle(.bordered) }
179+ }
180+ }
181+ }
182+
183+ public struct PrimaryButtonStyle: ButtonStyle {
184+ var role: ButtonRole?
185+ public init(role: ButtonRole? = nil) { self.role = role }
186+ public func makeBody(configuration: Configuration) -> some View {
187+ configuration.label
188+ .font(.body.weight(.semibold))
189+ .foregroundStyle(.white)
190+ .padding(.horizontal, 16).padding(.vertical, 9)
191+ .background(role == .destructive ? Theme.danger : Theme.fill, in: Capsule())
192+ .opacity(configuration.isPressed ? 0.8 : 1)
193+ }
194+ }
195+
196+ public struct SecondaryButtonStyle: ButtonStyle {
197+ public init() {}
198+ public func makeBody(configuration: Configuration) -> some View {
199+ configuration.label
200+ .font(.body.weight(.medium))
201+ .foregroundStyle(Theme.ink)
202+ .padding(.horizontal, 14).padding(.vertical, 8)
203+ .overlay(Capsule().strokeBorder(Theme.line, lineWidth: 1.2))
204+ .contentShape(Capsule())
205+ .opacity(configuration.isPressed ? 0.7 : 1)
206+ }
207+ }
208+
209+ /// Opens a mail draft for the person to read and send (the API sends no email in v1).
210+ public enum MailDraft {
211+ public static func url(to: [String], subject: String, body: String) -> URL? {
212+ var components = URLComponents()
213+ components.scheme = "mailto"
214+ components.path = to.joined(separator: ",")
215+ components.queryItems = [.init(name: "subject", value: subject), .init(name: "body", value: body)]
216+ return components.url
217+ }
218+
219+ public static func sendBack(_ job: Job, reason: String) -> URL? {
220+ guard let contact = job.contact else { return nil }
221+ let body = """
222+ Hi \(contact.name),
223+
224+ Thank you for posting “\(job.title)” on Jobley. We read every post before it goes on the board, and we couldn't publish this one yet:
225+
226+ \(reason)
227+
228+ If you can fix that, post it again at https://jobley.ai/post/ and we'll read it again.
229+
230+ The Jobley team
231+ """
232+ return url(to: [contact.email], subject: "Your Jobley post: \(job.title)", body: body)
233+ }
234+
235+ public static func introduction(candidate: Candidate, job: Job, note: String) -> URL? {
236+ guard let contact = job.contact else { return nil }
237+ let body = """
238+ Hi \(contact.name) and \(candidate.name),
239+
240+ \(note)
241+
242+ \(candidate.name): \(candidate.headline)\(candidate.links.isEmpty ? "" : "\n" + candidate.links.joined(separator: "\n"))\(candidate.resumeURL.map { "\nResume: \($0)" } ?? "")
243+
244+ \(contact.name) is hiring for “\(job.title)” at \(job.company): \(job.url)
245+
246+ We'll leave you both to it.
247+
248+ The Jobley team
249+ """
250+ return url(to: [contact.email, candidate.email], subject: "Introduction: \(candidate.name) for \(job.title)", body: body)
251+ }
252+ }

Sources/JobleyUI/FormViews.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// Search and the three filters, as on jobley.ai/jobs/.
5+ public struct BoardFilters: View {
6+ @ObservedObject var board: BoardModel
7+ public init(board: BoardModel) { self.board = board }
8+
9+ public var body: some View {
10+ HStack(spacing: 8) {
11+ picker("Any workplace", $board.workplace, Meta.workplaceOrder, board.labels.workplace)
12+ picker("Any job type", $board.type, Meta.employmentTypeOrder, board.labels.type)
13+ picker("Any category", $board.category, Meta.categoryOrder, board.labels.category)
14+ }
15+ .onChange(of: board.workplace) { Task { await board.reload() } }
16+ .onChange(of: board.type) { Task { await board.reload() } }
17+ .onChange(of: board.category) { Task { await board.reload() } }
18+ }
19+
20+ func picker(_ any: String, _ value: Binding<String>, _ order: [String], _ label: @escaping (String) -> String) -> some View {
21+ Menu {
22+ Picker(any, selection: value) {
23+ Text(any).tag("")
24+ ForEach(order, id: \.self) { Text(label($0)).tag($0) }
25+ }
26+ .pickerStyle(.inline)
27+ } label: {
28+ HStack(spacing: 4) {
29+ Text(value.wrappedValue.isEmpty ? any : label(value.wrappedValue)).lineLimit(1)
30+ Image(systemName: "chevron.down").font(.caption2)
31+ }
32+ .font(.subheadline)
33+ .foregroundStyle(value.wrappedValue.isEmpty ? Theme.ink2 : Theme.accent)
34+ .padding(.horizontal, 10).padding(.vertical, 6)
35+ .overlay(Capsule().strokeBorder(value.wrappedValue.isEmpty ? Theme.line : Theme.accent))
36+ }
37+ .menuStyle(.button)
38+ .buttonStyle(.plain)
39+ .fixedSize()
40+ }
41+ }
42+
43+ /// "Put me forward": for one job or for a kind of job. A person reads it; no software sorts it.
44+ public struct PutMeForwardForm: View {
45+ let api: APIClient
46+ let job: Job?
47+ var onDone: () -> Void
48+ @State private var draft: CandidateDraft
49+ @State private var sending = false
50+ @State private var error: APIError?
51+ @State private var received: Received?
52+ @StateObject private var gate = TurnstileGate()
53+
54+ public init(api: APIClient, job: Job?, onDone: @escaping () -> Void) {
55+ self.api = api; self.job = job; self.onDone = onDone
56+ _draft = State(initialValue: CandidateDraft(jobID: job?.id))
57+ }
58+
59+ public var body: some View {
60+ if let received {
61+ Confirmation(title: received.already == true ? "You're already on our list." : "Thank you. A person will read it.",
62+ detail: job.map { "If you're a good fit for “\($0.title)”, we'll introduce you to the people hiring by email." }
63+ ?? "When a good job comes in that fits, we'll introduce you by email.",
64+ done: onDone)
65+ } else {
66+ Form {
67+ if let job {
68+ Section { JobRow(job: job, labels: Labels()) } header: { Text("For this job") }
69+ }
70+ Section {
71+ field("Your name", $draft.name, "name")
72+ field("Email", $draft.email, "email")
73+ field("Headline, e.g. “Support engineer, six years”", $draft.headline, "headline")
74+ field("Where you are (optional)", $draft.location, "location")
75+ } header: { Text("About you") } footer: { Text("Private. Only the people hiring see it, and only when we introduce you.") }
76+ if job == nil {
77+ Section("What you're looking for") {
78+ TextField("The kind of job, place and hours", text: $draft.lookingFor, axis: .vertical).lineLimit(2...5)
79+ errorText("looking_for")
80+ }
81+ }
82+ Section {
83+ TextField("A few lines about your work (optional)", text: $draft.about, axis: .vertical).lineLimit(3...8)
84+ TextField("Links to your work, one per line (optional)", text: $draft.links, axis: .vertical).lineLimit(1...5)
85+ .autocorrectionDisabled()
86+ field("Link to your resume (optional)", $draft.resumeURL, "resume_url")
87+ } header: { Text("Your work") }
88+ Section {
89+ Toggle("I agree that Jobley may share these details with the people hiring when a person introduces me.", isOn: $draft.consent)
90+ errorText("consent")
91+ if TurnstileGate.isNeeded(for: api.base) {
92+ TurnstileView(page: api.turnstilePage, onResult: gate.receive).id(gate.generation)
93+ Text(gate.statusText).font(.caption).foregroundStyle(Theme.muted)
94+ }
95+ if let error { Text(error.message).foregroundStyle(Theme.danger).font(.callout) }
96+ Button {
97+ Task { await send() }
98+ } label: {
99+ Text(sending ? "Sending…" : "Put me forward").frame(maxWidth: .infinity)
100+ }
101+ .buttonStyle(PrimaryButtonStyle())
102+ .disabled(sending || !draft.consent || (TurnstileGate.isNeeded(for: api.base) && !gate.isReady))
103+ .accessibilityIdentifier("putMeForwardSend")
104+ } footer: { Text("A person reads every one. Nothing ranks, scores or filters you.") }
105+ }
106+ .formStyle(.grouped)
107+ }
108+ }
109+
110+ func field(_ title: String, _ text: Binding<String>, _ key: String) -> some View {
111+ VStack(alignment: .leading, spacing: 2) {
112+ TextField(title, text: text)
113+ .autocorrectionDisabled(key == "email" || key == "resume_url")
114+ #if os(iOS)
115+ .textInputAutocapitalization(key == "email" || key == "resume_url" ? .never : .words)
116+ .keyboardType(key == "email" ? .emailAddress : key == "resume_url" ? .URL : .default)
117+ #endif
118+ errorText(key)
119+ }
120+ }
121+
122+ @ViewBuilder func errorText(_ key: String) -> some View {
123+ if let message = error?.fields[key] { Text(message).font(.caption).foregroundStyle(Theme.danger) }
124+ }
125+
126+ func send() async {
127+ sending = true; error = nil
128+ defer { sending = false }
129+ do {
130+ received = try await api.putForward(draft, turnstileToken: gate.token)
131+ } catch let failure as APIError {
132+ error = failure
133+ gate.reset()
134+ } catch {}
135+ }
136+ }
137+
138+ /// "Post a job": one form, no account. It waits for a person to read it.
139+ public struct PostJobForm: View {
140+ let api: APIClient
141+ var onDone: () -> Void
142+ @State private var draft = JobDraft()
143+ @State private var sending = false
144+ @State private var error: APIError?
145+ @State private var posted: PostedJob?
146+ @StateObject private var gate = TurnstileGate()
147+ let labels = Labels()
148+
149+ public init(api: APIClient, onDone: @escaping () -> Void) { self.api = api; self.onDone = onDone }
150+
151+ public var body: some View {
152+ if let posted {
153+ VStack(alignment: .leading, spacing: 16) {
154+ Confirmation(title: "Thank you. Your post is waiting for a person.",
155+ detail: "\(HouseRules.guarantee) It's in the review queue as \(posted.id). If it's a good job it will appear on the board. If not, we'll write to you with the reason.",
156+ done: onDone)
157+ VStack(alignment: .leading, spacing: 6) {
158+ Text("Keep this. It's the only way to take the job down yourself when it's filled. We can't show it again.")
159+ .font(.callout).foregroundStyle(Theme.ink2)
160+ Text(posted.manageToken).font(Theme.mono(12)).textSelection(.enabled)
161+ .padding(10).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8))
162+ Button("Copy the id and token") { Clipboard.copy("\(posted.id)\n\(posted.manageToken)") }
163+ }
164+ .padding(.horizontal, 24)
165+ }
166+ } else {
167+ Form {
168+ Section("The job") {
169+ field("Job title", $draft.title, "title")
170+ field("Company", $draft.company, "company")
171+ field("Company website (optional)", $draft.companyURL, "company_url")
172+ choice("Workplace", $draft.workplace, Meta.workplaceOrder, labels.workplace, "workplace")
173+ choice("Job type", $draft.employmentType, Meta.employmentTypeOrder, labels.type, "employment_type")
174+ choice("Category", $draft.category, Meta.categoryOrder, labels.category, "category")
175+ field("Location", $draft.location, "location")
176+ }
177+ Section {
178+ field("Lowest, such as 100", $draft.payMin, "pay_min")
179+ field("Highest, such as 140", $draft.payMax, "pay_max")
180+ Picker("Per", selection: $draft.payPeriod) { ForEach(Meta.payPeriodOrder, id: \.self) { Text($0).tag($0) } }
181+ field("Currency", $draft.payCurrency, "pay_currency")
182+ } header: { Text("Pay") } footer: { Text("We publish jobs that pay \(HouseRules.payFloorShort) (or the same in local currency), by the hour or salaried, full or part time, with or without benefits. Give a lowest and a highest figure.") }
183+ Section("Description") {
184+ TextField("What the person would do, with whom, where and when", text: $draft.description, axis: .vertical).lineLimit(5...14)
185+ errorText("description")
186+ field("Your own job page (optional)", $draft.applyURL, "apply_url")
187+ }
188+ Section {
189+ field("Your name", $draft.contactName, "contact_name")
190+ field("Your email", $draft.contactEmail, "contact_email")
191+ } header: { Text("You") } footer: { Text("Private. We use it to reach you about this post and to introduce candidates.") }
192+ Section {
193+ if TurnstileGate.isNeeded(for: api.base) {
194+ TurnstileView(page: api.turnstilePage, onResult: gate.receive).id(gate.generation)
195+ Text(gate.statusText).font(.caption).foregroundStyle(Theme.muted)
196+ }
197+ if let error { Text(error.message).foregroundStyle(Theme.danger).font(.callout) }
198+ Button { Task { await send() } } label: {
199+ Text(sending ? "Sending…" : "Send for review").frame(maxWidth: .infinity)
200+ }
201+ .buttonStyle(PrimaryButtonStyle())
202+ .disabled(sending || (TurnstileGate.isNeeded(for: api.base) && !gate.isReady))
203+ } footer: { Text("Free. No account. \(HouseRules.guarantee)") }
204+ }
205+ .formStyle(.grouped)
206+ }
207+ }
208+
209+ func field(_ title: String, _ text: Binding<String>, _ key: String) -> some View {
210+ VStack(alignment: .leading, spacing: 2) {
211+ TextField(title, text: text)
212+ .autocorrectionDisabled(key.contains("url") || key.contains("email"))
213+ #if os(iOS)
214+ .textInputAutocapitalization(key.contains("url") || key.contains("email") ? .never : .sentences)
215+ .keyboardType(key.hasPrefix("pay_m") ? .numberPad : key.contains("email") ? .emailAddress : key.contains("url") ? .URL : .default)
216+ #endif
217+ errorText(key)
218+ }
219+ }
220+
221+ func choice(_ title: String, _ value: Binding<String>, _ order: [String], _ label: @escaping (String) -> String, _ key: String) -> some View {
222+ VStack(alignment: .leading, spacing: 2) {
223+ Picker(title, selection: value) {
224+ Text("Choose…").tag("")
225+ ForEach(order, id: \.self) { Text(label($0)).tag($0) }
226+ }
227+ errorText(key)
228+ }
229+ }
230+
231+ @ViewBuilder func errorText(_ key: String) -> some View {
232+ if let message = error?.fields[key] { Text(message).font(.caption).foregroundStyle(Theme.danger) }
233+ }
234+
235+ func send() async {
236+ sending = true; error = nil
237+ defer { sending = false }
238+ if HouseRules.belowPayFloor(min: Int(draft.payMin.filter(\.isNumber)), period: draft.payPeriod, currency: draft.payCurrency) {
239+ error = APIError(code: "invalid", message: "Please fix the marked fields.", fields: ["pay_min": HouseRules.payFloorMessage])
240+ return
241+ }
242+ do { posted = try await api.post(draft, turnstileToken: gate.token) }
243+ catch let failure as APIError { error = failure; gate.reset() }
244+ catch {}
245+ }
246+ }
247+
248+ struct Confirmation: View {
249+ let title: String, detail: String
250+ let done: () -> Void
251+ var body: some View {
252+ VStack(alignment: .leading, spacing: 12) {
253+ Image(systemName: "checkmark.seal.fill").font(.system(size: 40)).foregroundStyle(Theme.seal)
254+ Text(title).font(Theme.display(26)).foregroundStyle(Theme.ink)
255+ Text(detail).foregroundStyle(Theme.ink2)
256+ Button("Done", action: done).buttonStyle(PrimaryButtonStyle())
257+ }
258+ .padding(24)
259+ .frame(maxWidth: .infinity, alignment: .leading)
260+ }
261+ }
262+
263+ public enum Clipboard {
264+ public static func copy(_ text: String) {
265+ #if os(macOS)
266+ NSPasteboard.general.clearContents()
267+ NSPasteboard.general.setString(text, forType: .string)
268+ #else
269+ UIPasteboard.general.string = text
270+ #endif
271+ }
272+ }

Sources/JobleyUI/Models.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// The public board: search, filters and "load more", exactly as jobley.ai/jobs/ shows it.
5+ @MainActor
6+ public final class BoardModel: ObservableObject {
7+ @Published public var query = ""
8+ @Published public var workplace = ""
9+ @Published public var type = ""
10+ @Published public var category = ""
11+ @Published public private(set) var jobs: [Job] = []
12+ @Published public private(set) var nextCursor: String?
13+ @Published public private(set) var loading = false
14+ @Published public private(set) var error: String?
15+ @Published public private(set) var labels = Labels()
16+
17+ public private(set) var api: APIClient
18+
19+ public init(api: APIClient) { self.api = api }
20+
21+ public var hasFilters: Bool { !query.isEmpty || !workplace.isEmpty || !type.isEmpty || !category.isEmpty }
22+
23+ public func loadMeta() async {
24+ if let meta = try? await api.meta() { labels = Labels(meta) }
25+ }
26+
27+ public func reload() async {
28+ loading = true; error = nil
29+ defer { loading = false }
30+ do {
31+ let page = try await api.jobs(query: query, workplace: workplace, type: type, category: category)
32+ jobs = page.jobs; nextCursor = page.nextCursor
33+ } catch {
34+ self.error = error.localizedDescription
35+ }
36+ }
37+
38+ public func loadMore() async {
39+ guard let cursor = nextCursor, !loading else { return }
40+ loading = true
41+ defer { loading = false }
42+ do {
43+ let page = try await api.jobs(query: query, workplace: workplace, type: type, category: category, cursor: cursor)
44+ jobs += page.jobs; nextCursor = page.nextCursor
45+ } catch {
46+ self.error = error.localizedDescription
47+ }
48+ }
49+
50+ public func clearFilters() { query = ""; workplace = ""; type = ""; category = "" }
51+ }
52+
53+ /// Jobs saved on this device (iPhone). Kept as the job itself so the list works offline.
54+ @MainActor
55+ public final class SavedJobs: ObservableObject {
56+ static let key = "jobley.savedJobs"
57+ @Published public private(set) var jobs: [Job]
58+ let defaults: UserDefaults
59+
60+ public init(defaults: UserDefaults = .standard) {
61+ self.defaults = defaults
62+ jobs = (defaults.data(forKey: Self.key)).flatMap { try? JSONDecoder().decode([Job].self, from: $0) } ?? []
63+ }
64+
65+ public func contains(_ job: Job) -> Bool { jobs.contains { $0.id == job.id } }
66+
67+ public func toggle(_ job: Job) {
68+ if contains(job) { jobs.removeAll { $0.id == job.id } }
69+ else { jobs.insert(job, at: 0) }
70+ defaults.set(try? JSONEncoder().encode(jobs), forKey: Self.key)
71+ }
72+ }
73+
74+ /// The review queue and everything a curator or moderator does, for both apps.
75+ /// People decide here. Lists are oldest first and are never sorted by anything but time.
76+ @MainActor
77+ public final class CuratorModel: ObservableObject {
78+ public enum Queue: String, CaseIterable, Identifiable, Sendable {
79+ case pending, approved, published, rejected, unpublished
80+ public var id: Self { self }
81+ public var title: String {
82+ switch self {
83+ case .pending: "Review queue"
84+ case .approved: "Approved"
85+ case .published: "Published"
86+ case .rejected: "Sent back"
87+ case .unpublished: "Unpublished"
88+ }
89+ }
90+ public var systemImage: String {
91+ switch self {
92+ case .pending: "tray.full"
93+ case .approved: "checkmark.circle"
94+ case .published: "megaphone"
95+ case .rejected: "arrow.uturn.backward.circle"
96+ case .unpublished: "eye.slash"
97+ }
98+ }
99+ }
100+
101+ @Published public private(set) var me: Me?
102+ @Published public private(set) var stats: Stats?
103+ @Published public private(set) var lists: [Queue: [Job]] = [:]
104+ @Published public private(set) var item: JobReviewItem?
105+ @Published public var error: String?
106+ @Published public private(set) var busy = false
107+ @Published public private(set) var signingIn = false
108+ /// The signed-in person's passkeys (Settings shows them; a second one is the way to recover).
109+ @Published public private(set) var passkeys: [Passkey] = []
110+
111+ public private(set) var api: APIClient
112+ let saveToken: (String?) throws -> Void
113+ private let authorizer = PasskeyAuthorizer()
114+
115+ public init(api: APIClient, saveToken: @escaping (String?) throws -> Void = { token in
116+ if let token { try TokenStore.save(token) } else { TokenStore.remove() }
117+ }) {
118+ self.api = api
119+ self.saveToken = saveToken
120+ }
121+
122+ public var isSignedIn: Bool { me != nil }
123+ public var canSeeCandidates: Bool { me?.isCurator == true || me?.canSeeCandidates == true }
124+ public func jobs(_ queue: Queue) -> [Job] { lists[queue] ?? [] }
125+
126+ /// Checks the saved sign-in. Called at launch.
127+ public func start() async {
128+ guard api.hasToken else { return }
129+ do { me = try await api.me(); await refreshAll() }
130+ catch let error as APIError where error.code == "unauthorized" {
131+ try? saveToken(nil); api = api.withToken(nil); me = nil
132+ self.error = "You've been signed out. Sign in with your passkey."
133+ }
134+ catch { self.error = error.localizedDescription }
135+ }
136+
137+ /// Signs in with a passkey the person already has.
138+ @discardableResult
139+ public func signInWithPasskey() async -> Bool {
140+ await passkeyStep {
141+ let challenge = try await self.api.passkeySignInOptions()
142+ let assertion = try await self.authorizer.signIn(challenge)
143+ return try await self.api.signIn(challengeID: challenge.challengeID, assertion: assertion)
144+ }
145+ }
146+
147+ /// Adds a first passkey with a one-time setup link (from the curator, or the setup endpoint),
148+ /// then signs in with it.
149+ @discardableResult
150+ public func addFirstPasskey(setupLink: String) async -> Bool {
151+ guard let code = PasskeyResponse.setupCode(from: setupLink) else { error = PasskeyError.badLink.localizedDescription; return false }
152+ return await passkeyStep {
153+ let challenge = try await self.api.passkeyOptions(setupCode: code)
154+ let registration = try await self.authorizer.register(challenge)
155+ return try await self.api.addPasskey(challengeID: challenge.challengeID, registration: registration, name: PasskeyAuthorizer.deviceName)
156+ }
157+ }
158+
159+ /// Adds another passkey while signed in. A second passkey is how a person recovers.
160+ public func addAnotherPasskey() async {
161+ signingIn = true
162+ defer { signingIn = false }
163+ do {
164+ let challenge = try await api.anotherPasskeyOptions()
165+ let registration = try await authorizer.register(challenge)
166+ try await api.addAnotherPasskey(challengeID: challenge.challengeID, registration: registration, name: PasskeyAuthorizer.deviceName)
167+ error = nil
168+ await loadPasskeys()
169+ } catch PasskeyError.cancelled {
170+ } catch { report(error) }
171+ }
172+
173+ public func loadPasskeys() async {
174+ do { passkeys = try await api.passkeys() } catch { report(error) }
175+ }
176+
177+ /// The server keeps the last passkey; Settings only offers Remove when there are two or more.
178+ public func removePasskey(_ passkey: Passkey) async {
179+ do { try await api.removePasskey(passkey.id); await loadPasskeys() } catch { report(error) }
180+ }
181+
182+ public func signOut() {
183+ let ending = api
184+ Task { try? await ending.signOut() }
185+ try? saveToken(nil)
186+ api = api.withToken(nil); me = nil; stats = nil; lists = [:]; item = nil; passkeys = []
187+ }
188+
189+ private func passkeyStep(_ work: @escaping () async throws -> PasskeySession) async -> Bool {
190+ signingIn = true
191+ defer { signingIn = false }
192+ do {
193+ let session = try await work()
194+ let signedIn = api.withToken(session.token)
195+ let who = try await signedIn.me()
196+ try saveToken(session.token)
197+ api = signedIn; me = who; error = nil
198+ await refreshAll()
199+ await loadPasskeys()
200+ return true
201+ } catch PasskeyError.cancelled {
202+ return false
203+ } catch {
204+ report(error)
205+ return false
206+ }
207+ }
208+
209+ public func refreshAll() async {
210+ await refreshStats()
211+ for queue in Queue.allCases { await load(queue) }
212+ }
213+
214+ public func refreshStats() async {
215+ do { stats = try await api.stats() } catch { report(error) }
216+ }
217+
218+ public func load(_ queue: Queue) async {
219+ do { lists[queue] = try await api.adminJobs(status: queue.rawValue) } catch { report(error) }
220+ }
221+
222+ public func open(_ id: String?) async {
223+ guard let id else { item = nil; return }
224+ if item?.job.id != id { item = nil }
225+ do { item = try await api.reviewItem(id) } catch { report(error) }
226+ }
227+
228+ // MARK: Decisions (people only)
229+
230+ /// The normal one-step Publish: approve and publish.
231+ public func publishNow(_ job: Job) async -> Bool {
232+ await decide(job) { try await self.api.approve(job: job.id, publish: true) }
233+ }
234+ public func approveOnly(_ job: Job) async -> Bool {
235+ await decide(job) { try await self.api.approve(job: job.id, publish: false) }
236+ }
237+ public func publish(_ job: Job) async -> Bool {
238+ await decide(job) { try await self.api.publish(job: job.id) }
239+ }
240+ public func sendBack(_ job: Job, reason: String) async -> Bool {
241+ await decide(job) { try await self.api.reject(job: job.id, reason: reason) }
242+ }
243+ public func unpublish(_ job: Job, reason: String) async -> Bool {
244+ await decide(job) { try await self.api.unpublish(job: job.id, reason: reason) }
245+ }
246+
247+ public func save(_ job: Job, edit: JobEdit) async -> Bool {
248+ let changes = edit.changes(from: job)
249+ guard !changes.isEmpty else { return true }
250+ return await decide(job) { try await self.api.edit(job: job.id, changes: changes) }
251+ }
252+
253+ public func addNote(_ job: Job, note: String) async -> Bool {
254+ let text = note.trimmingCharacters(in: .whitespacesAndNewlines)
255+ guard !text.isEmpty else { return false }
256+ busy = true
257+ defer { busy = false }
258+ do {
259+ try await api.addNote(job: job.id, note: text)
260+ await open(job.id)
261+ return true
262+ } catch { report(error); return false }
263+ }
264+
265+ private func decide(_ job: Job, _ work: @escaping () async throws -> Job) async -> Bool {
266+ busy = true
267+ defer { busy = false }
268+ do {
269+ _ = try await work()
270+ await refreshAll()
271+ await open(job.id)
272+ return true
273+ } catch { report(error); return false }
274+ }
275+
276+ func report(_ error: Error) {
277+ self.error = error.localizedDescription
278+ }
279+ }
280+
281+ /// Candidates and introductions (the curator, or moderators the curator switched on).
282+ @MainActor
283+ public final class CandidatesModel: ObservableObject {
284+ public enum Scope: Hashable, Sendable { case everyone, anyJob, job(String) }
285+
286+ @Published public var scope: Scope = .everyone
287+ @Published public var status = ""
288+ @Published public private(set) var candidates: [Candidate] = []
289+ @Published public private(set) var detail: CandidateDetail?
290+ @Published public var error: String?
291+
292+ let api: () -> APIClient
293+ public init(api: @escaping () -> APIClient) { self.api = api }
294+
295+ public func reload() async {
296+ let jobID: String? = switch scope { case .everyone: nil; case .anyJob: "none"; case .job(let id): id }
297+ do { candidates = try await api().candidates(jobID: jobID, status: status.isEmpty ? nil : status) }
298+ catch { self.error = error.localizedDescription }
299+ }
300+
301+ public func open(_ id: String?) async {
302+ guard let id else { detail = nil; return }
303+ do { detail = try await api().candidate(id) } catch { self.error = error.localizedDescription }
304+ }
305+
306+ public func setStatus(_ candidate: Candidate, _ status: String) async {
307+ do { _ = try await api().setStatus(candidate: candidate.id, status: status); await reload(); await open(candidate.id) }
308+ catch { self.error = error.localizedDescription }
309+ }
310+
311+ /// Records an introduction a person made (the email itself goes from their own mail app).
312+ public func introduce(_ candidate: Candidate, jobID: String, note: String) async -> Bool {
313+ do {
314+ _ = try await api().introduce(candidate: candidate.id, jobID: jobID, note: note)
315+ await reload(); await open(candidate.id)
316+ return true
317+ } catch { self.error = error.localizedDescription; return false }
318+ }
319+ }
320+
321+ /// Moderator applications and moderators (curator only).
322+ @MainActor
323+ public final class ModeratorsModel: ObservableObject {
324+ @Published public private(set) var applications: [ModeratorApplication] = []
325+ @Published public private(set) var moderators: [Moderator] = []
326+ /// Shown once, right after approving (or making a new link), with a Copy button.
327+ @Published public var newSetupLink: ModeratorSetupLink?
328+ @Published public var error: String?
329+
330+ let api: () -> APIClient
331+ public init(api: @escaping () -> APIClient) { self.api = api }
332+
333+ public func reload() async {
334+ do {
335+ applications = try await api().moderatorApplications()
336+ moderators = try await api().moderators()
337+ } catch { self.error = error.localizedDescription }
338+ }
339+
340+ public func approve(_ application: ModeratorApplication, canSeeCandidates: Bool) async {
341+ do {
342+ let made = try await api().approve(application: application.id, canSeeCandidates: canSeeCandidates)
343+ newSetupLink = ModeratorSetupLink(id: made.moderator.id, name: made.moderator.name, link: made.setup)
344+ await reload()
345+ } catch { self.error = error.localizedDescription }
346+ }
347+
348+ /// A new one-time setup link, for a moderator adding their first passkey or one who lost theirs.
349+ public func makeSetupLink(_ moderator: Moderator) async {
350+ do { newSetupLink = ModeratorSetupLink(id: moderator.id, name: moderator.name, link: try await api().setupLink(moderator: moderator.id)) }
351+ catch { self.error = error.localizedDescription }
352+ }
353+
354+ public func decline(_ application: ModeratorApplication) async {
355+ do { try await api().decline(application: application.id); await reload() } catch { self.error = error.localizedDescription }
356+ }
357+
358+ public func setAccess(_ moderator: Moderator, _ value: Bool) async {
359+ do { try await api().setAccess(moderator: moderator.id, canSeeCandidates: value); await reload() }
360+ catch { self.error = error.localizedDescription }
361+ }
362+
363+ public func revoke(_ moderator: Moderator) async {
364+ do { try await api().revoke(moderator: moderator.id); await reload() } catch { self.error = error.localizedDescription }
365+ }
366+ }
367+
368+ /// A moderator's one-time passkey setup link, shown once to the curator to hand on.
369+ public struct ModeratorSetupLink: Identifiable, Sendable {
370+ public var id: String
371+ public var name: String
372+ public var link: SetupLink
373+ }

Sources/JobleyUI/PasskeyAuthorizer.swift added

1+ import AuthenticationServices
2+ import JobleyKit
3+ #if os(macOS)
4+ import AppKit
5+ #else
6+ import UIKit
7+ #endif
8+
9+ /// Asks the system for a passkey: sign in with one (assertion) or make a new one (registration).
10+ /// The apps' `webcredentials:jobley.ai` associated domain lets them use jobley.ai passkeys.
11+ @MainActor
12+ final class PasskeyAuthorizer: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
13+ private var continuation: CheckedContinuation<ASAuthorization, Error>?
14+ private var controller: ASAuthorizationController?
15+
16+ /// The WebAuthn assertion JSON for `challenge`, from a passkey the person picks.
17+ func signIn(_ challenge: PasskeyChallenge) async throws -> [String: Any] {
18+ guard let bytes = challenge.challenge else { throw PasskeyError.badReply }
19+ let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty)
20+ let request = provider.createCredentialAssertionRequest(challenge: bytes)
21+ request.userVerificationPreference = .required
22+ let authorization = try await perform(request)
23+ guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.badReply }
24+ return PasskeyResponse.assertion(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON,
25+ authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, userID: credential.userID)
26+ }
27+
28+ /// The WebAuthn registration JSON for `challenge`: a new passkey for the person it names.
29+ func register(_ challenge: PasskeyChallenge) async throws -> [String: Any] {
30+ guard let bytes = challenge.challenge, let userID = challenge.userID, let user = challenge.options.user else { throw PasskeyError.badReply }
31+ let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: challenge.relyingParty)
32+ let request = provider.createCredentialRegistrationRequest(challenge: bytes, name: user.name, userID: userID)
33+ request.userVerificationPreference = .required
34+ request.excludedCredentials = challenge.excludedCredentialIDs.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }
35+ let authorization = try await perform(request)
36+ guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration,
37+ let attestation = credential.rawAttestationObject else { throw PasskeyError.badReply }
38+ return PasskeyResponse.registration(credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, attestationObject: attestation)
39+ }
40+
41+ private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {
42+ try await withCheckedThrowingContinuation { continuation in
43+ self.continuation = continuation
44+ let controller = ASAuthorizationController(authorizationRequests: [request])
45+ controller.delegate = self
46+ controller.presentationContextProvider = self
47+ self.controller = controller
48+ controller.performRequests()
49+ }
50+ }
51+
52+ nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
53+ MainActor.assumeIsolated { finish(.success(authorization)) }
54+ }
55+
56+ nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
57+ MainActor.assumeIsolated {
58+ let cancelled = (error as? ASAuthorizationError)?.code == .canceled
59+ finish(.failure(cancelled ? PasskeyError.cancelled : error))
60+ }
61+ }
62+
63+ private func finish(_ result: Result<ASAuthorization, Error>) {
64+ continuation?.resume(with: result)
65+ continuation = nil
66+ controller = nil
67+ }
68+
69+ nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
70+ MainActor.assumeIsolated {
71+ #if os(macOS)
72+ return NSApplication.shared.keyWindow ?? NSApplication.shared.windows.first ?? ASPresentationAnchor()
73+ #else
74+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
75+ return scenes.flatMap(\.windows).first(where: \.isKeyWindow) ?? scenes.first?.windows.first ?? ASPresentationAnchor()
76+ #endif
77+ }
78+ }
79+
80+ /// What this device is called, so a person can tell their passkeys apart.
81+ static var deviceName: String {
82+ #if os(macOS)
83+ return Host.current().localizedName ?? "Mac"
84+ #else
85+ return UIDevice.current.name
86+ #endif
87+ }
88+ }
89+
90+ enum PasskeyError: Error, LocalizedError {
91+ case cancelled, badReply, badLink
92+
93+ var errorDescription: String? {
94+ switch self {
95+ case .cancelled: "Passkey sign-in was cancelled."
96+ case .badReply: "The passkey reply couldn't be read. Please try again."
97+ case .badLink: "That doesn't look like a Jobley setup link. Paste the whole link you were given."
98+ }
99+ }
100+ }

Sources/JobleyUI/PasskeyViews.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// Signing in, for the curator and moderators: a passkey, nothing else. A first passkey is added
5+ /// with the one-time setup link the curator (or, for the curator, the setup endpoint) gives you.
6+ public struct PasskeySignIn: View {
7+ @ObservedObject var curator: CuratorModel
8+ @State private var setupLink = ""
9+
10+ public init(curator: CuratorModel) { self.curator = curator }
11+
12+ public var body: some View {
13+ VStack(alignment: .leading, spacing: 12) {
14+ Button {
15+ Task { await curator.signInWithPasskey() }
16+ } label: {
17+ Label(curator.signingIn ? "Waiting for your passkey…" : "Sign in with passkey", systemImage: "person.badge.key")
18+ }
19+ .buttonStyle(PrimaryButtonStyle())
20+ .disabled(curator.signingIn)
21+
22+ Divider().padding(.vertical, 4)
23+ Text("First time? Paste the setup link you were given, then add a passkey on this device.")
24+ .font(.callout).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)
25+ TextField("Setup link", text: $setupLink, prompt: Text("https://jobley.ai/passkey/#…"))
26+ .textFieldStyle(.roundedBorder)
27+ .autocorrectionDisabled()
28+ #if os(iOS)
29+ .textInputAutocapitalization(.never)
30+ .keyboardType(.URL)
31+ #endif
32+ Button("Add a passkey") { Task { if await curator.addFirstPasskey(setupLink: setupLink) { setupLink = "" } } }
33+ .disabled(setupLink.isEmpty || curator.signingIn)
34+
35+ if let error = curator.error { Text(error).font(.caption).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true) }
36+ }
37+ }
38+ }
39+
40+ /// The signed-in person's passkeys: add another (the way to recover) and remove any but the last.
41+ public struct PasskeyList: View {
42+ @ObservedObject var curator: CuratorModel
43+
44+ public init(curator: CuratorModel) { self.curator = curator }
45+
46+ public var body: some View {
47+ Group {
48+ ForEach(curator.passkeys) { passkey in
49+ HStack {
50+ VStack(alignment: .leading, spacing: 2) {
51+ Text(passkey.name ?? "Passkey")
52+ Text(passkey.lastUsedAt.map { "Last used \(APIDate.short($0))" } ?? "Added \(APIDate.short(passkey.createdAt))")
53+ .font(.caption).foregroundStyle(.secondary)
54+ }
55+ Spacer()
56+ if curator.passkeys.count > 1 {
57+ Button("Remove", role: .destructive) { Task { await curator.removePasskey(passkey) } }
58+ }
59+ }
60+ }
61+ Button {
62+ Task { await curator.addAnotherPasskey() }
63+ } label: {
64+ Label(curator.signingIn ? "Waiting for your passkey…" : "Add a passkey", systemImage: "plus")
65+ }
66+ .disabled(curator.signingIn)
67+ if let error = curator.error { Text(error).font(.caption).foregroundStyle(Theme.danger) }
68+ }
69+ .task { await curator.loadPasskeys() }
70+ }
71+ }

Sources/JobleyUI/ReviewViews.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// One post under review: the post in full, the rules as a checklist ticked by hand, the decisions,
5+ /// notes and history. Used by the Mac desk and the iPhone Review tab.
6+ public struct ReviewDetail: View {
7+ @ObservedObject var model: CuratorModel
8+ let item: JobReviewItem
9+ let labels: Labels
10+ var allowsEdit = true
11+
12+ @State private var ticked: Set<String> = []
13+ @State private var sheet: Sheet?
14+ @State private var note = ""
15+ @Environment(\.openURL) private var openURL
16+
17+ enum Sheet: String, Identifiable { case sendBack, unpublish, edit; var id: String { rawValue } }
18+
19+ public init(model: CuratorModel, item: JobReviewItem, labels: Labels, allowsEdit: Bool = true) {
20+ self.model = model; self.item = item; self.labels = labels; self.allowsEdit = allowsEdit
21+ }
22+
23+ var job: Job { item.job }
24+ var status: String { job.status ?? "pending" }
25+
26+ public var body: some View {
27+ ScrollView {
28+ VStack(alignment: .leading, spacing: 22) {
29+ HStack {
30+ StatusPill(status)
31+ Text("Posted \(APIDate.full(job.createdAt))").font(.caption).foregroundStyle(Theme.muted)
32+ Spacer()
33+ if item.candidateCount > 0 {
34+ Label("\(item.candidateCount) asked to be put forward", systemImage: "person.2").font(.caption).foregroundStyle(Theme.ink2)
35+ }
36+ }
37+ actions
38+ if let reason = job.review?.reason, status == "rejected" || status == "unpublished" {
39+ Label("Reason: \(reason)", systemImage: "text.quote").font(.callout).foregroundStyle(Theme.danger)
40+ }
41+ JobBody(job: job, labels: labels)
42+ if let contact = job.contact {
43+ GroupBox {
44+ VStack(alignment: .leading, spacing: 4) {
45+ Text(contact.name).font(.body.weight(.semibold))
46+ Text(contact.email).font(.callout).textSelection(.enabled).foregroundStyle(Theme.ink2)
47+ }.frame(maxWidth: .infinity, alignment: .leading)
48+ } label: {
49+ Label("Poster (private, never shown on the site)", systemImage: "lock").font(.caption.weight(.semibold)).foregroundStyle(Theme.muted)
50+ }
51+ }
52+ rules
53+ notes
54+ history
55+ }
56+ .padding(24)
57+ .frame(maxWidth: 760, alignment: .leading)
58+ .frame(maxWidth: .infinity, alignment: .leading)
59+ }
60+ .background(Theme.background)
61+ .disabled(model.busy)
62+ .sheet(item: $sheet) { which in
63+ switch which {
64+ case .sendBack:
65+ ReasonSheet(title: "Send back “\(job.title)”", detail: "Say which rule it misses, in plain words. We'll open a mail draft to the poster with it; you send it.",
66+ action: "Send back", required: true) { reason in
67+ if await model.sendBack(job, reason: reason) {
68+ if let mail = MailDraft.sendBack(job, reason: reason) { openURL(mail) }
69+ return true
70+ }
71+ return false
72+ }
73+ case .unpublish:
74+ ReasonSheet(title: "Unpublish “\(job.title)”", detail: "It comes off the board now. A reason helps the next person who reads it.",
75+ action: "Unpublish", required: false) { reason in await model.unpublish(job, reason: reason) }
76+ case .edit:
77+ EditJobSheet(job: job, labels: labels) { edit in await model.save(job, edit: edit) }
78+ }
79+ }
80+ }
81+
82+ @ViewBuilder var actions: some View {
83+ FlowLayout(spacing: 10) {
84+ switch status {
85+ case "pending", "rejected":
86+ Button { Task { _ = await model.publishNow(job) } } label: { Label("Publish", systemImage: "checkmark.seal") }
87+ .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("reviewPublish")
88+ if status == "pending" {
89+ Button { sheet = .sendBack } label: { Label("Send back", systemImage: "arrow.uturn.backward") }
90+ .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("reviewSendBack")
91+ }
92+ Button { Task { _ = await model.approveOnly(job) } } label: { Text("Approve, publish later") }
93+ .buttonStyle(SecondaryButtonStyle())
94+ case "approved":
95+ Button { Task { _ = await model.publish(job) } } label: { Label("Publish", systemImage: "megaphone") }
96+ .buttonStyle(PrimaryButtonStyle())
97+ Button { sheet = .sendBack } label: { Label("Send back", systemImage: "arrow.uturn.backward") }
98+ .buttonStyle(SecondaryButtonStyle())
99+ case "published":
100+ Button { sheet = .unpublish } label: { Label("Unpublish", systemImage: "eye.slash") }
101+ .buttonStyle(SecondaryButtonStyle())
102+ Link(destination: URL(string: job.url) ?? AppLinks.website) { Label("Open on the site", systemImage: "safari") }
103+ .buttonStyle(SecondaryButtonStyle())
104+ case "unpublished":
105+ Button { Task { _ = await model.publish(job) } } label: { Label("Publish again", systemImage: "megaphone") }
106+ .buttonStyle(PrimaryButtonStyle())
107+ default:
108+ EmptyView()
109+ }
110+ if allowsEdit && status != "closed" {
111+ Button { sheet = .edit } label: { Label("Edit wording", systemImage: "pencil") }
112+ .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("reviewEdit")
113+ }
114+ }
115+ }
116+
117+ var rules: some View {
118+ VStack(alignment: .leading, spacing: 10) {
119+ HStack {
120+ Text("The rules").font(Theme.display(19)).foregroundStyle(Theme.ink)
121+ Spacer()
122+ Text("\(ticked.count) of \(HouseRules.all.count) ticked").font(Theme.mono(11)).foregroundStyle(Theme.muted)
123+ }
124+ Text("Tick each one you've checked yourself. Nothing here is checked for you.").font(.caption).foregroundStyle(Theme.muted)
125+ ForEach(HouseRules.all) { rule in
126+ Button {
127+ if ticked.contains(rule.id) { ticked.remove(rule.id) } else { ticked.insert(rule.id) }
128+ } label: {
129+ HStack(alignment: .top, spacing: 10) {
130+ Image(systemName: ticked.contains(rule.id) ? "checkmark.square.fill" : "square")
131+ .foregroundStyle(ticked.contains(rule.id) ? Theme.accent : Theme.muted).font(.title3)
132+ VStack(alignment: .leading, spacing: 2) {
133+ Text(rule.title).font(.callout.weight(.semibold)).foregroundStyle(Theme.ink)
134+ Text(rule.detail).font(.caption).foregroundStyle(Theme.ink2).fixedSize(horizontal: false, vertical: true)
135+ }
136+ }
137+ .frame(maxWidth: .infinity, alignment: .leading)
138+ .contentShape(Rectangle())
139+ }
140+ .buttonStyle(.plain)
141+ }
142+ }
143+ .padding(16)
144+ .background(Theme.surface, in: RoundedRectangle(cornerRadius: 14))
145+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Theme.line))
146+ }
147+
148+ var notes: some View {
149+ VStack(alignment: .leading, spacing: 8) {
150+ Text("Notes").font(Theme.display(19)).foregroundStyle(Theme.ink)
151+ HStack(alignment: .bottom) {
152+ TextField("A note for whoever reads this next", text: $note, axis: .vertical)
153+ .textFieldStyle(.roundedBorder).lineLimit(1...4)
154+ Button("Add") { Task { if await model.addNote(job, note: note) { note = "" } } }
155+ .disabled(note.trimmingCharacters(in: .whitespaces).isEmpty)
156+ }
157+ }
158+ }
159+
160+ var history: some View {
161+ VStack(alignment: .leading, spacing: 8) {
162+ Text("History").font(Theme.display(19)).foregroundStyle(Theme.ink)
163+ if item.activity.isEmpty { Text("Nothing yet.").font(.caption).foregroundStyle(Theme.muted) }
164+ ForEach(item.activity.reversed()) { entry in
165+ HStack(alignment: .top, spacing: 10) {
166+ Image(systemName: entry.client == "mcp" ? "cpu" : "person").foregroundStyle(Theme.muted).frame(width: 18)
167+ VStack(alignment: .leading, spacing: 2) {
168+ Text("\(entry.actor) · \(entry.action)\(entry.client.map { " · \($0)" } ?? "")").font(.caption.weight(.semibold)).foregroundStyle(Theme.ink2)
169+ if let detail = entry.detail, !detail.isEmpty { Text(detail).font(.caption).foregroundStyle(Theme.ink2).textSelection(.enabled) }
170+ Text(APIDate.full(entry.createdAt)).font(.caption2).foregroundStyle(Theme.muted)
171+ }
172+ }
173+ }
174+ }
175+ }
176+ }
177+
178+ /// Asks for a reason, then runs the action. A required reason must be at least three characters.
179+ public struct ReasonSheet: View {
180+ let title: String, detail: String, action: String
181+ let required: Bool
182+ let run: (String) async -> Bool
183+ @State private var reason = ""
184+ @State private var working = false
185+ @Environment(\.dismiss) private var dismiss
186+
187+ public init(title: String, detail: String, action: String, required: Bool, run: @escaping (String) async -> Bool) {
188+ self.title = title; self.detail = detail; self.action = action; self.required = required; self.run = run
189+ }
190+
191+ var valid: Bool { !required || reason.trimmingCharacters(in: .whitespacesAndNewlines).count >= 3 }
192+
193+ public var body: some View {
194+ VStack(alignment: .leading, spacing: 14) {
195+ Text(title).font(Theme.display(20))
196+ Text(detail).font(.callout).foregroundStyle(Theme.ink2)
197+ TextEditor(text: $reason)
198+ .font(.body).frame(minHeight: 120)
199+ .scrollContentBackground(.hidden)
200+ .padding(6).background(Theme.surface2, in: RoundedRectangle(cornerRadius: 8))
201+ .accessibilityIdentifier("reasonField")
202+ HStack {
203+ Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
204+ Spacer()
205+ Button(action) {
206+ working = true
207+ Task { if await run(reason.trimmingCharacters(in: .whitespacesAndNewlines)) { dismiss() }; working = false }
208+ }
209+ .buttonStyle(PrimaryButtonStyle())
210+ .disabled(!valid || working)
211+ }
212+ }
213+ .padding(22)
214+ #if os(macOS)
215+ .frame(width: 460)
216+ #endif
217+ }
218+ }
219+
220+ /// Edit a post's wording before it is published. Contact details and status are never edited here.
221+ public struct EditJobSheet: View {
222+ let job: Job
223+ let labels: Labels
224+ let save: (JobEdit) async -> Bool
225+ @State private var edit: JobEdit
226+ @State private var payMin: String
227+ @State private var payMax: String
228+ @Environment(\.dismiss) private var dismiss
229+
230+ public init(job: Job, labels: Labels, save: @escaping (JobEdit) async -> Bool) {
231+ self.job = job; self.labels = labels; self.save = save
232+ _edit = State(initialValue: JobEdit(job))
233+ _payMin = State(initialValue: String(job.pay.min)); _payMax = State(initialValue: String(job.pay.max))
234+ }
235+
236+ public var body: some View {
237+ NavigationStack {
238+ Form {
239+ Section("The job") {
240+ TextField("Job title", text: $edit.title)
241+ TextField("Company", text: $edit.company)
242+ TextField("Company website", text: $edit.companyURL)
243+ TextField("Location", text: $edit.location)
244+ Picker("Workplace", selection: $edit.workplace) { ForEach(Meta.workplaceOrder, id: \.self) { Text(labels.workplace($0)).tag($0) } }
245+ Picker("Job type", selection: $edit.employmentType) { ForEach(Meta.employmentTypeOrder, id: \.self) { Text(labels.type($0)).tag($0) } }
246+ Picker("Category", selection: $edit.category) { ForEach(Meta.categoryOrder, id: \.self) { Text(labels.category($0)).tag($0) } }
247+ }
248+ Section("Pay") {
249+ TextField("Lowest", text: $payMin)
250+ TextField("Highest", text: $payMax)
251+ TextField("Currency", text: $edit.payCurrency)
252+ Picker("Per", selection: $edit.payPeriod) { ForEach(Meta.payPeriodOrder, id: \.self) { Text($0).tag($0) } }
253+ }
254+ Section("Description") {
255+ TextEditor(text: $edit.description).frame(minHeight: 200)
256+ TextField("Company's own job page", text: $edit.applyURL)
257+ }
258+ }
259+ .formStyle(.grouped)
260+ .navigationTitle("Edit wording")
261+ .toolbar {
262+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
263+ ToolbarItem(placement: .confirmationAction) {
264+ Button("Save") {
265+ edit.payMin = Int(payMin.filter(\.isNumber)) ?? edit.payMin
266+ edit.payMax = Int(payMax.filter(\.isNumber)) ?? edit.payMax
267+ Task { if await save(edit) { dismiss() } }
268+ }
269+ }
270+ }
271+ }
272+ #if os(macOS)
273+ .frame(width: 560, height: 680)
274+ #endif
275+ }
276+ }

Sources/JobleyUI/Theme.swift added

1+ import SwiftUI
2+ import JobleyKit
3+
4+ /// The "Noticeboard" direction from jobley.ai: paper cream, forest green, a marigold seal.
5+ /// The values are the site's `:root` tokens in assets/site.css, light and dark.
6+ public enum Theme {
7+ public static let background = Color(light: 0xfaf6ee, dark: 0x0d1511)
8+ public static let surface = Color(light: 0xfffdf8, dark: 0x16221c)
9+ public static let surface2 = Color(light: 0xf7f2e7, dark: 0x1b2922)
10+ public static let line = Color(light: 0xe4dccb, dark: 0x25352c)
11+ public static let ink = Color(light: 0x15241c, dark: 0xf3efe4)
12+ public static let ink2 = Color(light: 0x3c4a42, dark: 0xc5cdc4)
13+ public static let muted = Color(light: 0x677268, dark: 0x8f9c93)
14+ /// Text and icons in the accent colour.
15+ public static let accent = Color(light: 0x17603f, dark: 0x7fd6a6)
16+ /// Filled buttons.
17+ public static let fill = Color(light: 0x17603f, dark: 0x23784f)
18+ public static let seal = Color(hex: 0xf5b83d)
19+ public static let sealText = Color(light: 0x8a5a00, dark: 0xf5b83d)
20+ public static let danger = Color(light: 0xb3391f, dark: 0xf08a6f)
21+
22+ /// Fraunces on the site; the system serif is the closest built-in face.
23+ public static func display(_ size: CGFloat, weight: Font.Weight = .semibold) -> Font {
24+ .system(size: size, weight: weight, design: .serif)
25+ }
26+ public static func mono(_ size: CGFloat) -> Font { .system(size: size, design: .monospaced) }
27+ }
28+
29+ public extension Color {
30+ init(hex: UInt32) {
31+ self.init(red: Double((hex >> 16) & 0xff) / 255, green: Double((hex >> 8) & 0xff) / 255, blue: Double(hex & 0xff) / 255)
32+ }
33+
34+ init(light: UInt32, dark: UInt32) {
35+ #if os(macOS)
36+ self.init(nsColor: NSColor(name: nil) { appearance in
37+ let isDark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua
38+ return NSColor(Color(hex: isDark ? dark : light))
39+ })
40+ #else
41+ self.init(uiColor: UIColor { traits in UIColor(Color(hex: traits.userInterfaceStyle == .dark ? dark : light)) })
42+ #endif
43+ }
44+ }
45+
46+ /// The app mark: a job card with an approval seal (jobley-site/mark.svg), drawn natively.
47+ public struct JobleyMark: View {
48+ var size: CGFloat
49+ public init(size: CGFloat = 28) { self.size = size }
50+ public var body: some View {
51+ ZStack {
52+ RoundedRectangle(cornerRadius: size * 0.24, style: .continuous).fill(Theme.fill)
53+ VStack(alignment: .leading, spacing: size * 0.09) {
54+ Capsule().fill(.white).frame(width: size * 0.42, height: size * 0.09)
55+ Capsule().fill(.white.opacity(0.75)).frame(width: size * 0.3, height: size * 0.07)
56+ Capsule().fill(.white.opacity(0.75)).frame(width: size * 0.36, height: size * 0.07)
57+ }
58+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
59+ .padding(size * 0.2)
60+ Circle().fill(Theme.seal).frame(width: size * 0.34)
61+ .overlay(Image(systemName: "checkmark").font(.system(size: size * 0.17, weight: .heavy)).foregroundStyle(Color(hex: 0x3a2a05)))
62+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
63+ .padding(size * 0.12)
64+ }
65+ .frame(width: size, height: size)
66+ .accessibilityHidden(true)
67+ }
68+ }

16 more files changed.

Browse files at this commit