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.
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.plistDependency rules
Features -> Services -> Core
| |
+-> DesignSystem -> Core/Models, Core/Networking (APIError, Fetched) only
App -> everything (it is the composition root)Coreimports nothing from the other modules and has no SwiftUI view. (APIConfigurationreads the OS version from UIKit;Reachabilityis@Observable.)DesignSystemknows the models it draws (Repository,CommitSummary,APIError) and nothing about services, navigation orAppEnvironment.ServicesuseAPIClientand expose protocols. They validate names, refs and paths (GitValidation) before building a request.- A feature uses services, the design system,
RouteandRouter. It never touchesAPIClient,URLSession,DiskCache, the Keychain or another feature's types. Two features share code by moving it toDesignSystem(views) orServices/Core(logic). Appbuilds the graph (AppEnvironment.live) and maps routes to screens (RouteDestination).
3. Data flow
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 | SPBErrorStateFetched<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:), whichLoadableViewrenders as the content under a one-line banner. - Typical
load: showservice.cached…()at once if the state has no value, then call the service with.cacheFirst(or.revalidatefor pull to refresh), map errors withAPIErrorMapper.map, ignore.cancelled.RepositoryStore.loadandDashboardViewModel.loadStatsare 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
APIClientactor, 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 Sendablein the app target; the only dispatch queue is the oneNWPathMonitorrequires inReachability.
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(_:)…, inCore/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 withMozilla/, never contains "bot" (the shield classifies clients on that). - Coalescing: identical GETs in flight share one request (key = path + query).
- Cache policy:
.cacheFirstserves a disk copy younger thanEndpoint.freshnesswithout network, otherwise revalidates;.revalidatealways asks, withIf-None-Matchwhen an ETag is known, and a304keeps the stored body;.networkOnlybypasses the cache. Raw file bytes are never cached (Endpoint.isCacheable). - One policy per explicit reload:
ContentService.tree/blobandRepositoryService.readme/branches/tagstake aCachePolicy(default implementations keep older conformers working); view models pass.revalidatewhenload(force: true)comes from pull to refresh or a retry,.cacheFirstotherwise. - Rate limits: a plain
429becomes.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 byAPIErrorMappertooffline, timeout, shieldBusy, rateLimited, notFound, unauthorized, tokenExpired, forbidden, conflict (code, payload), validation, server, decoding, cancelled, unsupported. Each hasuserTitle,userMessage(localized),symbolName,isRetryable. - Offline copies: a GET pinned to the full SHA of a downloaded repository is answered by
OfflineLibrarybefore 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 carriesAuthorization: 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 withrequiresTokenfails with.unauthorizedbefore any request when there is no token. Today the provider isAnonymousTokenProvider.
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:
GET /pass/challengegives{challenge, bits, expiresIn}.ProofOfWork.solvefinds a decimal nonce such thatSHA-256("<challenge>:<nonce>")starts withbitszero bits (CryptoKit, parallel workers, cancellable; refuses more than 28 bits).POST /pass/redeem {challenge, nonce}answers204with the cookiesspb_pass(HttpOnly) andspb_pass_exp; they live in the persistentHTTPCookieStorageof 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 selectedAppTaband one path per tab.TabStackbinds a tab'sNavigationStackto it and registersnavigationDestination(for: Route.self)once.RouteDestinationis the only switch from a route to a view; every route has its screen.- Push with
NavigationLink(value: Route.…); jump across tabs withrouter.open(route); switch tab withrouter.select(.repositories). DeepLink.route(for:)parseshttps://git.spboucher.ai/…URLs (the shapesPermalinkproduces) and refuses everything else. Links from outside go throughDeepLinkOpener(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);RouteDestinationapplies.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 pushesRoute.search;router.select(.search)and search deep links are redirected the same way. On regular widths the system search tab is shown. - iPad: the
TabViewissidebarAdaptable; the Repositories tab becomes aNavigationSplitViewon 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),LanguagePaletteis 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). SyntaxHighlightingturns one line into anAttributedStringand may only set attributes: the characters stay those of the line.SPBSyntaxHighlighteris used by the code canvas, the editor and the diff viewer (DiffBuilderpaints its word-level emphasis by character offset on the highlighted line; a test pins the rule).PlainSyntaxHighlighterexists for tests.- A
Labelthat is a chip, a badge or a caption inside aListrow 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) showSPBStateNotice(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:
RepositoriesSidebarHeaderis 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).
- Folder:
SPBGit/Features/Commits/. Files are picked up automatically. - Service: use an existing protocol (
CommitService.commits(repository:options:)). If the route is new, add the model inCore/Models/, the endpoint factory inCore/Networking/Endpoints/(withshield: .deepfor a costly route andsince: .v3_3for a 3.3.0 route), a method on the service protocol and itsLive…implementation, a fixture and a decoding test. - View model:
@MainActor @Observable final class CommitsViewModelholdingprivate(set) var state: LoadState<[CommitSummary]> = .idle, taking the service protocol in its initialiser, withfunc load(force: Bool = false) asyncwritten likeRepositoryStore.load. - Screen:
struct CommitsScreen: Viewreading@Environment(AppEnvironment.self), creating its view model in.task, renderingLoadableView(model.state, retry: { await model.load(force: true) }) { … }inside aScrollVieworList, with.refreshable,.navigationTitle,.spbScreenBackground(). Build rows from design-system components (SPBCommitRow). UseSPBEmptyStatefor an empty result. - Route: in
RouteDestination, movecase .commitsout of the placeholder list and returnCommitsScreen(repository:ref:). If the screen needs a new destination, add a case toRoute(withtitle,symbol,repositoryName) and, if it has a web URL, toDeepLinkandPermalinkwith tests. - Capabilities: for a 3.3.0 route, check
environment.capabilities.current.supports(…)and handleAPIError.unsupported(the defaultSPBErrorStatealready explains it). - Strings: add every new string to
Localizable.xcstringsin English and French; runpython3 scripts/l10n-audit.py. - Tests: view-model tests with
StubServer(success, stale on failure, no request per row), pure logic tests, and a preview usingPreviewData.environment(). - 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).ITSAppUsesNonExemptEncryptionisfalse. No ATS exception. The only host in the binary isgit.spboucher.ai. Keychainstores generic passwords withkSecAttrAccessibleWhenUnlockedThisDeviceOnly, never synchronised. Nothing uses it yet; the owner token store will.Redactionmasks 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
SPBNameTextorSPBFormat.displayName:Core/Git/DisplayNamereplaces 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 forexe.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.
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 throwsvalidation(code: "not_confirmed")when the read does not show the change. Screens show what was read. - Nothing is retried. A
409is thrown to the view model as it is.CommitComposerturnshead_movedandblob_changedinto 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()inRootView. - 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 byDraftStore(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:)); a404means 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 theSyntaxHighlightingthe editor uses (SPBSyntaxHighlighter, line by line);EditorMarkdownPreviewdraws the text being edited withMarkdownReader. The editor followsReaderSettingsfor 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).
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 byteOfflineRequestturns an endpoint into(repository, route, ref, parameters); itskeyignores the ref, sotree?path=srcis one stored answer whether the screen asked for the SHA, the branch or nothing.OfflineLibrary(actor,OfflineResponseSource):.pinnedlookups servetree,blobandreadmerequests that name the full SHA of a stored copy;.fallbacklookups (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.fetchedAtis 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.OfflineEstimateusesfileCountandlanguageBytesof 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 forRetry-Afterof a rate limit (three times, 120 s at most), pauses on a shield refusal or a lost connection, keeps a blob only whenGitBlobIDof its content equals itsoid, and resumes from what is stored. It runs on its own anonymousAPIClient: 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.LoadableViewshowsSPBOfflineIndicator("Offline. Saved 3 hours ago.") above loaded content when\.spbConnectivitysays the device is offline;SceneRootsets it fromReachability.
13. Platform integrations
- Links:
DeepLink.route(for:refs:)resolves refs containing a slash against branch and tag names (longest match, first component otherwise);DeepLinkOpenerasks for those names only whenDeepLink.refQuestionsays 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;SPBLinkis the same thing underspbgit://r/…, plusspbgit://tab/<name>,spbgit://offline,spbgit://notifications. - Windows:
SceneRootgives each window its ownRouter(AppEnvironment.claimRouter()), restored fromSceneStorage(Router.Snapshot).PlatformCoordinatorknows the window used last: notifications and intents open there. - Spotlight:
SpotlightIndexerreplaces the domainai.spboucher.git.repositorieswhen the repository list changes (name, description, topics, languages); it can be turned off, which removes the index. - Handoff:
RouteDestinationapplies.spbUserActivity(route); the activity carries the web URL and comes back throughDeepLinklike any link. - Intents:
OpenRepositoryIntent,SearchSPBGitIntent,ShowActivityIntent,GetForgeStatsIntent,LastCommitIntent,SPBShortcuts(phrases inAppShortcuts.xcstrings),SelectRepositoryIntentfor the widget. - Notifications:
ActivityCheck(pure) decides what is announced;ActivityCheckerreads/api/v1/activitysince 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".PushRegistrarandNotificationModelregister the APNs token withPOST /api/v1/deviceswhenmeta.features.pushis true and fall back to the local path on501. - Keyboard:
SPBCommands(⌘F, ⌘1…⌘5, ⌘[ and ⌘], ⌘R, ⌘,). ⌘R incrementsRouter.refreshRequest, whichLoadableViewobserves through\.spbRefreshRequestand answers by calling itsretry. - Sharing and pointer:
ShareItem+SPBShareLink(always thePermalinkURL),.spbLinkInteractions(url:)(hover highlight, drag of the URL).