SPB Git

Repository Public

IOS_ARCHITECTURE.md 31.8 KB

# iOS architecture

How SPB Git for iOS and iPadOS is organised, and how to build a feature on it. This document describes the code as it is; commands and conventions are in DEVELOPMENT.md, the server interface in API_CONTRACT.md, the security rules in SECURITY_MODEL.md.

# 1. Stack

Swift 6 (strict concurrency complete), SwiftUI, Observation (@Observable), Swift Concurrency, URLSession, CryptoKit. iOS and iPadOS 26.0. No third-party dependency, no WebView. One app target (SPBGit), a WidgetKit extension (SPBGitWidgets), unit tests (SPBGitTests), UI tests (SPBGitUITests). The folder Shared/ is compiled into the app and the extension (section 11).

# 2. Modules

Modules are folders of the app target. The compiler does not enforce their borders; the rules below do.

text
SPBGit/
  App/                 SPBGitApp, AppEnvironment, RootView (+ TabStack, RouteDestination), Router, Route,
                       AppTab, DeepLink, LaunchOptions
  Core/
    Networking/        APIClient, Endpoint (+ Endpoints/), APIError (+ APIErrorMapper, RetryAfter),
                       APIConfiguration, VisitorPass, ProofOfWork, Reachability
    Models/            Codable models, one file per domain (Repository, Commit, Content, Refs, Stats, Search,
                       Activity, ServerMeta, Account, Writes)
    Authentication/    TokenProvider (seam), AnonymousTokenProvider, OwnerSession
    Security/          Keychain (+ access control), Redaction, UserAuthenticator, OwnerCredentialStore
    Persistence/       SharedContainer, FavouritesStore, HistoryStore, LibraryStore
    Cache/             DiskCache
    Git/               GitValidation, Permalink, LanguageDetector
  DesignSystem/
    Colors/            SPBColor, LanguagePalette
    Typography/        SPBTypography, SPBFormat
    Motion/            SPBMotion, SPBHaptics
    Themes/            SPBSpacing, SPBRadius, spbSurface, SPBAppearance, spbTheme
    Components/        LoadState, LoadableView, SPBStateNotice, SPBEmptyState, SPBErrorState, SPBSkeletonView,
                       SPBGlassCard, SPBRepositoryCard, SPBMetricCard, SPBLanguageBadge, SPBLanguageBar,
                       SPBCommitRow, SPBActivityHeatmap, SPBSearchBar, SPBSparkline, SPBFlowLayout, SPBTopicChip,
                       SPBChips, SPBInlineLabelStyle
    Code/              SPBCodeCanvas, SyntaxTheme (SPBSyntaxHighlighter), SyntaxHighlighting (the protocol)
    Charts/            SPBTimeSeriesChart, SPBRankedBarChart, SPBLanguageDonut, SPBChartSupport
    Markdown/          SPBMarkdownView, MarkdownImageView
  Services/            RepositoryService, ContentService, CommitService, StatsService, SearchService,
                       ActivityService (protocols + Live… implementations), RepositoryStore, CapabilitiesStore
  Features/<Feature>/  Dashboard, Repositories, RepositoryDetail, FileExplorer, CodeViewer, FileViewers, Commits,
                       DiffViewer, Branches, Releases, Activity, Insights, Search, Settings, Administration,
                       CodeEditor: every route of `Route` has its screen
  Features/Offline/    Offline screen, download sheet, repository card, badge, settings rows
  Platform/            Apple platform integrations: DeepLinks, Spotlight, Handoff, Intents, Background,
                       Notifications, Keyboard, Sharing, Scenes, Widgets (bridge), Debug
  PreviewSupport/      PreviewData (Debug only)
  Resources/           Assets.xcassets, Localizable.xcstrings, PrivacyInfo.xcprivacy, Info.plist

# Dependency rules

text
Features  ->  Services  ->  Core
   |             |
   +-> DesignSystem -> Core/Models, Core/Networking (APIError, Fetched) only
