Skip to content

Commit f2f4366

Browse files
committed
One web view data store per server (Cloud included), so a change of server waits on nothing and the old store is removed in the background; a sign-in whose site-data clear does not finish fails instead of going on; a picture taken at touch-down for the slide back; and a test that a self-hosted session does not survive a change to Cloud and back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq
1 parent cc8ecbc commit f2f4366

5 files changed

Lines changed: 113 additions & 29 deletions

File tree

‎ios-shell/OpenBotShell/BackTransition.swift‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ final class BackTransition {
5454
private var latestAskedAt = Date.distantPast
5555
private var lastRouteAt = Date.distantPast
5656
private var refreshWork: DispatchWorkItem?
57+
/// A push that went ahead before its picture arrived: filled in when it does (same page).
58+
private var pendingFill: (tab: String, index: Int, routeAt: Date)?
59+
60+
/// A finger came down on the page: a picture now, before a tap can change the page.
61+
func touchDown() {
62+
refresh(after: 0)
63+
}
5764

5865
func refresh(after seconds: TimeInterval) {
5966
refreshWork?.cancel()
@@ -62,8 +69,16 @@ final class BackTransition {
6269
let config = WKSnapshotConfiguration()
6370
config.afterScreenUpdates = false
6471
let asked = Date()
72+
let routeAtAsk = self.lastRouteAt
6573
webView.takeSnapshot(with: config) { [weak self] image, _ in
66-
guard let self = self, let image = image, asked >= self.lastRouteAt else { return }
74+
guard let self = self, let image = image else { return }
75+
if let pending = self.pendingFill, pending.routeAt == routeAtAsk,
76+
pending.index < (self.stacks[pending.tab]?.count ?? 0) {
77+
self.stacks[pending.tab]?[pending.index] = image
78+
self.pendingFill = nil
79+
return
80+
}
81+
guard routeAtAsk == self.lastRouteAt else { return }
6782
self.latest = image
6883
self.latestAskedAt = asked
6984
}
@@ -75,9 +90,11 @@ final class BackTransition {
7590
/// The page is about to show a new page in this tab: keep the picture of what is on screen now,
7691
/// at once, so the page can go ahead.
7792
func willPush(tab: String, completion: @escaping () -> Void) {
78-
refreshWork?.cancel()
79-
// No fresh picture of this page: no slide for it later (better than the wrong page).
80-
stacks[tab, default: []].append(latestAskedAt >= lastRouteAt ? latest : nil)
93+
// No fresh picture of this page yet: the one asked for at touch-down fills it in when it
94+
// comes; without one, no slide for it later (better than the wrong page).
95+
let fresh = latestAskedAt >= lastRouteAt ? latest : nil
96+
stacks[tab, default: []].append(fresh)
97+
if fresh == nil { pendingFill = (tab, (stacks[tab]?.count ?? 1) - 1, lastRouteAt) }
8198
latest = nil
8299
completion()
83100
}
@@ -194,3 +211,14 @@ final class BackTransition {
194211
}
195212
}
196213
}
214+
215+
/// Reports every touch-down on the web view and then steps aside (it never recognizes): the moment
216+
/// to take the picture of the page a tap is about to leave, before the page changes.
217+
final class TouchDownRecognizer: UIGestureRecognizer {
218+
var onTouchDown: (() -> Void)?
219+
220+
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
221+
onTouchDown?()
222+
state = .failed
223+
}
224+
}

‎ios-shell/OpenBotShell/ShellConfig.swift‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import CryptoKit
12
import Foundation
23

34
/// Where the app points and which test hooks are on, read once at launch.
@@ -170,6 +171,20 @@ struct ShellConfig {
170171
}
171172
}
172173

174+
/// The web view's own data store for this server (iOS 17 `WKWebsiteDataStore(forIdentifier:)`):
175+
/// a stable id derived from the origin, so each server, Cloud included, keeps its cookies and
176+
/// storage apart, and changing server is simply another store.
177+
var dataStoreID: UUID { ShellConfig.dataStoreID(for: baseURL) }
178+
179+
static func dataStoreID(for origin: URL) -> UUID {
180+
var digest = Array(SHA256.hash(data: Data(("openbot-shell-store:" + origin.absoluteString).utf8)).prefix(16))
181+
digest[6] = (digest[6] & 0x0F) | 0x50 // version 5-style
182+
digest[8] = (digest[8] & 0x3F) | 0x80 // RFC 4122 variant
183+
let t = (digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7],
184+
digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15])
185+
return UUID(uuid: t)
186+
}
187+
173188
var baseHost: String { baseURL.host?.lowercased() ?? "" }
174189

175190
/// The base URL with a path (which may carry a query) appended.

‎ios-shell/OpenBotShell/ShellController.swift‎

