merge: B-M4e Android usage/storage dashboards + settings

# Conflicts:
#	android/app/src/main/kotlin/app/hapi/companion/Navigation.kt
This commit is contained in:
weishu
2026-08-18 10:45:42 +08:00
27 changed files with 3033 additions and 2 deletions
+2
View File
@@ -41,6 +41,8 @@ android {
buildFeatures {
compose = true
// About screen surfaces BuildConfig.VERSION_NAME (B-M4e).
buildConfig = true
}
testOptions {
@@ -5,15 +5,21 @@ import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import app.hapi.companion.di.AppGraph
import app.hapi.companion.di.LocalAppGraph
import app.hapi.companion.feature.settings.ThemeMode
import app.hapi.companion.feature.settings.ThemeSettings
import app.hapi.companion.ui.theme.HapiTheme
import app.hapi.protocol.pairing.BindLink
/**
* Single-activity entry point (`launchMode="singleTask"`). Hosts the
* Navigation Compose graph and feeds `hapicompanion://bind?hub=…&code=…`
* Navigation Compose graph under the persisted theme choice
* ([AppGraph.themePrefs], B-M4e) and feeds `hapicompanion://bind?hub=…&code=…`
* deep links — cold start and [onNewIntent] — into
* [AppGraph.pendingBindLink]; all parsing stays in [BindLink].
*/
@@ -31,7 +37,18 @@ class MainActivity : ComponentActivity() {
handleBindIntent(intent)
}
setContent {
HapiTheme {
// Follow-system default renders for the first frames while the
// DataStore read completes; the persisted choice then applies.
val theme by appGraph.themePrefs.settings.collectAsState(initial = ThemeSettings())
HapiTheme(
darkTheme = when (theme.mode) {
ThemeMode.SYSTEM -> isSystemInDarkTheme()
ThemeMode.LIGHT -> false
ThemeMode.DARK, ThemeMode.OLED -> true
},
dynamicColor = theme.dynamicColor,
oled = theme.mode == ThemeMode.OLED,
) {
CompositionLocalProvider(LocalAppGraph provides appGraph) {
HapiNavigation()
}
@@ -22,6 +22,7 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.navigation
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import app.hapi.companion.di.AppGraph
import app.hapi.companion.di.HubGraph
import app.hapi.companion.di.LocalAppGraph
import app.hapi.companion.di.viewModelFactory
@@ -48,6 +49,12 @@ import app.hapi.companion.feature.pairing.PairingUiState
import app.hapi.companion.feature.pairing.PairingViewModel
import app.hapi.companion.feature.pairing.QrScanScreen
import app.hapi.companion.feature.sessions.SessionListViewModel
import app.hapi.companion.feature.settings.SettingsScreen
import app.hapi.companion.feature.settings.SettingsViewModel
import app.hapi.companion.feature.settings.StorageScreen
import app.hapi.companion.feature.settings.StorageViewModel
import app.hapi.companion.feature.settings.UsageScreen
import app.hapi.companion.feature.settings.UsageViewModel
import app.hapi.data.auth.AuthTerminalReason
import java.util.Base64
import kotlinx.coroutines.CoroutineScope
@@ -110,6 +117,11 @@ object Routes {
const val PAIRING_LANDING = "pairing/landing"
const val PAIRING_SCAN = "pairing/scan"
const val PAIRING_MANUAL = "pairing/manual"
/** Settings scaffold + owner-only dashboards (B-M4e). */
const val SETTINGS = "settings"
const val SETTINGS_USAGE = "settings/usage"
const val SETTINGS_STORAGE = "settings/storage"
}
/**
@@ -191,6 +203,45 @@ fun HapiNavigation() {
onSignOut = { scope.launch { graph.signOut(activeHubUrl) } },
onOpenSession = { sessionId -> navController.navigate(Routes.chat(sessionId)) },
onNewSession = { navController.navigate(Routes.newSession()) },
onOpenSettings = { navController.navigate(Routes.SETTINGS) },
)
}
composable(Routes.SETTINGS) {
val hubGraph = activeHubGraph ?: return@composable
val holder = viewModel<SettingsViewModelHolder>(
key = "settings:${hubGraph.hubUrl}",
factory = viewModelFactory { SettingsViewModelHolder(graph, hubGraph) },
)
SettingsScreen(
viewModel = holder.viewModel,
onOpenUsage = { navController.navigate(Routes.SETTINGS_USAGE) },
onOpenStorage = { navController.navigate(Routes.SETTINGS_STORAGE) },
onBack = { navController.popBackStack() },
)
}
composable(Routes.SETTINGS_USAGE) {
val hubGraph = activeHubGraph ?: return@composable
val holder = viewModel<UsageViewModelHolder>(
key = "settingsUsage:${hubGraph.hubUrl}",
factory = viewModelFactory { UsageViewModelHolder(hubGraph) },
)
UsageScreen(
viewModel = holder.viewModel,
onBack = { navController.popBackStack() },
)
}
composable(Routes.SETTINGS_STORAGE) {
val hubGraph = activeHubGraph ?: return@composable
val holder = viewModel<StorageViewModelHolder>(
key = "settingsStorage:${hubGraph.hubUrl}",
factory = viewModelFactory { StorageViewModelHolder(hubGraph) },
)
StorageScreen(
viewModel = holder.viewModel,
onBack = { navController.popBackStack() },
)
}
@@ -494,6 +545,59 @@ private class FileViewerViewModelHolder(
}
}
/**
* Shells for the settings graph (B-M4e). Settings/usage/storage are hub-scoped
* (keys include the hub origin): a hub switch swaps in fresh state.
*/
private class SettingsViewModelHolder(graph: AppGraph, hubGraph: HubGraph) : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val viewModel = SettingsViewModel(
themePrefs = graph.themePrefs,
languagePrefs = graph.languagePrefs,
hubUrl = hubGraph.hubUrl,
currentJwt = {
// Store reads may block (EncryptedSharedPreferences) and the
// fallback exchange is network I/O.
withContext(Dispatchers.IO) {
hubGraph.session.authenticator.currentJwt() ?: hubGraph.session.ensureFreshToken()
}
},
fetchHealth = { hubGraph.session.api.health() },
scope = scope,
)
override fun onCleared() {
scope.cancel()
}
}
private class UsageViewModelHolder(hubGraph: HubGraph) : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val viewModel = UsageViewModel(
gateway = hubGraph.session.api::getUsageSummary,
scope = scope,
)
override fun onCleared() {
scope.cancel()
}
}
private class StorageViewModelHolder(hubGraph: HubGraph) : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val viewModel = StorageViewModel(
gateway = hubGraph.session.api::getSqliteStorageUsage,
scope = scope,
)
override fun onCleared() {
scope.cancel()
}
}
/** Shell for the create form (B-M3d); draft persistence survives via prefs. */
private class NewSessionViewModelHolder(
hubGraph: HubGraph,
@@ -6,6 +6,8 @@ import app.hapi.companion.feature.newsession.DataStoreNewSessionPrefs
import app.hapi.companion.feature.newsession.NewSessionPrefs
import app.hapi.companion.feature.pairing.PairingClient
import app.hapi.companion.feature.pairing.PairingClientFactory
import app.hapi.companion.feature.settings.LanguagePrefs
import app.hapi.companion.feature.settings.ThemePrefs
import app.hapi.data.api.HapiApi
import app.hapi.data.auth.AuthEvents
import app.hapi.data.auth.AuthTerminalReason
@@ -77,6 +79,12 @@ class AppGraph(context: Context) {
*/
val newSessionPrefs: NewSessionPrefs = DataStoreNewSessionPrefs(appContext.hapiDataStore)
/** Appearance choice (B-M4e); MainActivity reads it at setContent. */
val themePrefs: ThemePrefs = ThemePrefs(appContext.hapiDataStore)
/** Language choice (persist-only until the M5 i18n pass). */
val languagePrefs: LanguagePrefs = LanguagePrefs(appContext.hapiDataStore)
private val mutableAuthTerminals = MutableSharedFlow<AuthTerminal>(extraBufferCapacity = 16)
/**
@@ -51,6 +51,8 @@ fun HomeScreen(
onOpenSession: (sessionId: String) -> Unit,
/** "+" FAB on the session list → new-session form (B-M3d). */
onNewSession: (() -> Unit)? = null,
/** Overflow menu → settings scaffold (B-M4e). */
onOpenSettings: (() -> Unit)? = null,
) {
var menuOpen by rememberSaveable { mutableStateOf(false) }
var showSwitcher by rememberSaveable { mutableStateOf(false) }
@@ -79,6 +81,15 @@ fun HomeScreen(
Icon(Icons.Default.MoreVert, contentDescription = stringResource(R.string.home_menu))
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
if (onOpenSettings != null) {
DropdownMenuItem(
text = { Text(stringResource(R.string.home_settings)) },
onClick = {
menuOpen = false
onOpenSettings()
},
)
}
DropdownMenuItem(
text = { Text(stringResource(R.string.home_switch_hub)) },
onClick = {
@@ -0,0 +1,46 @@
package app.hapi.companion.feature.settings
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
/**
* App language choice (web `Locale` twin: `'en' | 'zh-Hans'`).
*
* B-M4e persists the selection only — the zh-CN string resources and the
* per-app locale application (`LocaleManager` / `AppCompatDelegate`) land with
* the M5 i18n pass, so changing this has no visible effect yet.
*/
enum class AppLanguage(val storageKey: String) {
ENGLISH("en"),
SIMPLIFIED_CHINESE("zh-Hans");
companion object {
fun fromStorageKey(raw: String?): AppLanguage =
entries.firstOrNull { it.storageKey == raw } ?: ENGLISH
}
}
/** Language persistence over the app-wide `hapi_prefs` DataStore. */
class LanguagePrefs(private val dataStore: DataStore<Preferences>) {
val language: Flow<AppLanguage> = dataStore.data
.catch { error -> if (error is IOException) emit(emptyPreferences()) else throw error }
.map { prefs -> AppLanguage.fromStorageKey(prefs[LANGUAGE_KEY]) }
.distinctUntilChanged()
suspend fun setLanguage(language: AppLanguage) {
dataStore.edit { it[LANGUAGE_KEY] = language.storageKey }
}
companion object {
val LANGUAGE_KEY: Preferences.Key<String> = stringPreferencesKey("app_language")
}
}
@@ -0,0 +1,143 @@
package app.hapi.companion.feature.settings
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import app.hapi.companion.ui.theme.HapiTheme
import app.hapi.protocol.wire.SqliteStorageUsageResponse
import app.hapi.protocol.wire.UsageSummaryBucket
import app.hapi.protocol.wire.UsageSummaryRange
import app.hapi.protocol.wire.UsageSummaryResponse
import app.hapi.protocol.wire.UsageSummaryTotals
import java.time.LocalDate
/**
* Compile-checked previews doubling as visual regressions for the B-M4e
* dashboards: stat tiles, the daily bar chart, the ranked bar list, and the
* storage donut — light, dark, and OLED.
*/
private fun bucket(
key: String,
input: Long,
output: Long,
cacheRead: Long = 0,
cacheCreation: Long = 0,
requests: Long = 10,
): UsageSummaryBucket = UsageSummaryBucket(
key = key,
inputTokens = input,
outputTokens = output,
cacheReadTokens = cacheRead,
cacheCreationTokens = cacheCreation,
totalTokens = input + output,
uncachedTokens = input - cacheRead,
requests = requests,
)
internal val SAMPLE_USAGE_SUMMARY: UsageSummaryResponse = UsageSummaryResponse(
range = UsageSummaryRange(from = 1755000000000, to = 1755600000000),
totals = UsageSummaryTotals(
inputTokens = 12_400_000,
outputTokens = 310_000,
cacheReadTokens = 9_800_000,
cacheCreationTokens = 1_100_000,
totalTokens = 12_710_000,
uncachedTokens = 2_600_000,
requests = 1_842,
sessions = 23,
),
daily = listOf(
bucket("2026-08-12", 1_200_000, 40_000, requests = 210),
bucket("2026-08-13", 3_400_000, 90_000, requests = 480),
bucket("2026-08-15", 900_000, 25_000, requests = 130),
bucket("2026-08-16", 5_100_000, 120_000, requests = 720),
bucket("2026-08-18", 1_800_000, 35_000, requests = 302),
),
byAgent = listOf(
bucket("claude", 8_600_000, 220_000, requests = 1_300),
bucket("codex", 3_100_000, 70_000, requests = 420),
bucket("gemini", 700_000, 20_000, requests = 122),
),
byModel = listOf(
bucket("claude-sonnet-4-5", 7_900_000, 190_000, requests = 1_150),
bucket("gpt-5.1-codex", 3_100_000, 70_000, requests = 420),
bucket("unknown", 1_400_000, 50_000, requests = 272),
),
updatedAt = 1755600000000,
)
internal val SAMPLE_STORAGE_USAGE: SqliteStorageUsageResponse = SqliteStorageUsageResponse(
path = "/home/hapi/.hapi/hapi.db",
databaseBytes = 84_930_560,
walBytes = 4_194_304,
shmBytes = 32_768,
totalBytes = 89_157_632,
)
private val SAMPLE_DAILY_BARS: List<UsageMath.DailyBar> =
UsageMath.dailyBars(SAMPLE_USAGE_SUMMARY.daily, days = 7, today = LocalDate.of(2026, 8, 18))
@Preview(name = "Usage tiles", showBackground = true)
@Composable
private fun UsageStatTilesPreview() {
HapiTheme(darkTheme = false, dynamicColor = false) {
Surface { UsageStatTiles(summary = SAMPLE_USAGE_SUMMARY) }
}
}
@Preview(name = "Daily bars", showBackground = true)
@Composable
private fun DailyBarChartPreview() {
HapiTheme(darkTheme = false, dynamicColor = false) {
Surface { DailyBarChart(bars = SAMPLE_DAILY_BARS, modifier = Modifier.padding(12.dp)) }
}
}
@Preview(name = "Daily bars · dark", showBackground = true, backgroundColor = 0xFF1B1B1F)
@Composable
private fun DailyBarChartDarkPreview() {
HapiTheme(darkTheme = true, dynamicColor = false) {
Surface { DailyBarChart(bars = SAMPLE_DAILY_BARS, modifier = Modifier.padding(12.dp)) }
}
}
@Preview(name = "Bar list", showBackground = true)
@Composable
private fun UsageBarListPreview() {
HapiTheme(darkTheme = false, dynamicColor = false) {
Surface { UsageBarList(rows = SAMPLE_USAGE_SUMMARY.byAgent) }
}
}
@Preview(name = "Usage · full body", showBackground = true, heightDp = 1400)
@Composable
private fun UsageSummaryContentPreview() {
HapiTheme(darkTheme = false, dynamicColor = false) {
Surface {
UsageSummaryContent(
summary = SAMPLE_USAGE_SUMMARY,
dailyBars = SAMPLE_DAILY_BARS,
)
}
}
}
@Preview(name = "Storage donut", showBackground = true)
@Composable
private fun StorageCardPreview() {
HapiTheme(darkTheme = false, dynamicColor = false) {
Surface { StorageUsageCard(usage = SAMPLE_STORAGE_USAGE) }
}
}
@Preview(name = "Storage donut · OLED", showBackground = true, backgroundColor = 0xFF000000)
@Composable
private fun StorageCardOledPreview() {
HapiTheme(oled = true) {
Surface { StorageUsageCard(usage = SAMPLE_STORAGE_USAGE) }
}
}
@@ -0,0 +1,374 @@
package app.hapi.companion.feature.settings
import android.os.Build
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.hapi.companion.BuildConfig
import app.hapi.companion.R
import app.hapi.protocol.wire.SUPPORTED_PROTOCOL_VERSION
/**
* Settings home (B-M4e scaffold): Appearance (theme mode + Material You),
* Language (persist-only until M5), the owner-only Usage/Storage entries, and
* About (app/protocol versions + hub health).
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
viewModel: SettingsViewModel,
onOpenUsage: () -> Unit,
onOpenStorage: () -> Unit,
onBack: () -> Unit,
) {
val theme by viewModel.themeSettings.collectAsState()
val language by viewModel.language.collectAsState()
val isOwner by viewModel.isOwner.collectAsState()
val hubInfo by viewModel.hubInfo.collectAsState()
var showThemeDialog by rememberSaveable { mutableStateOf(false) }
var showLanguageDialog by rememberSaveable { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.settings_title)) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.settings_back),
)
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
SettingsSection(title = stringResource(R.string.settings_section_appearance)) {
SettingsRow(
label = stringResource(R.string.settings_theme),
value = stringResource(themeModeLabelRes(theme.mode)),
onClick = { showThemeDialog = true },
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
SettingsDivider()
SwitchRow(
label = stringResource(R.string.settings_dynamic_color),
description = stringResource(
if (theme.mode == ThemeMode.OLED) R.string.settings_dynamic_color_oled_note
else R.string.settings_dynamic_color_description
),
checked = theme.dynamicColor && theme.mode != ThemeMode.OLED,
enabled = theme.mode != ThemeMode.OLED,
onCheckedChange = viewModel::setDynamicColor,
)
}
}
SettingsSection(title = stringResource(R.string.settings_section_language)) {
SettingsRow(
label = stringResource(R.string.settings_language),
value = languageLabel(language),
description = stringResource(R.string.settings_language_pending_note),
onClick = { showLanguageDialog = true },
)
}
if (isOwner) {
SettingsSection(title = stringResource(R.string.settings_section_insights)) {
SettingsRow(
label = stringResource(R.string.settings_usage),
description = stringResource(R.string.settings_usage_summary),
onClick = onOpenUsage,
)
SettingsDivider()
SettingsRow(
label = stringResource(R.string.settings_storage),
description = stringResource(R.string.settings_storage_summary),
onClick = onOpenStorage,
)
}
}
SettingsSection(title = stringResource(R.string.settings_section_about)) {
SettingsRow(
label = stringResource(R.string.settings_app_version),
value = BuildConfig.VERSION_NAME,
)
SettingsDivider()
SettingsRow(
label = stringResource(R.string.settings_protocol_version),
value = SUPPORTED_PROTOCOL_VERSION.toString(),
)
SettingsDivider()
SettingsRow(
label = stringResource(R.string.settings_hub),
value = viewModel.hubUrl,
description = when (val info = hubInfo) {
is HubInfoState.Loading -> stringResource(R.string.settings_hub_checking)
is HubInfoState.Loaded -> stringResource(
R.string.settings_hub_health,
info.health.status,
info.health.protocolVersion,
)
is HubInfoState.Failed -> stringResource(R.string.settings_hub_unreachable)
},
onClick = if (hubInfo is HubInfoState.Failed) viewModel::retryHubInfo else null,
)
}
}
}
if (showThemeDialog) {
ThemeModeDialog(
selected = theme.mode,
onSelect = { mode ->
showThemeDialog = false
viewModel.setThemeMode(mode)
},
onDismiss = { showThemeDialog = false },
)
}
if (showLanguageDialog) {
LanguageDialog(
selected = language,
onSelect = { choice ->
showLanguageDialog = false
viewModel.setLanguage(choice)
},
onDismiss = { showLanguageDialog = false },
)
}
}
// ------------------------------------------------------------- primitives --
@Composable
private fun SettingsSection(title: String, content: @Composable () -> Unit) {
Column {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(start = 4.dp, bottom = 6.dp),
)
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceContainerLow,
modifier = Modifier.fillMaxWidth(),
) {
Column { content() }
}
}
}
@Composable
private fun SettingsDivider() {
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant,
modifier = Modifier.padding(horizontal = 16.dp),
)
}
@Composable
private fun SettingsRow(
label: String,
value: String? = null,
description: String? = null,
onClick: (() -> Unit)? = null,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.let { if (onClick != null) it.clickable(onClick = onClick) else it }
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(text = label, style = MaterialTheme.typography.bodyLarge)
if (description != null) {
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
}
if (value != null) {
Text(
text = value,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(start = 12.dp),
)
}
}
}
@Composable
private fun SwitchRow(
label: String,
description: String,
checked: Boolean,
enabled: Boolean,
onCheckedChange: (Boolean) -> Unit,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(modifier = Modifier.weight(1f)) {
Text(text = label, style = MaterialTheme.typography.bodyLarge)
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 2.dp),
)
}
Spacer(modifier = Modifier.padding(start = 12.dp))
Switch(checked = checked, onCheckedChange = onCheckedChange, enabled = enabled)
}
}
// ---------------------------------------------------------------- dialogs --
@Composable
private fun ThemeModeDialog(
selected: ThemeMode,
onSelect: (ThemeMode) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.settings_theme)) },
text = {
Column {
ThemeMode.entries.forEach { mode ->
RadioRow(
label = stringResource(themeModeLabelRes(mode)),
selected = mode == selected,
onClick = { onSelect(mode) },
)
}
}
},
confirmButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.settings_cancel)) }
},
)
}
@Composable
private fun LanguageDialog(
selected: AppLanguage,
onSelect: (AppLanguage) -> Unit,
onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.settings_language)) },
text = {
Column {
AppLanguage.entries.forEach { language ->
RadioRow(
label = languageLabel(language),
selected = language == selected,
onClick = { onSelect(language) },
)
}
Text(
text = stringResource(R.string.settings_language_pending_note),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 8.dp),
)
}
},
confirmButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.settings_cancel)) }
},
)
}
@Composable
private fun RadioRow(label: String, selected: Boolean, onClick: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected = selected, onClick = onClick)
Text(
text = label,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(start = 4.dp),
)
}
}
private fun themeModeLabelRes(mode: ThemeMode): Int = when (mode) {
ThemeMode.SYSTEM -> R.string.settings_theme_system
ThemeMode.LIGHT -> R.string.settings_theme_light
ThemeMode.DARK -> R.string.settings_theme_dark
ThemeMode.OLED -> R.string.settings_theme_oled
}
/**
* Language names are shown in their own language (standard picker
* convention), so they are string literals, not resources — nothing to
* translate in M5 either.
*/
private fun languageLabel(language: AppLanguage): String = when (language) {
AppLanguage.ENGLISH -> "English"
AppLanguage.SIMPLIFIED_CHINESE -> "简体中文"
}
@@ -0,0 +1,95 @@
package app.hapi.companion.feature.settings
import app.hapi.data.auth.JwtPeek
import app.hapi.protocol.wire.HubHealthResponse
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/** Namespace whose JWT belongs to the hub owner (usage/storage visible). */
const val OWNER_NAMESPACE: String = "default"
/**
* Owner gate for the usage/storage entries: peeks the (unverified) `ns` claim
* — the web twin is `getNamespaceFromToken(token) === 'default'`
* (`SettingsNav.tsx`). Fails closed: no JWT / undecodable / missing claim all
* hide the owner-only rows; the endpoints' own 403 stays the real enforcement.
*/
fun isOwnerNamespace(jwt: String?): Boolean =
jwt != null && JwtPeek.peek(jwt)?.ns == OWNER_NAMESPACE
/** About-section hub probe (`GET /health`). */
sealed interface HubInfoState {
data object Loading : HubInfoState
data class Loaded(val health: HubHealthResponse) : HubInfoState
data class Failed(val message: String?) : HubInfoState
}
/**
* Settings-home state: appearance + language prefs (DataStore-backed), the
* owner gate, and the About hub probe. Plain constructor for JVM tests;
* Navigation hosts it behind a per-hub lifecycle holder.
*/
class SettingsViewModel(
private val themePrefs: ThemePrefs,
private val languagePrefs: LanguagePrefs,
/** Active hub origin, shown in About. */
val hubUrl: String,
/** Current JWT for the active hub (blocking-safe: called on a worker). */
private val currentJwt: suspend () -> String?,
private val fetchHealth: suspend () -> HubHealthResponse,
private val scope: CoroutineScope,
) {
val themeSettings: StateFlow<ThemeSettings> = themePrefs.settings
.stateIn(scope, SharingStarted.Eagerly, ThemeSettings())
val language: StateFlow<AppLanguage> = languagePrefs.language
.stateIn(scope, SharingStarted.Eagerly, AppLanguage.ENGLISH)
private val mutableIsOwner = MutableStateFlow(false)
/** True when the active hub's JWT namespace is [OWNER_NAMESPACE]. */
val isOwner: StateFlow<Boolean> = mutableIsOwner.asStateFlow()
private val mutableHubInfo = MutableStateFlow<HubInfoState>(HubInfoState.Loading)
val hubInfo: StateFlow<HubInfoState> = mutableHubInfo.asStateFlow()
init {
scope.launch { mutableIsOwner.value = isOwnerNamespace(runCatching { currentJwt() }.getOrNull()) }
scope.launch { loadHubInfo() }
}
fun setThemeMode(mode: ThemeMode) {
scope.launch { themePrefs.setMode(mode) }
}
fun setDynamicColor(enabled: Boolean) {
scope.launch { themePrefs.setDynamicColor(enabled) }
}
fun setLanguage(language: AppLanguage) {
scope.launch { languagePrefs.setLanguage(language) }
}
fun retryHubInfo() {
mutableHubInfo.value = HubInfoState.Loading
scope.launch { loadHubInfo() }
}
private suspend fun loadHubInfo() {
mutableHubInfo.value = try {
HubInfoState.Loaded(fetchHealth())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
HubInfoState.Failed(e.message)
}
}
}
@@ -0,0 +1,75 @@
package app.hapi.companion.feature.settings
import app.hapi.protocol.wire.SqliteStorageUsageResponse
/**
* Donut geometry for the sqlite storage chart — the Kotlin twin of
* `web/src/components/settings/storageUsageSlices.ts` (same fixed slice
* order, zero-byte filtering, 12-o'clock start, one-decimal percents).
*/
object StorageMath {
enum class SliceKey { DATABASE, WAL, SHM }
data class Slice(
val key: SliceKey,
val bytes: Long,
/** Share of the drawn total, one decimal (e.g. `97.3`). */
val percent: Double,
/** Degrees, `-90` = 12 o'clock, clockwise (Android sweep convention). */
val startAngle: Float,
val endAngle: Float,
)
/** Fixed entity order — colors follow the entity, never its rank. */
private val SLICE_ORDER = listOf(SliceKey.DATABASE, SliceKey.WAL, SliceKey.SHM)
private const val FULL_CIRCLE = 360f
/** Start at 12 o'clock so the first slice reads top-heavy on mobile. */
const val START_ANGLE = -90f
/**
* Slices for the donut: zero-byte files are dropped, angles partition the
* full circle exactly (the last slice absorbs rounding), empty when
* nothing is drawn.
*/
fun slices(usage: SqliteStorageUsageResponse): List<Slice> {
val entries = SLICE_ORDER
.map { key -> key to bytesFor(usage, key).coerceAtLeast(0) }
.filter { (_, bytes) -> bytes > 0 }
val total = entries.sumOf { (_, bytes) -> bytes }
if (total <= 0) return emptyList()
var cursor = START_ANGLE
return entries.mapIndexed { index, (key, bytes) ->
val isLast = index == entries.lastIndex
val endAngle = if (isLast) {
START_ANGLE + FULL_CIRCLE
} else {
cursor + (bytes.toFloat() / total) * FULL_CIRCLE
}
Slice(
key = key,
bytes = bytes,
// Math.round: half-up like JS (kotlin.math.round is half-even).
percent = Math.round(bytes * 1000.0 / total) / 10.0,
startAngle = cursor,
endAngle = endAngle,
).also { cursor = endAngle }
}
}
/** `97.25` → `"97.3%"` (web `formatStoragePercent`, half-up). */
fun formatPercent(percent: Double): String {
val rounded = Math.round(percent * 10) / 10.0
val text = if (rounded == Math.floor(rounded)) rounded.toInt().toString() else rounded.toString()
return "$text%"
}
private fun bytesFor(usage: SqliteStorageUsageResponse, key: SliceKey): Long = when (key) {
SliceKey.DATABASE -> usage.databaseBytes
SliceKey.WAL -> usage.walBytes
SliceKey.SHM -> usage.shmBytes
}
}
@@ -0,0 +1,316 @@
package app.hapi.companion.feature.settings
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import app.hapi.companion.R
import app.hapi.protocol.wire.SqliteStorageUsageResponse
/**
* Owner-only sqlite storage dashboard (web
* `web/src/routes/settings/storage.tsx` + `StorageUsagePie` twin): a Canvas
* donut of db/wal/shm plus legend rows with byte formatting, total and path,
* and an explicit refresh.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StorageScreen(
viewModel: StorageViewModel,
onBack: () -> Unit,
) {
LaunchedEffect(viewModel) { viewModel.start() }
val state by viewModel.state.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.settings_storage)) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.settings_back),
)
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
Text(
text = stringResource(R.string.settings_storage_description),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
when (val current = state) {
is StorageUiState.Loading -> Box(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 48.dp),
contentAlignment = Alignment.Center,
) { CircularProgressIndicator() }
is StorageUiState.Error -> DashboardError(
isForbidden = current.isForbidden,
message = current.message,
onRetry = viewModel::refresh,
)
is StorageUiState.Data -> {
StorageUsageCard(usage = current.usage)
Button(
onClick = viewModel::refresh,
enabled = !current.isRefreshing,
modifier = Modifier.align(Alignment.End),
) {
Text(
stringResource(
if (current.isRefreshing) R.string.settings_storage_refreshing
else R.string.settings_storage_refresh
),
)
}
}
}
}
}
}
/** Shared owner-gate/error body for both dashboards (usage + storage). */
@Composable
internal fun DashboardError(
isForbidden: Boolean,
message: String?,
onRetry: () -> Unit,
) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceContainerLow,
modifier = Modifier.fillMaxWidth(),
) {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
Text(
text = stringResource(
if (isForbidden) R.string.settings_owner_only else R.string.settings_load_error
),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface,
)
if (!isForbidden && !message.isNullOrBlank()) {
Text(
text = message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (!isForbidden) {
Button(onClick = onRetry) { Text(stringResource(R.string.settings_retry)) }
}
}
}
}
/** Donut + legend + total/path rows for one sqlite usage snapshot. */
@Composable
internal fun StorageUsageCard(usage: SqliteStorageUsageResponse, modifier: Modifier = Modifier) {
val slices = StorageMath.slices(usage)
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceContainerLow,
modifier = modifier.fillMaxWidth(),
) {
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(
text = stringResource(R.string.settings_storage_chart_title),
style = MaterialTheme.typography.titleSmall,
)
if (slices.isEmpty()) {
Text(
text = stringResource(R.string.settings_storage_chart_empty),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
StorageDonut(slices = slices, modifier = Modifier.size(180.dp))
Column(horizontalAlignment = Alignment.CenterHorizontally) {
// Hero number: the one figure the chart exists for.
Text(
text = UsageMath.formatBytes(usage.totalBytes),
style = MaterialTheme.typography.titleLarge,
)
Text(
text = stringResource(R.string.settings_storage_total),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
Column {
slices.forEach { slice -> StorageLegendRow(slice) }
}
}
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
LabeledValueRow(
label = stringResource(R.string.settings_storage_total),
value = UsageMath.formatBytes(usage.totalBytes),
)
Column {
Text(
text = stringResource(R.string.settings_storage_path),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
text = usage.path,
style = MaterialTheme.typography.bodySmall,
fontFamily = FontFamily.Monospace,
)
}
}
}
}
@Composable
private fun StorageLegendRow(slice: StorageMath.Slice) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Box(
modifier = Modifier
.size(10.dp)
.background(sliceColor(slice.key), RoundedCornerShape(3.dp)),
)
Text(
text = stringResource(sliceLabelRes(slice.key)),
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(start = 10.dp),
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = "${UsageMath.formatBytes(slice.bytes)} · ${StorageMath.formatPercent(slice.percent)}",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun LabeledValueRow(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(modifier = Modifier.weight(1f))
Text(text = value, style = MaterialTheme.typography.bodyMedium)
}
}
/**
* Slice colors mirror the web formula (link / 55% link–hint mix / hint) in
* Material tokens, so they track dynamic color and every theme mode. Fixed
* per entity — a missing wal/shm file never repaints its neighbors — and the
* legend rows carry identity, so color is never the only channel.
*/
@Composable
private fun sliceColor(key: StorageMath.SliceKey): Color = when (key) {
StorageMath.SliceKey.DATABASE -> MaterialTheme.colorScheme.primary
StorageMath.SliceKey.WAL -> lerp(
MaterialTheme.colorScheme.primary,
MaterialTheme.colorScheme.onSurfaceVariant,
0.45f,
)
StorageMath.SliceKey.SHM -> MaterialTheme.colorScheme.onSurfaceVariant
}
private fun sliceLabelRes(key: StorageMath.SliceKey): Int = when (key) {
StorageMath.SliceKey.DATABASE -> R.string.settings_storage_database
StorageMath.SliceKey.WAL -> R.string.settings_storage_wal
StorageMath.SliceKey.SHM -> R.string.settings_storage_shm
}
/**
* The donut ring on a plain [Canvas]: stroke arcs per slice with a small
* angular gap standing in for the 2px surface spacer whenever more than one
* slice is drawn. Angles come precomputed from [StorageMath.slices].
*/
@Composable
internal fun StorageDonut(slices: List<StorageMath.Slice>, modifier: Modifier = Modifier) {
val colors = slices.map { sliceColor(it.key) }
Canvas(modifier = modifier) {
val thickness = 26.dp.toPx()
val inset = thickness / 2
val arcSize = Size(size.width - thickness, size.height - thickness)
val gapDegrees = if (slices.size > 1) 2f else 0f
slices.forEachIndexed { index, slice ->
val rawSweep = slice.endAngle - slice.startAngle
// Keep hairline slices visible: drop the gap before dropping the arc.
val gapped = rawSweep - gapDegrees > MIN_SWEEP_DEGREES
val sweep = if (gapped) rawSweep - gapDegrees else rawSweep.coerceAtLeast(MIN_SWEEP_DEGREES)
drawArc(
color = colors[index],
startAngle = if (gapped) slice.startAngle + gapDegrees / 2 else slice.startAngle,
sweepAngle = sweep,
useCenter = false,
topLeft = Offset(inset, inset),
size = arcSize,
style = Stroke(width = thickness),
)
}
}
}
private const val MIN_SWEEP_DEGREES = 0.5f
@@ -0,0 +1,69 @@
package app.hapi.companion.feature.settings
import app.hapi.data.api.ApiError
import app.hapi.protocol.wire.SqliteStorageUsageResponse
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
/** Transport seam (`HapiApi.getSqliteStorageUsage`) for JVM tests. */
fun interface StorageGateway {
suspend fun sqliteUsage(): SqliteStorageUsageResponse
}
sealed interface StorageUiState {
data object Loading : StorageUiState
data class Error(
val message: String?,
/** 403: non-owner namespace (mirror of the usage screen). */
val isForbidden: Boolean,
) : StorageUiState
data class Data(
val usage: SqliteStorageUsageResponse,
val isRefreshing: Boolean = false,
) : StorageUiState
}
/** Storage-dashboard state: initial load + explicit refresh (web parity). */
class StorageViewModel(
private val gateway: StorageGateway,
private val scope: CoroutineScope,
) {
private val mutableState = MutableStateFlow<StorageUiState>(StorageUiState.Loading)
val state: StateFlow<StorageUiState> = mutableState.asStateFlow()
private var loadJob: Job? = null
fun start() {
if (loadJob == null) refresh()
}
fun refresh() {
if ((mutableState.value as? StorageUiState.Data)?.isRefreshing == true) return
loadJob?.cancel()
mutableState.value = when (val current = mutableState.value) {
is StorageUiState.Data -> current.copy(isRefreshing = true)
else -> StorageUiState.Loading
}
loadJob = scope.launch {
mutableState.value = try {
StorageUiState.Data(gateway.sqliteUsage())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
StorageUiState.Error(
message = e.message,
isForbidden = (e as? ApiError)?.status == 403,
)
}
}
}
}
@@ -0,0 +1,70 @@
package app.hapi.companion.feature.settings
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
/**
* Theme choice (web `ThemeMode` twin plus the Android-only Material You
* switch). [OLED] is the pure-black variant — it implies dark and disables
* dynamic color at the [app.hapi.companion.ui.theme.HapiTheme] call site.
*/
enum class ThemeMode(val storageKey: String) {
SYSTEM("system"),
LIGHT("light"),
DARK("dark"),
OLED("oled");
companion object {
/** Unknown/corrupt stored values degrade to [SYSTEM]. */
fun fromStorageKey(raw: String?): ThemeMode =
entries.firstOrNull { it.storageKey == raw } ?: SYSTEM
}
}
/** The persisted appearance choice, defaults = follow system + Material You. */
data class ThemeSettings(
val mode: ThemeMode = ThemeMode.SYSTEM,
/** Material You wallpaper color (effective only on API 31+, non-OLED). */
val dynamicColor: Boolean = true,
)
/**
* Appearance persistence over the app-wide `hapi_prefs` DataStore. Read at
* `MainActivity.setContent` to drive `HapiTheme`, written by the settings
* screen; unreadable prefs degrade to defaults (roster storage precedent).
*/
class ThemePrefs(private val dataStore: DataStore<Preferences>) {
/** Current settings; emits again on every change. */
val settings: Flow<ThemeSettings> = dataStore.data
.catch { error -> if (error is IOException) emit(emptyPreferences()) else throw error }
.map { prefs ->
ThemeSettings(
mode = ThemeMode.fromStorageKey(prefs[MODE_KEY]),
dynamicColor = prefs[DYNAMIC_COLOR_KEY] ?: true,
)
}
.distinctUntilChanged()
suspend fun setMode(mode: ThemeMode) {
dataStore.edit { it[MODE_KEY] = mode.storageKey }
}
suspend fun setDynamicColor(enabled: Boolean) {
dataStore.edit { it[DYNAMIC_COLOR_KEY] = enabled }
}
companion object {
val MODE_KEY: Preferences.Key<String> = stringPreferencesKey("theme_mode")
val DYNAMIC_COLOR_KEY: Preferences.Key<Boolean> = booleanPreferencesKey("theme_dynamic_color")
}
}
@@ -0,0 +1,230 @@
package app.hapi.companion.feature.settings
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.hapi.companion.R
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Daily token bars on a plain [Canvas] (no chart library by design — plan
* track B). Single series, one hue; rounded data-ends anchored to a hairline
* baseline; recessive max/mid gridlines; first/mid/last day labels. Tapping a
* bar selects it and floats a tooltip with the day's numbers; tapping it
* again (or the chart padding) clears the selection.
*/
@Composable
fun DailyBarChart(
bars: List<UsageMath.DailyBar>,
modifier: Modifier = Modifier,
chartHeight: Dp = 168.dp,
) {
var selectedIndex by remember(bars) { mutableStateOf<Int?>(null) }
var plotSize by remember { mutableStateOf(IntSize.Zero) }
var tooltipSize by remember { mutableStateOf(IntSize.Zero) }
val barColor = MaterialTheme.colorScheme.primary
val gridColor = MaterialTheme.colorScheme.outlineVariant
val labelColor = MaterialTheme.colorScheme.onSurfaceVariant
val labelStyle = TextStyle(color = labelColor, fontSize = 10.sp)
val textMeasurer = rememberTextMeasurer()
val maxTokens = max(bars.maxOfOrNull { it.totalTokens } ?: 0L, 1L)
val density = LocalDensity.current
val labelRowPx = with(density) { LABEL_ROW_HEIGHT.toPx() }
Box(modifier = modifier.fillMaxWidth()) {
Canvas(
modifier = Modifier
.fillMaxWidth()
.height(chartHeight)
.onSizeChanged { plotSize = it }
.pointerInput(bars) {
detectTapGestures { offset ->
val index = UsageMath.barIndexAt(offset.x, size.width.toFloat(), bars.size)
selectedIndex = if (index == selectedIndex) null else index
}
},
) {
drawDailyBars(
bars = bars,
maxTokens = maxTokens,
selectedIndex = selectedIndex,
plotBottomInset = labelRowPx,
barColor = barColor,
gridColor = gridColor,
labelStyle = labelStyle,
textMeasurer = textMeasurer,
)
}
val index = selectedIndex
if (index != null && index < bars.size && plotSize.width > 0) {
val slot = plotSize.width.toFloat() / bars.size
val centerX = slot * (index + 0.5f)
val offsetX = (centerX - tooltipSize.width / 2f)
.coerceIn(0f, max(0f, (plotSize.width - tooltipSize.width).toFloat()))
DayTooltip(
bar = bars[index],
modifier = Modifier
.onSizeChanged { tooltipSize = it }
.offset { IntOffset(offsetX.roundToInt(), 0) },
)
}
}
}
@Composable
private fun DayTooltip(bar: UsageMath.DailyBar, modifier: Modifier = Modifier) {
Surface(
modifier = modifier,
shape = MaterialTheme.shapes.small,
color = MaterialTheme.colorScheme.surfaceContainerHigh,
tonalElevation = 2.dp,
shadowElevation = 2.dp,
) {
Column(modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)) {
Text(
text = bar.key,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
)
val bucket = bar.bucket
Text(
text = if (bucket == null) {
stringResource(R.string.settings_usage_tooltip_empty)
} else {
stringResource(
R.string.settings_usage_tooltip,
UsageMath.formatTokens(bucket.totalTokens),
bucket.requests,
UsageMath.formatTokens(bucket.inputTokens),
UsageMath.formatTokens(bucket.outputTokens),
)
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
private fun DrawScope.drawDailyBars(
bars: List<UsageMath.DailyBar>,
maxTokens: Long,
selectedIndex: Int?,
plotBottomInset: Float,
barColor: Color,
gridColor: Color,
labelStyle: TextStyle,
textMeasurer: TextMeasurer,
) {
if (bars.isEmpty()) return
val plotHeight = size.height - plotBottomInset
if (plotHeight <= 0f) return
val baselineY = plotHeight
// Recessive scale: hairline baseline + max/mid gridlines with value labels.
drawLine(gridColor, Offset(0f, baselineY), Offset(size.width, baselineY), strokeWidth = 1.dp.toPx())
val topPad = 14.dp.toPx() // room for the max label above its gridline
for ((fraction, value) in listOf(1f to maxTokens, 0.5f to maxTokens / 2)) {
val y = baselineY - (plotHeight - topPad) * fraction
drawLine(gridColor.copy(alpha = 0.5f), Offset(0f, y), Offset(size.width, y), strokeWidth = 1f)
drawText(
textMeasurer = textMeasurer,
text = UsageMath.formatTokens(value),
topLeft = Offset(0f, (y - 12.sp.toPx()).coerceAtLeast(0f)),
style = labelStyle,
)
}
val slot = size.width / bars.size
val gap = max(2.dp.toPx(), slot * 0.15f).coerceAtMost(slot / 2)
val barWidth = max(slot - gap, 1f)
val corner = CornerRadius(min(4.dp.toPx(), barWidth / 2f), min(4.dp.toPx(), barWidth / 2f))
bars.forEachIndexed { index, bar ->
if (bar.totalTokens <= 0) return@forEachIndexed
val barHeight = max(
(plotHeight - topPad) * (bar.totalTokens.toFloat() / maxTokens),
2.dp.toPx(),
)
val left = slot * index + (slot - barWidth) / 2f
val dimmed = selectedIndex != null && selectedIndex != index
// Rounded data-end at the top, flat edge on the baseline.
val path = Path().apply {
addRoundRect(
RoundRect(
rect = Rect(
offset = Offset(left, baselineY - barHeight),
size = Size(barWidth, barHeight),
),
topLeft = corner,
topRight = corner,
bottomLeft = CornerRadius.Zero,
bottomRight = CornerRadius.Zero,
),
)
}
drawPath(path, color = if (dimmed) barColor.copy(alpha = 0.45f) else barColor)
}
// First / middle / last day labels, clamped into the canvas.
val labelIndexes = buildSet {
add(0)
add(bars.lastIndex)
if (bars.size >= 5) add(bars.size / 2)
}
for (index in labelIndexes) {
val text = UsageMath.shortDayLabel(bars[index].key)
val measured = textMeasurer.measure(text, labelStyle)
val centerX = slot * (index + 0.5f)
val x = (centerX - measured.size.width / 2f)
.coerceIn(0f, max(0f, size.width - measured.size.width))
drawText(
textMeasurer = textMeasurer,
text = text,
topLeft = Offset(x, baselineY + 4.dp.toPx()),
style = labelStyle,
)
}
}
private val LABEL_ROW_HEIGHT: Dp = 20.dp
@@ -0,0 +1,99 @@
package app.hapi.companion.feature.settings
import app.hapi.protocol.wire.UsageSummaryBucket
import app.hapi.protocol.wire.UsageSummaryTotals
import java.time.LocalDate
import java.util.Locale
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.min
import kotlin.math.roundToLong
/**
* Pure derivations behind the usage/storage dashboards — formatting twins of
* the web reference (`web/src/routes/settings/usage.tsx` `formatTokens`,
* `web/src/lib/file-metadata.ts` `formatFileSize`) plus the daily-bar series
* builder. Kept view-free for JVM tests.
*/
object UsageMath {
/** `1234` → `1.2K`, `4560000` → `4.6M` … (web `formatTokens` thresholds). */
fun formatTokens(value: Long): String = when {
value < 1_000 -> value.toString()
value < 1_000_000 ->
"${fixed(value / 1_000.0, decimals = if (value < 10_000) 1 else 0)}K"
value < 1_000_000_000 ->
"${fixed(value / 1_000_000.0, decimals = if (value < 10_000_000) 1 else 0)}M"
else -> "${fixed(value / 1_000_000_000.0, decimals = 1)}B"
}
/**
* `87231` → `85.2 KB` (web `formatFileSize`): 1024 steps, ≥ 10 rounds to
* an integer, < 10 keeps one decimal with a trailing `.0` stripped.
*/
fun formatBytes(bytes: Long): String {
if (bytes < 0) return "0 B"
if (bytes < 1024) return "$bytes B"
val unitIndex = min(floor(ln(bytes.toDouble()) / ln(1024.0)).toInt(), BYTE_UNITS.lastIndex)
val value = bytes / Math.pow(1024.0, unitIndex.toDouble())
val formatted = if (value >= 10) {
value.roundToLong().toString()
} else {
fixed(value, decimals = 1).removeSuffix(".0")
}
return "$formatted ${BYTE_UNITS[unitIndex]}"
}
/** `cacheReadTokens / inputTokens` as `"37.4%"`; `"0%"` when there is no input. */
fun cacheHitRate(totals: UsageSummaryTotals): String =
if (totals.inputTokens > 0) {
"${fixed(totals.cacheReadTokens * 100.0 / totals.inputTokens, decimals = 1)}%"
} else {
"0%"
}
/** One bar of the daily chart; [bucket] is null for a zero-usage fill day. */
data class DailyBar(
/** `YYYY-MM-DD` in the summary's timeZone. */
val key: String,
val totalTokens: Long,
val bucket: UsageSummaryBucket? = null,
)
/**
* Bars for the daily chart. The hub's `daily` list is sparse (only days
* with usage); a bounded range ([days] = 7/30) is filled to a complete
* calendar window ending [today] so the time axis is honest. `range=all`
* ([days] = null) keeps the sparse buckets as-is — the span is unbounded.
*/
fun dailyBars(daily: List<UsageSummaryBucket>, days: Int?, today: LocalDate): List<DailyBar> {
if (days == null) {
return daily.map { DailyBar(key = it.key, totalTokens = it.totalTokens, bucket = it) }
}
val byKey = daily.associateBy { it.key }
return (days - 1 downTo 0).map { offset ->
val key = today.minusDays(offset.toLong()).toString()
val bucket = byKey[key]
DailyBar(key = key, totalTokens = bucket?.totalTokens ?: 0, bucket = bucket)
}
}
/**
* Bar slot under a tap at [x] px in a chart [width] px wide holding
* [count] equal slots; null when outside `[0, width)` or the chart is empty.
*/
fun barIndexAt(x: Float, width: Float, count: Int): Int? {
if (count <= 0 || width <= 0f || x < 0f || x >= width) return null
return min((x / (width / count)).toInt(), count - 1)
}
/** `"2026-08-07"` → `"08-07"` for compact x-axis labels; junk passes through. */
fun shortDayLabel(key: String): String =
if (key.length == 10 && key[4] == '-') key.substring(5) else key
/** JS `toFixed` twin: US decimal separator, HALF_UP is close enough here. */
private fun fixed(value: Double, decimals: Int): String =
String.format(Locale.US, "%.${decimals}f", value)
private val BYTE_UNITS = listOf("B", "KB", "MB", "GB", "TB")
}
@@ -0,0 +1,310 @@
package app.hapi.companion.feature.settings
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.hapi.companion.R
import app.hapi.protocol.wire.UsageSummaryBucket
import app.hapi.protocol.wire.UsageSummaryResponse
import kotlin.math.max
/**
* Owner-only token-usage dashboard (web `web/src/routes/settings/usage.tsx`
* twin): range segmented control, stat tiles, the Canvas daily bar chart, and
* byAgent/byModel bar lists.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UsageScreen(
viewModel: UsageViewModel,
onBack: () -> Unit,
) {
LaunchedEffect(viewModel) { viewModel.start() }
val range by viewModel.range.collectAsState()
val state by viewModel.state.collectAsState()
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.settings_usage)) },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(
Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.settings_back),
)
}
},
)
},
) { padding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(padding)
.verticalScroll(rememberScrollState())
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
UsageRangeControl(selected = range, onSelect = viewModel::setRange)
when (val current = state) {
is UsageUiState.Loading -> Box(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 48.dp),
contentAlignment = Alignment.Center,
) { CircularProgressIndicator() }
is UsageUiState.Error -> DashboardError(
isForbidden = current.isForbidden,
message = current.message,
onRetry = viewModel::retry,
)
is UsageUiState.Data -> UsageSummaryContent(
summary = current.summary,
dailyBars = current.dailyBars,
)
}
}
}
}
@Composable
private fun UsageRangeControl(selected: UsageRange, onSelect: (UsageRange) -> Unit) {
val options = UsageRange.entries
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
options.forEachIndexed { index, option ->
SegmentedButton(
selected = option == selected,
onClick = { onSelect(option) },
shape = SegmentedButtonDefaults.itemShape(index = index, count = options.size),
) {
Text(stringResource(rangeLabelRes(option)))
}
}
}
}
private fun rangeLabelRes(range: UsageRange): Int = when (range) {
UsageRange.SEVEN_DAYS -> R.string.settings_usage_range_7d
UsageRange.THIRTY_DAYS -> R.string.settings_usage_range_30d
UsageRange.ALL -> R.string.settings_usage_range_all
}
/** The loaded dashboard body — also the preview entry point. */
@Composable
internal fun UsageSummaryContent(
summary: UsageSummaryResponse,
dailyBars: List<UsageMath.DailyBar>,
) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
UsageStatTiles(summary = summary)
UsageSection(title = stringResource(R.string.settings_usage_daily_title)) {
if (summary.daily.isEmpty()) {
EmptyHint()
} else {
DailyBarChart(
bars = dailyBars,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 12.dp),
)
}
}
UsageSection(title = stringResource(R.string.settings_usage_by_agent)) {
UsageBarList(rows = summary.byAgent)
}
UsageSection(title = stringResource(R.string.settings_usage_by_model)) {
UsageBarList(rows = summary.byModel)
}
Text(
text = stringResource(R.string.settings_usage_sessions, summary.totals.sessions),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
/** The eight headline tiles, two per row (web tile grid twin). */
@Composable
internal fun UsageStatTiles(summary: UsageSummaryResponse) {
val totals = summary.totals
val tiles: List<Pair<Int, String>> = listOf(
R.string.settings_usage_total to UsageMath.formatTokens(totals.totalTokens),
R.string.settings_usage_uncached to UsageMath.formatTokens(totals.uncachedTokens),
R.string.settings_usage_input to UsageMath.formatTokens(totals.inputTokens),
R.string.settings_usage_output to UsageMath.formatTokens(totals.outputTokens),
R.string.settings_usage_cache_read to UsageMath.formatTokens(totals.cacheReadTokens),
R.string.settings_usage_cache_creation to UsageMath.formatTokens(totals.cacheCreationTokens),
R.string.settings_usage_cache_hit_rate to UsageMath.cacheHitRate(totals),
R.string.settings_usage_requests to UsageMath.formatTokens(totals.requests),
)
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
tiles.chunked(2).forEach { rowTiles ->
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
rowTiles.forEach { (labelRes, value) ->
StatTile(
label = stringResource(labelRes),
value = value,
modifier = Modifier.weight(1f),
)
}
}
}
}
}
@Composable
private fun StatTile(label: String, value: String, modifier: Modifier = Modifier) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceContainerLow,
modifier = modifier,
) {
Column(modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp)) {
Text(
text = label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = value,
style = MaterialTheme.typography.titleLarge,
modifier = Modifier.padding(top = 2.dp),
)
}
}
}
@Composable
private fun UsageSection(title: String, content: @Composable () -> Unit) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceContainerLow,
modifier = Modifier.fillMaxWidth(),
) {
Column {
Text(
text = title,
style = MaterialTheme.typography.titleSmall,
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 4.dp),
)
content()
}
}
}
@Composable
private fun EmptyHint() {
Text(
text = stringResource(R.string.settings_usage_empty),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
)
}
/**
* Ranked share list (byAgent/byModel): name + tokens + a thin track bar
* scaled to the top row, sub-line with requests and in/out split. Top 8 rows,
* like the web.
*/
@Composable
internal fun UsageBarList(rows: List<UsageSummaryBucket>) {
if (rows.isEmpty()) {
EmptyHint()
return
}
val maxTokens = max(rows.first().totalTokens, 1L)
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
rows.take(MAX_BUCKET_ROWS).forEach { row ->
Column(modifier = Modifier.padding(vertical = 6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = row.key,
style = MaterialTheme.typography.bodyMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
)
Text(
text = UsageMath.formatTokens(row.totalTokens),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 12.dp),
)
}
ShareTrack(fraction = row.totalTokens.toFloat() / maxTokens)
Text(
text = stringResource(
R.string.settings_usage_bucket_details,
row.requests,
UsageMath.formatTokens(row.inputTokens),
UsageMath.formatTokens(row.outputTokens),
),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 4.dp),
)
}
}
}
}
/** Thin rounded share bar (web 6px track twin); min 2% so tiny rows register. */
@Composable
private fun ShareTrack(fraction: Float) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 6.dp)
.height(6.dp)
.background(MaterialTheme.colorScheme.surfaceContainerHighest, RoundedCornerShape(3.dp)),
) {
Box(
modifier = Modifier
.fillMaxWidth(fraction.coerceIn(0.02f, 1f))
.height(6.dp)
.background(MaterialTheme.colorScheme.primary, RoundedCornerShape(3.dp)),
)
}
}
private const val MAX_BUCKET_ROWS = 8
@@ -0,0 +1,100 @@
package app.hapi.companion.feature.settings
import app.hapi.data.api.ApiError
import app.hapi.protocol.wire.UsageSummaryResponse
import java.time.LocalDate
import java.time.ZoneId
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
/** Wire values of the `range` query param (web `UsageRange`). */
enum class UsageRange(val wireValue: String, val days: Int?) {
SEVEN_DAYS("7d", 7),
THIRTY_DAYS("30d", 30),
ALL("all", null),
}
/** Transport seam (`HapiApi.getUsageSummary`) so JVM tests fake the hub. */
fun interface UsageGateway {
suspend fun summary(range: String, timeZone: String): UsageSummaryResponse
}
sealed interface UsageUiState {
data object Loading : UsageUiState
data class Error(
val message: String?,
/** 403: the hub rejected a non-owner namespace — explain, don't retry. */
val isForbidden: Boolean,
) : UsageUiState
data class Data(
val summary: UsageSummaryResponse,
/** Chart series: calendar-filled for 7d/30d, sparse for all. */
val dailyBars: List<UsageMath.DailyBar>,
) : UsageUiState
}
/**
* Usage-dashboard state: one in-flight load per range selection (a range
* switch cancels the previous fetch), device zone for both the `timeZone`
* param and the calendar fill so the two agree on day keys.
*/
class UsageViewModel(
private val gateway: UsageGateway,
private val scope: CoroutineScope,
private val zone: ZoneId = ZoneId.systemDefault(),
/** Injectable for deterministic calendar-fill tests. */
private val today: () -> LocalDate = { LocalDate.now(zone) },
) {
private val mutableRange = MutableStateFlow(UsageRange.SEVEN_DAYS)
val range: StateFlow<UsageRange> = mutableRange.asStateFlow()
private val mutableState = MutableStateFlow<UsageUiState>(UsageUiState.Loading)
val state: StateFlow<UsageUiState> = mutableState.asStateFlow()
private var loadJob: Job? = null
fun start() {
if (loadJob == null) load(mutableRange.value)
}
fun setRange(range: UsageRange) {
if (mutableRange.value == range) return
mutableRange.value = range
load(range)
}
fun retry() {
load(mutableRange.value)
}
private fun load(range: UsageRange) {
loadJob?.cancel()
mutableState.value = UsageUiState.Loading
loadJob = scope.launch {
mutableState.value = try {
val summary = gateway.summary(range.wireValue, zone.id)
UsageUiState.Data(
summary = summary,
dailyBars = UsageMath.dailyBars(summary.daily, range.days, today()),
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
UsageUiState.Error(
message = e.message,
isForbidden = (e as? ApiError)?.status == 403,
)
}
}
}
}
@@ -47,6 +47,7 @@
<!-- Home (session list top bar + hub chores) -->
<string name="home_menu">Menu</string>
<string name="home_settings">Settings</string>
<string name="home_switch_hub">Switch hub</string>
<string name="home_pair_another">Pair another hub…</string>
<string name="home_sign_out">Sign out</string>
@@ -91,4 +92,73 @@
<string name="new_session_create">Create</string>
<string name="new_session_creating">Creating…</string>
<string name="new_session_create_and_make_directory">Create and make directory</string>
<!-- Settings scaffold (B-M4e) -->
<string name="settings_title">Settings</string>
<string name="settings_back">Back</string>
<string name="settings_cancel">Cancel</string>
<string name="settings_retry">Retry</string>
<string name="settings_load_error">Could not load this dashboard.</string>
<string name="settings_owner_only">This dashboard is only available to the hub owner (default namespace).</string>
<string name="settings_section_appearance">Appearance</string>
<string name="settings_theme">Theme</string>
<string name="settings_theme_system">Follow system</string>
<string name="settings_theme_light">Light</string>
<string name="settings_theme_dark">Dark</string>
<string name="settings_theme_oled">OLED black</string>
<string name="settings_dynamic_color">Material You colors</string>
<string name="settings_dynamic_color_description">Derive app colors from your wallpaper.</string>
<string name="settings_dynamic_color_oled_note">Not available with OLED black.</string>
<string name="settings_section_language">Language</string>
<string name="settings_language">App language</string>
<string name="settings_language_pending_note">Saved now; the 简体中文 translation ships in an upcoming update.</string>
<string name="settings_section_insights">Insights</string>
<string name="settings_usage_summary">Token usage across agents and models</string>
<string name="settings_storage_summary">Hub database size on disk</string>
<string name="settings_section_about">About</string>
<string name="settings_app_version">App version</string>
<string name="settings_protocol_version">Protocol version</string>
<string name="settings_hub">Hub</string>
<string name="settings_hub_checking">Checking hub…</string>
<string name="settings_hub_health">Status: %1$s · protocol v%2$d</string>
<string name="settings_hub_unreachable">Hub unreachable — tap to retry.</string>
<!-- Usage dashboard -->
<string name="settings_usage">Usage</string>
<string name="settings_usage_range_7d">7 days</string>
<string name="settings_usage_range_30d">30 days</string>
<string name="settings_usage_range_all">All time</string>
<string name="settings_usage_total">Total tokens</string>
<string name="settings_usage_uncached">Uncached</string>
<string name="settings_usage_input">Input</string>
<string name="settings_usage_output">Output</string>
<string name="settings_usage_cache_read">Cache read</string>
<string name="settings_usage_cache_creation">Cache creation</string>
<string name="settings_usage_cache_hit_rate">Cache hit rate</string>
<string name="settings_usage_requests">Requests</string>
<string name="settings_usage_daily_title">Daily tokens</string>
<string name="settings_usage_tooltip">%1$s tokens · %2$d req · in %3$s / out %4$s</string>
<string name="settings_usage_tooltip_empty">0 tokens</string>
<string name="settings_usage_by_agent">By agent</string>
<string name="settings_usage_by_model">By model</string>
<string name="settings_usage_bucket_details">%1$d requests · in %2$s · out %3$s</string>
<string name="settings_usage_sessions">Sessions with usage: %1$d</string>
<string name="settings_usage_empty">No usage recorded in this period.</string>
<!-- Storage dashboard -->
<string name="settings_storage">Storage</string>
<string name="settings_storage_description">Disk footprint of the hub\'s SQLite database (database, write-ahead log, shared memory).</string>
<string name="settings_storage_chart_title">SQLite files</string>
<string name="settings_storage_chart_empty">No storage data reported.</string>
<string name="settings_storage_database">Database</string>
<string name="settings_storage_wal">Write-ahead log</string>
<string name="settings_storage_shm">Shared memory</string>
<string name="settings_storage_total">Total</string>
<string name="settings_storage_path">Path</string>
<string name="settings_storage_refresh">Refresh</string>
<string name="settings_storage_refreshing">Refreshing…</string>
</resources>
@@ -0,0 +1,124 @@
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package app.hapi.companion.feature.settings
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import app.hapi.protocol.wire.HubHealthResponse
import java.io.File
import java.util.Base64
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.rules.TemporaryFolder
/** Builds an unsigned JWT with hub-shaped claims — `JwtPeek` never verifies. */
private fun fakeJwt(ns: String? = "default", uid: Long = 1): String {
fun b64(text: String): String =
Base64.getUrlEncoder().withoutPadding().encodeToString(text.toByteArray(Charsets.UTF_8))
val nsPart = ns?.let { ""","ns":"$it"""" } ?: ""
return "${b64("""{"alg":"HS256","typ":"JWT"}""")}.${b64("""{"uid":$uid$nsPart}""")}.sig"
}
/** Owner gating (`ns === 'default'`) and the About hub probe. */
class SettingsViewModelTest {
@get:Rule
val tmp = TemporaryFolder()
// ------------------------------------------------------------- gating --
@Test
fun `only the default namespace is the owner`() {
assertTrue(isOwnerNamespace(fakeJwt(ns = "default")))
assertFalse(isOwnerNamespace(fakeJwt(ns = "family")))
assertFalse(isOwnerNamespace(fakeJwt(ns = "Default"))) // case-sensitive, like the hub
}
@Test
fun `gate fails closed on missing or undecodable tokens`() {
assertFalse(isOwnerNamespace(null))
assertFalse(isOwnerNamespace(""))
assertFalse(isOwnerNamespace("not-a-jwt"))
assertFalse(isOwnerNamespace(fakeJwt(ns = null))) // claim absent
}
// ---------------------------------------------------------- viewmodel --
/**
* VM + DataStore scope on the test scheduler as FOREGROUND work —
* `advanceUntilIdle` drives it; `backgroundScope`-hosted work would never
* run under pure virtual time (same pattern as `NewSessionViewModelTest`).
*/
private fun runWithViewModel(
jwt: String?,
health: suspend () -> HubHealthResponse,
assertions: suspend TestScope.(SettingsViewModel) -> Unit,
) = runTest {
val scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler))
try {
val dataStore = PreferenceDataStoreFactory.create(scope = scope) {
File(tmp.root, "settings-vm-${System.nanoTime()}.preferences_pb")
}
val viewModel = SettingsViewModel(
themePrefs = ThemePrefs(dataStore),
languagePrefs = LanguagePrefs(dataStore),
hubUrl = "https://hub.example",
currentJwt = { jwt },
fetchHealth = health,
scope = scope,
)
advanceUntilIdle()
assertions(viewModel)
} finally {
scope.coroutineContext[Job]?.cancelAndJoin()
}
}
@Test
fun `owner flag and hub health resolve from the injected seams`() = runWithViewModel(
jwt = fakeJwt(ns = "default"),
health = { HubHealthResponse(status = "ok", protocolVersion = 1) },
) { viewModel ->
assertTrue(viewModel.isOwner.value)
val info = viewModel.hubInfo.value
assertTrue(info is HubInfoState.Loaded)
assertEquals("ok", info.health.status)
assertEquals(1, info.health.protocolVersion)
}
@Test
fun `non-owner namespace hides the dashboards and health failures surface`() = runWithViewModel(
jwt = fakeJwt(ns = "guest"),
health = { throw RuntimeException("connection refused") },
) { viewModel ->
assertFalse(viewModel.isOwner.value)
val info = viewModel.hubInfo.value
assertTrue(info is HubInfoState.Failed)
assertEquals("connection refused", info.message)
}
@Test
fun `theme and language setters persist through the prefs`() = runWithViewModel(
jwt = null,
health = { HubHealthResponse(status = "ok", protocolVersion = 1) },
) { viewModel ->
viewModel.setThemeMode(ThemeMode.OLED)
viewModel.setDynamicColor(false)
viewModel.setLanguage(AppLanguage.SIMPLIFIED_CHINESE)
advanceUntilIdle()
assertEquals(ThemeMode.OLED, viewModel.themeSettings.value.mode)
assertFalse(viewModel.themeSettings.value.dynamicColor)
assertEquals(AppLanguage.SIMPLIFIED_CHINESE, viewModel.language.value)
}
}
@@ -0,0 +1,69 @@
package app.hapi.companion.feature.settings
import app.hapi.protocol.wire.SqliteStorageUsageResponse
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/** Donut slice math — twin of `storageUsageSlices.test.ts` semantics. */
class StorageMathTest {
private fun usage(db: Long, wal: Long, shm: Long): SqliteStorageUsageResponse =
SqliteStorageUsageResponse(
path = "/x/hapi.db",
databaseBytes = db,
walBytes = wal,
shmBytes = shm,
totalBytes = db + wal + shm,
)
@Test
fun `slices keep entity order and partition the full circle`() {
val slices = StorageMath.slices(usage(db = 750, wal = 200, shm = 50))
assertEquals(
listOf(StorageMath.SliceKey.DATABASE, StorageMath.SliceKey.WAL, StorageMath.SliceKey.SHM),
slices.map { it.key },
)
assertEquals(StorageMath.START_ANGLE, slices.first().startAngle)
assertEquals(StorageMath.START_ANGLE + 360f, slices.last().endAngle)
// Contiguous: each slice starts where the previous ended.
slices.zipWithNext().forEach { (a, b) -> assertEquals(a.endAngle, b.startAngle) }
assertEquals(75.0, slices[0].percent)
assertEquals(20.0, slices[1].percent)
assertEquals(5.0, slices[2].percent)
// db = 75% of the circle.
assertEquals(270f, slices[0].endAngle - slices[0].startAngle, absoluteTolerance = 0.001f)
}
@Test
fun `zero-byte files are dropped without repainting the survivors`() {
val slices = StorageMath.slices(usage(db = 100, wal = 0, shm = 25))
assertEquals(listOf(StorageMath.SliceKey.DATABASE, StorageMath.SliceKey.SHM), slices.map { it.key })
assertEquals(StorageMath.START_ANGLE + 360f, slices.last().endAngle)
assertEquals(80.0, slices[0].percent)
}
@Test
fun `all-zero usage yields no slices`() {
assertTrue(StorageMath.slices(usage(db = 0, wal = 0, shm = 0)).isEmpty())
// Negative (corrupt) sizes are treated as zero, not drawn.
assertTrue(StorageMath.slices(usage(db = -10, wal = 0, shm = 0)).isEmpty())
}
@Test
fun `percent rounds to one decimal`() {
val slices = StorageMath.slices(usage(db = 1, wal = 2, shm = 0))
assertEquals(33.3, slices[0].percent)
assertEquals(66.7, slices[1].percent)
}
@Test
fun `formatPercent drops the decimal on whole numbers`() {
assertEquals("75%", StorageMath.formatPercent(75.0))
assertEquals("33.3%", StorageMath.formatPercent(33.3))
assertEquals("97.3%", StorageMath.formatPercent(97.25))
assertEquals("0%", StorageMath.formatPercent(0.0))
assertEquals("100%", StorageMath.formatPercent(100.0))
}
}
@@ -0,0 +1,106 @@
package app.hapi.companion.feature.settings
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.edit
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.Rule
import org.junit.rules.TemporaryFolder
/**
* Theme/language pref round-trips against a real temp-file Preferences
* DataStore (pure JVM), including the cold-start reload path and unknown-value
* degradation.
*/
class ThemePrefsTest {
@get:Rule
val tmp = TemporaryFolder()
private fun newScope(): CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private fun storeFile(name: String): File = File(tmp.root, "$name.preferences_pb")
@Test
fun `theme settings round-trip and survive a cold start`() = runTest {
val file = storeFile("theme")
val firstScope = newScope()
try {
val prefs = ThemePrefs(PreferenceDataStoreFactory.create(scope = firstScope) { file })
assertEquals(ThemeSettings(ThemeMode.SYSTEM, dynamicColor = true), prefs.settings.first())
prefs.setMode(ThemeMode.OLED)
prefs.setDynamicColor(false)
assertEquals(ThemeSettings(ThemeMode.OLED, dynamicColor = false), prefs.settings.first())
} finally {
firstScope.coroutineContext[Job]?.cancelAndJoin()
}
// "Second process": a fresh DataStore over the same file.
val secondScope = newScope()
try {
val prefs = ThemePrefs(PreferenceDataStoreFactory.create(scope = secondScope) { file })
assertEquals(ThemeSettings(ThemeMode.OLED, dynamicColor = false), prefs.settings.first())
} finally {
secondScope.coroutineContext[Job]?.cancelAndJoin()
}
}
@Test
fun `every theme mode round-trips through its storage key`() = runTest {
val scope = newScope()
try {
val prefs = ThemePrefs(PreferenceDataStoreFactory.create(scope = scope) { storeFile("modes") })
for (mode in ThemeMode.entries) {
prefs.setMode(mode)
assertEquals(mode, prefs.settings.first().mode)
}
} finally {
scope.coroutineContext[Job]?.cancelAndJoin()
}
}
@Test
fun `unknown stored values degrade to defaults`() = runTest {
val scope = newScope()
try {
val dataStore = PreferenceDataStoreFactory.create(scope = scope) { storeFile("junk") }
dataStore.edit {
it[ThemePrefs.MODE_KEY] = "amoled-ultra"
it[LanguagePrefs.LANGUAGE_KEY] = "klingon"
}
assertEquals(ThemeMode.SYSTEM, ThemePrefs(dataStore).settings.first().mode)
assertEquals(AppLanguage.ENGLISH, LanguagePrefs(dataStore).language.first())
} finally {
scope.coroutineContext[Job]?.cancelAndJoin()
}
}
@Test
fun `language choice round-trips and coexists with theme keys`() = runTest {
val scope = newScope()
try {
val dataStore = PreferenceDataStoreFactory.create(scope = scope) { storeFile("lang") }
val language = LanguagePrefs(dataStore)
val theme = ThemePrefs(dataStore)
assertEquals(AppLanguage.ENGLISH, language.language.first())
language.setLanguage(AppLanguage.SIMPLIFIED_CHINESE)
theme.setMode(ThemeMode.DARK)
assertEquals(AppLanguage.SIMPLIFIED_CHINESE, language.language.first())
assertEquals(ThemeMode.DARK, theme.settings.first().mode)
} finally {
scope.coroutineContext[Job]?.cancelAndJoin()
}
}
}
@@ -0,0 +1,140 @@
package app.hapi.companion.feature.settings
import app.hapi.protocol.wire.UsageSummaryBucket
import app.hapi.protocol.wire.UsageSummaryTotals
import java.time.LocalDate
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
* Tile/format derivations — thresholds mirror the web reference
* (`formatTokens` in `usage.tsx`, `formatFileSize` in `file-metadata.ts`).
*/
class UsageMathTest {
// ------------------------------------------------------- formatTokens --
@Test
fun `token formatting mirrors the web thresholds`() {
assertEquals("0", UsageMath.formatTokens(0))
assertEquals("999", UsageMath.formatTokens(999))
assertEquals("1.0K", UsageMath.formatTokens(1_000))
assertEquals("1.2K", UsageMath.formatTokens(1_234))
assertEquals("10.0K", UsageMath.formatTokens(9_999))
assertEquals("10K", UsageMath.formatTokens(10_000))
assertEquals("1000K", UsageMath.formatTokens(999_999))
assertEquals("1.5M", UsageMath.formatTokens(1_500_000))
assertEquals("10.0M", UsageMath.formatTokens(9_999_999))
assertEquals("12M", UsageMath.formatTokens(12_000_000))
assertEquals("2.3B", UsageMath.formatTokens(2_300_000_000))
}
// -------------------------------------------------------- formatBytes --
@Test
fun `byte formatting mirrors the web formatFileSize`() {
assertEquals("0 B", UsageMath.formatBytes(0))
assertEquals("512 B", UsageMath.formatBytes(512))
assertEquals("1 KB", UsageMath.formatBytes(1_024))
assertEquals("1.5 KB", UsageMath.formatBytes(1_536))
// < 10 keeps one decimal, trailing .0 stripped; >= 10 rounds whole.
assertEquals("9.9 KB", UsageMath.formatBytes(10_186))
assertEquals("10 KB", UsageMath.formatBytes(10_240))
assertEquals("4 MB", UsageMath.formatBytes(4_194_304))
assertEquals("81 MB", UsageMath.formatBytes(84_930_560))
assertEquals("2 GB", UsageMath.formatBytes(2_147_483_648))
assertEquals("0 B", UsageMath.formatBytes(-5))
}
// ------------------------------------------------------- cacheHitRate --
private fun totals(input: Long, cacheRead: Long): UsageSummaryTotals = UsageSummaryTotals(
inputTokens = input,
outputTokens = 0,
cacheReadTokens = cacheRead,
cacheCreationTokens = 0,
totalTokens = input,
uncachedTokens = input - cacheRead,
requests = 1,
sessions = 1,
)
@Test
fun `cache hit rate is cacheRead over input with one decimal`() {
assertEquals("79.0%", UsageMath.cacheHitRate(totals(input = 12_400_000, cacheRead = 9_800_000)))
assertEquals("100.0%", UsageMath.cacheHitRate(totals(input = 5, cacheRead = 5)))
assertEquals("33.3%", UsageMath.cacheHitRate(totals(input = 3, cacheRead = 1)))
}
@Test
fun `cache hit rate degrades to 0 percent without input tokens`() {
assertEquals("0%", UsageMath.cacheHitRate(totals(input = 0, cacheRead = 0)))
}
// ---------------------------------------------------------- dailyBars --
private fun bucket(key: String, total: Long): UsageSummaryBucket = UsageSummaryBucket(
key = key,
inputTokens = total,
outputTokens = 0,
cacheReadTokens = 0,
cacheCreationTokens = 0,
totalTokens = total,
uncachedTokens = total,
requests = 1,
)
@Test
fun `bounded ranges fill the calendar window ending today`() {
val today = LocalDate.of(2026, 8, 18)
val sparse = listOf(bucket("2026-08-13", 5), bucket("2026-08-18", 9))
val bars = UsageMath.dailyBars(sparse, days = 7, today = today)
assertEquals(7, bars.size)
assertEquals("2026-08-12", bars.first().key)
assertEquals("2026-08-18", bars.last().key)
assertEquals(0, bars.first().totalTokens)
assertNull(bars.first().bucket)
assertEquals(5, bars[1].totalTokens)
assertEquals(9, bars.last().totalTokens)
assertEquals(sparse[1], bars.last().bucket)
}
@Test
fun `range=all keeps the sparse buckets as-is`() {
val sparse = listOf(bucket("2025-01-01", 3), bucket("2026-08-18", 4))
val bars = UsageMath.dailyBars(sparse, days = null, today = LocalDate.of(2026, 8, 18))
assertEquals(listOf("2025-01-01", "2026-08-18"), bars.map { it.key })
assertEquals(listOf(3L, 4L), bars.map { it.totalTokens })
}
@Test
fun `calendar fill spans month boundaries`() {
val bars = UsageMath.dailyBars(emptyList(), days = 30, today = LocalDate.of(2026, 3, 5))
assertEquals(30, bars.size)
assertEquals("2026-02-04", bars.first().key)
assertEquals("2026-03-05", bars.last().key)
}
// --------------------------------------------------------- barIndexAt --
@Test
fun `tap x maps to bar slots with edges clamped`() {
assertEquals(0, UsageMath.barIndexAt(0f, width = 700f, count = 7))
assertEquals(0, UsageMath.barIndexAt(99.9f, width = 700f, count = 7))
assertEquals(1, UsageMath.barIndexAt(100f, width = 700f, count = 7))
assertEquals(6, UsageMath.barIndexAt(699.9f, width = 700f, count = 7))
assertNull(UsageMath.barIndexAt(700f, width = 700f, count = 7))
assertNull(UsageMath.barIndexAt(-1f, width = 700f, count = 7))
assertNull(UsageMath.barIndexAt(10f, width = 700f, count = 0))
assertNull(UsageMath.barIndexAt(10f, width = 0f, count = 7))
}
@Test
fun `short day labels drop the year`() {
assertEquals("08-18", UsageMath.shortDayLabel("2026-08-18"))
assertEquals("odd-key", UsageMath.shortDayLabel("odd-key"))
}
}
@@ -0,0 +1,190 @@
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
package app.hapi.companion.feature.settings
import app.hapi.data.api.ApiError
import app.hapi.protocol.wire.SqliteStorageUsageResponse
import app.hapi.protocol.wire.UsageSummaryBucket
import app.hapi.protocol.wire.UsageSummaryRange
import app.hapi.protocol.wire.UsageSummaryResponse
import app.hapi.protocol.wire.UsageSummaryTotals
import java.time.LocalDate
import java.time.ZoneId
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
/** Range/reload/error-state behavior of the two dashboard ViewModels. */
class UsageViewModelTest {
private val zone = ZoneId.of("Asia/Shanghai")
/**
* VM scope on the test scheduler as FOREGROUND work — `advanceUntilIdle`
* drives it; a `backgroundScope`-hosted VM would never run under pure
* virtual time (same pattern as `NewSessionViewModelTest`).
*/
private fun TestScope.newVmScope(): CoroutineScope =
CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler))
private fun bucket(key: String, total: Long): UsageSummaryBucket = UsageSummaryBucket(
key = key,
inputTokens = total,
outputTokens = 0,
cacheReadTokens = 0,
cacheCreationTokens = 0,
totalTokens = total,
uncachedTokens = total,
requests = 1,
)
private fun summary(daily: List<UsageSummaryBucket>): UsageSummaryResponse = UsageSummaryResponse(
range = UsageSummaryRange(from = null, to = 2),
totals = UsageSummaryTotals(0, 0, 0, 0, 0, 0, 0, 0),
daily = daily,
byAgent = emptyList(),
byModel = emptyList(),
updatedAt = 2,
)
@Test
fun `loads on start with the device zone and fills the 7d calendar`() = runTest {
val requested = mutableListOf<Pair<String, String>>()
val viewModel = UsageViewModel(
gateway = { range, timeZone ->
requested += range to timeZone
summary(listOf(bucket("2026-08-18", 7)))
},
scope = newVmScope(),
zone = zone,
today = { LocalDate.of(2026, 8, 18) },
)
viewModel.start()
advanceUntilIdle()
assertEquals(listOf("7d" to "Asia/Shanghai"), requested)
val state = viewModel.state.value
assertTrue(state is UsageUiState.Data)
assertEquals(7, state.dailyBars.size)
assertEquals("2026-08-12", state.dailyBars.first().key)
assertEquals(7, state.dailyBars.last().totalTokens)
}
@Test
fun `switching range refetches and range=all keeps sparse bars`() = runTest {
val requested = mutableListOf<String>()
val viewModel = UsageViewModel(
gateway = { range, _ ->
requested += range
summary(listOf(bucket("2024-01-01", 3)))
},
scope = newVmScope(),
zone = zone,
today = { LocalDate.of(2026, 8, 18) },
)
viewModel.start()
advanceUntilIdle()
viewModel.setRange(UsageRange.ALL)
// Re-selecting the current range must not refetch.
viewModel.setRange(UsageRange.ALL)
advanceUntilIdle()
assertEquals(listOf("7d", "all"), requested)
val state = viewModel.state.value
assertTrue(state is UsageUiState.Data)
assertEquals(listOf("2024-01-01"), state.dailyBars.map { it.key })
}
@Test
fun `403 maps to the forbidden error state`() = runTest {
val viewModel = UsageViewModel(
gateway = { _, _ -> throw ApiError(status = 403, body = """{"error":"owner only"}""") },
scope = newVmScope(),
zone = zone,
)
viewModel.start()
advanceUntilIdle()
val state = viewModel.state.value
assertTrue(state is UsageUiState.Error)
assertTrue(state.isForbidden)
}
@Test
fun `plain failures keep retry available and retry recovers`() = runTest {
var fail = true
val viewModel = UsageViewModel(
gateway = { _, _ ->
if (fail) throw RuntimeException("boom") else summary(emptyList())
},
scope = newVmScope(),
zone = zone,
)
viewModel.start()
advanceUntilIdle()
val error = viewModel.state.value
assertTrue(error is UsageUiState.Error)
assertFalse(error.isForbidden)
assertEquals("boom", error.message)
fail = false
viewModel.retry()
advanceUntilIdle()
assertTrue(viewModel.state.value is UsageUiState.Data)
}
// ------------------------------------------------------------ storage --
@Test
fun `storage refresh keeps data while refreshing and surfaces 403`() = runTest {
var bytes = 100L
val viewModel = StorageViewModel(
gateway = {
SqliteStorageUsageResponse(
path = "/x/hapi.db",
databaseBytes = bytes,
walBytes = 0,
shmBytes = 0,
totalBytes = bytes,
)
},
scope = newVmScope(),
)
viewModel.start()
advanceUntilIdle()
assertEquals(100, (viewModel.state.value as StorageUiState.Data).usage.totalBytes)
bytes = 250
viewModel.refresh()
// Mid-refresh the old snapshot stays on screen, flagged refreshing.
val midway = viewModel.state.value
assertTrue(midway is StorageUiState.Data)
assertTrue(midway.isRefreshing)
assertEquals(100, midway.usage.totalBytes)
advanceUntilIdle()
val refreshed = viewModel.state.value
assertTrue(refreshed is StorageUiState.Data)
assertFalse(refreshed.isRefreshing)
assertEquals(250, refreshed.usage.totalBytes)
}
@Test
fun `storage 403 maps to forbidden`() = runTest {
val viewModel = StorageViewModel(
gateway = { throw ApiError(status = 403) },
scope = newVmScope(),
)
viewModel.start()
advanceUntilIdle()
val state = viewModel.state.value
assertTrue(state is StorageUiState.Error)
assertTrue(state.isForbidden)
}
}
@@ -37,6 +37,7 @@ import app.hapi.protocol.wire.SkillsResponse
import app.hapi.protocol.wire.SlashCommandsResponse
import app.hapi.protocol.wire.SpawnResponse
import app.hapi.protocol.wire.SpawnSessionRequest
import app.hapi.protocol.wire.SqliteStorageUsageResponse
import app.hapi.protocol.wire.SteerQueuedMessageResponse
import app.hapi.protocol.wire.TranscriptionProvidersResponse
import app.hapi.protocol.wire.TranscriptionResponse
@@ -44,6 +45,7 @@ import app.hapi.protocol.wire.UnregisterDeviceRequest
import app.hapi.protocol.wire.UpdateSessionSummaryRequest
import app.hapi.protocol.wire.UploadFileRequest
import app.hapi.protocol.wire.UploadFileResponse
import app.hapi.protocol.wire.UsageSummaryResponse
import app.hapi.protocol.wire.VisibilityRequest
import java.io.IOException
import kotlin.coroutines.resume
@@ -593,6 +595,26 @@ class HapiApi(
DeleteUploadRequest(path).toJsonBody(),
)
// ---------------------------------------------------- usage & storage --
// Owner-only dashboards: both 403 unless the JWT namespace is `default`
// (`docs/api/client-contract/rest.md#usage--storage-owner-only`).
/**
* `GET /api/usage/summary?range=7d|30d|all&timeZone=<IANA>` — token-usage
* dashboard aggregates. The hub validates [timeZone] (400 when invalid)
* and buckets `daily` by that zone's calendar days.
*/
suspend fun getUsageSummary(range: String = "7d", timeZone: String = "UTC"): UsageSummaryResponse {
val target = url("api", "usage", "summary")
.addQueryParameter("range", range)
.addQueryParameter("timeZone", timeZone)
return request("GET", target.build())
}
/** `GET /api/storage/sqlite` — hub db/wal/shm file sizes. */
suspend fun getSqliteStorageUsage(): SqliteStorageUsageResponse =
request("GET", url("api", "storage", "sqlite").build())
// ------------------------------------------------------------- devices --
/** `POST /api/devices/register` (upsert) — FCM contract (`native-companion-contract.md`). */
@@ -283,6 +283,48 @@ class HapiApiTest {
// --------------------------------------------------- health & binaries --
@Test
fun `usage summary sends range and timeZone and decodes with auth`() {
server.enqueue(
ok(
"""
{"range":{"from":null,"to":1755600000000},
"totals":{"inputTokens":10,"outputTokens":2,"cacheReadTokens":4,"cacheCreationTokens":1,
"totalTokens":12,"uncachedTokens":6,"requests":3,"sessions":2},
"daily":[],"byAgent":[],"byModel":[],"updatedAt":1755600000000}
""".trimIndent()
)
)
val summary = runBlocking { session.api.getUsageSummary(range = "all", timeZone = "Asia/Shanghai") }
val request = server.takeRequest()
val url = requireNotNull(request.requestUrl)
assertEquals("/api/usage/summary", url.encodedPath)
assertEquals("all", url.queryParameter("range"))
assertEquals("Asia/Shanghai", url.queryParameter("timeZone"))
assertEquals("Bearer $jwt", request.getHeader("Authorization"))
assertNull(summary.range.from)
assertEquals(12L, summary.totals.totalTokens)
}
@Test
fun `sqlite storage usage decodes and a 403 surfaces as coded ApiError`() {
server.enqueue(
ok("""{"path":"/x/hapi.db","databaseBytes":100,"walBytes":20,"shmBytes":4,"totalBytes":124}""")
)
val storage = runBlocking { session.api.getSqliteStorageUsage() }
assertEquals("/api/storage/sqlite", server.takeRequest().path)
assertEquals(124L, storage.totalBytes)
server.enqueue(
MockResponse().setResponseCode(403)
.setBody("""{"error":"Storage usage is only available to the hub owner"}""")
)
val error = assertFailsWith<ApiError> { runBlocking { session.api.getSqliteStorageUsage() } }
assertEquals(403, error.status)
}
@Test
fun `health is fetched without an authorization header`() {
server.enqueue(ok("""{"status":"ok","protocolVersion":1,"capabilities":{"titleSuggestion":true,"brandNew":true}}"""))
@@ -0,0 +1,76 @@
package app.hapi.protocol.wire
import kotlinx.serialization.Serializable
/**
* Wire types of the owner-only usage/storage dashboards
* (`docs/api/client-contract/rest.md#usage--storage-owner-only`;
* `UsageSummaryResponse` / `SqliteStorageUsageResponse` in
* `shared/src/apiTypes.ts`). Both endpoints answer `403` unless the caller's
* namespace is `default` (hub owner).
*
* Token counts are [Long]: `range=all` totals over a long-lived hub can pass
* 2^31.
*/
/** One aggregation bucket (a day / an agent / a model), keyed by [key]. */
@Serializable
data class UsageSummaryBucket(
/** Day buckets: `YYYY-MM-DD` in the requested timeZone; else agent/model id. */
val key: String,
val inputTokens: Long,
val outputTokens: Long,
val cacheReadTokens: Long,
val cacheCreationTokens: Long,
val totalTokens: Long,
/** Input that missed the cache: `inputTokens - cacheReadTokens`. */
val uncachedTokens: Long,
val requests: Long,
)
/** Epoch-ms window the summary covers; [from] is null for `range=all`. */
@Serializable
data class UsageSummaryRange(
val from: Long? = null,
val to: Long? = null,
)
/** Grand totals over the window (bucket counters + distinct [sessions]). */
@Serializable
data class UsageSummaryTotals(
val inputTokens: Long,
val outputTokens: Long,
val cacheReadTokens: Long,
val cacheCreationTokens: Long,
val totalTokens: Long,
val uncachedTokens: Long,
val requests: Long,
val sessions: Long,
)
/**
* `GET /api/usage/summary?range=7d|30d|all&timeZone=<IANA>`.
*
* [daily] is ascending by key and **sparse** — only days with usage appear.
* [byAgent]/[byModel] are sorted by descending [UsageSummaryBucket.totalTokens]
* (the web dashboard shows the top 8).
*/
@Serializable
data class UsageSummaryResponse(
val range: UsageSummaryRange,
val totals: UsageSummaryTotals,
val daily: List<UsageSummaryBucket>,
val byAgent: List<UsageSummaryBucket>,
val byModel: List<UsageSummaryBucket>,
val updatedAt: Long,
)
/** `GET /api/storage/sqlite` — hub database file sizes in bytes. */
@Serializable
data class SqliteStorageUsageResponse(
val path: String,
val databaseBytes: Long,
val walBytes: Long,
val shmBytes: Long,
val totalBytes: Long,
)
@@ -0,0 +1,123 @@
package app.hapi.protocol.wire
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
/**
* Decoding of the owner-only dashboard payloads (`GET /api/usage/summary`,
* `GET /api/storage/sqlite`) — shaped like `hub/src/sync/usageService.ts`
* output: sparse ascending `daily`, desc-sorted `byAgent`/`byModel`,
* `range.from = null` on `range=all`, plus the [HapiJson] unknown-key rule.
*/
class UsageDecodingTest {
@Test
fun `decodes a realistic usage summary`() {
val summary = HapiJson.decodeFromString(
UsageSummaryResponse.serializer(),
"""
{
"range": {"from": 1754995200000, "to": 1755600000000},
"totals": {
"inputTokens": 12400000,
"outputTokens": 310000,
"cacheReadTokens": 9800000,
"cacheCreationTokens": 1100000,
"totalTokens": 12710000,
"uncachedTokens": 2600000,
"requests": 1842,
"sessions": 23
},
"daily": [
{"key": "2026-08-12", "inputTokens": 1200000, "outputTokens": 40000,
"cacheReadTokens": 900000, "cacheCreationTokens": 100000,
"totalTokens": 1240000, "uncachedTokens": 300000, "requests": 210},
{"key": "2026-08-16", "inputTokens": 5100000, "outputTokens": 120000,
"cacheReadTokens": 4000000, "cacheCreationTokens": 500000,
"totalTokens": 5220000, "uncachedTokens": 1100000, "requests": 720}
],
"byAgent": [
{"key": "claude", "inputTokens": 8600000, "outputTokens": 220000,
"cacheReadTokens": 7000000, "cacheCreationTokens": 800000,
"totalTokens": 8820000, "uncachedTokens": 1600000, "requests": 1300}
],
"byModel": [
{"key": "claude-sonnet-4-5", "inputTokens": 8600000, "outputTokens": 220000,
"cacheReadTokens": 7000000, "cacheCreationTokens": 800000,
"totalTokens": 8820000, "uncachedTokens": 1600000, "requests": 1300,
"futureField": {"nested": true}}
],
"updatedAt": 1755600000000,
"unknownTopLevel": "ignored"
}
""".trimIndent(),
)
assertEquals(1754995200000, summary.range.from)
assertEquals(1755600000000, summary.range.to)
assertEquals(12710000, summary.totals.totalTokens)
assertEquals(2600000, summary.totals.uncachedTokens)
assertEquals(23, summary.totals.sessions)
assertEquals(listOf("2026-08-12", "2026-08-16"), summary.daily.map { it.key })
assertEquals(720, summary.daily[1].requests)
assertEquals("claude", summary.byAgent.single().key)
assertEquals(8820000, summary.byModel.single().totalTokens)
assertEquals(1755600000000, summary.updatedAt)
}
@Test
fun `range=all carries a null from and token counts may exceed Int range`() {
val summary = HapiJson.decodeFromString(
UsageSummaryResponse.serializer(),
"""
{
"range": {"from": null, "to": 1755600000000},
"totals": {
"inputTokens": 5100000000,
"outputTokens": 200000000,
"cacheReadTokens": 4000000000,
"cacheCreationTokens": 300000000,
"totalTokens": 5300000000,
"uncachedTokens": 1100000000,
"requests": 250000,
"sessions": 4100
},
"daily": [],
"byAgent": [],
"byModel": [],
"updatedAt": 1755600000000
}
""".trimIndent(),
)
assertNull(summary.range.from)
assertEquals(5_300_000_000, summary.totals.totalTokens)
assertTrue(summary.totals.totalTokens > Int.MAX_VALUE.toLong())
assertTrue(summary.daily.isEmpty())
}
@Test
fun `decodes sqlite storage usage`() {
val storage = HapiJson.decodeFromString(
SqliteStorageUsageResponse.serializer(),
"""
{
"path": "/home/hapi/.hapi/hapi.db",
"databaseBytes": 84930560,
"walBytes": 4194304,
"shmBytes": 32768,
"totalBytes": 89157632,
"futureField": 1
}
""".trimIndent(),
)
assertEquals("/home/hapi/.hapi/hapi.db", storage.path)
assertEquals(84_930_560, storage.databaseBytes)
assertEquals(4_194_304, storage.walBytes)
assertEquals(32_768, storage.shmBytes)
assertEquals(89_157_632, storage.totalBytes)
}
}