App  ->  everything (it is the composition root)
  • Core imports nothing from the other modules and has no SwiftUI view. (APIConfiguration reads the OS version from UIKit; Reachability is @Observable.)
  • DesignSystem knows the models it draws (Repository, CommitSummary, APIError) and nothing about services, navigation or AppEnvironment.
  • Services use APIClient and expose protocols. They validate names, refs and paths (GitValidation) before building a request.
  • A feature uses services, the design system, Route and Router. It never touches APIClient, URLSession, DiskCache, the Keychain or another feature's types. Two features share code by moving it to DesignSystem (views) or Services/Core (logic).
  • App builds the graph (AppEnvironment.live) and maps routes to screens (RouteDestination).

# 3. Data flow

text
View (.task / .refreshable)
  -> ViewModel (@MainActor @Observable, exposes LoadState<Value>)
       -> Service protocol (Sendable, async throws)
            -> APIClient actor -> URLSession          (and DiskCache, VisitorPass, TokenProvider)
       <- Fetched<Value> (value + fetchedAt + source)  or  APIError
  <- LoadState  ->  LoadableView  ->  skeleton | content | stale banner + content | SPBErrorState
  • Fetched<Value> carries the date the server last confirmed the value; LoadState.loaded(_, updatedAt:) keeps it so that screens can print "updated N min ago".
  • A view model that has something on screen keeps it when a refresh fails: state = state.failing(with: error) gives .failed(error, stale: value, updatedAt:), which LoadableView renders as the content under a one-line banner.
  • Typical load: show service.cached…() at once if the state has no value, then call the service with .cacheFirst (or .revalidate for pull to refresh), map errors with APIErrorMapper.map, ignore .cancelled. RepositoryStore.load and DashboardViewModel.loadStats are the reference implementations.

# The repository list is fetched once

GET /api/v1/repos returns every repository (about 290, about 780 KB). RepositoryStore (in AppEnvironment.repositories) holds the single in-memory copy. Home, Repositories, Search and the repository screen all read it; filtering, sorting and search are local (RepositoryQuery, DashboardSummary). Opening a repository from a list costs no request (RepositoryDetailViewModel reads the store first). No screen may issue one request per row.

# The global metrics and the collections are fetched once

MetricsStore (AppEnvironment.metrics) holds the answer of GET /api/v1/metrics as a PreparedMetrics: every series is parsed, ranked and trimmed once, off the main actor (MetricsPreparation, Services/Metrics/), and Home, Insights and the metric detail read the same value. The store shows the disk copy first, shares one request between concurrent callers, and waits and retries (bounded) when the server answers 503 with Retry-After while it computes its first aggregate; screens show SPBWarmUpPlaceholder meanwhile. CollectionsStore (AppEnvironment.collections) does the same for GET /api/v1/collections. Charts are Swift Charts components of DesignSystem/Charts/ fed with the plain values of Core/Models/ChartSeries.swift; the catalogue of charts and figures (titles, one-line definitions, keys of the server definitions) is Core/Models/MetricCatalog.swift and MetricFigure.swift. Size on disk (sizeBytes) and source volume (codeBytes) are separate charts and labels.

# 4. Concurrency model

Type Isolation Why
Views, view models, Router, AppEnvironment, RepositoryStore, CapabilitiesStore, Reachability @MainActor UI state
APIClient, VisitorPass, DiskCache, LibraryStore actor shared mutable state, off the main thread
Models, Endpoint, APIError, Fetched, LoadState, services, Keychain, Permalink Sendable values cross actors freely
ProofOfWork.solve task group of synchronous workers CPU-bound, cancellable
  • JSON decoding happens inside the APIClient actor, never on the main actor.
  • Cancellation is structural: screens load from .task, so leaving a screen cancels its requests. A shared (coalesced) request is cancelled only when all its callers are cancelled.
  • No completion handler and no @unchecked Sendable in the app target; the only dispatch queue is the one NWPathMonitor requires in Reachability.

# 5. Networking

# APIClient

