// SWITCHING, LIKE TABS (owner, 25 Nov 2026; sites/DECISIONS.md "Kept as left", CONTRACT "Switching"): leaving a page// for the list or another site never closes it. The most recent sites stay alive, exactly as left (scroll, typed// words, a video's place), up to a budget measured from this phone's memory; the core's `sites.live` decides which// are let go, so both phones let go the same ones, and only under real pressure. A page the system took back comes// back silently by its saved `interactionState` (kept sealed in the book by `sites.state`), under a still picture of// it held in memory only. Load again and Close this page are separate, deliberate actions.//// Each site's page lives in WebKit's store named by its id (walled off: spike 0, `spike/RESULTS-ios.md`); a quick// visit or a search lives in a store never written to disk. Everything a page asks (an alert, a question, a link out// of the web, a file it gives) is put to Sites' own sheets, headed by the page's address.#if os(iOS)importCottonKitimportNetworkimport osimportSwiftUIimport UIKitimportWebKit/// What a page asks of Sites, for the screen to draw in its own sheet.enumSitesAsking: Identifiable {/// An alert, a confirm or a prompt: the page's own words under Sites' head.case panel(kind: String, text: String, defaultText: String?, answer: (Bool, String?) -> Void)/// A link out of the web (a call, a map, a store, a mail): asked first.case exit(URL)/// A file the page gave, held in memory until saved or shared.case file(URL, from: String)/// A result tapped on the search page: the chooser, since a result never opens in a signed-in site by itself.case choose(URL)var id: String {switchself {case .panel(let kind, let text, _, _): "panel-\(kind)-\(text.hashValue)"case .exit(let url): "exit-\(url.absoluteString)"case .file(let url, _): "file-\(url.path)"case .choose(let url): "choose-\(url.absoluteString)" } }}/// One live page: a site's (signed in as it) or a quick visit's.@MainActor @ObservablefinalclassSitesPage: NSObject, WKNavigationDelegate, WKUIDelegate, WKDownloadDelegate {/// The site's id, or the quick visit's throwaway store name.let id: Stringprivate(set) var row: SitesRow?/// A quick visit's or a search's words (strip, dashed name, Close).let quick: SitesOpened.Quick?let web: WKWebViewvar url: URL?var title: String?var canBack = falsevar canForward = falsevar loading = falsevar progress = 0.0/// The page did not open: Sites draws its own page, with the address it was going to.var failed: URL?/// One line after a link from another app landed here.var arrived: SitesOpened.Arrived?/// A picture of the page as it was left, shown while a page the system took back loads again.var picture: UIImage?/// What the page is asking now.var asking: SitesAsking?/// A search's throwaway place: the engine's host, whose own links stay; a result elsewhere goes to the chooser.var engineHost: String?/// Page text size, 0.5 to 2.var zoom: CGFloat = 1 { didSet { web.pageZoom = zoom } }/// Told where the page settled and its title, for the list's second line (a site that stays signed in).var report: ((URL, String?) -> Void)?privatevar reporting: Task<Void, Never>?/// The page on screen is a form's answer: its address alone cannot bring it back, so it is not kept.privatevar posted = falseprivatevar watching: [NSKeyValueObservation] = []privatevar downloads: [ObjectIdentifier: URL] = [:]/// Whether the tracker list is on this page's web view now.private(set) var blocking = falseinit(id: String, row: SitesRow?, quick: SitesOpened.Quick?, url: URL?, state: Data?, quickTrackers: Bool = true) {self.id = idself.row = rowself.quick = quicklet config = WKWebViewConfiguration()iflet row, let uuid = UUID(uuidString: row.storeUUID) { config.websiteDataStore = WKWebsiteDataStore(forIdentifier: uuid) } else { config.websiteDataStore = .nonPersistent() } config.preferences.javaScriptCanOpenWindowsAutomatically = true config.allowsInlineMediaPlayback = true config.mediaTypesRequiringUserActionForPlayback = .all config.defaultWebpagePreferences.preferredContentMode = .mobile// Trackers: blocked by WebKit while the site's switch is on (a quick visit: as the core opened it, on by default).let blocking = row?.trackers ?? quickTrackersif blocking, let list = SitesTrackers.list { config.userContentController.add(list) }self.blocking = blocking && SitesTrackers.list != nil web = WKWebView(frame: .zero, configuration: config) web.allowsBackForwardNavigationGestures = true web.isInspectable = SitesPage.inspectable web.scrollView.contentInsetAdjustmentBehavior = .automaticself.url = urlsuper.init() web.navigationDelegate = self web.uiDelegate = self watching = [ web.observe(\.url) { [weakself] web, _ inMainActor.assumeIsolated { self?.moved(to: web.url) } }, web.observe(\.title) { [weakself] web, _ inMainActor.assumeIsolated { self?.title = web.title.flatMap { $0.isEmpty ? nil : $0 } } }, web.observe(\.canGoBack) { [weakself] web, _ inMainActor.assumeIsolated { self?.canBack = web.canGoBack } }, web.observe(\.canGoForward) { [weakself] web, _ inMainActor.assumeIsolated { self?.canForward = web.canGoForward } }, web.observe(\.isLoading) { [weakself] web, _ inMainActor.assumeIsolated { self?.loading = web.isLoading } }, web.observe(\.estimatedProgress) { [weakself] web, _ inMainActor.assumeIsolated { self?.progress = web.estimatedProgress } }, ]iflet state {// Back where it was: history, the page and its scroll (spike 0, check 3). web.interactionState = state } elseiflet url { web.load(URLRequest(url: url)) } } #if COTTON_DEVstaticlet inspectable = true #elsestaticlet inspectable = false #endif/// The row changed (renamed, a new home, pinned): the page keeps going.func update(_ row: SitesRow) {self.row = row block(row.trackers) }/// The site's Trackers switch changed: the list is added or taken off this live page, which loads again so the/// switch holds for what is on screen.func block(_ on: Bool) {let wanted = on && SitesTrackers.list != nilguard wanted != blocking, let list = SitesTrackers.list else { return }if wanted { web.configuration.userContentController.add(list) } else { web.configuration.userContentController.remove(list) } blocking = wantedif web.url != nil { web.reload() } }var isQuick: Bool { row == nil }func go(_ url: URL) { failed = nil web.load(URLRequest(url: url)) }/// Load again: a reload, or the address a page that did not open was going to.func again() {iflet failing = failed { failed = nil; web.load(URLRequest(url: failing)); return } web.reload() }/// The page as WebKit keeps it now, to bring it back after the system lets it go.var state: Data? { web.interactionState as? Data }/// A still picture of the page, taken as it is left.func takePicture() async {guard web.window != nil, web.bounds.width > 0else { return }let config = WKSnapshotConfiguration() config.afterScreenUpdates = false picture = try? await web.takeSnapshot(configuration: config) }// MARK: Loadingfunc webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { failed = nil }func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { picture = nil }func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { picture = nil settled() } @objc(webView:didFailProvisionalNavigation:withError:)func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { fail(error) } @objc(webView:didFailNavigation:withError:)func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { fail(error) }/// A load stopped on purpose (a new one began, a link handed elsewhere, a file) is not a failure.privatefunc fail(_ error: Error) {let error = error as NSErrorif error.domain == NSURLErrorDomain, error.code == NSURLErrorCancelled { return }if error.domain == "WebKitErrorDomain", [102, 204].contains(error.code) { return } picture = nil failed = (error.userInfo[NSURLErrorFailingURLErrorKey] as? URL) ?? url ?? row.flatMap { URL(string: $0.open) } }/// Whether the phone is offline now (a failure says "You're offline" and tries again by itself).staticvar offline: Bool { !SitesReach.shared.online }privatefunc moved(to now: URL?) {guardlet now else { return } url = now }/// The page settled: where it is and its title go to the book a moment later (a site that stays signed in,/// never a form's answer), so it reopens there and the list says which page.privatefunc settled() {guardlet report, !posted, let now = web.url, ["http", "https"].contains(now.scheme?.lowercased() ?? "") else { return } reporting?.cancel() reporting = Task { @MainActor [weakself] intry? awaitTask.sleep(for: .milliseconds(600))guardletself, !Task.isCancelled else { return } report(now, self.title) } }func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { posted = false }/// The system ended the page's web process: it loads again where it was, saying nothing.func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {SitesLive.shared.webEnded()if webView.backForwardList.currentItem != nil { webView.reload() } elseiflet url { webView.load(URLRequest(url: url)) } }/// A page asking for a new window (a sign-in's pop-up, a link with a target) opens in this same page: no piles.func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {if action.targetFrame == nil, let url = action.request.url {iflet engine = engineHost, let host = url.host(), !host.hasSuffix(engine), !engine.hasSuffix(host) { asking = .choose(url) }else { webView.load(action.request) } }returnnil }/// The web's own pages load here; anything else is asked first, through the core (`sites.exit`).func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, preferences: WKWebpagePreferences) async -> (WKNavigationActionPolicy, WKWebpagePreferences) {if action.targetFrame?.isMainFrame ?? true { posted = action.request.httpMethod?.uppercased() == "POST" }if action.shouldPerformDownload { return (.download, preferences) }guardlet url = action.request.url, let scheme = url.scheme?.lowercased() else { return (.allow, preferences) }iflet engine = engineHost, ["http", "https"].contains(scheme), action.navigationType == .linkActivated || action.targetFrame == nil,let host = url.host(), !host.hasSuffix(engine), !engine.hasSuffix(host) { asking = .choose(url)return (.cancel, preferences) }if ["http", "https", "about", "blob", "data"].contains(scheme) { return (.allow, preferences) }if action.targetFrame?.isMainFrame == false, action.navigationType == .other { return (.cancel, preferences) } asking = .exit(url)return (.cancel, preferences) }/// What the page cannot show itself (a file to keep) is fetched into Sites' own viewer.func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse) async -> WKNavigationResponsePolicy {iflet http = response.response as? HTTPURLResponse, (http.value(forHTTPHeaderField: "Content-Disposition") ?? "").lowercased().hasPrefix("attachment") { return .download }return response.canShowMIMEType ? .allow : .download }func webView(_ webView: WKWebView, navigationAction: WKNavigationAction, didBecome download: WKDownload) { download.delegate = self }func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) { download.delegate = self }func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String) async -> URL? {let folder = FileManager.default.temporaryDirectory.appendingPathComponent("sites-files-\(UUID().uuidString)", isDirectory: true)try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)let file = folder.appendingPathComponent(suggestedFilename.isEmpty ? "file" : suggestedFilename) downloads[ObjectIdentifier(download)] = filereturn file }func downloadDidFinish(_ download: WKDownload) {guardlet file = downloads.removeValue(forKey: ObjectIdentifier(download)) else { return } asking = .file(file, from: download.originalRequest?.url?.host() ?? url?.host() ?? "") }func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { downloads.removeValue(forKey: ObjectIdentifier(download)) }// MARK: A page's own words, in Sites' sheetfunc webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async {await withCheckedContinuation { done in asking = .panel(kind: "alert", text: message, defaultText: nil) { _, _ in done.resume() } } }func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo) async -> Bool {await withCheckedContinuation { done in asking = .panel(kind: "confirm", text: message, defaultText: nil) { yes, _ in done.resume(returning: yes) } } }func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo) async -> String? {await withCheckedContinuation { done in asking = .panel(kind: "prompt", text: prompt, defaultText: defaultText) { yes, text in done.resume(returning: yes ? (text ?? "") : nil) } } }// MARK: Find on this page/// How many times `words` stand in the page's text, counted in Sites' own script world (the page never sees it).func count(_ words: String) async -> Int {guard !words.isEmpty else { return0 }let script = "const t=(document.body&&document.body.innerText||'').toLowerCase();const w=q.toLowerCase();let n=0,i=0;while((i=t.indexOf(w,i))!==-1){n++;i+=w.length}return n;"let n = try? await web.callAsyncJavaScript(script, arguments: ["q": words], contentWorld: SitesPage.world)return (n as? Int) ?? (n as? NSNumber)?.intValue ?? 0 }/// The next or the previous match, chosen in the page.func find(_ words: String, back: Bool) async -> Bool {guard !words.isEmpty else { returnfalse }let config = WKFindConfiguration() config.backwards = back config.caseSensitive = false config.wraps = truereturn (try? await web.find(words, configuration: config))?.matchFound ?? false }staticlet world = WKContentWorld.world(name: "cotton-sites")}/// Whether the phone is online, so a failed page says whose fault it likely is, and tries again by itself offline.@MainActor @ObservablefinalclassSitesReach {staticlet shared = SitesReach()private(set) var online = trueprivatelet monitor = NWPathMonitorBox()privateinit() { monitor.start { [weakself] online inTask { @MainActor inself?.online = online } } }}/// The path monitor, held apart so the class above stays on the main actor.finalclass NWPathMonitorBox: @unchecked Sendable {privatelet monitor = NWPathMonitor()func start(_ changed: @escaping @Sendable (Bool) -> Void) { monitor.pathUpdateHandler = { path in changed(path.status == .satisfied) } monitor.start(queue: DispatchQueue(label: "cotton.sites.reach")) }}/// The live pages, most recent first: as many as this phone's memory comfortably allows (`budget`), the least/// recently used let go first, and only under real pressure (a memory warning, the system ending a web process).@MainActorfinalclassSitesLive {staticlet shared = SitesLive()private(set) var pages: [String: SitesPage] = [:]/// Pictures of pages let go, held in memory only, shown while they load again.privatevar pictures: [String: UIImage] = [:]/// How many pages stay alive, from this phone's memory (raised from Comms' four); halved for a while after a warning.private(set) var budget: Int = SitesLive.measuredprivatevar warned: NSObjectProtocol?privatevar figures = SitesFigures(limit: UInt32(SitesLive.measured))privatevar said: SitesFigures?var core: (any CottonCalling)?/// The budget for this phone: about one live page per 512 MB of memory past the first 1.5 GB, at least 4, at most 12.staticvar measured: Int {let gb = Double(ProcessInfo.processInfo.physicalMemory) / 1_073_741_824return min(12, max(4, Int((gb - 1.5) * 2))) }privateinit() { warned = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main) { _ inMainActor.assumeIsolated { SitesLive.shared.warning() } } }/// Whether a site has a live page now (the list's dot).func isAlive(_ id: String) -> Bool { pages[id] != nil }/// A site's live page, if the phone still keeps it.func page(_ id: String) -> SitesPage? { pages[id] }/// The page for an opening: the live one, else a new one (back by its saved state when the book kept one).func page(for row: SitesRow?, opened: SitesOpened, link: URL?) -> SitesPage {iflet row, let live = pages[row.id] { live.update(row)iflet link { live.go(link) }iflet arrived = opened.arrived { live.arrived = arrived }return live }let id = row?.id ?? opened.storelet state = link == nil ? opened.state.flatMap { Data(base64Encoded: $0) } : nillet page = SitesPage(id: id, row: row, quick: opened.quick, url: URL(string: opened.url), state: state, quickTrackers: opened.trackers ?? true) page.arrived = opened.arrivedif state != nil { page.picture = pictures[id] } pictures[id] = niliflet row { page.zoom = zooms[row.id] ?? 1 } pages[id] = page tell()return page }/// Page text size, kept per site while Sites runs.privatevar zooms: [String: CGFloat] = [:]func keepZoom(_ page: SitesPage) { iflet row = page.row { zooms[row.id] = page.zoom } }/// Switched to `id`: the core says which pages stay alive, and the rest are let go.func switched(to id: String?, book: SitesCalls, showing: String?) async {guardlet answer = try? await book.live(id, budget: budget) else { return }for gone in answer.letGo where gone != showing { letGo(gone) } }/// A page let go: its picture kept in memory, its state already in the book.func letGo(_ id: String) {guardlet page = pages.removeValue(forKey: id) else { return }iflet picture = page.picture { pictures[id] = picture } page.report = nil page.web.stopLoading() figures.letGo += 1 tell() }/// Close this page, Sign out, Remove, a site that forgets closed, a quick visit closed: the page ends now.func end(_ id: String) {guardlet page = pages.removeValue(forKey: id) else { return } pictures[id] = nil page.report = nil page.web.stopLoading() tell() }/// Every quick visit ends (Sites left the screen with none open, or Sites is quit).func endQuick(except showing: String?) {for (id, page) in pages where page.isQuick && id != showing { end(id) } }/// A memory warning: the budget halves, and every page past it not on screen is let go.privatefunc warning() { figures.warnings += 1 budget = max(2, budget / 2)Task { @MainActor iniflet core { await switched(to: nil, book: SitesCalls(core: core), showing: SitesLive.shared.showing) }// The budget comes back after a quiet minute.try? awaitTask.sleep(for: .seconds(60)) budget = SitesLive.measured } tell() }/// The page on screen now (never let go).var showing: String?func webEnded() { figures.webEnded += 1 tell() }/// The figures on the device's row (`diagnostics.say {sites}`): counts and megabytes, never a name or an address.privatefunc tell() { figures.limit = UInt32(budget) figures.alive = UInt32(pages.count) figures.mostAlive = max(figures.mostAlive, figures.alive)iflet footprint = SitesFigures.footprintMB() { figures.peakFootprintMb = max(figures.peakFootprintMb ?? 0, footprint) }iflet headroom = SitesFigures.headroomMB() { figures.leastHeadroomMb = min(figures.leastHeadroomMb ?? .max, headroom) }guard figures != said, let core else { return } said = figuresstructBody: Encodable { let sites: SitesFigures }let body = Body(sites: figures)Task { _ = try? await core.callJSON("diagnostics.say", body) } }}/// A live page in the screen. The view is the page's own, so switching away and back keeps it exactly as it was.structSitesWebView: UIViewRepresentable {let page: SitesPagefunc makeUIView(context: Context) -> UIView {let box = UIView() box.backgroundColor = .clearreturn box }func updateUIView(_ box: UIView, context: Context) {guard page.web.superview !== box else { return } box.subviews.forEach { $0.removeFromSuperview() } page.web.frame = box.bounds page.web.autoresizingMask = [.flexibleWidth, .flexibleHeight] box.addSubview(page.web) }}#endif