Repository Public
1# Apple architecture — `ClaudeRemoteKit`23Reference for everything built on the shared package (`Packages/ClaudeRemoteKit`, swift-tools 6.0,4Swift 6 language mode, macOS 15 / iOS 18). Server side: `docs/NATIVE-API-CONTRACT.md` plus the5server's `docs/native-clients.md`.67## 1. Package graph89```10ClaudeRemoteModels Foundation only: DTOs, states, wire messages, AgentProfile11 ▲ ▲12ClaudeRemoteAPI ClaudeRemoteDesign (SwiftUI; imports Models only)13 ▲ ▲14ClaudeRemoteAuth ClaudeRemoteTerminal (+ SwiftTerm 1.99.2)15 ▲16ClaudeRemoteCore17 ▲18ClaudeRemoteTestSupport (mocks, fixtures, fakes; link it in tests and, if wanted, in previews)19```2021`Terminal` does not import `Core`, and `Design` imports neither: the app maps between them22(`ConnectionState` → `ConnectionIndicator.Status`, see §9).2324| Product | Exposes |25|---|---|26| `ClaudeRemoteModels` | `AgentProfile` (`.claude`, `.codex`), `AgentAccent`, `HexColor`; every DTO of `dto.ts` / `native.ts` (`TerminalSession`, `Project`, `AgentTask`, `FileEntry`, `ClusterOverview`, `SkillInfo`, `McpServerInfo`, `SystemStatus`, `ServerNotification`, `UserSettings`, `NativeSession`, `NativeDevice`, `NativeSummary`, `NativeInfo`, …); `SessionState`, `TaskState`, `Health`; wire: `TermClientMessage`, `TermServerMessage`, `ServerEvent`, `WSCloseCode`, `TerminalLimits`; `JSONValue`, `CRJSON`, `Base64URL` |27| `ClaudeRemoteAPI` | `APIClient` (actor), `APIError` (+ `Kind`), `ClientInfo`, `RequestAuth`, `TransferProgress`, `SessionAuthority`; `WebSocketTransport` / `WebSocketConnection` / `WebSocketClosed`, `URLSessionWebSocketTransport`; `ReconnectPolicy`, `Sleeper`, `NetworkPathMonitoring`, `SystemNetworkMonitor`; `CRLog` |28| `ClaudeRemoteAuth` | `AuthService` (actor), `AuthState`, `SecondFactorChallenge`, `SignedOutReason`, `AuthFlowError`; `PasskeyAuthenticator`, `SystemPasskeyAuthenticator`, `PasskeyError`; `DeviceKey`, `DeviceKeyStore`, `KeychainDeviceKeyStore`, `RefreshSignature`, `DeviceDescriptor`; `KeychainStoring`, `SystemKeychain`, `InMemoryKeychain`, `CredentialStore`; `BiometricLock`, `LocalAuthenticating`, `LocalAuthError` |29| `ClaudeRemoteCore` | `AppSession`, `AppSessionConfiguration`; `EventStream`, `ConnectionState`, `LoadState`; stores `SessionsStore`, `ProjectsStore`, `TasksStore` (+ `TaskLogFollower`), `FilesStore` (+ `OpenDocument`, `SaveOutcome`), `ClusterStore`, `SkillsMCPStore`, `SystemStore`, `NotificationsStore`, `SettingsStore`, `SummaryStore`; `SharedSummaryCache`, `CachedSummary`; `Route`, `DeepLinkRouter`; `LocalNotifier`, `PushRegistrar`; `ProjectShortcuts` |30| `ClaudeRemoteTerminal` | `TerminalSessionController`, `TerminalSurface`, `TerminalConnection`, `TerminalConnectionState`, `TerminalOutputSink`; `TerminalKey`, `TerminalKeyDescriptor`, `StickyModifiers`, `KeyEncoder`; `TerminalTheme`, `TerminalAppearance` |31| `ClaudeRemoteDesign` | tokens `CRSpacing`, `CRRadius`, `CRTypography`, `CRMotion`, `CRShadow`; `CRPalette`, `CRTheme` (`.crTheme(profile)`); `StatusStyle` / `StatusPill` / `HealthDot` for every state enum; `ConnectionIndicator`; `StatTile`, `SectionCard`, `EmptyStateView`, `LoadingStateView`, `ErrorStateView`, `SkeletonBlock`, `RelativeTimeText`, `KeyValueRow`, `TagChip`, `ProgressBar`, `AgentMark`; button styles; `CRFormat`; `Haptics` |32| `ClaudeRemoteTestSupport` | `StubServer` (URLProtocol), `StubNativeAuth` (in-memory native auth contract), `FakeWebSocketTransport` / `FakeWebSocket`, `ManualSleeper`, `FakeNetworkMonitor`, `SoftwareAuthenticator`, `MockLocalAuthenticator`, `RecordingNotificationCenter`, `TOTP`, `Fixtures`, `IntegrationFixtures` |3334## 2. Conventions of the models3536- **Open enums.** Every server enum conforms to `OpenStringEnum`: known cases plus `.unknown(String)`.37 An unknown value never fails decoding and is encoded back unchanged. Always handle `.unknown` in a38 `switch` (the design system already does: neutral style, humanised label). They are deliberately39 not `RawRepresentable`; use `.rawValue` and `Type("RAW")`.40- `SessionKind.agent` has the wire value `"claude"` on both instances (it means "the instance's agent").41- `Health`: the server's `UNKNOWN` is `.unknown("UNKNOWN")` (`Health.unknownHealth`). Stale data is unknown, never online.42- Timestamps are `Date` (ISO-8601 with or without fractional seconds). Paths are project-relative strings.43- Response DTOs have no public memberwise initialiser; for previews and tests decode JSON or use44 `Fixtures.sampleSession`, `.sampleProject`, `.sampleTask`, `.sampleSummary`, … Properties are `var`.45- `ServerNotification` is the server's `Notification` (renamed to avoid `Foundation.Notification`).4647## 3. Concurrency model4849| Layer | Isolation |50|---|---|51| Models | `Sendable` values |52| `APIClient`, `AuthService`, `TerminalConnection` | actors |53| `AppSession`, `EventStream`, every store, `BiometricLock`, `TerminalSessionController`, `PushRegistrar`, `LocalNotifier` | `@MainActor`, `@Observable` |54| Terminal output | fed to SwiftTerm off the main thread (`feedSender`), in stream order |5556Views read the observable objects directly. Mutations are `async` methods on the stores; they throw57`APIError`. Nothing in the kit polls while an event exists: lists are kept live by `/events`, refetched58after each re-connection, and the cluster (no events) refreshes on demand or on a view-scoped timer.5960## 4. Data flow6162```63 ┌────────── AppSession (@MainActor) ───────────┐64 SwiftUI views ─►│ authState · connection · stores · lock · push │65 └───┬───────────────┬──────────────────────┬────┘66 │ AuthService │ EventStream (WS /events) stores ── APIClient ── HTTPS /api/v167 │ (actor) │ session.updated → SessionsStore, ProjectsStore, SummaryStore68 │ │ task.updated → TasksStore, SummaryStore69 │ │ notification → NotificationsStore → LocalNotifier70 │ │ auth.expired / 4401 → AuthService → .signedOut(.revoked)71 ▼ ▼72 Keychain (credential, device key, install id) App Group file (SharedSummaryCache) → widgets73```7475## 5. Bootstrapping7677```swift78import ClaudeRemoteCore // re-export what you use: ClaudeRemoteModels, ClaudeRemoteAPI, ClaudeRemoteAuth7980@main struct ClaudeRemoteApp: App {81 @State private var session: AppSession = {82 var config = AppSessionConfiguration(83 client: ClientInfo.current(), // X-CR-Client: native/<platform>/<version>84 device: DeviceDescriptor(name: deviceName, model: DeviceDescriptor.hardwareModel(),85 platform: ClientInfo.currentPlatform, appVersion: appVersion),86 isDebugBuild: isDebug, // ".dev" keychain service + push topic87 appGroup: "group.ai.spboucher.clauderemote", // nil if there is no widget88 apnsEnvironment: isDebug ? .sandbox : .production,89 passkeyAnchor: { keyWindow }) // window for the passkey sheet90 // Dev stack: config.baseURL = URL(string: "http://localhost:8625") (HTTP is accepted for localhost only)91 return try! AppSession(profile: .claude, configuration: config) // .codex for Codex Remote92 }()93 @Environment(\.scenePhase) private var phase9495 var body: some Scene {96 WindowGroup {97 RootView().environment(session).crTheme(session.profile)98 .task { await session.start() } // restores the stored session, no network needed99 .onOpenURL { session.open(url: $0) }100 .onChange(of: phase) { _, p in101 if p == .active { session.appDidBecomeActive() }102 if p == .background { session.appDidEnterBackground() }103 }104 }105 }106}107```108109`AppSession.init` throws `APIError` (`insecure_url`) for a non-HTTPS base URL. App target requirements:110Associated Domains `webcredentials:<host>` and `applinks:<host>` (`profile.associatedDomains`), the111URL scheme `profile.urlScheme`, Keychain sharing left at the default, an App Group if widgets exist,112`NSFaceIDUsageDescription` (iOS), push entitlement.113114## 6. Authentication and token lifecycle115116```swift117switch session.authState {118case .unknown: SplashView()119case .signedOut(let reason): SignInView(reason: reason) // .revoked → "You were signed out"120case .secondFactorRequired(let c): SecondFactorView(challenge: c) // c.canUseTOTP / c.canUsePasskey / c.preferred121case .enrollmentRequired: EnrollSecondFactorView()122case .signedIn: session.lock.isLocked ? AnyView(LockView()) : AnyView(MainView())123}124125try await session.signInWithPasskey() // same passkey as the website; Touch ID / Face ID126try await session.signIn(username: u, password: p) // → .signedIn, .secondFactorRequired or .enrollmentRequired127try await session.signIn(username: u, password: p, totp: c) // code in the same request128try await session.submitTOTP(code: "123456")129try await session.completeSecondFactorWithPasskey()130let enrol = try await session.startTOTPEnrollment() // enrol.secret / enrol.otpauthUrl (QR)131try await session.finishTOTPEnrollment(code: "123456")132try await session.registerPasskey(label: "MacBook Pro") // enrolment, or adding a passkey when signed in133await session.cancelSignIn()134await session.signOut() // revokes server-side (best effort) + local wipe135await session.wipeLocalData() // also device key + install id136```137138Errors: `APIError` (`.kind == .invalidCredentials`, `.locked` with `retryAfter` seconds, `.network`, …),139`PasskeyError` (`.reason == .cancelled` is not an error to show, `.notAssociated` = AASA not fetched yet),140`AuthFlowError`. A failed step leaves the state where it was, except an expired second-factor window141(`.signedOut(.secondFactorTimedOut)`).142143Lifecycle:1441451. Sign-in sends `NativeDevice` = install id (Keychain, stable) + P-256 **device public key**. The146 private key is created in the Secure Enclave when there is one (`KeychainDeviceKeyStore`), else as147 a Keychain item; in both cases non-exportable / this-device-only, `AfterFirstUnlockThisDeviceOnly`.1482. The full `NativeSession` (token 1 h, session 30 d absolute, 14 d idle) is stored in the Keychain by149 `CredentialStore`. A session waiting for its second factor is kept in memory only. Nothing secret150 goes to `UserDefaults` or to logs (`os.Logger`, private interpolation; tokens are never logged).1513. `APIClient` holds the token in memory. A token expiring within 30 s is refreshed before the request;152 a 401 `token_expired` **or** `unauthenticated` triggers ONE refresh shared by all concurrent153 requests (single flight), then each request is retried once.1544. Refresh = `POST /native/auth/refresh/challenge` → sign `cr-native-refresh:v1:<sessionId>:<challenge>`155 (DER ECDSA-P256-SHA256, base64) with the device key → `POST /native/auth/refresh`. The token rotates.1565. Refused refresh, or a 401 that survives it, or `auth.expired` / close 4401 on a socket ⇒ the157 credential is wiped and `authState` becomes `.signedOut(.revoked)`: the root view returns to sign-in.158 The device key and install id are kept. A network failure during refresh changes nothing.159160Destructive actions go through the local gate (Face ID / Touch ID / passcode, unrelated to the server):161162```swift163do {164 try await session.reauthenticate(reason: "Terminate “\(s.title)”")165 try await session.sessions.terminate(id: s.id)166} catch LocalAuthError.cancelled { } catch LocalAuthError.unavailable { /* fall back to a confirmation dialog */ }167```168169App lock (`session.lock`, a `BiometricLock`): `isEnabled`, `timeout` (`BiometricLock.timeoutChoices`),170`isLocked`, `biometry`, `await lock.unlock()`, `try await lock.enable()` / `disable()`, `noteActivity()`.171`AppSession.appDidBecomeActive/EnterBackground` already drive it. A cold start begins locked when enabled.172173## 7. Stores174175All on `AppSession`; each has `load: LoadState` (`.idle / .loading / .loaded(at:) / .failed(APIError)`),176`refresh()` (never throws; keeps old data on failure) and `reset()`.177178```swift179@Environment(AppSession.self) private var session180181List(session.sessions.sessions) { s in // waiting first, then pinned, live, recent182 HStack { StatusPill(s.state); Text(s.title); Spacer(); RelativeTimeText(s.lastActivityAt) }183}184.refreshable { await session.sessions.refresh() }185.overlay { if case .failed(let e) = session.sessions.load { ErrorStateView("Could not load", message: e.message) { Task { await session.sessions.refresh() } } } }186187let s = try await session.sessions.create(CreateSession(projectId: p.id, kind: .agent, resumeConversationId: conv.id))188try await session.sessions.rename(id:title:) / setPinned / setArchived / terminate / restart(id:) // restart = RECOVERABLE only189try await session.tasks.create(CreateTask(title: "Tests", command: "pnpm test", idempotent: true))190let log = session.tasks.logFollower(taskId: t.id); log.start() // log.text, log.phase, log.truncatedBytes; log.stop()191192let files = session.files(for: project.id) // one FilesStore per project193await files.list("src"); let doc = try await files.open("src/main.swift")194files.edit(doc.path, content: text)195switch try await files.save(doc.path) {196case .saved: break197case .conflict: /* offer files.reloadDocument(path) or files.save(path, overwriteConflict: true) */ break198}199try await files.upload(localURL, toDirectory: "assets"); files.transfers[path]?.fraction200201await session.cluster.refresh(); session.cluster.startAutoRefresh(every: 30) // stop it in onDisappear202try await session.settings.update { $0.terminalFontSize = 14 } // optimistic, rolls back on failure203session.notifications.unreadCount; try await session.notifications.markAllRead()204try await session.system.refreshDevices(); try await session.system.revokeDevice(id:)205session.projects.recents / favourites / noteOpened(id) / setFavourite(id, true)206```207208`session.connection` (`ConnectionState`: `.idle / .connecting / .online / .reconnecting(attempt:nextRetry:) /209.offline / .unauthorized`) and `session.latencyMs` describe the live link. Endpoints without a store210method are on `session.client` (typed, one method per route — see `Endpoints.swift`).211212## 8. Terminal213214```swift215import ClaudeRemoteTerminal216217@State private var term = TerminalSessionController(218 sessionId: s.id, client: session.client,219 appearance: TerminalAppearance(settings: session.settings.settings, agent: session.profile.id,220 systemIsDark: scheme == .dark, compact: isPhone))221222TerminalSurface(controller: term)223 .transaction { $0.animation = nil } // NEVER animate a container holding a terminal224 .onAppear { term.connect() }225 .onChange(of: scenePhase) { _, p in if p == .active { term.wake() } }226 .safeAreaInset(edge: .bottom) { // iOS: your own key row (SwiftTerm's accessory is hidden)227 HStack { ForEach(TerminalKey.defaultToolbar) { key in228 Button(TerminalKeyDescriptor(key).label) { term.send(key: key) } } }229 }230// term.state, term.latencyMs, term.title, term.exitCode, term.detail, term.isScrolledUp, term.hasUnreadOutput231// term.paste(text) (bracketed-paste aware), term.copySelection(), term.search("needle"), term.apply(appearance)232// After session.sessions.restart(id:) → term.reconnectNow(). term.disconnect() only when the tab really closes.233```234235Pipeline: `APIClient.openTerminalStream` (WS `/sessions/:id/stream?cols=&rows=`, bearer on the upgrade)236→ `TerminalConnection` (actor: binary frames = PTY bytes both ways, JSON text control frames, 80 ms237resize debounce clamped to 20…500 × 5…200, ping every 5 s with latency, 16 s pong timeout, input chunked238at 64 KiB and dropped while disconnected) → `TerminalOutputSink` → SwiftTerm `feedSender` off the main239thread → `TerminalSessionController` (`@MainActor`, owns the one SwiftTerm view) → `TerminalSurface`240(re-parents that view; never recreates it).241242On every (re)attach the server replays history and repaints into the **normal** buffer, so the emulator243is reset first (`ESC[?1049l`, RIS, `ESC[3J`, home) and only then fed. Reconnecting never creates a244process. Close codes: 4401 → `.unauthorized`, 4403 → `.forbidden`, 4404 → `.notFound`, 4410 →245`.ended(exitCode:)`, 4429 / 4503 / anything else → backoff retry (0.5 s → 10 s, jitter), with a246`GET /sessions/:id` probe that turns into `.ended` / `.recoverable` when the session is gone.247248Lessons carried over from SP Term: no animated resizing; never read the whole scrollback in a loop249(`visibleText()` and `recentText(scrollbackRows:)` are bounded); measure performance in Release.250JetBrains Mono is not bundled: register it in the app or the system monospaced font is used.251252## 9. Design system253254```swift255import ClaudeRemoteDesign256257RootView().crTheme(session.profile) // injects CRTheme + tint (Claude: indigo/violet/coral; Codex: emerald/teal)258@Environment(\.crTheme) private var theme // theme.accent, .warm, .gradient, .ink259StatusPill(session.state) StatusPill(task.state, compact: true) HealthDot(node.health)260StatTile("Live sessions", value: "\(summary.sessions.live)", symbolName: "terminal", tone: .accent)261SectionCard("Cluster", subtitle: "29 nodes") { … } .crCard() .crPanel()262ConnectionIndicator(indicatorStatus(session.connection, session.latencyMs))263264func indicatorStatus(_ c: ConnectionState, _ ms: Int?) -> ConnectionIndicator.Status {265 switch c {266 case .online: .online(latencyMs: ms)267 case .idle, .connecting: .connecting268 case .reconnecting(let attempt, let next): .reconnecting(attempt: attempt, nextRetry: next)269 case .offline: .offline270 case .unauthorized: .unauthorized271 }272}273```274275Colours are the web application's tokens (`apps/web/src/app/globals.css`), contrast-checked in tests.276Motion helpers return no animation under Reduce Motion. `Haptics` is a no-op on macOS.277278## 10. Deep links, notifications, push, summary cache279280```swift281.onOpenURL { session.open(url: $0) } // clauderemote:// / codexremote:// / https://<host>/open/…282// UNUserNotificationCenterDelegate.didReceive:283session.open(notificationUserInfo: response.notification.request.content.userInfo) // reads cr.link284// Root view, once signed in and unlocked:285if let route = session.takePendingRoute() { navigate(to: route) } // Route: .terminal(sessionId:), .task(id:), .files(projectId:path:), …286session.router.appURL(for: .terminal(sessionId: id)) // for widgets / Shortcuts287session.router.webURL(for: .task(id: id)) // "Open in browser"288289await session.notifier.requestAuthorization() // local notifications for live events290session.notifier.shouldPost = { $0.link != currentTerminalLink } // skip what is on screen291// AppDelegate: didRegisterForRemoteNotificationsWithDeviceToken292await session.push.register(deviceToken: token) // PUT /native/push; status .registered(serverConfigured:)293```294295Local notifications and pushes carry only the server's generic title (and the body the user opted296into): never terminal content. They share the notification id as identifier, so a push replaces the297local one. `cr.notificationId` can be null in a push.298299Widgets never hold a credential and never call the server. The app writes counters to the App Group:300301```swift302// Widget extension (same App Group):303let cached = SharedSummaryCache(appGroup: "group.ai.spboucher.clauderemote", agent: .claude)?.read()304// cached.signedIn, cached.summary?.sessions.waiting, cached.isStale()305// App: session.summary.onChange = { _ in WidgetCenter.shared.reloadAllTimelines() }306```307308`SummaryStore` refreshes on sign-in, on `appDidBecomeActive`, after each re-connection, and (coalesced)309when a session / task / notification event arrives.310311## 11. Testing312313`Scripts/kit.sh test` runs the unit tests (Swift Testing). For UI tests and previews, build an314`AppSession` on fakes:315316```swift317let server = StubServer(); let backend = StubNativeAuth(server: server, secondFactor: .totp)318server.on("GET", "/api/v1/sessions", backend.guarded { _ in .json("[\(Fixtures.session())]") })319var c = AppSessionConfiguration(client: .test, device: …, baseURL: server.baseURL, passkeyAnchor: { nil })320c.keychain = InMemoryKeychain(); c.urlSessionConfiguration = server.configuration321c.webSocketTransport = FakeWebSocketTransport(); c.passkeys = SoftwareAuthenticator(origin: "https://stub.test")322```323324Integration tests (`Tests/IntegrationTests`) run against the native dev stack; see the README.325326## 12. Known limits327328- No real device, Secure Enclave key in a signed app, or platform passkey sheet has exercised the kit:329 the system implementations (`SystemPasskeyAuthenticator`, `SystemKeychain`, `SystemLocalAuthenticator`,330 `SystemUserNotifications`) compile on both platforms but are covered through their protocols only.331- Terminal rendering, soft / hardware keyboard and IME behaviour are unverified outside headless tests.332- Request bodies and query limits are not validated client-side beyond clamping; the server's 400333 `invalid_request` is surfaced through `APIError.validationIssues`.334