APIClient.send(_ endpoint: Endpoint<Response>, policy: CachePolicy = .cacheFirst) async throws -> Fetched<Response> is the only way out. It throws APIError and nothing else. cached(_:) returns the disk copy without network.

  • Endpoints are values built by static factories (.repositories(), .tree(repository:ref:path:), .commits(repository:options:), .search(_:)…, in Core/Networking/Endpoints/). Every path component is percent-encoded, slashes included; file paths are split into components first.
  • User agent: SPBGit-iOS/<version> (<build>; iOS <os>). Never starts with Mozilla/, never contains "bot" (the shield classifies clients on that).
  • Coalescing: identical GETs in flight share one request (key = path + query).
  • Cache policy: .cacheFirst serves a disk copy younger than Endpoint.freshness without network, otherwise revalidates; .revalidate always asks, with If-None-Match when an ETag is known, and a 304 keeps the stored body; .networkOnly bypasses the cache. Raw file bytes are never cached (Endpoint.isCacheable).
  • One policy per explicit reload: ContentService.tree/blob and RepositoryService.readme/branches/tags take a CachePolicy (default implementations keep older conformers working); view models pass .revalidate when load(force: true) comes from pull to refresh or a retry, .cacheFirst otherwise.
  • Rate limits: a plain 429 becomes .rateLimited(retryAfter:); Retry-After (seconds or HTTP date) is always surfaced. The global limit is 200 requests per minute per address.
  • Errors: the envelope {"error":{"code","message"}} is mapped by APIErrorMapper to offline, timeout, shieldBusy, rateLimited, notFound, unauthorized, tokenExpired, forbidden, conflict (code, payload), validation, server, decoding, cancelled, unsupported. Each has userTitle, userMessage (localized), symbolName, isRetryable.
  • Offline copies: a GET pinned to the full SHA of a downloaded repository is answered by OfflineLibrary before any request (FetchSource.offline); when the forge is unreachable (APIError.offline, or the Debug argument -SPBOffline) a GET the library can resolve is answered by it too (section 12).
  • Authentication seam: TokenProvider.token(for: .required | .optional). When it returns a token the request carries Authorization: Bearer, goes through an ephemeral session (no cookie, redirects to another host refused), is not coalesced with anonymous callers, and its answer is never written to the disk cache. An endpoint with requiresToken fails with .unauthorized before any request when there is no token. Today the provider is AnonymousTokenProvider.

# Server versions and capabilities

Production runs 3.2.0; the routes of section 2 of the contract arrive with 3.3.0. Every 3.3.0 endpoint is declared with since: .v3_3; on a server that answers 404 not_found "no such endpoint" the client throws APIError.unsupported (shown as "Not available yet"), while a 3.2.0 route answering 404 stays .notFound. CapabilitiesStore.current (Capabilities) is read from GET /api/v1/meta, falling back to the version of /healthz, and starts at Capabilities.baseline (3.2.0). A feature checks environment.capabilities.current.supports(.metrics) before offering a 3.3.0 screen or action, and still handles .unsupported.

# Shield and visitor pass

Costly routes (tree, commits, search, raw, and their 3.3.0 siblings: Endpoint.shield == .deep) share a tiny world-wide budget for clients without a visitor pass. The app obtains the pass like the website:

  1. GET /pass/challenge gives {challenge, bits, expiresIn}.
  2. ProofOfWork.solve finds a decimal nonce such that SHA-256("<challenge>:<nonce>") starts with bits zero bits (CryptoKit, parallel workers, cancellable; refuses more than 28 bits).
  3. POST /pass/redeem {challenge, nonce} answers 204 with the cookies spb_pass (HttpOnly) and spb_pass_exp; they live in the persistent HTTPCookieStorage of the public session.

VisitorPass (actor) does this once at launch in the background (AppEnvironment.start, skipped while a valid pass is stored), again shortly before expiry (prepare() is called before each costly request and when the scene becomes active), and after a shield refusal: APIClient sees 429/503 with X-Spbgit-Shield, asks recover(shieldReason:), and retries the request once if a new pass was obtained. Reasons that mean "the pass is known and rationed" (pass-rate, pass-quota, ip-rate, net-rate, global-budget, bytes-budget) never trigger a new pass: the error is .shieldBusy(retryAfter:). A 429 on redeem sets a back-off until Retry-After; any other failure backs off 30 s. Nothing loops. The server issues six passes per hour and per address in attack mode: the client asks for one only when it has none.

