Android: returning from a file picker loses page state after the server restarts
❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.
Overview
Opening a file picker from the WebView backgrounds the activity. After roughly 60 seconds Android stops KolibriServerService. The server restarts on a different port, the shell reloads the WebView at the new URL, and all page state is lost — including the File the user just picked. To the user this reads as "the server disconnected": the picked file is gone and Continue cannot proceed.
Android stopping the service is a given. What should change is that returning to an already-open page survives it: the page is frozen while backgrounded, and the restarted server comes back on the port that page was loaded on.
Complexity: Medium Target branch: develop
Context
Reproduced on a Redmi 10C / Android 13, during QA of #15050. Nothing about it is specific to the CSV import — any flow that hands off to another activity for longer than the idle timeout is affected.
Android stops the service while the picker is open:
00:34:43.896 ActivityManager W Stopping service due to app idle: u0a1 -3m16s676ms
org.learningequality.Kolibri/.KolibriServerService
The server then comes back on a different port and the WebView is reloaded at the new URL:
00:34:43,908 main Stopping Kolibri server
00:36:50,174 main Kolibri server ready on port 45791 <- was 46655
00:36:51,375 cherrypy.access "GET /en/facility/" 200 <- full reload, SPA state gone
The picker is launched by our own startActivityForResult, so the user has not left Kolibri.
Relevant code: platforms/android/app/src/main/java/org/learningequality/Kolibri/KolibriServerService.java, WebViewActivity.java, and AndroidKolibriProcessBus in platforms/android/app/src/main/python/main.py — which calls super().__init__() with no arguments, so BaseKolibriProcessBus's port=0 default gives a fresh ephemeral port on every start.
The Change
- Freeze the WebView while the activity is backgrounded —
webView.onPause()andpauseTimers()fromonStop, resumed fromonStart— so the page issues no requests against a stopped server. - Persist the port the page was loaded on alongside
PREF_LAST_PATH. - Start
AndroidKolibriProcessBuson that persisted port rather than lettingBaseKolibriProcessBus'sport=0default pick a new one. - Fall back to an ephemeral port if that bind fails.
- Gate the
serverReadyLiveDataobserver soloadInitializeUrl()runs only when there is no live page or the origin has changed; a restart on the same port leaves the existing page as it is. - Keep today's behaviour when the origin does have to change: swap the origin, restore the saved path, clear history.
- Restore the hash route on that reload too.
- Capture the current hash when the page is frozen —
onPageFinishedonly ever sees the hash present at document load.
How to Get There
- Put a users CSV on Google Drive on the test device.
- In Kolibri on Android, go to the facility CSV import and tap
Choose file. - Select the CSV from Google Drive in the system picker — fetching it from Drive is what keeps the picker foregrounded past the idle timeout.
- Press
Continue.
The Stopping service due to app idle line in logcat confirms the idle stop fired.
Out of Scope
- Preventing Android from stopping the service. Making
KolibriServerServicea foreground service is not an acceptable fix. - Any move toward a globally fixed port. A cold start still elects an ephemeral port; only a restart with a page already loaded reuses one.
Acceptance Criteria
Status (PR #15104): none of the five is verified. All five are on-device outcomes and the agent has no Android device — see this comment for the automated coverage behind each one and exactly what is left to run on a physical Android 13+ device.
- [ ] A CSV stored on Google Drive can be imported from the facility CSV import: after returning from the picker the chosen filename is still shown and
Continueproceeds. - [ ] Returning to a backgrounded page never shows the disconnection snackbar — the heartbeat makes no request while the page is frozen, so it never registers a disconnect.
- [ ] A restart that rebinds the previous port leaves the open page in place: no reload, no lost page state.
- [ ] When the previous port cannot be rebound, the WebView reloads at the new origin and lands on the same path and hash route it was on.
- [ ] Manually verified on a physical device running Android 13 or later, where the idle stop actually fires.
References
- QA report of the disconnect on #15050: https://github.com/learningequality/kolibri/pull/15050#issuecomment-5097854135
AI usage
Drafted with Claude from the QA report and the logcat traces. I confirmed the reproduction myself, and the specifics — the ephemeral-port default in AndroidKolibriProcessBus, the reload path through the serverReady observer, the origin saveLastPath discards — were verified against the code rather than taken from the model. The approach is mine.
Plan: When Android stops KolibriServerService while the user is in a file picker, the page they left is still there when they come back — same port, no reload, no lost File.
- [x] Remember where the page is
- [x] Rebind the remembered port on restart
- [x] Freeze the WebView while the server is away
- [x] Leave the page in place when the origin is unchanged
@rtibblesbot's comments are generated by an LLM, and should be evaluated accordingly
How was this generated?
- Implemented code following the pre-approved plan using test-driven development (red-green-refactor)
- Ran the project's full test suite and linter before committing
- For UI changes: captured live screenshots to verify rendering
- For backend changes: verified with example API/CLI output
The WebView freeze (onStop → onPause() + pauseTimers(), thawed from onStart when the server is already up, or from the serverReady observer otherwise) is implemented and covered by three Robolectric tests. Full JVM suite green at 29 tests, spotless clean.
One step of that phase could not be done here: the on-device check of the freeze. No physical device is attached to this environment, and the kolibri-test AVD segfaults during startup (exit 139) under -gpu swiftshader_indirect, -gpu guest and -gpu off alike, with KVM present and usable. Two things the plan wanted checked early therefore remain open for a human on an Android 13+ device:
- Whether a picked file survives delivery to a frozen WebView —
onActivityResultlands betweenonStartandonResume, sopendingFilePickerCallback.onReceiveValue(...)runs against paused timers. This is the whole of AC 1. Event dispatch is not a timer, so it should reach the page, but it is worth confirming directly rather than inferring. - How long the frozen window lasts on return, and whether a tap during it can still fire a request. If it can, the fallback is to re-show the existing splash from
onStopand hide it fromonServerReady.
The acceptance-criteria run in the remaining phase needs the same physical device.
@rtibblesbot's comments are generated by an LLM, and should be evaluated accordingly
The origin gate is implemented and the plan's four coding phases are complete.
loadInitializeUrl still builds the initialize URL on every serverReady, but the load now goes through loadIfOriginChanged: when there is a live page and its origin matches the freshly built URL, the page is left alone. hasLivePage is set from onPageFinished and cleared from a new main-frame onReceivedError, so a document that died against the stopped server does not count as live — without that the user would be left on the WebView's own error page after the restart. The reload path keeps today's behaviour: clear history, restore the saved path and hash.
Four Robolectric tests drive the WebViewClient directly rather than loadInitializeUrl, which is unreachable off-device: same-origin restart leaves the page, new-origin reloads, no-live-page always loads, and a main-frame error makes a same-origin restart reload. Full JVM suite green at 33 tests, Python at 14, spotless clean.
Still outstanding, and it is the whole of the manual acceptance criteria: no physical device is available in this environment, so the on-device run has not been done. Carried over from the previous phase and unchanged — nothing is attached over adb, and the kolibri-test AVD segfaults during startup (exit 139) under -gpu swiftshader_indirect, -gpu guest and -gpu off alike. A human on an Android 13+ device needs to cover:
- The CSV-from-Drive round trip: filename still shown on return, no disconnection snackbar,
Continueproceeds. This includes the open question from the last phase — whether a picked file survives delivery to a WebView with paused timers, sinceonActivityResultlands betweenonStartandonResume. - That
Kolibri server ready on port Nmatches the port in thecherrypy.accesslines from before the stop, with no full pageGETafterwards. - The failed-rebind path, by holding the old port from another process:
Port N is no longer free, electing an ephemeral port, then a reload landing on the same path and hash route. Test a deep route such as…/en/facility/#/data— the hash is the part that regressed. - That
doUpdateVisitedHistoryactually fires on this device's WebView. This is the one mechanism in the plan resting on a callback whose same-document behaviour is not documented in detail; if it does not fire, the fallback is aWebViewLocation.savefromonStop. - A cold restart afterwards still landing on the last page, confirming
last_pathnever holds an/api/device/initialize/…URL.
Also worth flagging as a follow-up rather than folding in here: ZipContentServerPlugin binds its own ephemeral port and is not restored, so a page left open on an HTML5 or EPUB item keeps zipcontent iframe URLs pointing at the old zip port. That iframe breaks after a restart even when the main origin is preserved. Restoring it needs the zip port plumbed back from Python, which is beyond what this issue asks for.
Acceptance-criteria status. None of the five is met, and none can be met from this environment — every one is an on-device outcome, no Android device is attached over adb, there is no display (DISPLAY, WAYLAND_DISPLAY, XDG_SESSION_TYPE all unset), and both local AVDs die during startup: kolibri-test (API 35) segfaults with exit 139, kolibri-test-24 (API 24) exits silently right after Emulator is performing a full startup, under -gpu swiftshader_indirect, -gpu guest and -gpu off alike. AC 5 asks for a physical Android 13+ device in any case, since the idle stop does not fire reliably on an emulator.
Reproduced verbatim from the body, left unticked deliberately — the automated suites cover the mechanisms, not the outcomes, and ticking these without a device run would be a false claim:
- [ ] A CSV stored on Google Drive can be imported from the facility CSV import: after returning from the picker the chosen filename is still shown and
Continueproceeds. — not verified. No off-device coverage is possible. TheregisterForActivityResultcallback lands betweenonStartandonResume, so the pickedUrireaches a WebView whose timers are still paused; event dispatch is not a timer, but confirm it rather than infer it. - [ ] Returning to a backgrounded page never shows the disconnection snackbar — the heartbeat makes no request while the page is frozen, so it never registers a disconnect. — not verified. The freeze is covered by
WebViewActivityTest(pause fromonStop, thaw fromonStartwhen the server never went away, thaw from theserverReadyobserver otherwise). What needs a device is that the frozen window on return is short and cannot be tapped through into a request. - [ ] A restart that rebinds the previous port leaves the open page in place: no reload, no lost page state. — not verified. Gate covered by
sameOriginRestart_leavesTheLivePageAlone; rebind bytest_resolve_server_port_reuses_a_free_port. On a device:Kolibri server ready on port Nshould match the port in thecherrypy.accesslines from before the stop, with no full-pageGETafter it. - [ ] When the previous port cannot be rebound, the WebView reloads at the new origin and lands on the same path and hash route it was on. — not verified. Covered off-device by
newOriginRestart_reloads, both_resolve_server_portfallback tests, andWebViewLocationTeston the hash round trip. On a device, use a deep route such as…/en/facility/#/data— the hash is the part that regressed — and confirmdoUpdateVisitedHistoryfires on that WebView. - [ ] Manually verified on a physical device running Android 13 or later, where the idle stop actually fires. — not verified: no physical device in this environment.
I cannot tick the boxes in the issue body either way: gh issue edit fails as rtibblesbot with GraphQL: rtibblesbot does not have the correct permissions to execute UpdateIssue.
@rtibblesbot's comments are generated by an LLM, and should be evaluated accordingly
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.
The bot has been waiting for a response for 2 hour(s). It will resume automatically when someone replies.