diff options
Diffstat (limited to 'makima/ios/Sources/Makima/Net')
| -rw-r--r-- | makima/ios/Sources/Makima/Net/AuthStore.swift | 44 | ||||
| -rw-r--r-- | makima/ios/Sources/Makima/Net/DemoSession.swift | 122 |
2 files changed, 144 insertions, 22 deletions
diff --git a/makima/ios/Sources/Makima/Net/AuthStore.swift b/makima/ios/Sources/Makima/Net/AuthStore.swift index d09488f..8d70a6c 100644 --- a/makima/ios/Sources/Makima/Net/AuthStore.swift +++ b/makima/ios/Sources/Makima/Net/AuthStore.swift @@ -1,7 +1,5 @@ import Foundation -/// Top-level authentication state. Mediates between ServerProfileStore -/// (on-disk) and APIClient (in-memory, per session). @MainActor @Observable final class AuthStore { @@ -22,8 +20,6 @@ final class AuthStore { bootstrap() } - // MARK: - Bootstrap from persistence - private func bootstrap() { guard let profile = profiles.activeProfile else { state = .needsOnboarding @@ -41,10 +37,6 @@ final class AuthStore { } } - // MARK: - Onboarding entry point - - /// Validate and persist a new (server, key) pair. On success, becomes the - /// active profile and flips state to `.authenticated`. func configure(baseURLString: String, apiKey: String, label: String? = nil) async { state = .validating @@ -60,16 +52,12 @@ final class AuthStore { let client = APIClient(profile: profile, apiKey: apiKey) do { - // Auth probe — daemons list is small and gated by the same middleware - // as every other authed endpoint. let _: ListEnvelope<Daemon> = try await client.get("/mesh/daemons") } catch APIError.unauthorized { state = .error("Server rejected the API key. Double-check `mk_…` and try again.") return } catch APIError.notFound { - // Tolerate 404 — auth middleware runs first, so a 404 means auth - // passed but the endpoint was renamed. Proceed; deeper surfaces - // will surface the real problem. + // tolerate } catch { state = .error(error.localizedDescription) return @@ -91,11 +79,6 @@ final class AuthStore { self.state = .authenticated } - // MARK: - Settings operations - - /// Overwrite the server URL on the active profile. Re-validates; on 401 - /// prompts for a new key (caller shows UI). Keeps the existing key if the - /// URL works against it. func updateBaseURL(_ baseURLString: String) async { guard var profile = profiles.activeProfile, let key = try? Keychain.get(profile.keychainID), !key.isEmpty else { @@ -119,7 +102,6 @@ final class AuthStore { state = .needsOnboarding return } catch APIError.notFound { - // tolerate } catch { state = .error(error.localizedDescription) return @@ -131,17 +113,14 @@ final class AuthStore { self.state = .authenticated } - /// Rotate the API key via `POST /auth/api-keys/refresh`. func rotateKey() async throws { guard let client = client else { throw APIError.notConfigured } struct RefreshBody: Encodable { let confirm: Bool = true } struct RefreshResp: Decodable { let apiKey: String? let api_key: String? - /// Server may return either casing; take whichever is present. var value: String? { apiKey ?? api_key } } - let resp: RefreshResp = try await client.post("/auth/api-keys/refresh", body: RefreshBody()) guard let new = resp.value else { throw APIError.decoding("refresh response missing apiKey") } try Keychain.set(new, for: client.profile.keychainID) @@ -160,4 +139,25 @@ final class AuthStore { static func labelFrom(_ urlString: String) -> String? { URL(string: urlString)?.host } + + // MARK: - Screenshot / demo hooks + + func seedSetClient(_ client: APIClient?) { + self.client = client + } + + /// Screenshot mode: inject a fake authenticated client backed by an + /// in-process URLProtocol that returns canned demo payloads. + /// Called from AppState.init when SCREENSHOT_MODE is on. + func seedScreenshotData() { + let profile = ScreenshotMode.profile + let session = DemoSession.make() + let client = APIClient(profile: profile, apiKey: ScreenshotMode.apiKey, session: session) + self.seedSetClient(client) + self.seedSetState(.authenticated) + } + + func seedSetState(_ new: State) { + self.state = new + } } diff --git a/makima/ios/Sources/Makima/Net/DemoSession.swift b/makima/ios/Sources/Makima/Net/DemoSession.swift new file mode 100644 index 0000000..3d14a64 --- /dev/null +++ b/makima/ios/Sources/Makima/Net/DemoSession.swift @@ -0,0 +1,122 @@ +import Foundation + +/// In-process URLSession that returns canned demo payloads for screenshot +/// builds. Never hits the network. Used only when SCREENSHOT_MODE is on. +enum DemoSession { + static func make() -> URLSession { + let cfg = URLSessionConfiguration.ephemeral + cfg.protocolClasses = [DemoURLProtocol.self] + (cfg.protocolClasses ?? []) + return URLSession(configuration: cfg) + } +} + +final class DemoURLProtocol: URLProtocol, @unchecked Sendable { + override class func canInit(with request: URLRequest) -> Bool { + request.url?.host == "makima.jp" + } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + + override func startLoading() { + let (status, body) = DemoPayloads.response(for: request) + let response = HTTPURLResponse( + url: request.url!, + statusCode: status, + httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/json"] + )! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: body) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} + +enum DemoPayloads { + static func response(for request: URLRequest) -> (Int, Data) { + let path = request.url?.path ?? "" + switch path { + case let p where p.hasSuffix("/mesh/daemons"): + return (200, data(daemonsJSON)) + case let p where p.hasSuffix("/mesh/tasks"): + return (200, data(tasksJSON)) + case let p where p.hasSuffix("/contracts"): + return (200, data(contractsJSON)) + case let p where p.hasSuffix("/directives"): + return (200, data(directivesJSON)) + case let p where p.hasSuffix("/listen/sessions"): + return (200, data(listenJSON)) + case let p where p.contains("/mesh/tasks/") && p.hasSuffix("/output"): + return (200, data(taskOutputJSON)) + case let p where p.contains("/mesh/tasks/"): + return (200, data(taskDetailJSON)) + default: + return (200, data(#"{"items":[],"total":0}"#)) + } + } + + private static func data(_ s: String) -> Data { Data(s.utf8) } + + static let daemonsJSON = #""" + { + "daemons": [ + {"id":"d1","status":"online","hostname":"soryu-alpha","maxConcurrentTasks":4,"currentTaskCount":2,"lastHeartbeatAt":"2026-04-24T10:42:00Z"}, + {"id":"d2","status":"online","hostname":"soryu-beta","maxConcurrentTasks":4,"currentTaskCount":1,"lastHeartbeatAt":"2026-04-24T10:42:10Z"}, + {"id":"d3","status":"offline","hostname":"isolated-box","maxConcurrentTasks":2,"currentTaskCount":0,"lastHeartbeatAt":"2026-04-23T19:10:00Z"} + ], + "total": 3 + } + """# + + static let contractsJSON = #""" + { + "contracts": [ + {"id":"c1","name":"Ingest pipeline rework","description":"Migrate transcript ingest from SSE to WS","contractType":"specification","phase":"execute","status":"active","autonomousLoop":true,"phaseGuard":false,"localOnly":false,"version":3,"updatedAt":"2026-04-24T10:30:00Z"}, + {"id":"c2","name":"Dashboard layout v2","description":"Port masthead + nav to dense mode","contractType":"simple","phase":"plan","status":"active","autonomousLoop":false,"phaseGuard":true,"updatedAt":"2026-04-24T09:15:00Z"}, + {"id":"c3","name":"Makima iOS app","description":"Native client shipping M0-M8","contractType":"specification","phase":"review","status":"active","updatedAt":"2026-04-24T10:50:00Z"}, + {"id":"c4","name":"Archive Q1 traces","description":"Cold-store transcripts >90d","contractType":"simple","phase":"done","status":"completed","updatedAt":"2026-03-30T17:00:00Z"} + ], + "total": 4 + } + """# + + static let tasksJSON = #""" + { + "tasks": [ + {"id":"t1","contractId":"c3","name":"Implement HomeStore + cards","status":"done","priority":2,"plan":"Wire parallel fetch, render 5 cards","daemonId":"d1","progressSummary":"All cards render, live refresh working","updatedAt":"2026-04-24T10:48:00Z","lastOutput":"Implementation complete. Running tests…\n\n```swift\nasync let contractsTask = tryGet(\"/contracts\")\nasync let daemonsTask = tryGet(\"/mesh/daemons\")\n```\n\n<COMPLETION_GATE>\nready: true\nreason: \"All cards render live data; pull-to-refresh verified\"\nprogress: \"Home composite landed in 4 files\"\n</COMPLETION_GATE>"}, + {"id":"t2","contractId":"c3","name":"WebSocket livestream","status":"running","priority":2,"plan":"Implement TaskWebSocket + event merging","daemonId":"d1","progressSummary":"Handler wiring in progress","updatedAt":"2026-04-24T10:51:00Z","lastOutput":"Connecting to wss://makima.jp/api/v1/mesh/tasks/subscribe…\nSubscribed to all tasks."}, + {"id":"t3","contractId":"c3","name":"Markdown renderer","status":"done","priority":1,"daemonId":"d2","updatedAt":"2026-04-24T10:35:00Z"}, + {"id":"t4","contractId":"c1","name":"SSE->WS migration probe","status":"blocked","priority":3,"daemonId":"d2","errorMessage":"Needs schema review from supervisor","updatedAt":"2026-04-24T09:02:00Z"}, + {"id":"t5","contractId":"c2","name":"Dense masthead spec","status":"pending","priority":1,"updatedAt":"2026-04-24T08:00:00Z"} + ], + "total": 5 + } + """# + + static let directivesJSON = #""" + { + "directives": [ + {"id":"dir1","name":"Schema review required","goal":"Approve SSE->WS schema change for transcript events","status":"pending","updatedAt":"2026-04-24T10:45:00Z"}, + {"id":"dir2","name":"Choose archive tier","goal":"S3 Glacier vs R2 cold for Q1 traces","status":"pending","updatedAt":"2026-04-24T10:12:00Z"}, + {"id":"dir3","name":"Approve deploy window","goal":"Ship iOS v1 build to TestFlight tonight 22:00 BST","status":"pending","updatedAt":"2026-04-24T09:55:00Z"} + ], + "total": 3 + } + """# + + static let listenJSON = #""" + { + "items": [ + {"id":"l1","title":"Dispatch — ridge sector","startedAt":"2026-04-24T10:10:00Z","endedAt":"2026-04-24T10:31:00Z","transcriptPreview":"…rotated assets to sector 7, mark-two, maintaining comms on channel…","duration":1260} + ], + "total": 1 + } + """# + + static let taskDetailJSON = #""" + {"id":"t2","contractId":"c3","name":"WebSocket livestream","status":"running","priority":2,"plan":"Implement TaskWebSocket + event merging","daemonId":"d1","progressSummary":"Handler wiring in progress","updatedAt":"2026-04-24T10:51:00Z","lastOutput":""} + """# + + static let taskOutputJSON = #""" + {"output":"Connecting to wss://makima.jp/api/v1/mesh/tasks/subscribe…\n\nSubscribed to all task updates.\n\n```swift\nfunc subscribe(taskId: String) {\n send(.subscribe(taskId: taskId))\n send(.subscribeOutput(taskId: taskId))\n}\n```\n\nReceived first `taskOutput` event for task `t2` (messageType=assistant).\n\n<COMPLETION_GATE>\nready: false\nreason: \"Awaiting reconnect test pass\"\nprogress: \"Protocol parity verified against mesh_ws.rs; reconnect backoff in progress\"\nblockers: \"reconnect not yet tested end-to-end, resync frame TBD\"\n</COMPLETION_GATE>","truncated":false} + """# +} |