FileDownloader (raw files for the viewers) and RemoteImageLoader (images of the forge in Markdown) use their own URLSession, which shares the cookie storage, and the same VisitorPassProviding: prepare() before the request, and one retry after a shield refusal when recover(shieldReason:) obtained a new pass. Images of other hosts never involve the pass.

# Disk cache and offline

DiskCache (actor) stores each public GET body with metadata {etag, storedAt, validatedAt, size} under SharedContainer.apiCacheDirectory (caches directory, purgeable), bounded to 96 MiB, least recently validated first out. Offline, APIClient.cached(_:) (through service.cached…()) gives the last copy and its date.

# 6. Navigation

  • Route (one enum, Hashable, Codable) names every pushable screen: repository, tree, blob, commits, commit, branches, tags, releases, repositoryInsights, search, settings.
  • Router (@Observable) holds the selected AppTab and one path per tab. TabStack binds a tab's NavigationStack to it and registers navigationDestination(for: Route.self) once.
  • RouteDestination is the only switch from a route to a view; every route has its screen.
  • Push with NavigationLink(value: Route.…); jump across tabs with router.open(route); switch tab with router.select(.repositories).
  • DeepLink.route(for:) parses https://git.spboucher.ai/… URLs (the shapes Permalink produces) and refuses everything else. Links from outside go through DeepLinkOpener (section 13). The Associated Domains entitlement (applinks:git.spboucher.ai) is enabled; the association file is live on the forge.
  • Zoom transitions: mark the tapped card with .spbZoomSource(route); RouteDestination applies .spbZoomDestination(route) (a plain push with Reduce Motion).
  • Search tab: an iPhone tab bar holds five items, the search tab included; a sixth is folded under "More". On compact widths the search tab is therefore hidden (Router.hasSearchTab == false) and search is the magnifier of the Home toolbar, which pushes Route.search; router.select(.search) and search deep links are redirected the same way. On regular widths the system search tab is shown.
  • iPad: the TabView is sidebarAdaptable; the Repositories tab becomes a NavigationSplitView on regular widths. The same router path serves both layouts: its first element is the selected repository, the rest is the detail column's stack.

# 7. Design system

Tokens and components are described in their files, each with previews. Rules:

  • Content rests on opaque surfaces (.spbSurface()); Liquid Glass (SPBGlassCard, .buttonStyle(.glass), the system tab bar and toolbars) is the control layer, used natively and never imitated with blur stacks.
  • Every colour is a token with light, dark and Increase Contrast values. Language colours come from the API (languages[].color), LanguagePalette is the fallback.
  • Accessibility is part of the component: Dynamic Type text styles only, combined VoiceOver labels on cards, Reduce Motion (spbAnimation, zoom fallback, static skeleton), Reduce Transparency (SPBGlassCard).
  • SyntaxHighlighting turns one line into an AttributedString and may only set attributes: the characters stay those of the line. SPBSyntaxHighlighter is used by the code canvas, the editor and the diff viewer (DiffBuilder paints its word-level emphasis by character offset on the highlighted line; a test pins the rule). PlainSyntaxHighlighter exists for tests.
  • A Label that is a chip, a badge or a caption inside a List row uses .labelStyle(.spbInline): the system style reserves an icon column there and pushes the text away from its icon.
  • Screens that own their layout instead of using LoadableView (the file viewers, the repository list) show SPBStateNotice(state) so that the offline line and the stale banner appear everywhere.
  • Title rule: the five tabs use a large title, except Insights, whose group bar is pinned under the navigation bar (a large title would be drawn behind it). Pushed screens use inline titles. In the iPad split view the repository list has no navigation bar: RepositoriesSidebarHeader is the first row of the list (under the floating tab bar the system keeps the top safe area inside the sidebar panel, which left an empty band).

# 8. How to add a feature