Lines changed: 41 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,16 @@ final class ShellController: NSObject, WebControllerDelegate {
9797
#if DEBUG
9898
if config.resetDataStore {
9999
steps.append { [weak self] next in
100-
let store = WKWebsiteDataStore.default()
100+
guard let self = self else { return }
101+
let store = self.web.webView.configuration.websiteDataStore
102+
let current = self.config.dataStoreID
101103
store.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast) {
102-
self?.diagnostics.log("test-hook", ["hook": "reset-data-store"])
103-
DispatchQueue.main.async { next() }
104+
// Other servers' stores from earlier tests go too.
105+
WKWebsiteDataStore.fetchAllDataStoreIdentifiers { ids in
106+
for id in ids where id != current { WKWebsiteDataStore.remove(forIdentifier: id) { _ in } }
107+
self.diagnostics.log("test-hook", ["hook": "reset-data-store", "otherStores": ids.count])
108+
DispatchQueue.main.async { next() }
109+
}
104110
}
105111
}
106112
}
@@ -404,14 +410,21 @@ final class ShellController: NSObject, WebControllerDelegate {
404410
web.stop()
405411
model.signIn = .idle
406412
model.addressChecking = true
407-
// Everything the web view stored, for every site: nothing of one server carries to the other.
408-
WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast) { [weak self] in
409-
DispatchQueue.main.async {
410-
guard let self = self else { return }
411-
self.diagnostics.log("site-data-cleared", ["reason": "server-switch", "all": true])
412-
ShellConfig.saveSelfHosted(origin)
413-
self.model.addressChecking = false
414-
self.onRestart?()
413+
// Each server has a data store of its own: the new one is simply another store, nothing to
414+
// wait for. The old one is removed once its web view is gone.
415+
let oldStore = config.dataStoreID
416+
ShellConfig.saveSelfHosted(origin)
417+
model.addressChecking = false
418+
onRestart?()
419+
ShellController.removeStore(oldStore, attempt: 1)
420+
}
421+
422+
/// Removes a server's data store in the background (it fails while a web view still uses it:
423+
/// tried again a few times).
424+
static func removeStore(_ id: UUID, attempt: Int) {
425+
DispatchQueue.main.asyncAfter(deadline: .now() + Double(attempt)) {
426+
WKWebsiteDataStore.remove(forIdentifier: id) { error in
427+
if error != nil, attempt < 5 { removeStore(id, attempt: attempt + 1) }
415428
}
416429
}
417430
}
@@ -516,9 +529,14 @@ final class ShellController: NSObject, WebControllerDelegate {
516529
// at a cold launch, see decideLaunchState). The server refuses `enter` for a web view
517530
// holding another person's session, so the site's data goes first, and `enter` loads
518531
// only once that has finished.
519-
clearSiteData(reason: "before-enter") { [weak self] in
532+
clearSiteData(reason: "before-enter") { [weak self] finished in
520533
guard let self = self, self.model.signIn == .entering else { return }
521-
load()
534+
if finished {
535+
load()
536+
} else {
537+
// Never sign in on unknown state: the leftover session may still be there.
538+
self.failSignIn("Sign-in didn't finish. Try again.")
539+
}
522540
}
523541
}
524542
}
@@ -582,20 +600,21 @@ final class ShellController: NSObject, WebControllerDelegate {
582600
/// that is still running is waited for, so a sign-in that starts during sign-out's clear loads
583601
/// `enter` only after it.
584602
private var siteDataClearWaiters: [() -> Void]?
585-
private func clearSiteData(reason: String, completion: (() -> Void)? = nil) {
586-
// Never left waiting: WebKit once did not call back at all (run 46164083101, right after the
587-
// app was built again for another server). After 4 s the caller goes ahead.
603+
/// Calls back with true once the clear has finished, or false after 4 s without an answer from
604+
/// WebKit (it did not answer once, right after a change of server in run 46164083101, when all
605+
/// servers shared 1 store; each now has its own). The caller then fails rather than going on.
606+
private func clearSiteData(reason: String, completion: ((Bool) -> Void)? = nil) {
588607
var completion = completion
589608
if let inner = completion {
590609
var called = false
591-
let once = { [weak self] (timedOut: Bool) in
610+
let once = { [weak self] (finished: Bool) in
592611
guard !called else { return }
593612
called = true
594-
if timedOut { self?.diagnostics.log("site-data-clear-timeout", ["reason": reason]) }
595-
inner()
613+
if !finished { self?.diagnostics.log("site-data-clear-timeout", ["reason": reason]) }
614+
inner(finished)
596615
}
597-
completion = { once(false) }
598-
DispatchQueue.main.asyncAfter(deadline: .now() + 4) { once(true) }
616+
completion = { _ in once(true) }
617+
DispatchQueue.main.asyncAfter(deadline: .now() + 4) { once(false) }
599618
}
600619
if siteDataClearWaiters != nil {
601620
// One clear at a time; a later caller waits for this one and then clears again.
@@ -627,7 +646,7 @@ final class ShellController: NSObject, WebControllerDelegate {
627646
self.model.siteDataClears += 1
628647
let waiters = self.siteDataClearWaiters ?? []
629648
self.siteDataClearWaiters = nil
630-
completion?()
649+
completion?(true)
631650
waiters.forEach { $0() }
632651
}
633652
}

‎ios-shell/OpenBotShell/WebController.swift‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,9 @@ final class WebController: NSObject, WKNavigationDelegate, WKUIDelegate, WKScrip
6060
self.diagnostics = diagnostics
6161

6262
let configuration = WKWebViewConfiguration()
63-
// Persistent store, so cookies and localStorage survive a relaunch like they do in Safari.
64-
configuration.websiteDataStore = WKWebsiteDataStore.default()
63+
// A persistent store of this server's own, so cookies and localStorage survive a relaunch like
64+
// they do in Safari, and nothing of one server is seen by another.
65+
configuration.websiteDataStore = WKWebsiteDataStore(forIdentifier: config.dataStoreID)
6566
// Audio and video play in the page instead of jumping to the full-screen player.
6667
configuration.allowsInlineMediaPlayback = true
6768
// Appended to the Safari-like UA: the web app recognizes the shell by it too.
@@ -114,6 +115,7 @@ final class WebController: NSObject, WKNavigationDelegate, WKUIDelegate, WKScrip
114115
hideKeyboardAccessory(when: "init")
115116
installKeyboardDragDismiss()
116117
installBackSwipe()
118+
installTouchDown()
117119
// Also sees the page's own route changes, which no navigation delegate call reports.
118120
urlObservation = webView.observe(\.url, options: [.new]) { [weak self] webView, _ in
119121
let url = webView.url
@@ -353,7 +355,7 @@ final class WebController: NSObject, WKNavigationDelegate, WKUIDelegate, WKScrip
353355
func updateBack(canGoBack: Bool?, depth: Int? = nil, tab: String? = nil) {
354356
if let tab = tab { transition.route(tab: tab, depth: depth) }
355357
// A fresh picture of the new page once it has settled, for the next push.
356-
transition.refresh(after: 0.6)
358+
transition.refresh(after: 0.3)
357359
// The page has its new route: once it has drawn, a cover left by a back goes.
358360
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in self?.transition.pageDrawn() }
359361
let mode = ShellBack.decide(canGoBack: canGoBack)
@@ -364,6 +366,16 @@ final class WebController: NSObject, WKNavigationDelegate, WKUIDelegate, WKScrip
364366
diagnostics.log("back-mode", ["mode": "\(mode)"])
365367
}
366368

369+
private func installTouchDown() {
370+
let touch = TouchDownRecognizer(target: nil, action: nil)
371+
touch.cancelsTouchesInView = false
372+
touch.delaysTouchesBegan = false
373+
touch.delaysTouchesEnded = false
374+
touch.delegate = self
375+
touch.onTouchDown = { [weak self] in self?.transition.touchDown() }
376+
webView.addGestureRecognizer(touch)
377+
}
378+
367379
private func installBackSwipe() {
368380
let edge = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleBackSwipe(_:)))
369381
edge.edges = .left

‎ios-shell/OpenBotShellUITests/SelfHostedUITests.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ final class SelfHostedUITests: ShellTestCase {
118118
XCTAssertTrue(app.buttons["self-hosted-toggle"].waitForExistence(timeout: 20), "Use OpenBot Cloud did not bring back the default first screen")
119119
XCTAssertEqual(stateValue(app, "server"), "127.0.0.1:3010")
120120
screenshot("5-back-on-cloud")
121+
122+
// Nothing of the self-hosted OpenBot survived: choosing it again starts signed out.
123+
open(app)
124+
submit(app, Self.selfHosted)
125+
XCTAssertTrue(app.staticTexts["server-host"].waitForExistence(timeout: 20))
126+
sleep(3)
127+
XCTAssertFalse(tab(app, .home).exists, "the self-hosted session survived the change to Cloud and back")
128+
XCTAssertEqual(stateValue(app, "phase"), "signedOut")
129+
app.buttons["use-cloud"].tap()
130+
XCTAssertTrue(app.buttons["self-hosted-toggle"].waitForExistence(timeout: 20))
121131
app.buttons["sign-in-button"].tap()
122132
XCTAssertTrue(tab(app, .home).waitForExistence(timeout: 45), "signing in to Cloud did not reach the tabs")
123133
XCTAssertEqual(stateValue(app, "server"), "127.0.0.1:3010")

0 commit comments

Comments
 (0)