Hub apps on iOS no longer have their timers stopped while the phone app is in the background

This commit is contained in:
James Babcock committed 2026-09-19 22:07:35 -07:00
1 parent 6c3144cc31
commit 313ba85708
5 files changed
+93 -19

No files matched your search

@@ -85,11 +85,14 @@
[_webView.bottomAnchor constraintEqualToAnchor:_host.safeAreaLayoutGuide.bottomAnchor] [_webView.bottomAnchor constraintEqualToAnchor:_host.safeAreaLayoutGuide.bottomAnchor]
]]; ]];
// Keep a nonzero attached view behind the dashboard; do not hide/detach it. // Keep a nonzero attached view behind the dashboard; do not hide/detach it.
// Tick whenever iOS gives us execution time, including in the background or
// with the phone locked. Gating on UIApplicationStateActive stalls the
// injected timers/rAF even while BLE input can still evaluate JavaScript.
// Bound host ticks to one evaluation in flight, including across suspension. // Bound host ticks to one evaluation in flight, including across suspension.
__weak typeof(self) weakSelf = self; __weak typeof(self) weakSelf = self;
_timer = [NSTimer timerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer *timer) { _timer = [NSTimer timerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer *timer) {
typeof(self) strongSelf = weakSelf; typeof(self) strongSelf = weakSelf;
if (!strongSelf || strongSelf.ticking || UIApplication.sharedApplication.applicationState != UIApplicationStateActive) return; if (!strongSelf || strongSelf.destroyed || strongSelf.ticking) return;
strongSelf.ticking = YES; strongSelf.ticking = YES;
[strongSelf.webView evaluateJavaScript:@"window.__fcTimerTick && window.__fcTimerTick(); window.__fcRafTick && window.__fcRafTick();" completionHandler:^(id result, NSError *error) { [strongSelf.webView evaluateJavaScript:@"window.__fcTimerTick && window.__fcTimerTick(); window.__fcRafTick && window.__fcRafTick();" completionHandler:^(id result, NSError *error) {
weakSelf.ticking = NO; weakSelf.ticking = NO;
+2
View File
@@ -2,8 +2,10 @@
## 0.7.3 - Future ## 0.7.3 - Future
### iOS port:
* Add iOS calendar integration * Add iOS calendar integration
* iOS main screen matches the Android version's styling * iOS main screen matches the Android version's styling
* Hub apps on iOS no longer have their timers stopped while the phone app is in the background
## 0.7.2 - 2026-09-19 ## 0.7.2 - 2026-09-19
+12
View File
@@ -25,3 +25,15 @@ which now call the Kotlin implementation from Android host tests. Common tests
also run as native iOS simulator binaries. See [the Kotlin README](../native/kotlin/README.md) also run as native iOS simulator binaries. See [the Kotlin README](../native/kotlin/README.md)
for SDK requirements, source layout and coverage. The compass and battery for SDK requirements, source layout and coverage. The compass and battery
fixtures retain the golden packets shared with firmware tests. fixtures retain the golden packets shared with firmware tests.
The native iOS EvenHub probe runs separately on a booted simulator:
node tests/ios-evenhub-native.cjs <simulator-UUID>
It compiles the production WKWebView host into an isolated app and checks local
and remote loading, document-start injection, assets, storage and navigation.
It then opens Safari to background the probe and verifies that injected timeouts,
intervals and animation callbacks still fire, and cancelled timers stay cancelled.
A short UIKit background task keeps the test process running without glasses.
This covers the ticker's background behavior; sustained execution with BLE and a
locked physical phone still requires device testing.
+28 -13
View File
@@ -39,17 +39,32 @@ const server = http.createServer((request, response) => {
response.setHeader('Content-Type', file.endsWith('.js') ? 'text/javascript' : file.endsWith('.json') ? 'application/json' : file.endsWith('.png') ? 'image/png' : 'text/html'); response.setHeader('Content-Type', file.endsWith('.js') ? 'text/javascript' : file.endsWith('.json') ? 'application/json' : file.endsWith('.png') ? 'image/png' : 'text/html');
response.end(fs.readFileSync(file)); response.end(fs.readFileSync(file));
}); });
server.listen(0, '127.0.0.1', () => { server.listen(0, '127.0.0.1', async () => {
fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${server.address().port}/`); try {
const device = process.argv[2] || 'booted'; fs.writeFileSync(path.join(bundle, 'remote.txt'), `http://127.0.0.1:${server.address().port}/`);
execFileSync('xcrun', ['simctl', 'install', device, bundle], { stdio: 'inherit' }); const device = process.argv[2] || 'booted';
execFileSync('xcrun', ['simctl', 'launch', '--terminate-running-process', device, 'com.faceclaw.evenhub-probe'], { stdio: 'inherit' }); execFileSync('xcrun', ['simctl', 'install', device, bundle], { stdio: 'inherit' });
const container = execFileSync('xcrun', ['simctl', 'get_app_container', device, 'com.faceclaw.evenhub-probe', 'data'], { encoding: 'utf8' }).trim(); const container = execFileSync('xcrun', ['simctl', 'get_app_container', device, 'com.faceclaw.evenhub-probe', 'data'], { encoding: 'utf8' }).trim();
const resultFile = path.join(container, 'Documents/result.json'); const resultFile = path.join(container, 'Documents/result.json');
setTimeout(() => { const readyFile = path.join(container, 'Documents/background-ready.json');
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8')); for (const file of [resultFile, readyFile]) fs.rmSync(file, { force: true });
console.log(JSON.stringify({ work, ...result })); execFileSync('xcrun', ['simctl', 'launch', '--terminate-running-process', device, 'com.faceclaw.evenhub-probe'], { stdio: 'inherit' });
if (!result.passed) process.exitCode = 1; let backgrounded = false;
server.closeAllConnections(); server.close(); const deadline = Date.now() + 50000;
}, 23000); while (!fs.existsSync(resultFile)) {
if (Date.now() > deadline) throw new Error(`EvenHub probe timed out (backgrounded=${backgrounded}); artifacts: ${work}`);
if (!backgrounded && fs.existsSync(readyFile)) {
execFileSync('xcrun', ['simctl', 'launch', device, 'com.apple.mobilesafari'], { stdio: 'inherit' });
backgrounded = true;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
const result = JSON.parse(fs.readFileSync(resultFile, 'utf8'));
console.log(JSON.stringify({ work, ...result }));
if (!result.passed) process.exitCode = 1;
} catch (error) {
console.error(error); process.exitCode = 1;
} finally {
server.closeAllConnections(); server.close();
}
}); });
+47 -5
View File
@@ -7,9 +7,18 @@
@property(nonatomic) FaceclawEvenHubWebView *host; @property(nonatomic) FaceclawEvenHubWebView *host;
@property(nonatomic) NSMutableSet *seen; @property(nonatomic) NSMutableSet *seen;
@property(nonatomic) NSInteger phase; @property(nonatomic) NSInteger phase;
@property(nonatomic) UIBackgroundTaskIdentifier backgroundTask;
@property(nonatomic) NSInteger backgroundIntervals;
@property(nonatomic) BOOL foregroundPassed;
@end @end
@implementation Probe @implementation Probe
- (void)writeResult:(NSDictionary *)result name:(NSString *)name {
NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
[data writeToFile:[documents stringByAppendingPathComponent:name] atomically:YES];
}
- (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)options { - (BOOL)application:(UIApplication *)app didFinishLaunchingWithOptions:(NSDictionary *)options {
self.backgroundTask = UIBackgroundTaskInvalid;
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds]; self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
self.window.rootViewController = [UIViewController new]; self.window.rootViewController = [UIViewController new];
self.window.rootViewController.view.backgroundColor = UIColor.whiteColor; self.window.rootViewController.view.backgroundColor = UIColor.whiteColor;
@@ -27,6 +36,12 @@
[weakSelf.seen addObject:event[@"name"]]; [weakSelf.seen addObject:event[@"name"]];
[weakSelf.seen addObject:[NSString stringWithFormat:@"%ld:%@", (long)weakSelf.phase, event[@"name"]]]; [weakSelf.seen addObject:[NSString stringWithFormat:@"%ld:%@", (long)weakSelf.phase, event[@"name"]]];
[weakSelf.host evaluate:[NSString stringWithFormat:@"window.__fcResolve(%@,true,true)", event[@"id"]]]; [weakSelf.host evaluate:[NSString stringWithFormat:@"window.__fcResolve(%@,true,true)", event[@"id"]]];
if (UIApplication.sharedApplication.applicationState == UIApplicationStateBackground) {
[weakSelf.seen addObject:[@"background:" stringByAppendingString:event[@"name"]]];
if ([event[@"name"] isEqual:@"interval"]) weakSelf.backgroundIntervals++;
}
if (weakSelf.phase == 6 && [event[@"name"] isEqual:@"timer"])
[weakSelf writeResult:@{@"ready": @YES} name:@"background-ready.json"];
} }
}; };
NSString *root = NSBundle.mainBundle.resourcePath; NSString *root = NSBundle.mainBundle.resourcePath;
@@ -53,14 +68,41 @@
BOOL passed = [[NSSet setWithArray:required] isSubsetOfSet:self.seen] && ![self.seen containsObject:@"UNTRUSTED"]; BOOL passed = [[NSSet setWithArray:required] isSubsetOfSet:self.seen] && ![self.seen containsObject:@"UNTRUSTED"];
NSString *signature = [FaceclawCrypto hmacSha256:@"key" message:@"The quick brown fox jumps over the lazy dog"]; NSString *signature = [FaceclawCrypto hmacSha256:@"key" message:@"The quick brown fox jumps over the lazy dog"];
passed &= [signature isEqual:@"97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg="]; passed &= [signature isEqual:@"97yD9DBThCSxMpjmqm+xQ+9NWaFJRhdZl0edvC0aPNg="];
self.foregroundPassed = passed;
void (^handler)(NSString *) = self.host.eventHandler;
[self.host showOnPhone]; [self.host hideOnPhone]; [self.host destroy]; [self.host showOnPhone]; [self.host hideOnPhone]; [self.host destroy];
NSDictionary *result = @{@"passed": @(passed), @"seen": self.seen.allObjects}; self.phase = 6; self.host = [FaceclawEvenHubWebView new];
NSData *data = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil]; self.host.eventHandler = handler;
NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; [self.host start:[root stringByAppendingPathComponent:@"dist"] entrypoint:@"index.html" script:script];
[data writeToFile:[documents stringByAppendingPathComponent:@"result.json"] atomically:YES];
NSLog(@"EHPROBE RESULT %@", result);
}); });
return YES; return YES;
} }
- (void)applicationDidEnterBackground:(UIApplication *)app {
if (self.phase != 6) return;
// Give the isolated probe a brief execution window without requiring BLE.
// Production relies on Faceclaw's existing background execution support.
self.backgroundTask = [app beginBackgroundTaskWithName:@"EvenHub timer regression" expirationHandler:^{
[app endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid;
}];
[self.host evaluate:@"flutter_inappwebview.callHandler('input');"
"setTimeout(function(){flutter_inappwebview.callHandler('timeout')},100);"
"var count=0; var interval=setInterval(function(){flutter_inappwebview.callHandler('interval');if(++count===3)clearInterval(interval)},100);"
"requestAnimationFrame(function(){flutter_inappwebview.callHandler('animation')});"
"var cancelled=setTimeout(function(){flutter_inappwebview.callHandler('CANCELLED')},100);clearTimeout(cancelled);"];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSArray *required = @[@"background:input", @"background:timeout", @"background:interval", @"background:animation"];
BOOL passed = self.foregroundPassed && app.applicationState == UIApplicationStateBackground &&
[[NSSet setWithArray:required] isSubsetOfSet:self.seen] && self.backgroundIntervals == 3 &&
![self.seen containsObject:@"CANCELLED"];
[self.host destroy];
NSDictionary *result = @{@"passed": @(passed), @"seen": self.seen.allObjects,
@"backgroundIntervals": @(self.backgroundIntervals)};
[self writeResult:result name:@"result.json"];
NSLog(@"EHPROBE RESULT %@", result);
if (self.backgroundTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:self.backgroundTask]; self.backgroundTask = UIBackgroundTaskInvalid;
}
});
}
@end @end
int main(int argc, char **argv) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass(Probe.class)); } } int main(int argc, char **argv) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass(Probe.class)); } }