Example: the commit list of a repository (Route.commits).

  1. Folder: SPBGit/Features/Commits/. Files are picked up automatically.
  2. Service: use an existing protocol (CommitService.commits(repository:options:)). If the route is new, add the model in Core/Models/, the endpoint factory in Core/Networking/Endpoints/ (with shield: .deep for a costly route and since: .v3_3 for a 3.3.0 route), a method on the service protocol and its Live… implementation, a fixture and a decoding test.
  3. View model: @MainActor @Observable final class CommitsViewModel holding private(set) var state: LoadState<[CommitSummary]> = .idle, taking the service protocol in its initialiser, with func load(force: Bool = false) async written like RepositoryStore.load.
  4. Screen: struct CommitsScreen: View reading @Environment(AppEnvironment.self), creating its view model in .task, rendering LoadableView(model.state, retry: { await model.load(force: true) }) { … } inside a ScrollView or List, with .refreshable, .navigationTitle, .spbScreenBackground(). Build rows from design-system components (SPBCommitRow). Use SPBEmptyState for an empty result.
  5. Route: in RouteDestination, move case .commits out of the placeholder list and return CommitsScreen(repository:ref:). If the screen needs a new destination, add a case to Route (with title, symbol, repositoryName) and, if it has a web URL, to DeepLink and Permalink with tests.
  6. Capabilities: for a 3.3.0 route, check environment.capabilities.current.supports(…) and handle APIError.unsupported (the default SPBErrorState already explains it).
  7. Strings: add every new string to Localizable.xcstrings in English and French; run python3 scripts/l10n-audit.py.
  8. Tests: view-model tests with StubServer (success, stale on failure, no request per row), pure logic tests, and a preview using PreviewData.environment().
  9. Check: scripts/build.sh test, sp-header check ., screenshots in light, dark, English, French and on iPad (scripts/screenshots.sh), then one commit.

A tab feature (Activity, Insights, Profile) replaces the body of its existing screen (ActivityScreen, InsightsScreen, ProfileScreen): the tab, its stack and its launch argument exist.

# 9. Privacy and security posture of the foundations

  • Privacy manifest: no tracking, no collected data; required-reason API declared: UserDefaults (CA92.1). ITSAppUsesNonExemptEncryption is false. No ATS exception. The only host in the binary is git.spboucher.ai.
  • Keychain stores generic passwords with kSecAttrAccessibleWhenUnlockedThisDeviceOnly, never synchronised. Nothing uses it yet; the owner token store will.
  • Redaction masks tokens, bearer credentials and pass cookies in anything that may be logged or displayed.
  • Repository content is data: names and paths from links and from the server are validated before they reach a URL, and rendered with Text(verbatim:).
  • A name that comes from a repository (file, path, branch, tag, commit subject in a row) is drawn with SPBNameText or SPBFormat.displayName: Core/Git/DisplayName replaces bidirectional controls and zero-width characters by U+FFFD and the row shows a warning glyph with a spoken label, so that "\u{202E}gnp.exe" cannot pass for exe.png. Only the drawing changes: requests, links and copies use the real name.

# 10. Owner mode

The owner mode follows SECURITY_MODEL.md; this is where its parts live.

text
Core/Authentication/OwnerSession      actor, the TokenProvider of the client: signedOut -> unlocked <-> locked,
                                      ended(expired | revoked). The only place the token is in memory.
Core/Security/OwnerCredentialStore    Keychain: the token behind SecAccessControl(.userPresence), this device
                                      only; the identity (owner, label, scopes, expiry) in a second item.
Core/Security/UserAuthenticator       LocalAuthentication behind a protocol (stubbed in tests and automation).
Core/Git/WriteValidation              the server's rules for names, paths, topics, messages.
Services/Owner/                       OwnerGateway (never cached, a 401 ends the session), the OwnerService
                                      family (account, repositories, commits, administration), OwnerAccount
                                      (the main-actor mirror the interface reads), OwnerPresenter (sheets and
                                      the "repository changed" signal), OwnerEnvironment (one property of
                                      AppEnvironment: `environment.owner`).
Features/Settings/                    Profile tab, settings, sign-in, QR scanner.
Features/Administration/              hub, server overview, audit log, tokens, repository form, branch and tag
                                      creation, release files, DestructiveConfirmationSheet, OwnerGate,
                                      OwnerActions (the hooks).
