Repository Public
1# iOS architecture23How SPB Git for iOS and iPadOS is organised, and how to build a feature on it. This document describes the4code as it is; commands and conventions are in [`DEVELOPMENT.md`](DEVELOPMENT.md), the server interface in5[`API_CONTRACT.md`](API_CONTRACT.md), the security rules in [`SECURITY_MODEL.md`](SECURITY_MODEL.md).67## 1. Stack89Swift 6 (strict concurrency `complete`), SwiftUI, Observation (`@Observable`), Swift Concurrency, `URLSession`,10CryptoKit. iOS and iPadOS 26.0. No third-party dependency, no WebView. One app target (`SPBGit`), a WidgetKit11extension (`SPBGitWidgets`), unit tests (`SPBGitTests`), UI tests (`SPBGitUITests`). The folder `Shared/` is12compiled into the app and the extension (section 11).1314## 2. Modules1516Modules are folders of the app target. The compiler does not enforce their borders; the rules below do.1718```19SPBGit/20 App/ SPBGitApp, AppEnvironment, RootView (+ TabStack, RouteDestination), Router, Route,21 AppTab, DeepLink, LaunchOptions22 Core/23 Networking/ APIClient, Endpoint (+ Endpoints/), APIError (+ APIErrorMapper, RetryAfter),24 APIConfiguration, VisitorPass, ProofOfWork, Reachability25 Models/ Codable models, one file per domain (Repository, Commit, Content, Refs, Stats, Search,26 Activity, ServerMeta, Account, Writes)27 Authentication/ TokenProvider (seam), AnonymousTokenProvider, OwnerSession28 Security/ Keychain (+ access control), Redaction, UserAuthenticator, OwnerCredentialStore29 Persistence/ SharedContainer, FavouritesStore, HistoryStore, LibraryStore30 Cache/ DiskCache31 Git/ GitValidation, Permalink, LanguageDetector32 DesignSystem/33 Colors/ SPBColor, LanguagePalette34 Typography/ SPBTypography, SPBFormat35 Motion/ SPBMotion, SPBHaptics36 Themes/ SPBSpacing, SPBRadius, spbSurface, SPBAppearance, spbTheme37 Components/ LoadState, LoadableView, SPBStateNotice, SPBEmptyState, SPBErrorState, SPBSkeletonView,38 SPBGlassCard, SPBRepositoryCard, SPBMetricCard, SPBLanguageBadge, SPBLanguageBar,39 SPBCommitRow, SPBActivityHeatmap, SPBSearchBar, SPBSparkline, SPBFlowLayout, SPBTopicChip,40 SPBChips, SPBInlineLabelStyle41 Code/ SPBCodeCanvas, SyntaxTheme (SPBSyntaxHighlighter), SyntaxHighlighting (the protocol)42 Charts/ SPBTimeSeriesChart, SPBRankedBarChart, SPBLanguageDonut, SPBChartSupport43 Markdown/ SPBMarkdownView, MarkdownImageView44 Services/ RepositoryService, ContentService, CommitService, StatsService, SearchService,45 ActivityService (protocols + Live… implementations), RepositoryStore, CapabilitiesStore46 Features/<Feature>/ Dashboard, Repositories, RepositoryDetail, FileExplorer, CodeViewer, FileViewers, Commits,47 DiffViewer, Branches, Releases, Activity, Insights, Search, Settings, Administration,48 CodeEditor: every route of `Route` has its screen49 Features/Offline/ Offline screen, download sheet, repository card, badge, settings rows50 Platform/ Apple platform integrations: DeepLinks, Spotlight, Handoff, Intents, Background,51 Notifications, Keyboard, Sharing, Scenes, Widgets (bridge), Debug52 PreviewSupport/ PreviewData (Debug only)53 Resources/ Assets.xcassets, Localizable.xcstrings, PrivacyInfo.xcprivacy, Info.plist54```5556### Dependency rules5758```59Features -> Services -> Core60 | |61 +-> DesignSystem -> Core/Models, Core/Networking (APIError, Fetched) only62App -> everything (it is the composition root)63```6465- `Core` imports nothing from the other modules and has no SwiftUI view. (`APIConfiguration` reads the OS66 version from UIKit; `Reachability` is `@Observable`.)67- `DesignSystem` knows the models it draws (`Repository`, `CommitSummary`, `APIError`) and nothing about68 services, navigation or `AppEnvironment`.69- `Services` use `APIClient` and expose protocols. They validate names, refs and paths (`GitValidation`)70 before building a request.71- A feature uses services, the design system, `Route` and `Router`. It never touches `APIClient`,72 `URLSession`, `DiskCache`, the Keychain or another feature's types. Two features share code by moving it to73 `DesignSystem` (views) or `Services`/`Core` (logic).74- `App` builds the graph (`AppEnvironment.live`) and maps routes to screens (`RouteDestination`).7576## 3. Data flow7778```79View (.task / .refreshable)80 -> ViewModel (@MainActor @Observable, exposes LoadState<Value>)81 -> Service protocol (Sendable, async throws)82 -> APIClient actor -> URLSession (and DiskCache, VisitorPass, TokenProvider)83 <- Fetched<Value> (value + fetchedAt + source) or APIError84 <- LoadState -> LoadableView -> skeleton | content | stale banner + content | SPBErrorState85```8687- `Fetched<Value>` carries the date the server last confirmed the value; `LoadState.loaded(_, updatedAt:)`88 keeps it so that screens can print "updated N min ago".89- A view model that has something on screen keeps it when a refresh fails:90 `state = state.failing(with: error)` gives `.failed(error, stale: value, updatedAt:)`, which `LoadableView`91 renders as the content under a one-line banner.92- Typical `load`: show `service.cached…()` at once if the state has no value, then call the service with93 `.cacheFirst` (or `.revalidate` for pull to refresh), map errors with `APIErrorMapper.map`, ignore94 `.cancelled`. `RepositoryStore.load` and `DashboardViewModel.loadStats` are the reference implementations.9596### The repository list is fetched once9798`GET /api/v1/repos` returns every repository (about 290, about 780 KB). `RepositoryStore` (in99`AppEnvironment.repositories`) holds the single in-memory copy. Home, Repositories, Search and the repository100screen all read it; filtering, sorting and search are local (`RepositoryQuery`, `DashboardSummary`). Opening a101repository from a list costs no request (`RepositoryDetailViewModel` reads the store first). No screen may102issue one request per row.103104### The global metrics and the collections are fetched once105106`MetricsStore` (`AppEnvironment.metrics`) holds the answer of `GET /api/v1/metrics` as a `PreparedMetrics`: every107series is parsed, ranked and trimmed once, off the main actor (`MetricsPreparation`, `Services/Metrics/`), and Home,108Insights and the metric detail read the same value. The store shows the disk copy first, shares one request between109concurrent callers, and waits and retries (bounded) when the server answers `503` with `Retry-After` while it110computes its first aggregate; screens show `SPBWarmUpPlaceholder` meanwhile. `CollectionsStore`111(`AppEnvironment.collections`) does the same for `GET /api/v1/collections`. Charts are Swift Charts components of112`DesignSystem/Charts/` fed with the plain values of `Core/Models/ChartSeries.swift`; the catalogue of charts and113figures (titles, one-line definitions, keys of the server `definitions`) is `Core/Models/MetricCatalog.swift` and114`MetricFigure.swift`. Size on disk (`sizeBytes`) and source volume (`codeBytes`) are separate charts and labels.115116## 4. Concurrency model117118| Type | Isolation | Why |119|---|---|---|120| Views, view models, `Router`, `AppEnvironment`, `RepositoryStore`, `CapabilitiesStore`, `Reachability` | `@MainActor` | UI state |121| `APIClient`, `VisitorPass`, `DiskCache`, `LibraryStore` | `actor` | shared mutable state, off the main thread |122| Models, `Endpoint`, `APIError`, `Fetched`, `LoadState`, services, `Keychain`, `Permalink` | `Sendable` values | cross actors freely |123| `ProofOfWork.solve` | task group of synchronous workers | CPU-bound, cancellable |124125- JSON decoding happens inside the `APIClient` actor, never on the main actor.126- Cancellation is structural: screens load from `.task`, so leaving a screen cancels its requests. A shared127 (coalesced) request is cancelled only when all its callers are cancelled.128- No completion handler and no `@unchecked Sendable` in the app target; the only dispatch queue is the one129 `NWPathMonitor` requires in `Reachability`.130131## 5. Networking132133### APIClient134135`APIClient.send(_ endpoint: Endpoint<Response>, policy: CachePolicy = .cacheFirst) async throws -> Fetched<Response>`136is the only way out. It throws `APIError` and nothing else. `cached(_:)` returns the disk copy without network.137138- **Endpoints** are values built by static factories (`.repositories()`, `.tree(repository:ref:path:)`,139 `.commits(repository:options:)`, `.search(_:)`…, in `Core/Networking/Endpoints/`). Every path component is140 percent-encoded, slashes included; file paths are split into components first.141- **User agent**: `SPBGit-iOS/<version> (<build>; iOS <os>)`. Never starts with `Mozilla/`, never contains142 "bot" (the shield classifies clients on that).143- **Coalescing**: identical GETs in flight share one request (key = path + query).144- **Cache policy**: `.cacheFirst` serves a disk copy younger than `Endpoint.freshness` without network,145 otherwise revalidates; `.revalidate` always asks, with `If-None-Match` when an ETag is known, and a `304`146 keeps the stored body; `.networkOnly` bypasses the cache. Raw file bytes are never cached147 (`Endpoint.isCacheable`).148- **One policy per explicit reload**: `ContentService.tree/blob` and `RepositoryService.readme/branches/tags`149 take a `CachePolicy` (default implementations keep older conformers working); view models pass `.revalidate`150 when `load(force: true)` comes from pull to refresh or a retry, `.cacheFirst` otherwise.151- **Rate limits**: a plain `429` becomes `.rateLimited(retryAfter:)`; `Retry-After` (seconds or HTTP date)152 is always surfaced. The global limit is 200 requests per minute per address.153- **Errors**: the envelope `{"error":{"code","message"}}` is mapped by `APIErrorMapper` to154 `offline, timeout, shieldBusy, rateLimited, notFound, unauthorized, tokenExpired, forbidden, conflict155 (code, payload), validation, server, decoding, cancelled, unsupported`. Each has `userTitle`,156 `userMessage` (localized), `symbolName`, `isRetryable`.157- **Offline copies**: a GET pinned to the full SHA of a downloaded repository is answered by `OfflineLibrary`158 before any request (`FetchSource.offline`); when the forge is unreachable (`APIError.offline`, or the Debug159 argument `-SPBOffline`) a GET the library can resolve is answered by it too (section 12).160- **Authentication seam**: `TokenProvider.token(for: .required | .optional)`. When it returns a token the161 request carries `Authorization: Bearer`, goes through an ephemeral session (no cookie, redirects to another162 host refused), is not coalesced with anonymous callers, and its answer is never written to the disk cache.163 An endpoint with `requiresToken` fails with `.unauthorized` before any request when there is no token.164 Today the provider is `AnonymousTokenProvider`.165166### Server versions and capabilities167168Production runs 3.2.0; the routes of section 2 of the contract arrive with 3.3.0. Every 3.3.0 endpoint is169declared with `since: .v3_3`; on a server that answers `404 not_found "no such endpoint"` the client throws170`APIError.unsupported` (shown as "Not available yet"), while a 3.2.0 route answering 404 stays `.notFound`.171`CapabilitiesStore.current` (`Capabilities`) is read from `GET /api/v1/meta`, falling back to the version of172`/healthz`, and starts at `Capabilities.baseline` (3.2.0). A feature checks173`environment.capabilities.current.supports(.metrics)` before offering a 3.3.0 screen or action, and still174handles `.unsupported`.175176### Shield and visitor pass177178Costly routes (`tree`, `commits`, `search`, `raw`, and their 3.3.0 siblings: `Endpoint.shield == .deep`) share179a tiny world-wide budget for clients without a visitor pass. The app obtains the pass like the website:1801811. `GET /pass/challenge` gives `{challenge, bits, expiresIn}`.1822. `ProofOfWork.solve` finds a decimal nonce such that `SHA-256("<challenge>:<nonce>")` starts with `bits`183 zero bits (CryptoKit, parallel workers, cancellable; refuses more than 28 bits).1843. `POST /pass/redeem {challenge, nonce}` answers `204` with the cookies `spb_pass` (HttpOnly) and185 `spb_pass_exp`; they live in the persistent `HTTPCookieStorage` of the public session.186187`VisitorPass` (actor) does this once at launch in the background (`AppEnvironment.start`, skipped while a188valid pass is stored), again shortly before expiry (`prepare()` is called before each costly request and when189the scene becomes active), and after a shield refusal: `APIClient` sees `429`/`503` with `X-Spbgit-Shield`,190asks `recover(shieldReason:)`, and retries the request **once** if a new pass was obtained. Reasons that mean191"the pass is known and rationed" (`pass-rate`, `pass-quota`, `ip-rate`, `net-rate`, `global-budget`,192`bytes-budget`) never trigger a new pass: the error is `.shieldBusy(retryAfter:)`. A `429` on redeem sets a193back-off until `Retry-After`; any other failure backs off 30 s. Nothing loops. The server issues six passes194per hour and per address in attack mode: the client asks for one only when it has none.195196`FileDownloader` (raw files for the viewers) and `RemoteImageLoader` (images of the forge in Markdown) use their197own `URLSession`, which shares the cookie storage, and the same `VisitorPassProviding`: `prepare()` before the198request, and one retry after a shield refusal when `recover(shieldReason:)` obtained a new pass. Images of other199hosts never involve the pass.200201### Disk cache and offline202203`DiskCache` (actor) stores each public GET body with metadata `{etag, storedAt, validatedAt, size}` under204`SharedContainer.apiCacheDirectory` (caches directory, purgeable), bounded to 96 MiB, least recently validated205first out. Offline, `APIClient.cached(_:)` (through `service.cached…()`) gives the last copy and its date.206207## 6. Navigation208209- `Route` (one enum, `Hashable`, `Codable`) names every pushable screen: `repository`, `tree`, `blob`,210 `commits`, `commit`, `branches`, `tags`, `releases`, `repositoryInsights`, `search`, `settings`.211- `Router` (`@Observable`) holds the selected `AppTab` and one path per tab. `TabStack` binds a tab's212 `NavigationStack` to it and registers `navigationDestination(for: Route.self)` once.213- `RouteDestination` is the only switch from a route to a view; every route has its screen.214- Push with `NavigationLink(value: Route.…)`; jump across tabs with `router.open(route)`; switch tab with215 `router.select(.repositories)`.216- `DeepLink.route(for:)` parses `https://git.spboucher.ai/…` URLs (the shapes `Permalink` produces) and217 refuses everything else. Links from outside go through `DeepLinkOpener` (section 13). The Associated Domains218 entitlement (`applinks:git.spboucher.ai`) is enabled; the association file is live on the forge.219- Zoom transitions: mark the tapped card with `.spbZoomSource(route)`; `RouteDestination` applies220 `.spbZoomDestination(route)` (a plain push with Reduce Motion).221- Search tab: an iPhone tab bar holds five items, the search tab included; a sixth is folded under "More".222 On compact widths the search tab is therefore hidden (`Router.hasSearchTab == false`) and search is the223 magnifier of the Home toolbar, which pushes `Route.search`; `router.select(.search)` and search deep links224 are redirected the same way. On regular widths the system search tab is shown.225- iPad: the `TabView` is `sidebarAdaptable`; the Repositories tab becomes a `NavigationSplitView` on regular226 widths. The same router path serves both layouts: its first element is the selected repository, the rest is227 the detail column's stack.228229## 7. Design system230231Tokens and components are described in their files, each with previews. Rules:232233- Content rests on opaque surfaces (`.spbSurface()`); Liquid Glass (`SPBGlassCard`, `.buttonStyle(.glass)`,234 the system tab bar and toolbars) is the control layer, used natively and never imitated with blur stacks.235- Every colour is a token with light, dark and Increase Contrast values. Language colours come from the API236 (`languages[].color`), `LanguagePalette` is the fallback.237- Accessibility is part of the component: Dynamic Type text styles only, combined VoiceOver labels on cards,238 Reduce Motion (`spbAnimation`, zoom fallback, static skeleton), Reduce Transparency (`SPBGlassCard`).239- `SyntaxHighlighting` turns one line into an `AttributedString` and may only set attributes: the characters240 stay those of the line. `SPBSyntaxHighlighter` is used by the code canvas, the editor and the diff viewer241 (`DiffBuilder` paints its word-level emphasis by character offset on the highlighted line; a test pins the242 rule). `PlainSyntaxHighlighter` exists for tests.243- A `Label` that is a chip, a badge or a caption inside a `List` row uses `.labelStyle(.spbInline)`: the system244 style reserves an icon column there and pushes the text away from its icon.245- Screens that own their layout instead of using `LoadableView` (the file viewers, the repository list) show246 `SPBStateNotice(state)` so that the offline line and the stale banner appear everywhere.247- Title rule: the five tabs use a large title, except Insights, whose group bar is pinned under the navigation248 bar (a large title would be drawn behind it). Pushed screens use inline titles. In the iPad split view the249 repository list has no navigation bar: `RepositoriesSidebarHeader` is the first row of the list (under the250 floating tab bar the system keeps the top safe area inside the sidebar panel, which left an empty band).251252## 8. How to add a feature253254Example: the commit list of a repository (`Route.commits`).2552561. **Folder**: `SPBGit/Features/Commits/`. Files are picked up automatically.2572. **Service**: use an existing protocol (`CommitService.commits(repository:options:)`). If the route is new,258 add the model in `Core/Models/`, the endpoint factory in `Core/Networking/Endpoints/` (with `shield: .deep`259 for a costly route and `since: .v3_3` for a 3.3.0 route), a method on the service protocol and its `Live…`260 implementation, a fixture and a decoding test.2613. **View model**: `@MainActor @Observable final class CommitsViewModel` holding262 `private(set) var state: LoadState<[CommitSummary]> = .idle`, taking the service protocol in its263 initialiser, with `func load(force: Bool = false) async` written like `RepositoryStore.load`.2644. **Screen**: `struct CommitsScreen: View` reading `@Environment(AppEnvironment.self)`, creating its view265 model in `.task`, rendering `LoadableView(model.state, retry: { await model.load(force: true) }) { … }`266 inside a `ScrollView` or `List`, with `.refreshable`, `.navigationTitle`, `.spbScreenBackground()`. Build267 rows from design-system components (`SPBCommitRow`). Use `SPBEmptyState` for an empty result.2685. **Route**: in `RouteDestination`, move `case .commits` out of the placeholder list and return269 `CommitsScreen(repository:ref:)`. If the screen needs a new destination, add a case to `Route` (with270 `title`, `symbol`, `repositoryName`) and, if it has a web URL, to `DeepLink` and `Permalink` with tests.2716. **Capabilities**: for a 3.3.0 route, check `environment.capabilities.current.supports(…)` and handle272 `APIError.unsupported` (the default `SPBErrorState` already explains it).2737. **Strings**: add every new string to `Localizable.xcstrings` in English and French; run274 `python3 scripts/l10n-audit.py`.2758. **Tests**: view-model tests with `StubServer` (success, stale on failure, no request per row), pure logic276 tests, and a preview using `PreviewData.environment()`.2779. **Check**: `scripts/build.sh test`, `sp-header check .`, screenshots in light, dark, English, French and278 on iPad (`scripts/screenshots.sh`), then one commit.279280A tab feature (Activity, Insights, Profile) replaces the body of its existing screen281(`ActivityScreen`, `InsightsScreen`, `ProfileScreen`): the tab, its stack and its launch argument exist.282283## 9. Privacy and security posture of the foundations284285- Privacy manifest: no tracking, no collected data; required-reason API declared: `UserDefaults` (`CA92.1`).286 `ITSAppUsesNonExemptEncryption` is `false`. No ATS exception. The only host in the binary is287 `git.spboucher.ai`.288- `Keychain` stores generic passwords with `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`, never289 synchronised. Nothing uses it yet; the owner token store will.290- `Redaction` masks tokens, bearer credentials and pass cookies in anything that may be logged or displayed.291- Repository content is data: names and paths from links and from the server are validated before they292 reach a URL, and rendered with `Text(verbatim:)`.293- A name that comes from a repository (file, path, branch, tag, commit subject in a row) is drawn with294 `SPBNameText` or `SPBFormat.displayName`: `Core/Git/DisplayName` replaces bidirectional controls and zero-width295 characters by U+FFFD and the row shows a warning glyph with a spoken label, so that `"\u{202E}gnp.exe"` cannot296 pass for `exe.png`. Only the drawing changes: requests, links and copies use the real name.297298## 10. Owner mode299300The owner mode follows [`SECURITY_MODEL.md`](SECURITY_MODEL.md); this is where its parts live.301302```303Core/Authentication/OwnerSession actor, the TokenProvider of the client: signedOut -> unlocked <-> locked,304 ended(expired | revoked). The only place the token is in memory.305Core/Security/OwnerCredentialStore Keychain: the token behind SecAccessControl(.userPresence), this device306 only; the identity (owner, label, scopes, expiry) in a second item.307Core/Security/UserAuthenticator LocalAuthentication behind a protocol (stubbed in tests and automation).308Core/Git/WriteValidation the server's rules for names, paths, topics, messages.309Services/Owner/ OwnerGateway (never cached, a 401 ends the session), the OwnerService310 family (account, repositories, commits, administration), OwnerAccount311 (the main-actor mirror the interface reads), OwnerPresenter (sheets and312 the "repository changed" signal), OwnerEnvironment (one property of313 AppEnvironment: `environment.owner`).314Features/Settings/ Profile tab, settings, sign-in, QR scanner.315Features/Administration/ hub, server overview, audit log, tokens, repository form, branch and tag316 creation, release files, DestructiveConfirmationSheet, OwnerGate,317 OwnerActions (the hooks).318Features/CodeEditor/ CodeTextView (TextKit 2), indentation, highlighting engine, ChangeSet,319 LineDiff, DraftStore, EditingWorkspace, review, conflict.320```321322- **The token is handed out only for routes that require one** (`TokenUse.required`). Public reads stay323 anonymous: same cache, same shield treatment as a visitor, and nothing private reaches the disk cache.324- **Every write is confirmed by a read.** A method of an owner service sends the write through the gateway,325 reads the result back with `CachePolicy.revalidate` (which also replaces the cached copy), and throws326 `validation(code: "not_confirmed")` when the read does not show the change. Screens show what was read.327- **Nothing is retried.** A `409` is thrown to the view model as it is. `CommitComposer` turns `head_moved` and328 `blob_changed` into a conflict state that lists the incoming commits and offers two explicit ways forward.329- **Hooks.** A reading screen adds owner actions with one line (`OwnerActions.repositoryMenu(for:)`,330 `.branchActions`, `.tagActions`, `.releaseActions`, `.fileActions`, `.directoryActions`, `.newBranchButton`,331 `.newTagButton`) and reloads after a write with `.ownerRefresh(repository:) { … }`. They render nothing in332 public mode. Sheets and the "token refused" dialog are installed once by `.ownerModeRoot()` in `RootView`.333- **An owner screen** wraps its content in `OwnerGate(scope:)`: sign-in prompt, unlock prompt, or the missing334 scope, instead of content the server would refuse.335- **Drafts.** Everything staged for a repository and branch is one `ChangeSet`, saved by `DraftStore` (complete336 file protection, file names derived from a hash) after each change and when the app leaves the foreground.337 When a screen restores a draft, `EditingWorkspace.verifyBase()` asks the server once whether the commit the338 draft started from still exists (`OwnerCommitService.knows(commit:in:)`); a `404` means the repository was339 deleted or recreated, and the draft is discarded with a notice instead of being flagged file by file as340 "changed on the server". Any other failure keeps the draft.341- **Highlighter and Markdown.** `EditorSyntax.highlighter()` returns the `SyntaxHighlighting` the editor uses342 (`SPBSyntaxHighlighter`, line by line); `EditorMarkdownPreview` draws the text being edited with343 `MarkdownReader`. The editor follows `ReaderSettings` for the size and the family of its font.344345## 11. Targets and shared code346347| Target | Sources | Notes |348|---|---|---|349| `SPBGit` | `SPBGit/`, `Shared/` | entitlements `SPBGit/Resources/SPBGit.entitlements`: App Group `group.ai.spboucher.git`, `applinks:git.spboucher.ai`, `aps-environment` |350| `SPBGitWidgets` | `SPBGitWidgets/`, `Shared/`, the app's `Assets.xcassets` and `Localizable.xcstrings` | App Group only; extension-safe API only |351352`Shared/` holds what both need and nothing that knows a credential: `ForgeSnapshot` and friends (public figures),353`ForgeFeed` (four open routes, anonymous, ephemeral session), `WidgetSnapshotStore` (JSON files in the App Group),354`WidgetDataLoader` and `WidgetRefreshPolicy`, `SPBLink` (the `spbgit://` scheme), `RepositoryEntity` and its query,355and the widget views themselves (`ForgeWidgetView`, `RepositoryWidgetView`). The views live there so that the app can356draw exactly what the extension draws (Debug gallery, `-SPBScreen widgets`). `Shared/` uses system fonts and the357colour sets of the shared asset catalog, never `SPBColor` or a service of the app.358359Widget data flow: the app writes `forge.json`, `repositories.json` and one snapshot per favourite or followed360repository each time its own data refreshes (`WidgetBridge`); a timeline shows that copy when it is younger than36130 minutes, otherwise the extension makes its own requests (`/api/v1/metrics`, falling back to `/api/v1/stats`, and362`/api/v1/activity?perPage=1&type=push`; `/api/v1/repos/:name` for the favourite repository) and stores the answer for363the other widgets. One entry per timeline, next reload 30 to 60 minutes later. No token ever reaches the App Group.364365## 12. Offline reading366367**Storage decision: files, not SwiftData.** What is stored is the body of API answers, written once, addressed by a368key, looked up by hash, measured and deleted by directory; the manifest of a copy is a few hundred small records with369no relation to query. Files give atomic writes, exact sizes, removal with one `removeItem`, exclusion from backups by370one resource value, and an actor that owns them off the main thread under strict concurrency. SwiftData would add a371model container, main-actor contexts and a schema to migrate, and would store the bodies as external files anyway.372The small stores that existed (favourites and history in `library.json`, follows and pins in `UserDefaults`) keep373their API and their backing: a few kilobytes read once gain nothing from a database. They move into the App Group the374first time the group is available (`SharedContainer.migrateToGroupIfNeeded`).375376```377Application Support/SPBGit/offline/ (app container, excluded from backups, never in the App Group)378 <sha256(repository@sha)>/manifest.json OfflineSet: status, counts, dates, items by key379 <sha256(repository@sha)>/objects/<sha256(key)> the stored answer, byte for byte380```381382- `OfflineRequest` turns an endpoint into `(repository, route, ref, parameters)`; its `key` ignores the ref, so383 `tree?path=src` is one stored answer whether the screen asked for the SHA, the branch or nothing.384- `OfflineLibrary` (actor, `OfflineResponseSource`): `.pinned` lookups serve `tree`, `blob` and `readme` requests385 that name the full SHA of a stored copy; `.fallback` lookups (network unreachable) also resolve no ref, the386 downloaded branch or an abbreviated SHA to the readable copy, and serve the metadata stored at download time387 (repository, languages, branches, tags, first page of commits). `Fetched.fetchedAt` is the synchronisation date.388- `OfflinePlanner` (pure): text files under 512 kB each, 48 MB and 3000 files per repository, binary extensions and389 dependency directories left out. `OfflineEstimate` uses `fileCount` and `languageBytes` of the repository list (no390 request): confirmation above 300 files or 8 MB, refusal above 20 000 files or 512 MB of source.391- `OfflineDownloader`: one request at a time, 0.4 s apart, `.networkOnly`, everything pinned to the SHA; waits for392 `Retry-After` of a rate limit (three times, 120 s at most), pauses on a shield refusal or a lost connection, keeps a393 blob only when `GitBlobID` of its content equals its `oid`, and resumes from what is stored. It runs on its own394 anonymous `APIClient`: what is stored is what any visitor can read.395- `OfflineStore` (`@MainActor @Observable`, `AppEnvironment.offline`): `availability(repository:head:)`, `estimate`,396 `download`, `pause`, `resume`, `cancel`, `remove`, `removeAll`, `verify`, `ceilingBytes` (least recently used397 copies are evicted first). Nothing starts a download but a tap; the background refresh never does.398- `LoadableView` shows `SPBOfflineIndicator` ("Offline. Saved 3 hours ago.") above loaded content when399 `\.spbConnectivity` says the device is offline; `SceneRoot` sets it from `Reachability`.400401## 13. Platform integrations402403- **Links**: `DeepLink.route(for:refs:)` resolves refs containing a slash against branch and tag names (longest404 match, first component otherwise); `DeepLinkOpener` asks for those names only when `DeepLink.refQuestion` says the405 link is ambiguous. Screens without a web page travel as parameters of the nearest page (`commits/<ref>?path=`,406 `commits?view=graph`, `commit/<sha>?view=diff&path=`, `branches?base=&head=`, `/?collection=`,407 `search?q=&repo=&scope=`), so a shared link still lands somewhere sensible in a browser. `Permalink.url(for:)` is408 the single route-to-URL mapping; `SPBLink` is the same thing under `spbgit://r/…`, plus `spbgit://tab/<name>`,409 `spbgit://offline`, `spbgit://notifications`.410- **Windows**: `SceneRoot` gives each window its own `Router` (`AppEnvironment.claimRouter()`), restored from411 `SceneStorage` (`Router.Snapshot`). `PlatformCoordinator` knows the window used last: notifications and intents412 open there.413- **Spotlight**: `SpotlightIndexer` replaces the domain `ai.spboucher.git.repositories` when the repository list414 changes (name, description, topics, languages); it can be turned off, which removes the index.415- **Handoff**: `RouteDestination` applies `.spbUserActivity(route)`; the activity carries the web URL and comes back416 through `DeepLink` like any link.417- **Intents**: `OpenRepositoryIntent`, `SearchSPBGitIntent`, `ShowActivityIntent`, `GetForgeStatsIntent`,418 `LastCommitIntent`, `SPBShortcuts` (phrases in `AppShortcuts.xcstrings`), `SelectRepositoryIntent` for the widget.419- **Notifications**: `ActivityCheck` (pure) decides what is announced; `ActivityChecker` reads `/api/v1/activity`420 since its cursor and posts one local notification per followed repository; it runs from421 `.backgroundTask(.appRefresh("ai.spboucher.git.refresh"))` when iOS grants one, when the app opens (at most every422 30 minutes) and from "Check now". `PushRegistrar` and `NotificationModel` register the APNs token with423 `POST /api/v1/devices` when `meta.features.push` is true and fall back to the local path on `501`.424- **Keyboard**: `SPBCommands` (⌘F, ⌘1…⌘5, ⌘[ and ⌘], ⌘R, ⌘,). ⌘R increments `Router.refreshRequest`, which425 `LoadableView` observes through `\.spbRefreshRequest` and answers by calling its `retry`.426- **Sharing and pointer**: `ShareItem` + `SPBShareLink` (always the `Permalink` URL), `.spbLinkInteractions(url:)`427 (hover highlight, drag of the URL).428