fix: 修复真机验证发现的三处问题

真机(Redmi K30 5G / Android 12 / MIUI)验证后修:

- 登录失效不再卡死:任意请求返回 401 时自动退出登录、停掉前台服务,并在登录页说明「登录已失效,请重新登录」;网络/HTTP 层错误统一转成可读文案,不再直接抛「HTTP 401」
- 会话错误条不再盖住任务页标题:从叠在最上层改成正常布局占位(叠层只留给会话冲突弹窗)
- 会话不再回不去:冲突出口处理后显式跳回会话页(hasSession 一直是 true,靠状态变化不会触发导航,原本会导致新会话的预期门禁被绕过);任务页在有进行中会话时新增「有一次学习正在进行 / 回到会话」入口
- 结束弹窗复用已缓存的报告草稿,重开不再白跑一次 AI
This commit is contained in:
2026-11-08 22:02:03 +08:00
parent 8a55621e2c
commit 17fb0fe3f2
8 changed files with 140 additions and 41 deletions
+29 -5
View File
@@ -4,6 +4,7 @@ import android.app.Application
import com.catshark.lpt.data.ApiClient
import com.catshark.lpt.data.LptRepository
import com.catshark.lpt.data.TokenStore
import com.catshark.lpt.service.StudySessionService
import com.catshark.lpt.session.SessionController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -45,7 +46,12 @@ class AppContainer(private val app: Application) {
private val _baseUrl = MutableStateFlow(ApiClient.DEFAULT_BASE_URL)
val baseUrl: StateFlow<String> = _baseUrl.asStateFlow()
/** 登录页要展示的一次性提示(比如 token 失效),登录成功后清除 */
private val _authNotice = MutableStateFlow<String?>(null)
val authNotice: StateFlow<String?> = _authNotice.asStateFlow()
init {
apiClient.onUnauthorized = { expireLogin() }
scope.launch {
val settings = tokenStore.load()
apiClient.setBaseUrl(settings.baseUrl)
@@ -72,6 +78,7 @@ class AppContainer(private val app: Application) {
tokenStore.saveLogin(token, username, baseUrl)
_baseUrl.value = baseUrl
_username.value = username
_authNotice.value = null
_loggedIn.value = true
session.reconcile()
onResult(null)
@@ -83,14 +90,31 @@ class AppContainer(private val app: Application) {
fun logout() {
scope.launch {
repository.logout()
tokenStore.clearLogin()
apiClient.token = null
session.clear()
_loggedIn.value = false
session.markResolved()
clearLoginState()
}
}
/**
* token 失效:本地直接退出登录并回登录页。
* 不调 /logout(这个 token 已经无效了),也不再发请求,避免递归。
*/
private fun expireLogin() {
if (!_loggedIn.value) return
scope.launch {
_authNotice.value = "登录已失效,请重新登录"
StudySessionService.stop(app)
clearLoginState()
}
}
private suspend fun clearLoginState() {
tokenStore.clearLogin()
apiClient.token = null
session.clear()
session.markResolved()
_loggedIn.value = false
}
fun updateBaseUrl(url: String) {
scope.launch {
apiClient.setBaseUrl(url)
@@ -89,6 +89,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
val username by container.username.collectAsState()
val baseUrl by container.baseUrl.collectAsState()
val sessionState by container.session.state.collectAsState()
val authNotice by container.authNotice.collectAsState()
val openEnd by openEndRequest
var screen by remember { mutableStateOf(Screen.Tasks) }
@@ -139,10 +140,22 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
}
Box(modifier = Modifier.fillMaxSize()) {
when {
Column(modifier = Modifier.fillMaxSize()) {
// 不在会话页时,会话层的失败也要让用户看到(用正常布局占位,不遮住下面的标题)
if (screen != Screen.Session) {
sessionState.error?.let { message ->
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
}
}
Box(modifier = Modifier.weight(1f)) {
when {
!ready -> LoadingScreen()
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
!loggedIn -> LoginScreen(
initialBaseUrl = baseUrl,
notice = authNotice,
) { user, password, url, onResult ->
container.login(user, password, url, onResult)
}
@@ -162,6 +175,8 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
reportTask = task
screen = Screen.Reports
},
hasActiveSession = sessionState.hasSession,
onOpenSession = { screen = Screen.Session },
onOpenSettings = { screen = Screen.Settings },
onOpenPermissions = { screen = Screen.Permissions },
onLogout = {
@@ -226,6 +241,8 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
onBack = { screen = Screen.Tasks },
)
}
}
}
}
// 会话-05:别的任务上还有未结束会话时,先让用户选出口
@@ -233,18 +250,15 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
SessionConflictDialog(
state = sessionState,
onAction = { action ->
container.session.resolveConflict(action) { StudySessionService.start(context) }
// 处理完必须显式回到会话页:hasSession 一直是 true,靠状态变化不会触发导航
container.session.resolveConflict(action) {
StudySessionService.start(context)
screen = Screen.Session
}
},
onDismiss = { container.session.dismissConflict() },
)
}
// 不在会话页时,会话层的失败也要让用户看到
if (screen != Screen.Session) {
sessionState.error?.let { message ->
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
}
}
}
}
@@ -16,6 +16,10 @@ class ApiClient {
@Volatile
var token: String? = null
/** 服务端返回 401(token 失效)时的回调,由 AppContainer 接管成“退出登录” */
@Volatile
var onUnauthorized: (() -> Unit)? = null
@Volatile
private var baseUrl: String? = null
@@ -32,7 +36,10 @@ class ApiClient {
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
token?.takeIf { it.isNotBlank() }?.let { builder.header("satoken", it) }
chain.proceed(builder.build())
val response = chain.proceed(builder.build())
// token 失效:登录接口本身的 401 由登录页自己处理,这里只处理已登录后的失效
if (response.code == 401) onUnauthorized?.invoke()
response
}
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS)
@@ -19,27 +19,40 @@ class LptRepository(private val apiClient: ApiClient) {
return env.data as T
}
/** 统一的请求包装:网络/HTTP 层错误都换成用户看得懂的话 */
private inline fun <T> call(block: () -> T): Result<T> = runCatching(block).friendly()
/**
* 把 HTTP 层错误换成用户看得懂的话。
* 部署环境的 dev 后端比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
* 把网络/HTTP 层错误换成用户看得懂的话。
* 部署环境的 dev 后端可能比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
*/
private fun <T> Result<T>.friendly(action: String): Result<T> {
private fun <T> Result<T>.friendly(action: String? = null): Result<T> {
val error = exceptionOrNull()
return if (error is HttpException) {
Result.failure(ApiException("$action 不可用(HTTP ${error.code()}),当前后端可能还没上这个接口"))
} else {
this
return when {
error is HttpException -> {
val detail = "HTTP ${error.code()}"
val message = if (action != null) {
"$action 不可用($detail),当前后端可能还没上这个接口"
} else {
"请求失败($detail),请稍后重试"
}
Result.failure(ApiException(message))
}
error is java.io.IOException -> Result.failure(ApiException("网络不可用,请检查网络或设置里的 API 地址"))
else -> this
}
}
suspend fun login(username: String, password: String): Result<String> = runCatching {
suspend fun login(username: String, password: String): Result<String> = call {
val env = api.login(LoginRequest(username, password))
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "登录失败")
extractToken(env.data)?.takeIf { it.isNotBlank() } ?: throw ApiException("登录响应缺少 token")
}
suspend fun logout(): Result<Unit> = runCatching { api.logout() }
suspend fun logout(): Result<Unit> = call { api.logout() }
suspend fun tasks(): Result<List<TaskItem>> = runCatching {
suspend fun tasks(): Result<List<TaskItem>> = call {
envelope(api.tasks(), "获取任务").records
}
@@ -49,41 +62,41 @@ class LptRepository(private val apiClient: ApiClient) {
* - 传入 `excludeTaskNum` 时,属于该任务的会话不算冲突(后端直接返回 null);
* - 业务失败(code != 200)与网络异常一律上抛:调用方需要区分「确实没有会话」和「没问到」。
*/
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = runCatching {
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = call {
val env = api.activeSession(excludeTaskNum)
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "查询未结束会话失败")
env.data?.takeIf { it.sessionNum.isNotBlank() }
}
suspend fun startOrContinue(taskNum: String): Result<SessionDetail> = runCatching {
suspend fun startOrContinue(taskNum: String): Result<SessionDetail> = call {
envelope(api.startOrContinue(taskNum), "开始学习会话")
}
suspend fun sessionDetail(sessionNum: String): Result<SessionDetail> = runCatching {
suspend fun sessionDetail(sessionNum: String): Result<SessionDetail> = call {
envelope(api.sessionDetail(sessionNum), "获取会话")
}
suspend fun getExpectation(sessionNum: String): Result<String> = runCatching {
suspend fun getExpectation(sessionNum: String): Result<String> = call {
api.getExpectation(sessionNum).takeIf { it.code == 200 }?.data?.description.orEmpty()
}
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = runCatching {
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = call {
envelope(api.putExpectation(sessionNum, ExpectationRequest(description)), "保存学习预期")
Unit
}
suspend fun continueSession(sessionNum: String): Result<Unit> = runCatching {
suspend fun continueSession(sessionNum: String): Result<Unit> = call {
envelope(api.continueSession(sessionNum), "继续学习会话")
Unit
}
suspend fun pauseSession(sessionNum: String): Result<Unit> = runCatching {
suspend fun pauseSession(sessionNum: String): Result<Unit> = call {
envelope(api.pauseSession(sessionNum), "暂停学习会话")
Unit
}
/** 结束会话;后端可能返回一条提示(如有效时间不足),作为 message 带回 */
suspend fun endSession(sessionNum: String, sections: ReportSections): Result<String?> = runCatching {
suspend fun endSession(sessionNum: String, sections: ReportSections): Result<String?> = call {
val env = api.endSession(
sessionNum,
EndSessionRequest(
@@ -97,12 +110,12 @@ class LptRepository(private val apiClient: ApiClient) {
env.message
}
suspend fun abortSession(sessionNum: String, confirmation: String): Result<Unit> = runCatching {
suspend fun abortSession(sessionNum: String, confirmation: String): Result<Unit> = call {
envelope(api.abortSession(sessionNum, AbortRequest(confirmation)), "误操作结束")
Unit
}
suspend fun createFragment(sessionNum: String, content: String): Result<Unit> = runCatching {
suspend fun createFragment(sessionNum: String, content: String): Result<Unit> = call {
envelope(
api.createFragment(CreateFragmentRequest(contextNum = sessionNum, sessionNum = sessionNum, content = content)),
"记录碎片",
@@ -110,7 +123,7 @@ class LptRepository(private val apiClient: ApiClient) {
Unit
}
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = runCatching {
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = call {
api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
}
@@ -30,6 +30,7 @@ import androidx.compose.ui.unit.dp
@Composable
fun LoginScreen(
initialBaseUrl: String,
notice: String? = null,
onLogin: (username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) -> Unit,
) {
var username by remember { mutableStateOf("") }
@@ -55,6 +56,16 @@ fun LoginScreen(
)
Spacer(Modifier.height(24.dp))
if (notice != null) {
// 一直留到下次登录成功:否则用户回到登录页时已经看不到原因了
Text(
notice,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(8.dp))
}
OutlinedTextField(
value = username,
onValueChange = { username = it },
@@ -374,7 +374,8 @@ private fun EndSessionDialog(
fun currentSections(): ReportSections = ReportSections(summary, verdict, free)
LaunchedEffect(Unit) {
if (currentSections().allBlank && hasFragments) onGenerateDraft()
// 已经有缓存草稿时直接用它,不要为了重开弹窗再化一次 AI
if (currentSections().allBlank && hasFragments && state.draft == null) onGenerateDraft()
}
// 草稿是整段覆盖的:它就是这次生成的编辑起点
LaunchedEffect(state.draft) {
@@ -33,6 +33,8 @@ fun TaskListScreen(
onRefresh: () -> Unit,
onStart: (TaskItem) -> Unit,
onOpenReports: (TaskItem) -> Unit,
hasActiveSession: Boolean,
onOpenSession: () -> Unit,
onOpenSettings: () -> Unit,
onOpenPermissions: () -> Unit,
onLogout: () -> Unit,
@@ -56,6 +58,33 @@ fun TaskListScreen(
TextButton(onClick = onOpenSettings) { Text("设置") }
}
if (hasActiveSession) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp)
.clickable { onOpenSession() },
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"有一次学习正在进行",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
Text(
"回到会话 ›",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
if (error != null) {
Row(
modifier = Modifier