Apple architecture — ClaudeRemoteKit
Reference for everything built on the shared package (Packages/ClaudeRemoteKit, swift-tools 6.0,
Swift 6 language mode, macOS 15 / iOS 18). Server side: docs/NATIVE-API-CONTRACT.md plus the
server's docs/native-clients.md.
1. Package graph
ClaudeRemoteModels Foundation only: DTOs, states, wire messages, AgentProfile
▲ ▲
ClaudeRemoteAPI ClaudeRemoteDesign (SwiftUI; imports Models only)
▲ ▲
ClaudeRemoteAuth ClaudeRemoteTerminal (+ SwiftTerm 1.99.2)
▲
ClaudeRemoteCore
▲
ClaudeRemoteTestSupport (mocks, fixtures, fakes; link it in tests and, if wanted, in previews)Terminal does not import Core, and Design imports neither: the app maps between them
(ConnectionState → ConnectionIndicator.Status, see §9).
| Product | Exposes |
|---|---|
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 |
ClaudeRemoteAPI |
APIClient (actor), APIError (+ Kind), ClientInfo, RequestAuth, TransferProgress, SessionAuthority; WebSocketTransport / WebSocketConnection / WebSocketClosed, URLSessionWebSocketTransport; ReconnectPolicy, Sleeper, NetworkPathMonitoring, SystemNetworkMonitor; CRLog |
ClaudeRemoteAuth |
AuthService (actor), AuthState, SecondFactorChallenge, SignedOutReason, AuthFlowError; PasskeyAuthenticator, SystemPasskeyAuthenticator, PasskeyError; DeviceKey, DeviceKeyStore, KeychainDeviceKeyStore, RefreshSignature, DeviceDescriptor; KeychainStoring, SystemKeychain, InMemoryKeychain, CredentialStore; BiometricLock, LocalAuthenticating, LocalAuthError |
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 |
ClaudeRemoteTerminal |
TerminalSessionController, TerminalSurface, TerminalConnection, TerminalConnectionState, TerminalOutputSink; TerminalKey, TerminalKeyDescriptor, StickyModifiers, KeyEncoder; TerminalTheme, TerminalAppearance |
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 |
ClaudeRemoteTestSupport |
StubServer (URLProtocol), StubNativeAuth (in-memory native auth contract), FakeWebSocketTransport / FakeWebSocket, ManualSleeper, FakeNetworkMonitor, SoftwareAuthenticator, MockLocalAuthenticator, RecordingNotificationCenter, TOTP, Fixtures, IntegrationFixtures |
2. Conventions of the models
- Open enums. Every server enum conforms to
OpenStringEnum: known cases plus.unknown(String). An unknown value never fails decoding and is encoded back unchanged. Always handle.unknownin aswitch(the design system already does: neutral style, humanised label). They are deliberately notRawRepresentable; use.rawValueandType("RAW"). SessionKind.agenthas the wire value"claude"on both instances (it means "the instance's agent").Health: the server'sUNKNOWNis.unknown("UNKNOWN")(Health.unknownHealth). Stale data is unknown, never online.- Timestamps are
Date(ISO-8601 with or without fractional seconds). Paths are project-relative strings. - Response DTOs have no public memberwise initialiser; for previews and tests decode JSON or use
Fixtures.sampleSession,.sampleProject,.sampleTask,.sampleSummary, … Properties arevar. ServerNotificationis the server'sNotification(renamed to avoidFoundation.Notification).
3. Concurrency model
| Layer | Isolation |
|---|---|
| Models | Sendable values |
APIClient, AuthService, TerminalConnection |
actors |
AppSession, EventStream, every store, BiometricLock, TerminalSessionController, PushRegistrar, LocalNotifier |
@MainActor, @Observable |
| Terminal output | fed to SwiftTerm off the main thread (feedSender), in stream order |
Views read the observable objects directly. Mutations are async methods on the stores; they throw
APIError. Nothing in the kit polls while an event exists: lists are kept live by /events, refetched
after each re-connection, and the cluster (no events) refreshes on demand or on a view-scoped timer.
4. Data flow
┌────────── AppSession (@MainActor) ───────────┐
SwiftUI views ─►│ authState · connection · stores · lock · push │
└───┬───────────────┬──────────────────────┬────┘
│ AuthService │ EventStream (WS /events) stores ── APIClient ── HTTPS /api/v1
│ (actor) │ session.updated → SessionsStore, ProjectsStore, SummaryStore
│ │ task.updated → TasksStore, SummaryStore
│ │ notification → NotificationsStore → LocalNotifier
│ │ auth.expired / 4401 → AuthService → .signedOut(.revoked)
▼ ▼
Keychain (credential, device key, install id) App Group file (SharedSummaryCache) → widgets5. Bootstrapping
import ClaudeRemoteCore // re-export what you use: ClaudeRemoteModels, ClaudeRemoteAPI, ClaudeRemoteAuth
@main struct ClaudeRemoteApp: App {
@State private var session: AppSession = {
var config = AppSessionConfiguration(
client: ClientInfo.current(), // X-CR-Client: native/<platform>/<version>
device: DeviceDescriptor(name: deviceName, model: DeviceDescriptor.hardwareModel(),
platform: ClientInfo.currentPlatform, appVersion: appVersion),
isDebugBuild: isDebug, // ".dev" keychain service + push topic
appGroup: "group.ai.spboucher.clauderemote", // nil if there is no widget
apnsEnvironment: isDebug ? .sandbox : .production,
passkeyAnchor: { keyWindow }) // window for the passkey sheet
// Dev stack: config.baseURL = URL(string: "http://localhost:8625") (HTTP is accepted for localhost only)
return try! AppSession(profile: .claude, configuration: config) // .codex for Codex Remote
}()
@Environment(\.scenePhase) private var phase
var body: some Scene {
WindowGroup {
RootView().environment(session).crTheme(session.profile)
.task { await session.start() } // restores the stored session, no network needed
.onOpenURL { session.open(url: $0) }
.onChange(of: phase) { _, p in
if p == .active { session.appDidBecomeActive() }
if p == .background { session.appDidEnterBackground() }
}
}
}
}AppSession.init throws APIError (insecure_url) for a non-HTTPS base URL. App target requirements:
Associated Domains webcredentials:<host> and applinks:<host> (profile.associatedDomains), the
URL scheme profile.urlScheme, Keychain sharing left at the default, an App Group if widgets exist,
NSFaceIDUsageDescription (iOS), push entitlement.
6. Authentication and token lifecycle
switch session.authState {
case .unknown: SplashView()
case .signedOut(let reason): SignInView(reason: reason) // .revoked → "You were signed out"
case .secondFactorRequired(let c): SecondFactorView(challenge: c) // c.canUseTOTP / c.canUsePasskey / c.preferred
case .enrollmentRequired: EnrollSecondFactorView()
case .signedIn: session.lock.isLocked ? AnyView(LockView()) : AnyView(MainView())
}
try await session.signInWithPasskey() // same passkey as the website; Touch ID / Face ID
try await session.signIn(username: u, password: p) // → .signedIn, .secondFactorRequired or .enrollmentRequired
try await session.signIn(username: u, password: p, totp: c) // code in the same request
try await session.submitTOTP(code: "123456")
try await session.completeSecondFactorWithPasskey()
let enrol = try await session.startTOTPEnrollment() // enrol.secret / enrol.otpauthUrl (QR)
try await session.finishTOTPEnrollment(code: "123456")
try await session.registerPasskey(label: "MacBook Pro") // enrolment, or adding a passkey when signed in
await session.cancelSignIn()
await session.signOut() // revokes server-side (best effort) + local wipe
await session.wipeLocalData() // also device key + install idErrors: APIError (.kind == .invalidCredentials, .locked with retryAfter seconds, .network, …),
PasskeyError (.reason == .cancelled is not an error to show, .notAssociated = AASA not fetched yet),
AuthFlowError. A failed step leaves the state where it was, except an expired second-factor window
(.signedOut(.secondFactorTimedOut)).
Lifecycle:
- Sign-in sends
NativeDevice= install id (Keychain, stable) + P-256 device public key. The private key is created in the Secure Enclave when there is one (KeychainDeviceKeyStore), else as a Keychain item; in both cases non-exportable / this-device-only,AfterFirstUnlockThisDeviceOnly. - The full
NativeSession(token 1 h, session 30 d absolute, 14 d idle) is stored in the Keychain byCredentialStore. A session waiting for its second factor is kept in memory only. Nothing secret goes toUserDefaultsor to logs (os.Logger, private interpolation; tokens are never logged). APIClientholds the token in memory. A token expiring within 30 s is refreshed before the request; a 401token_expiredorunauthenticatedtriggers ONE refresh shared by all concurrent requests (single flight), then each request is retried once.- Refresh =
POST /native/auth/refresh/challenge→ signcr-native-refresh:v1:<sessionId>:<challenge>(DER ECDSA-P256-SHA256, base64) with the device key →POST /native/auth/refresh. The token rotates. - Refused refresh, or a 401 that survives it, or
auth.expired/ close 4401 on a socket ⇒ the credential is wiped andauthStatebecomes.signedOut(.revoked): the root view returns to sign-in. The device key and install id are kept. A network failure during refresh changes nothing.
Destructive actions go through the local gate (Face ID / Touch ID / passcode, unrelated to the server):
do {
try await session.reauthenticate(reason: "Terminate “\(s.title)”")
try await session.sessions.terminate(id: s.id)
} catch LocalAuthError.cancelled { } catch LocalAuthError.unavailable { /* fall back to a confirmation dialog */ }App lock (session.lock, a BiometricLock): isEnabled, timeout (BiometricLock.timeoutChoices),
isLocked, biometry, await lock.unlock(), try await lock.enable() / disable(), noteActivity().
AppSession.appDidBecomeActive/EnterBackground already drive it. A cold start begins locked when enabled.
7. Stores
All on AppSession; each has load: LoadState (.idle / .loading / .loaded(at:) / .failed(APIError)),
refresh() (never throws; keeps old data on failure) and reset().
@Environment(AppSession.self) private var session
List(session.sessions.sessions) { s in // waiting first, then pinned, live, recent
HStack { StatusPill(s.state); Text(s.title); Spacer(); RelativeTimeText(s.lastActivityAt) }
}
.refreshable { await session.sessions.refresh() }
.overlay { if case .failed(let e) = session.sessions.load { ErrorStateView("Could not load", message: e.message) { Task { await session.sessions.refresh() } } } }
let s = try await session.sessions.create(CreateSession(projectId: p.id, kind: .agent, resumeConversationId: conv.id))
try await session.sessions.rename(id:title:) / setPinned / setArchived / terminate / restart(id:) // restart = RECOVERABLE only
try await session.tasks.create(CreateTask(title: "Tests", command: "pnpm test", idempotent: true))
let log = session.tasks.logFollower(taskId: t.id); log.start() // log.text, log.phase, log.truncatedBytes; log.stop()
let files = session.files(for: project.id) // one FilesStore per project
await files.list("src"); let doc = try await files.open("src/main.swift")
files.edit(doc.path, content: text)
switch try await files.save(doc.path) {
case .saved: break
case .conflict: /* offer files.reloadDocument(path) or files.save(path, overwriteConflict: true) */ break
}
try await files.upload(localURL, toDirectory: "assets"); files.transfers[path]?.fraction
await session.cluster.refresh(); session.cluster.startAutoRefresh(every: 30) // stop it in onDisappear
try await session.settings.update { $0.terminalFontSize = 14 } // optimistic, rolls back on failure
session.notifications.unreadCount; try await session.notifications.markAllRead()
try await session.system.refreshDevices(); try await session.system.revokeDevice(id:)
session.projects.recents / favourites / noteOpened(id) / setFavourite(id, true)session.connection (ConnectionState: .idle / .connecting / .online / .reconnecting(attempt:nextRetry:) / .offline / .unauthorized) and session.latencyMs describe the live link. Endpoints without a store
method are on session.client (typed, one method per route — see Endpoints.swift).
8. Terminal
import ClaudeRemoteTerminal
@State private var term = TerminalSessionController(
sessionId: s.id, client: session.client,
appearance: TerminalAppearance(settings: session.settings.settings, agent: session.profile.id,
systemIsDark: scheme == .dark, compact: isPhone))
TerminalSurface(controller: term)
.transaction { $0.animation = nil } // NEVER animate a container holding a terminal
.onAppear { term.connect() }
.onChange(of: scenePhase) { _, p in if p == .active { term.wake() } }
.safeAreaInset(edge: .bottom) { // iOS: your own key row (SwiftTerm's accessory is hidden)
HStack { ForEach(TerminalKey.defaultToolbar) { key in
Button(TerminalKeyDescriptor(key).label) { term.send(key: key) } } }
}
// term.state, term.latencyMs, term.title, term.exitCode, term.detail, term.isScrolledUp, term.hasUnreadOutput
// term.paste(text) (bracketed-paste aware), term.copySelection(), term.search("needle"), term.apply(appearance)
// After session.sessions.restart(id:) → term.reconnectNow(). term.disconnect() only when the tab really closes.Pipeline: APIClient.openTerminalStream (WS /sessions/:id/stream?cols=&rows=, bearer on the upgrade)
→ TerminalConnection (actor: binary frames = PTY bytes both ways, JSON text control frames, 80 ms
resize debounce clamped to 20…500 × 5…200, ping every 5 s with latency, 16 s pong timeout, input chunked
at 64 KiB and dropped while disconnected) → TerminalOutputSink → SwiftTerm feedSender off the main
thread → TerminalSessionController (@MainActor, owns the one SwiftTerm view) → TerminalSurface
(re-parents that view; never recreates it).
On every (re)attach the server replays history and repaints into the normal buffer, so the emulator
is reset first (ESC[?1049l, RIS, ESC[3J, home) and only then fed. Reconnecting never creates a
process. Close codes: 4401 → .unauthorized, 4403 → .forbidden, 4404 → .notFound, 4410 →
.ended(exitCode:), 4429 / 4503 / anything else → backoff retry (0.5 s → 10 s, jitter), with a
GET /sessions/:id probe that turns into .ended / .recoverable when the session is gone.
Lessons carried over from SP Term: no animated resizing; never read the whole scrollback in a loop
(visibleText() and recentText(scrollbackRows:) are bounded); measure performance in Release.
JetBrains Mono is not bundled: register it in the app or the system monospaced font is used.
9. Design system
import ClaudeRemoteDesign
RootView().crTheme(session.profile) // injects CRTheme + tint (Claude: indigo/violet/coral; Codex: emerald/teal)
@Environment(\.crTheme) private var theme // theme.accent, .warm, .gradient, .ink
StatusPill(session.state) StatusPill(task.state, compact: true) HealthDot(node.health)
StatTile("Live sessions", value: "\(summary.sessions.live)", symbolName: "terminal", tone: .accent)
SectionCard("Cluster", subtitle: "29 nodes") { … } .crCard() .crPanel()
ConnectionIndicator(indicatorStatus(session.connection, session.latencyMs))
func indicatorStatus(_ c: ConnectionState, _ ms: Int?) -> ConnectionIndicator.Status {
switch c {
case .online: .online(latencyMs: ms)
case .idle, .connecting: .connecting
case .reconnecting(let attempt, let next): .reconnecting(attempt: attempt, nextRetry: next)
case .offline: .offline
case .unauthorized: .unauthorized
}
}Colours are the web application's tokens (apps/web/src/app/globals.css), contrast-checked in tests.
Motion helpers return no animation under Reduce Motion. Haptics is a no-op on macOS.
10. Deep links, notifications, push, summary cache
.onOpenURL { session.open(url: $0) } // clauderemote:// / codexremote:// / https://<host>/open/…
// UNUserNotificationCenterDelegate.didReceive:
session.open(notificationUserInfo: response.notification.request.content.userInfo) // reads cr.link
// Root view, once signed in and unlocked:
if let route = session.takePendingRoute() { navigate(to: route) } // Route: .terminal(sessionId:), .task(id:), .files(projectId:path:), …
session.router.appURL(for: .terminal(sessionId: id)) // for widgets / Shortcuts
session.router.webURL(for: .task(id: id)) // "Open in browser"
await session.notifier.requestAuthorization() // local notifications for live events
session.notifier.shouldPost = { $0.link != currentTerminalLink } // skip what is on screen
// AppDelegate: didRegisterForRemoteNotificationsWithDeviceToken
await session.push.register(deviceToken: token) // PUT /native/push; status .registered(serverConfigured:)Local notifications and pushes carry only the server's generic title (and the body the user opted
into): never terminal content. They share the notification id as identifier, so a push replaces the
local one. cr.notificationId can be null in a push.
Widgets never hold a credential and never call the server. The app writes counters to the App Group:
// Widget extension (same App Group):
let cached = SharedSummaryCache(appGroup: "group.ai.spboucher.clauderemote", agent: .claude)?.read()
// cached.signedIn, cached.summary?.sessions.waiting, cached.isStale()
// App: session.summary.onChange = { _ in WidgetCenter.shared.reloadAllTimelines() }SummaryStore refreshes on sign-in, on appDidBecomeActive, after each re-connection, and (coalesced)
when a session / task / notification event arrives.
11. Testing
Scripts/kit.sh test runs the unit tests (Swift Testing). For UI tests and previews, build an
AppSession on fakes:
let server = StubServer(); let backend = StubNativeAuth(server: server, secondFactor: .totp)
server.on("GET", "/api/v1/sessions", backend.guarded { _ in .json("[\(Fixtures.session())]") })
var c = AppSessionConfiguration(client: .test, device: …, baseURL: server.baseURL, passkeyAnchor: { nil })
c.keychain = InMemoryKeychain(); c.urlSessionConfiguration = server.configuration
c.webSocketTransport = FakeWebSocketTransport(); c.passkeys = SoftwareAuthenticator(origin: "https://stub.test")Integration tests (Tests/IntegrationTests) run against the native dev stack; see the README.
12. Known limits
- No real device, Secure Enclave key in a signed app, or platform passkey sheet has exercised the kit:
the system implementations (
SystemPasskeyAuthenticator,SystemKeychain,SystemLocalAuthenticator,SystemUserNotifications) compile on both platforms but are covered through their protocols only. - Terminal rendering, soft / hardware keyboard and IME behaviour are unverified outside headless tests.
- Request bodies and query limits are not validated client-side beyond clamping; the server's 400
invalid_requestis surfaced throughAPIError.validationIssues.