Features/CodeEditor/                  CodeTextView (TextKit 2), indentation, highlighting engine, ChangeSet,
                                      LineDiff, DraftStore, EditingWorkspace, review, conflict.
  • The token is handed out only for routes that require one (TokenUse.required). Public reads stay anonymous: same cache, same shield treatment as a visitor, and nothing private reaches the disk cache.
  • Every write is confirmed by a read. A method of an owner service sends the write through the gateway, reads the result back with CachePolicy.revalidate (which also replaces the cached copy), and throws validation(code: "not_confirmed") when the read does not show the change. Screens show what was read.
  • Nothing is retried. A 409 is thrown to the view model as it is. CommitComposer turns head_moved and blob_changed into a conflict state that lists the incoming commits and offers two explicit ways forward.
  • Hooks. A reading screen adds owner actions with one line (OwnerActions.repositoryMenu(for:), .branchActions, .tagActions, .releaseActions, .fileActions, .directoryActions, .newBranchButton, .newTagButton) and reloads after a write with .ownerRefresh(repository:) { … }. They render nothing in public mode. Sheets and the "token refused" dialog are installed once by .ownerModeRoot() in RootView.
  • An owner screen wraps its content in OwnerGate(scope:): sign-in prompt, unlock prompt, or the missing scope, instead of content the server would refuse.
  • Drafts. Everything staged for a repository and branch is one ChangeSet, saved by DraftStore (complete file protection, file names derived from a hash) after each change and when the app leaves the foreground. When a screen restores a draft, EditingWorkspace.verifyBase() asks the server once whether the commit the draft started from still exists (OwnerCommitService.knows(commit:in:)); a 404 means the repository was deleted or recreated, and the draft is discarded with a notice instead of being flagged file by file as "changed on the server". Any other failure keeps the draft.
  • Highlighter and Markdown. EditorSyntax.highlighter() returns the SyntaxHighlighting the editor uses (SPBSyntaxHighlighter, line by line); EditorMarkdownPreview draws the text being edited with MarkdownReader. The editor follows ReaderSettings for the size and the family of its font.

# 11. Targets and shared code

Target Sources Notes
SPBGit SPBGit/, Shared/ entitlements SPBGit/Resources/SPBGit.entitlements: App Group group.ai.spboucher.git, applinks:git.spboucher.ai, aps-environment
SPBGitWidgets SPBGitWidgets/, Shared/, the app's Assets.xcassets and Localizable.xcstrings App Group only; extension-safe API only

