From 3f164de2f51ab3fc8b98f2d3dc3eca451fe61b62 Mon Sep 17 00:00:00 2001 From: SiteRelEnby <125829806+SiteRelEnby@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:47:51 -0400 Subject: [PATCH] feat(errors): let people see the status and the server's own message The web app has had a "Show technical error details" setting for a while. Android had nothing: every failure read as a canned sentence chosen by status code, and the server's own `detail` was not merely unused but actively thrown away, since toUserMessage read the error body only to sniff for Cloudflare and then discarded it. There was no path by which a server message reached a user. Settings, About gains the switch, off by default. On, an HTTP failure reads "[404] Field not found" and anything else names the exception behind it, which is the part a bug report was missing: four causes collapse into one sentence in the friendly register. About rather than a category of its own, which is where web keeps it. That screen is already the one somebody opens to copy a version, a commit and a server address into a report, and this changes what a report can say. Not the Debug Menu despite the name fitting: that row is behind BuildConfig.DEBUG, and the people who need this are on release builds. Three things worth saying about the shape: The preference is kept on the device as well as in the account's client settings. The account copy is what syncs between Android devices, but it arrives with the first successful load, and the failures this setting exists to explain are exactly the ones where that load does not happen. A preference you have to fetch is off precisely when somebody is trying to find out why nothing is loading. Verified by toggling it with the backend stopped. Reading `detail` now peeks the body instead of consuming it. An error body is a one-shot stream and `string()` closes it, which is why the sharing flows read it defensively and warned about toUserMessage racing them. Two readers on one exception is now the normal case rather than something to avoid. The client id is the platform, so turning this on in a browser does not turn it on here. A status code in a toast is least wanted on a phone, and the two clients disagreeing about that is the intent rather than a gap. Also fixes an inconsistency this surfaced. The sharing classifier, which tells step-up from bad credentials from publishing-is-off, carried a second table of per-status wordings for everything else, so the same status could read two ways depending on which call failed, and the new setting did nothing on any screen that routed through it (custom fields among them). Unclassified failures now go through the same formatter, keeping the server's prose where that is the useful part. The classified states keep their own wording: they are states with their own UI, and a status code in front of the step-up sheet's "incorrect password" would read as a fault rather than a prompt. Checked on device against a real instance: off and on for a network failure with the backend stopped, a 422 whose list-shaped detail correctly falls back to the summary rather than dumping JSON, and a 404 on a field deleted out from under the screen, which showed a bare "Field not found" before the classifier change and "[404] Field not found" after. --- CHANGELOG.md | 22 ++ .../systems/lupine/sheaf/SheafApplication.kt | 28 +++ .../data/repository/PreferencesRepository.kt | 22 ++ .../lupine/sheaf/ui/home/HomeViewModel.kt | 10 + .../lupine/sheaf/ui/settings/AboutScreen.kt | 54 +++++ .../sheaf/ui/settings/AboutViewModel.kt | 34 +++- .../lupine/sheaf/ui/sharing/ShareErrors.kt | 51 +++-- .../lupine/sheaf/util/ApiErrorDetail.kt | 47 +++++ .../lupine/sheaf/util/ErrorMessages.kt | 76 ++++++- .../lupine/sheaf/util/TechnicalErrors.kt | 74 +++++++ .../sheaf/ui/sharing/ShareErrorsTest.kt | 45 +++++ .../lupine/sheaf/util/ErrorMessagesTest.kt | 10 +- .../lupine/sheaf/util/TechnicalErrorsTest.kt | 191 ++++++++++++++++++ 13 files changed, 621 insertions(+), 43 deletions(-) create mode 100644 sheaf/app/src/main/java/systems/lupine/sheaf/util/ApiErrorDetail.kt create mode 100644 sheaf/app/src/main/java/systems/lupine/sheaf/util/TechnicalErrors.kt create mode 100644 sheaf/app/src/test/java/systems/lupine/sheaf/util/TechnicalErrorsTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index ffc8ab4..3b06b7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,20 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`). ### Added +- **Show technical error details.** Settings, About gains an Error reporting + switch, off by default. On, a failed request says which status came back and + what the server actually said, instead of a short summary: "[404] Field not + found" rather than "Not found", and a network failure names the exception + behind it. It sits on About because that is the screen you already open to + copy a version and a commit into a bug report. The web app has had the same + setting for a while, and turning it on here is remembered for your other + Android devices; the two clients keep their own answer, since a status code + in a toast is least wanted on a phone. + + The setting also applies when the server cannot be reached at all, which is + when it is most often wanted: it is kept on the device, not only on the + account, so it does not depend on the request that is failing. + - **Slider custom fields.** A field can now be a slider, matching the type the server and the web app gained: either a labelled one from 0 to 100 between two words of your choosing ("Drained" to "Wired", read as a percentage), or a @@ -28,6 +42,14 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`). ### Fixed +- **Sharing and custom fields no longer explain failures their own way.** The + screens that tell three kinds of refusal apart, so they can ask for a + password or say publishing is off, carried a second set of wordings for + everything else. So the same status could read differently depending on + which call had failed, and the new error-details setting did nothing on + those screens. They now share one formatter, keeping the server's own prose + where it is the useful part. + - **Image avatars now appear on the watch, on instances that serve files themselves.** A member with an uploaded avatar showed nothing where their picture should be: no image, and not even the initials circle, on Currently diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/SheafApplication.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/SheafApplication.kt index b51ecb2..b04e178 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/SheafApplication.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/SheafApplication.kt @@ -6,9 +6,15 @@ import androidx.work.Configuration import coil.ImageLoader import coil.ImageLoaderFactory import dagger.hilt.android.HiltAndroidApp +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import systems.lupine.sheaf.data.repository.PreferencesRepository import systems.lupine.sheaf.lock.AppLockManager import systems.lupine.sheaf.notification.FrontNotificationHelper import systems.lupine.sheaf.push.PushNotificationChannels +import systems.lupine.sheaf.util.TechnicalErrors import javax.inject.Inject @HiltAndroidApp @@ -19,6 +25,7 @@ class SheafApplication : Application(), ImageLoaderFactory, Configuration.Provid @Inject lateinit var imageLoader: ImageLoader @Inject lateinit var workerFactory: HiltWorkerFactory @Inject lateinit var lockManager: AppLockManager + @Inject lateinit var prefs: PreferencesRepository override val workManagerConfiguration: Configuration get() = Configuration.Builder().setWorkerFactory(workerFactory).build() @@ -28,6 +35,27 @@ class SheafApplication : Application(), ImageLoaderFactory, Configuration.Provid notificationHelper.createChannel() pushChannels.register() lockManager.start() + seedTechnicalErrorsPreference() + } + + /** + * Put the stored "show technical error details" choice where error + * formatting can see it, before anything has a chance to fail. + * + * Read from the device rather than the account on purpose. The account's + * copy arrives with the first successful load, and the failures this + * preference exists to explain are exactly the ones where that load does + * not happen: a preference that has to be fetched before it applies is off + * precisely when somebody is trying to find out why nothing is loading. + * + * Collected for the life of the process, not read once, so a change made + * on this device, or adopted from the account mid-session, takes effect on + * the next error rather than the next launch. + */ + private fun seedTechnicalErrorsPreference() { + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + prefs.showTechnicalErrors.collect { TechnicalErrors.set(it) } + } } override fun newImageLoader(): ImageLoader = imageLoader diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/repository/PreferencesRepository.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/repository/PreferencesRepository.kt index b6c5ae9..621ce28 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/repository/PreferencesRepository.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/repository/PreferencesRepository.kt @@ -53,6 +53,11 @@ class PreferencesRepository @Inject constructor( val KEY_CF_CLIENT_SECRET = stringPreferencesKey("cf_client_secret") val KEY_FILE_CDN_BASE = stringPreferencesKey("file_cdn_base") val KEY_APP_LOCK = booleanPreferencesKey("app_lock") + // "Show technical error details". Kept on the device as well as in the + // account's client settings, because the one time it matters most is + // when the server cannot be reached, and a preference that has to be + // fetched is a preference that is off exactly when it is wanted. + val KEY_TECHNICAL_ERRORS = booleanPreferencesKey("show_technical_errors") // Mirrors the backend's sheaf_trusted_device cookie. We store it // verbatim plus its expiry-millis so the CookieJar can drop it once // expired without a server round-trip. @@ -138,6 +143,10 @@ class PreferencesRepository @Inject constructor( val cfClientId: Flow = context.dataStore.data.map { it[KEY_CF_CLIENT_ID] } val cfClientSecret: Flow = context.dataStore.data.map { it[KEY_CF_CLIENT_SECRET] } val appLockEnabled: Flow = context.dataStore.data.map { it[KEY_APP_LOCK] ?: false } + + /** Off by default: most people do not want a status code in a toast. */ + val showTechnicalErrors: Flow = + context.dataStore.data.map { it[KEY_TECHNICAL_ERRORS] ?: false } val historyView: Flow = context.dataStore.data.map { it[KEY_HISTORY_VIEW] ?: "infinite" } val historyPageSize: Flow = context.dataStore.data.map { it[KEY_HISTORY_PAGE_SIZE] ?: 50 } val accountTimezone: Flow = context.dataStore.data.map { it[KEY_ACCOUNT_TIMEZONE] } @@ -257,6 +266,19 @@ class PreferencesRepository @Inject constructor( context.dataStore.edit { it[KEY_APP_LOCK] = enabled } } + /** + * Store the preference and update the copy error formatting reads. + * + * Both, always, and in that order: the flow is the durable value and + * [TechnicalErrors] is what `toUserMessage` can actually see. Writing only + * the first would leave the next error formatted by the old setting until + * something restarted the process. + */ + suspend fun saveShowTechnicalErrors(enabled: Boolean) { + context.dataStore.edit { it[KEY_TECHNICAL_ERRORS] = enabled } + systems.lupine.sheaf.util.TechnicalErrors.set(enabled) + } + suspend fun saveHistoryView(view: String) { context.dataStore.edit { it[KEY_HISTORY_VIEW] = view } } diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/home/HomeViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/home/HomeViewModel.kt index 8b5012f..0ad471c 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/home/HomeViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/home/HomeViewModel.kt @@ -326,6 +326,16 @@ class HomeViewModel @Inject constructor( _state.update { it.copy(user = u) } } } + launch { + // Adopt the account's "show technical error details" + // choice, if it has one. Done on the load that already + // fetches this blob, so it costs no extra round-trip, and + // early enough that the first error of the session is + // formatted the way the user asked for. + systems.lupine.sheaf.util.TechnicalErrors + .fromClientSettings(clientSettingsD.await().getOrNull()?.settings) + ?.let { prefs.saveShowTechnicalErrors(it) } + } launch { val announcements = announcementsD.await().getOrNull() // Server-side "don't show again" set. Merge (union) with diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutScreen.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutScreen.kt index 90f4a73..b136527 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutScreen.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutScreen.kt @@ -1,6 +1,7 @@ package systems.lupine.sheaf.ui.settings import android.content.ClipData +import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -19,6 +20,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -54,6 +56,7 @@ fun AboutScreen( ) { val serverVersion by viewModel.serverVersion.collectAsState() val baseUrl by viewModel.baseUrl.collectAsState() + val showTechnicalErrors by viewModel.showTechnicalErrors.collectAsState() Scaffold( contentWindowInsets = WindowInsets(0), @@ -120,7 +123,58 @@ fun AboutScreen( version.buildTime?.takeIf { it.isNotBlank() }?.let { DetailRow("Built", it) } version.mode?.takeIf { it.isNotBlank() }?.let { DetailRow("Mode", it) } } + + // Filed here rather than under its own settings category, which is + // where the web app keeps it. This screen is already the one + // somebody opens to put a build and a server into a bug report, + // and the setting changes what a bug report can say. + // + // Not the Debug Menu, despite the name fitting: that row is behind + // BuildConfig.DEBUG, and the people who need this are on release + // builds, reporting something that went wrong on their own phone. + SectionHeader("Error reporting", modifier = Modifier.padding(horizontal = 16.dp)) + TechnicalErrorsRow( + checked = showTechnicalErrors, + onCheckedChange = viewModel::setShowTechnicalErrors, + ) + } + } +} + +/** + * The "show me what actually went wrong" switch. + * + * Off by default, and worth keeping that way for most people: a status code in + * a toast is noise to somebody who cannot act on it. On, it is the difference + * between "Something went wrong" and a line that says which call failed and + * what the server said about it. + */ +@Composable +private fun TechnicalErrorsRow( + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onCheckedChange(!checked) } + .padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text("Show technical error details", style = MaterialTheme.typography.bodyLarge) + Text( + "When something goes wrong, show the status code and the server's exact " + + "message instead of a short summary. Useful for reporting a problem; " + + "noisy day to day.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) } + Switch(checked = checked, onCheckedChange = onCheckedChange) } } diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutViewModel.kt index 726ed39..699bba8 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/AboutViewModel.kt @@ -8,11 +8,18 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import systems.lupine.sheaf.data.api.SheafApiService +import systems.lupine.sheaf.data.model.ClientSettingsBody import systems.lupine.sheaf.data.model.ServerVersion import systems.lupine.sheaf.data.repository.PreferencesRepository import systems.lupine.sheaf.data.repository.ServerInfoRepository +import systems.lupine.sheaf.util.TechnicalErrors import javax.inject.Inject +// Same blob SettingsViewModel and HomeViewModel write to; the client id is the +// platform, so every Android device on the account shares one set. +private const val CLIENT_ID = "android" + /** * What About needs beyond `BuildConfig`: which instance this is and what it is * running. @@ -24,7 +31,8 @@ import javax.inject.Inject @HiltViewModel class AboutViewModel @Inject constructor( private val serverInfo: ServerInfoRepository, - prefs: PreferencesRepository, + private val prefs: PreferencesRepository, + private val api: SheafApiService, ) : ViewModel() { val serverVersion: StateFlow = serverInfo.version @@ -33,9 +41,33 @@ class AboutViewModel @Inject constructor( .map { it.orEmpty() } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "") + val showTechnicalErrors: StateFlow = prefs.showTechnicalErrors + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) + init { refresh() } fun refresh() { viewModelScope.launch { serverInfo.ensureLoaded() } } + + /** + * Apply the choice here, then tell the account. + * + * Local first and unconditionally: this is the one preference whose whole + * job is to explain a failing request, so it cannot depend on a request + * succeeding. The PATCH is best-effort and carries only its own nested + * group, so a failure leaves the device's setting in force and nothing + * else in the blob disturbed. + */ + fun setShowTechnicalErrors(enabled: Boolean) { + viewModelScope.launch { + prefs.saveShowTechnicalErrors(enabled) + runCatching { + api.patchClientSettings( + CLIENT_ID, + ClientSettingsBody(TechnicalErrors.toClientSettings(enabled)), + ) + } + } + } } diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/sharing/ShareErrors.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/sharing/ShareErrors.kt index 916816a..31824b6 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/sharing/ShareErrors.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/sharing/ShareErrors.kt @@ -1,7 +1,7 @@ package systems.lupine.sheaf.ui.sharing -import com.squareup.moshi.Moshi import retrofit2.HttpException +import systems.lupine.sheaf.util.errorDetail import systems.lupine.sheaf.util.toUserMessage /** @@ -53,37 +53,32 @@ fun Throwable.toShareError(fallback: String): ShareError { code() == 403 && detail != null && "turned off on this instance" in detail -> ShareError.PublishingUnavailable(detail) code() == 403 -> ShareError.BadCredentials(detail ?: "Incorrect password or authenticator code") - else -> ShareError.Other(detail ?: httpFallback(fallback)) + // Not one of the states above, so it is an ordinary failure being + // reported as a message, and it goes through the same formatter as + // every other one. preferDetail keeps what this branch already did + // (these endpoints answer with prose worth reading) while letting the + // technical register add the status, which it could not before: the + // preference used to do nothing on any screen that classified its + // errors through here, so the same setting said different things + // depending on which call had failed. + // + // The classified states above keep their own wording. They are states + // with their own UI, not messages, and a status code in the step-up + // sheet's "incorrect password" line would read as a fault rather than + // as a prompt. + else -> ShareError.Other(toUserMessage(fallback, preferDetail = true)) } } -// Moshi rather than org.json: the classification is the interesting part of -// this file and org.json is an Android framework stub off-device, so parsing -// with it would make these branches untestable on the JVM. -private val errorBodyAdapter by lazy { - Moshi.Builder().build().adapter>( - com.squareup.moshi.Types.newParameterizedType( - Map::class.java, - String::class.java, - Any::class.java, - ), - ) -} - -// The body is a one-shot stream, so read it once here rather than letting -// toUserMessage race us for it. -private fun HttpException.errorDetail(): String? = runCatching { - val body = response()?.errorBody()?.string().orEmpty() - if (body.isBlank()) return@runCatching null - (errorBodyAdapter.fromJson(body)?.get("detail") as? String)?.takeIf { it.isNotBlank() } -}.getOrNull() +// The detail reader moved to util/ApiErrorDetail.kt, which peeks the body +// instead of consuming it. That retires the race this file used to work +// around: toUserMessage now reads the detail too, for the technical-errors +// preference, and two readers on one exception is the normal case rather than +// something to avoid. -private fun HttpException.httpFallback(fallback: String): String = when (code()) { - 401 -> "Session expired, please log in again" - 404 -> "Not found" - 429 -> "Too many requests, please wait a moment" - else -> fallback -} +// The per-status wording this file used to carry has gone: toUserMessage +// already maps every one of those codes, and keeping a second table meant the +// same status could read two ways depending on which screen asked. fun ShareError.message(fallback: String): String = when (this) { is ShareError.StepUpRequired -> fallback diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/util/ApiErrorDetail.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/util/ApiErrorDetail.kt new file mode 100644 index 0000000..e6cb363 --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/util/ApiErrorDetail.kt @@ -0,0 +1,47 @@ +package systems.lupine.sheaf.util + +import com.squareup.moshi.Moshi +import com.squareup.moshi.Types +import retrofit2.HttpException + +/** + * Reading the server's own explanation out of a failed response. + * + * The API puts it in `detail`, and every surface that wants it has to read the + * same body. That is the catch: an error body is a one-shot stream, and + * `ResponseBody.string()` closes the source, so the second reader gets nothing. + * The sharing flows already hit this and worked around it locally, with a + * comment about not letting `toUserMessage` "race us for it". Once the + * technical-errors toggle exists, two readers on one exception stops being + * hypothetical: the detail is wanted for the message AND for classification on + * the same failure. + * + * So this peeks rather than consumes. Retrofit buffers the error body before + * building the exception, so `peek()` hands back an independent view and the + * original stays readable for whoever asks next. Call it as many times as you + * like, in any order. + */ + +private val errorBodyAdapter by lazy { + Moshi.Builder().build().adapter>( + Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java), + ) +} + +/** The raw error body, without consuming it. Empty string when there is none. */ +fun HttpException.errorBodyText(): String = runCatching { + response()?.errorBody()?.source()?.peek()?.readUtf8().orEmpty() +}.getOrDefault("") + +/** + * The server's `detail` string, or null when the body has none. + * + * A validation failure (422) answers with a list of field errors rather than a + * string, which is not something to put in front of somebody as prose, so it + * reads as "no detail" here and the caller falls back to its summary. + */ +fun HttpException.errorDetail(): String? = runCatching { + val body = errorBodyText() + if (body.isBlank()) return@runCatching null + (errorBodyAdapter.fromJson(body)?.get("detail") as? String)?.takeIf { it.isNotBlank() } +}.getOrNull() diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/util/ErrorMessages.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/util/ErrorMessages.kt index 1cc7e1f..42ef1c3 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/util/ErrorMessages.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/util/ErrorMessages.kt @@ -12,22 +12,80 @@ import java.security.cert.CertificateNotYetValidException import javax.net.ssl.SSLHandshakeException import javax.net.ssl.SSLPeerUnverifiedException -fun Throwable.toUserMessage(fallback: String = "Something went wrong — please try again"): String = - certificateProblem() ?: when (this) { +/** + * What to show somebody when a call failed. + * + * Two registers, chosen by the "Show technical error details" preference + * ([TechnicalErrors]). Off, which is the default, every failure reads as a + * short sentence about what to do next. On, an HTTP failure reads + * `[] ` and anything else names the + * exception behind it, which is what a bug report needs and what the web app + * has shown behind the same toggle. + * + * [preferDetail] is for the handful of endpoints whose 4xx detail IS the + * actionable content, written for the account holder about their own settings + * ("set your system to public first"). The friendly summaries exist because + * most server details are noise to somebody who did not cause them, but + * replacing one of these with "Invalid request" throws away the only thing + * that says what to do next. Use it where the detail names a step the reader + * can take, not as a general escape hatch. Same meaning as the argument of the + * same name on the web helper. + */ +fun Throwable.toUserMessage( + fallback: String = "Something went wrong - please try again", + preferDetail: Boolean = false, +): String { + val technical = TechnicalErrors.enabled() + certificateProblem()?.let { return if (technical) it.withCause(this) else it } + return when (this) { is HttpException -> { - val body = runCatching { response()?.errorBody()?.string() ?: "" }.getOrDefault("") - if (isCloudflareResponse(body)) { + // Cloudflare answers for the server without being it, so that + // check stays ahead of the status table in both registers: a 403 + // from the edge is not "access denied" by Sheaf. + val friendly = if (isCloudflareResponse(errorBodyText())) { cloudflareMessage(code()) } else { httpMessage(code(), fallback) } + val detail = errorDetail() + when { + // The status is half the value of this mode: "[404] Not found" + // says which layer answered, where "Not found" alone does not. + technical -> "[${code()}] ${detail ?: friendly}" + preferDetail && detail != null -> detail + else -> friendly + } } - is UnknownHostException -> "Can't reach the server — check your internet connection" - is ConnectException -> "Unable to connect — check your internet connection" - is SocketTimeoutException -> "Connection timed out — please try again" - is IOException -> "Network error — check your connection and try again" - else -> fallback + is UnknownHostException -> + "Can't reach the server - check your internet connection".orCause(technical, this) + is ConnectException -> + "Unable to connect - check your internet connection".orCause(technical, this) + is SocketTimeoutException -> + "Connection timed out - please try again".orCause(technical, this) + is IOException -> + "Network error - check your connection and try again".orCause(technical, this) + else -> fallback.orCause(technical, this) } +} + +/** + * The exception's own name and message, appended when the technical register + * is on. + * + * There is no status or server message to show for anything that is not an + * HTTP response, and the friendly line is already more use than + * `Throwable.message` by itself: "Network error" beats a bare hostname. What a + * bug report is missing is which exception it actually was, because several + * distinct causes collapse into one sentence above. + */ +private fun String.orCause(technical: Boolean, error: Throwable): String = + if (technical) withCause(error) else this + +private fun String.withCause(error: Throwable): String { + val name = error::class.simpleName ?: return this + val detail = error.message?.takeIf { it.isNotBlank() } + return if (detail == null) "$this ($name)" else "$this ($name: $detail)" +} // These are IOExceptions too, so without this they read as "check your // connection", which sends people debugging their network. Release builds only; diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/util/TechnicalErrors.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/util/TechnicalErrors.kt new file mode 100644 index 0000000..3e2b58f --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/util/TechnicalErrors.kt @@ -0,0 +1,74 @@ +package systems.lupine.sheaf.util + +import java.util.concurrent.atomic.AtomicBoolean + +/** + * Whether errors should show their technical detail, readable from anywhere. + * + * [Throwable.toUserMessage] is an ordinary function called from view models, + * repositories and interceptors, often while handling a failure that has + * nothing to hand but the exception. Threading a preference through every one + * of those call sites would mean touching most of the app to add one checkbox, + * and would still leave the paths that format an error before any view model + * exists. + * + * So the resolved value is mirrored here, the same shape the web app uses for + * the same reason (its api-client is not a React component and cannot read a + * hook). [PreferencesRepository] owns the stored value; this is a cache of it. + * + * Off until something says otherwise, which is also the right answer when + * nobody is signed in. + */ +object TechnicalErrors { + + private val enabled = AtomicBoolean(false) + + /** True when the user asked to see status codes and server messages. */ + fun enabled(): Boolean = enabled.get() + + /** Called when the stored preference is read or changed. */ + fun set(value: Boolean) { + enabled.set(value) + } + + /** + * Run [block] with the flag forced, then put it back. For tests, which + * would otherwise leak state between cases through a process-wide object. + */ + internal fun withEnabled(value: Boolean, block: () -> T): T { + val previous = enabled.getAndSet(value) + return try { + block() + } finally { + enabled.set(previous) + } + } + + /** + * Where the account-wide copy lives in the client-settings blob. + * + * Nested under `developer` rather than sitting at the top level so the + * namespace has room for the next preference of this kind, and so it + * matches the shape the web app writes under its own client id. The blob + * is per-client, so turning this on in a browser does not turn it on here: + * a phone is where a status code in a toast is least wanted, and the two + * clients disagreeing about that is the point rather than a gap. + */ + const val SETTINGS_GROUP = "developer" + const val SETTINGS_KEY = "show_technical_errors" + + /** + * Read the stored value out of a client-settings blob, or null when the + * account has never set it. + * + * Null matters: absent is not the same as false. Absent means "this device + * decides", so a local preference survives a sync with an account that has + * never touched the setting, rather than being reset to off on every load. + */ + fun fromClientSettings(settings: Map?): Boolean? = + ((settings?.get(SETTINGS_GROUP) as? Map<*, *>)?.get(SETTINGS_KEY) as? Boolean) + + /** The patch body for writing it back, as one nested group. */ + fun toClientSettings(enabled: Boolean): Map = + mapOf(SETTINGS_GROUP to mapOf(SETTINGS_KEY to enabled)) +} diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/ui/sharing/ShareErrorsTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/ui/sharing/ShareErrorsTest.kt index 08c7bed..faa08d6 100644 --- a/sheaf/app/src/test/java/systems/lupine/sheaf/ui/sharing/ShareErrorsTest.kt +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/ui/sharing/ShareErrorsTest.kt @@ -83,6 +83,51 @@ class ShareErrorsTest { assertIs(err) } + @Test + fun `an unclassified failure still says what the server said`() { + // These endpoints answer with prose worth reading, so the detail is + // the message whether or not the technical register is on. + systems.lupine.sheaf.util.TechnicalErrors.withEnabled(false) { + val err = error(404, "Field not found").toShareError("fallback") + assertIs(err) + assertEquals("Field not found", err.message) + } + } + + @Test + fun `the technical register reaches this screen too`() { + // It used to stop at the classifier: every surface that routed its + // errors through here ignored the preference, so the same setting + // said different things depending on which call had failed. + systems.lupine.sheaf.util.TechnicalErrors.withEnabled(true) { + val err = error(404, "Field not found").toShareError("fallback") + assertIs(err) + assertEquals("[404] Field not found", err.message) + } + } + + @Test + fun `a classified state keeps its own wording in either register`() { + // The step-up sheet prompts for a credential; a status code in front + // of "incorrect password" would read as a fault rather than a prompt. + for (technical in listOf(false, true)) { + systems.lupine.sheaf.util.TechnicalErrors.withEnabled(technical) { + val err = error(403, "Incorrect password").toShareError("fallback") + assertIs(err) + assertEquals("Incorrect password", err.message) + } + } + } + + @Test + fun `an unclassified failure with no detail falls back to the status wording`() { + systems.lupine.sheaf.util.TechnicalErrors.withEnabled(false) { + val err = error(404, null).toShareError("fallback") + assertIs(err) + assertEquals("Not found", err.message) + } + } + @Test fun `raise detection only fires on the way up`() { kotlin.test.assertTrue(isRaiseToPublic("private", "public")) diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/util/ErrorMessagesTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/util/ErrorMessagesTest.kt index 9563c89..801e2f7 100644 --- a/sheaf/app/src/test/java/systems/lupine/sheaf/util/ErrorMessagesTest.kt +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/util/ErrorMessagesTest.kt @@ -22,7 +22,7 @@ class ErrorMessagesTest { @Test fun `unknown host maps to connectivity message`() { assertEquals( - "Can't reach the server — check your internet connection", + "Can't reach the server - check your internet connection", UnknownHostException("nope").toUserMessage(), ) } @@ -30,7 +30,7 @@ class ErrorMessagesTest { @Test fun `connect exception maps to connectivity message`() { assertEquals( - "Unable to connect — check your internet connection", + "Unable to connect - check your internet connection", ConnectException("refused").toUserMessage(), ) } @@ -38,7 +38,7 @@ class ErrorMessagesTest { @Test fun `socket timeout maps to retry message`() { assertEquals( - "Connection timed out — please try again", + "Connection timed out - please try again", SocketTimeoutException().toUserMessage(), ) } @@ -46,7 +46,7 @@ class ErrorMessagesTest { @Test fun `generic IO exception maps to network error`() { assertEquals( - "Network error — check your connection and try again", + "Network error - check your connection and try again", IOException("disk full or whatever").toUserMessage(), ) } @@ -102,7 +102,7 @@ class ErrorMessagesTest { @Test fun `unmapped exception falls back to default`() { assertEquals( - "Something went wrong — please try again", + "Something went wrong - please try again", IllegalStateException("boom").toUserMessage(), ) } diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/util/TechnicalErrorsTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/util/TechnicalErrorsTest.kt new file mode 100644 index 0000000..c3ab1af --- /dev/null +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/util/TechnicalErrorsTest.kt @@ -0,0 +1,191 @@ +package systems.lupine.sheaf.util + +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.ResponseBody.Companion.toResponseBody +import retrofit2.HttpException +import retrofit2.Response +import java.net.UnknownHostException +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The "Show technical error details" register. + * + * Off is the default and is covered by [ErrorMessagesTest]; this is what + * changes when somebody turns it on, plus the two things that make the switch + * possible at all: reading the server's `detail` without consuming the body, + * and carrying the preference in and out of the account's client settings. + */ +class TechnicalErrorsTest { + + private fun httpError(code: Int, body: String = ""): HttpException = + HttpException( + Response.error(code, body.toResponseBody("application/json".toMediaType())), + ) + + private fun detailBody(detail: String) = """{"detail":"$detail"}""" + + // ── The technical register ─────────────────────────────────────────────── + + @Test fun `on, an http failure leads with its status and the server's words`() { + TechnicalErrors.withEnabled(true) { + assertEquals( + "[403] Publishing is turned off on this instance", + httpError(403, detailBody("Publishing is turned off on this instance")) + .toUserMessage(), + ) + } + } + + @Test fun `on, a failure with nothing to say still shows its status`() { + // The status is the point: "[500]" tells a reporter which layer + // answered, where the summary alone does not. Asserted as a prefix + // because the summary itself is untouched by this change. + TechnicalErrors.withEnabled(true) { + val message = httpError(500).toUserMessage() + assertTrue(message.startsWith("[500] Server error"), message) + } + } + + @Test fun `on, a network failure names the exception behind it`() { + // Four different causes collapse into one sentence in the friendly + // register, and which one it was is the thing a bug report is missing. + TechnicalErrors.withEnabled(true) { + assertEquals( + "Can't reach the server - check your internet connection " + + "(UnknownHostException: sheaf.example.com)", + UnknownHostException("sheaf.example.com").toUserMessage(), + ) + } + } + + @Test fun `on, an exception with no message still names its type`() { + TechnicalErrors.withEnabled(true) { + assertTrue( + UnknownHostException().toUserMessage().endsWith("(UnknownHostException)"), + UnknownHostException().toUserMessage(), + ) + } + } + + @Test fun `off, nothing technical leaks out`() { + TechnicalErrors.withEnabled(false) { + val message = httpError(403, detailBody("Publishing is turned off")).toUserMessage() + assertEquals("Access denied", message) + assertTrue("403" !in message) + } + } + + @Test fun `the edge answering for the server is still said so in both registers`() { + // A 403 from Cloudflare is not Sheaf denying access, and that stays + // true when the status is on show. + val cloudflare = "cloudflare cf-ray" + TechnicalErrors.withEnabled(false) { + val message = httpError(403, cloudflare).toUserMessage() + assertTrue(message.startsWith("Access blocked by Cloudflare"), message) + assertTrue("Access denied" !in message, message) + } + TechnicalErrors.withEnabled(true) { + assertTrue( + "Cloudflare" in httpError(403, cloudflare).toUserMessage(), + httpError(403, cloudflare).toUserMessage(), + ) + } + } + + // ── preferDetail ───────────────────────────────────────────────────────── + + @Test fun `preferDetail shows the server's instruction without the status`() { + // For the endpoints whose 4xx detail IS what to do next. Replacing one + // of these with "Invalid request" throws away the only actionable part. + TechnicalErrors.withEnabled(false) { + assertEquals( + "Set your system to public first", + httpError(400, detailBody("Set your system to public first")) + .toUserMessage(preferDetail = true), + ) + } + } + + @Test fun `preferDetail falls back to the summary when there is no detail`() { + TechnicalErrors.withEnabled(false) { + assertEquals("Invalid request", httpError(400).toUserMessage(preferDetail = true)) + } + } + + @Test fun `a validation list is not prose, so it is not shown as the message`() { + // 422 answers with a list of field errors rather than a string. Putting + // that in front of somebody as a sentence would be worse than the + // summary. + TechnicalErrors.withEnabled(false) { + assertEquals( + "Invalid data provided", + httpError(422, """{"detail":[{"loc":["body","name"],"msg":"required"}]}""") + .toUserMessage(preferDetail = true), + ) + } + } + + // ── Reading the body more than once ────────────────────────────────────── + + @Test fun `the detail can be read repeatedly`() { + // An error body is a one-shot stream and `string()` closes it, which is + // why the sharing flows used to read it defensively and warn about + // `toUserMessage` racing them. Both now read it on the same exception, + // in whatever order, so peeking rather than consuming is load-bearing. + val error = httpError(403, detailBody("Incorrect password")) + assertEquals("Incorrect password", error.errorDetail()) + assertEquals("Incorrect password", error.errorDetail()) + assertEquals("Incorrect password", error.errorDetail()) + } + + @Test fun `formatting a message does not consume the detail`() { + val error = httpError(403, detailBody("Incorrect password")) + TechnicalErrors.withEnabled(true) { + assertEquals("[403] Incorrect password", error.toUserMessage()) + } + // The sharing classifier reads the same body afterwards to tell + // "credentials rejected" from "publishing is off". + assertEquals("Incorrect password", error.errorDetail()) + } + + @Test fun `an empty or unparseable body is simply no detail`() { + assertNull(httpError(500).errorDetail()) + assertNull(httpError(500, "nginx").errorDetail()) + assertNull(httpError(500, """{"something_else":"x"}""").errorDetail()) + assertNull(httpError(500, """{"detail":""}""").errorDetail()) + } + + // ── Carrying the preference on the account ─────────────────────────────── + + @Test fun `the preference round-trips through the client settings blob`() { + assertEquals(true, TechnicalErrors.fromClientSettings(TechnicalErrors.toClientSettings(true))) + assertEquals(false, TechnicalErrors.fromClientSettings(TechnicalErrors.toClientSettings(false))) + } + + @Test fun `an account that never set it reads as null, not false`() { + // Absent means "this device decides". Reading it as false would reset + // a device's setting to off on every load against such an account. + assertNull(TechnicalErrors.fromClientSettings(null)) + assertNull(TechnicalErrors.fromClientSettings(emptyMap())) + assertNull(TechnicalErrors.fromClientSettings(mapOf("theme" to "dark"))) + assertNull(TechnicalErrors.fromClientSettings(mapOf("developer" to emptyMap()))) + } + + @Test fun `a wrongly typed value is ignored rather than guessed at`() { + assertNull( + TechnicalErrors.fromClientSettings( + mapOf("developer" to mapOf("show_technical_errors" to "true")), + ), + ) + } + + @Test fun `the patch body carries only this setting's own group`() { + // PATCH merges top-level keys, so sending anything wider would clobber + // a sibling key written by another feature. + val body = TechnicalErrors.toClientSettings(true) + assertEquals(setOf("developer"), body.keys) + } +}