Shared/ holds what both need and nothing that knows a credential: ForgeSnapshot and friends (public figures), ForgeFeed (four open routes, anonymous, ephemeral session), WidgetSnapshotStore (JSON files in the App Group), WidgetDataLoader and WidgetRefreshPolicy, SPBLink (the spbgit:// scheme), RepositoryEntity and its query, and the widget views themselves (ForgeWidgetView, RepositoryWidgetView). The views live there so that the app can draw exactly what the extension draws (Debug gallery, -SPBScreen widgets). Shared/ uses system fonts and the colour sets of the shared asset catalog, never SPBColor or a service of the app.

Widget data flow: the app writes forge.json, repositories.json and one snapshot per favourite or followed repository each time its own data refreshes (WidgetBridge); a timeline shows that copy when it is younger than 30 minutes, otherwise the extension makes its own requests (/api/v1/metrics, falling back to /api/v1/stats, and /api/v1/activity?perPage=1&type=push; /api/v1/repos/:name for the favourite repository) and stores the answer for the other widgets. One entry per timeline, next reload 30 to 60 minutes later. No token ever reaches the App Group.

# 12. Offline reading

Storage decision: files, not SwiftData. What is stored is the body of API answers, written once, addressed by a key, looked up by hash, measured and deleted by directory; the manifest of a copy is a few hundred small records with no relation to query. Files give atomic writes, exact sizes, removal with one removeItem, exclusion from backups by one resource value, and an actor that owns them off the main thread under strict concurrency. SwiftData would add a model container, main-actor contexts and a schema to migrate, and would store the bodies as external files anyway. The small stores that existed (favourites and history in library.json, follows and pins in UserDefaults) keep their API and their backing: a few kilobytes read once gain nothing from a database. They move into the App Group the first time the group is available (SharedContainer.migrateToGroupIfNeeded).

text
Application Support/SPBGit/offline/            (app container, excluded from backups, never in the App Group)
  <sha256(repository@sha)>/manifest.json       OfflineSet: status, counts, dates, items by key
  <sha256(repository@sha)>/objects/<sha256(key)>   the stored answer, byte for byte
  • OfflineRequest turns an endpoint into (repository, route, ref, parameters); its key ignores the ref, so tree?path=src is one stored answer whether the screen asked for the SHA, the branch or nothing.
  • OfflineLibrary (actor, OfflineResponseSource): .pinned lookups serve tree, blob and readme requests that name the full SHA of a stored copy; .fallback lookups (network unreachable) also resolve no ref, the downloaded branch or an abbreviated SHA to the readable copy, and serve the metadata stored at download time (repository, languages, branches, tags, first page of commits). Fetched.fetchedAt is the synchronisation date.
  • OfflinePlanner (pure): text files under 512 kB each, 48 MB and 3000 files per repository, binary extensions and dependency directories left out. OfflineEstimate uses fileCount and languageBytes of the repository list (no request): confirmation above 300 files or 8 MB, refusal above 20 000 files or 512 MB of source.
  • OfflineDownloader: one request at a time, 0.4 s apart, .networkOnly, everything pinned to the SHA; waits for Retry-After of a rate limit (three times, 120 s at most), pauses on a shield refusal or a lost connection, keeps a blob only when GitBlobID of its content equals its oid, and resumes from what is stored. It runs on its own anonymous APIClient: what is stored is what any visitor can read.
  • OfflineStore (@MainActor @Observable, AppEnvironment.offline): availability(repository:head:), estimate, download, pause, resume, cancel, remove, removeAll, verify, ceilingBytes (least recently used copies are evicted first). Nothing starts a download but a tap; the background refresh never does.
  • LoadableView shows SPBOfflineIndicator ("Offline. Saved 3 hours ago.") above loaded content when \.spbConnectivity says the device is offline; SceneRoot sets it from Reachability.

# 13. Platform integrations

  • Links: DeepLink.route(for:refs:) resolves refs containing a slash against branch and tag names (longest match, first component otherwise); DeepLinkOpener asks for those names only when DeepLink.refQuestion says the link is ambiguous. Screens without a web page travel as parameters of the nearest page (commits/<ref>?path=, commits?view=graph, commit/<sha>?view=diff&path=, branches?base=&head=, /?collection=, search?q=&repo=&scope=), so a shared link still lands somewhere sensible in a browser. Permalink.url(for:) is the single route-to-URL mapping; SPBLink is the same thing under spbgit://r/…, plus spbgit://tab/<name>, spbgit://offline, spbgit://notifications.
  • Windows: SceneRoot gives each window its own Router (AppEnvironment.claimRouter()), restored from SceneStorage (Router.Snapshot). PlatformCoordinator knows the window used last: notifications and intents open there.
  • Spotlight: SpotlightIndexer replaces the domain ai.spboucher.git.repositories when the repository list changes (name, description, topics, languages); it can be turned off, which removes the index.
  • Handoff: RouteDestination applies .spbUserActivity(route); the activity carries the web URL and comes back through DeepLink like any link.
  • Intents: OpenRepositoryIntent, SearchSPBGitIntent, ShowActivityIntent, GetForgeStatsIntent, LastCommitIntent, SPBShortcuts (phrases in AppShortcuts.xcstrings), SelectRepositoryIntent for the widget.
  • Notifications: ActivityCheck (pure) decides what is announced; ActivityChecker reads /api/v1/activity since its cursor and posts one local notification per followed repository; it runs from .backgroundTask(.appRefresh("ai.spboucher.git.refresh")) when iOS grants one, when the app opens (at most every 30 minutes) and from "Check now". PushRegistrar and NotificationModel register the APNs token with POST /api/v1/devices when meta.features.push is true and fall back to the local path on 501.
  • Keyboard: SPBCommands (⌘F, ⌘1…⌘5, ⌘[ and ⌘], ⌘R, ⌘,). ⌘R increments Router.refreshRequest, which LoadableView observes through \.spbRefreshRequest and answers by calling its retry.
  • Sharing and pointer: ShareItem + SPBShareLink (always the Permalink URL), .spbLinkInteractions(url:) (hover highlight, drag of the URL).
Files main
Menu

Theme