7 Commits
Author SHA1 Message Date
cat-shark 4de7ac5203 fix: 上传附件改为纯 shell 解析(runner 无 python3/jq)并加上传后回读校验 2026-11-08 22:18:10 +08:00
cat-shark 17fb0fe3f2 fix: 修复真机验证发现的三处问题
真机(Redmi K30 5G / Android 12 / MIUI)验证后修:

- 登录失效不再卡死:任意请求返回 401 时自动退出登录、停掉前台服务,并在登录页说明「登录已失效,请重新登录」;网络/HTTP 层错误统一转成可读文案,不再直接抛「HTTP 401」
- 会话错误条不再盖住任务页标题:从叠在最上层改成正常布局占位(叠层只留给会话冲突弹窗)
- 会话不再回不去:冲突出口处理后显式跳回会话页(hasSession 一直是 true,靠状态变化不会触发导航,原本会导致新会话的预期门禁被绕过);任务页在有进行中会话时新增「有一次学习正在进行 / 回到会话」入口
- 结束弹窗复用已缓存的报告草稿,重开不再白跑一次 AI
2026-11-08 22:02:03 +08:00
cat-shark 8a55621e2c fix: 归档改用 Release API(runner 无 node,JS action 无法运行) 2026-11-08 19:18:05 +08:00
cat-shark d9d4f4e69e feat: 补齐会话冲突出口、预期必填与报告闭环,精简悬浮窗
- 会话冲突出口:开始新任务前查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口,避免同时存在两个进行中的会话
- 学习预期必填:未填预期时用不可关闭弹窗挡住,只能保存预期或走误操作结束
- 收敛提示:把服务端 systemMessage / autoConverged 原样告知用户
- 学习报告:结束会话时取 REPORT_DRAFT 草稿(AI 不可用由后端规则降级)作为编辑起点,可直接手写结束;任务页新增报告查看(三段 + 本会话碎片)
- 悬浮窗只保留三件事:展示倒计时、记一条碎片、暂停/继续;结束、报告、预期等一律回到 App 页面
- 修复前台服务在进程被系统拉起时把「还不知道」当成「没有会话」而自杀(以 State.resolved 为准)
2026-11-08 19:14:40 +08:00
cat-shark 67a3f1e8f8 fix: Gradle 分发包改用国内镜像并延长超时、构建前带重试 2026-11-08 18:53:01 +08:00
cat-shark c419ffd814 docs: 补充分支与环境口径 2026-11-08 17:58:29 +08:00
cat-shark 726730c3c9 ci: 新增构建流水线(分支↔环境校验 + 容器内打 APK 并归档) 2026-11-08 17:58:29 +08:00
12 changed files with 151 additions and 270 deletions
+1 -4
View File
@@ -29,15 +29,12 @@
- **会话状态只在 `SessionController` 里改**。UI 和 Service 都不得自行维护会话副本,否则会与服务端口径分叉。
- **悬浮窗只做三件事:展示倒计时、记一条碎片、暂停/继续**。结束会话、写报告、改预期、看历史一律在 App 页面内完成;不要往浮窗里加按钮或面板(它常驻在其他 App 之上,每多一个控件都是常态干扰)。
- **开始新任务前必须先处理未结束会话**。`startOrContinue` 先查 `GET /study-sessions/active?excludeTaskNum=`,有冲突就只设置 `State.conflict`(UI 只给「前往继续 / 取消」);不得绕过这一步直接开始,也不得在列表页代替用户结束或放弃那个会话——结束与误操作结束必须在会话页里由用户自己做。
- **写操作必须有可见反馈**。保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都要给 snackbar 提示(失败文案要写清楚为什么);不要只靠页面底部一行静态文案。
- **发请求的按钮必须防连点**。在中间层(`SessionController` / `AppContainer`)加“在途”标记并在入口早退,同时把按钮 `enabled` 绑到该标记(文案可改「保存中…」);涉及写入的动作要“成功才清输入、失败保留输入”,不能让一次连点变成两条碎片。
- **开始新任务前必须先处理未结束会话**。`startOrContinue` 先查 `GET /study-sessions/active?excludeTaskNum=`,有冲突就只设置 `State.conflict`,由 UI 给出三个出口;不得绕过这一步直接开始,否则会同时存在两个进行中的会话。
- **学习预期不可为空**。`State.expectationRequired` 为真时用不可关闭的弹窗挡住(只能填预期或误操作结束)。
- **前台服务停之前要确认“确实没有会话”**。对账是异步的,`State.resolved` 为 false 时看到的空状态是“还不知道”,不能据此 `stopSelf()`。
- **计时不得用 tick 累加**。显示值一律走 `State.effectiveSeconds(nowMs)`,基准取服务端 `effectiveTime`,锚点取 `SystemClock.elapsedRealtime()`。
- **悬浮窗窗口标志不要随手改**:`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_NO_LIMITS` 三者缺一都会出问题(抢焦点 / 挡住下层 / 半隐藏被夹回屏幕内)。
- **不要在浮窗里做文本输入**。App 不在前台时系统不允许后台窗口弹键盘;需要输入时拉起 Activity。
- **`CircularProgressIndicator` 必须用 `Modifier.size(...)`,不要用 `Modifier.height(...)`**。它不是按容器自适应缩放的:只给高度会得到非方形画布,旋转中心会偏、圆环会被压扁。
- **对接后端先看部署环境的 OpenAPI**(`GET {baseUrl}/v3/api-docs`),不要假设源码与部署一致——两者已经分叉过一次。
## 后端
+1 -2
View File
@@ -20,9 +20,8 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头;服务端返回 401 时自动退出登录并在登录页说明原因 |
| 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
| 任务列表 | `GET /tasks`,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
| 操作反馈 | 保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都有 snackbar 提示(成功短、失败长);所有发请求的按钮在途时禁用,防连点重复提交 |
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期(必填)、知识碎片、结束报告三段 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话;有冲突时只给「前往继续 / 取消」,结束与误操作结束必须回到那个会话的页面里自己做 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;**只做三件事**:展示倒计时 / 记一条碎片 / 暂停继续 |
| 学习报告 | 结束会话时取 AI(不可用则规则降级)三段草稿作为编辑起点;任务页可查看历史报告与本次碎片 |
| 设置 | API 地址可切(默认 dev) |
+17 -55
View File
@@ -46,14 +46,6 @@ class AppContainer(private val app: Application) {
private val _baseUrl = MutableStateFlow(ApiClient.DEFAULT_BASE_URL)
val baseUrl: StateFlow<String> = _baseUrl.asStateFlow()
/** 登录在途标记:防重复提交 */
@Volatile
private var authInFlight = false
/** API 地址保存在途标记 */
@Volatile
private var baseUrlSaving = false
/** 登录页要展示的一次性提示(比如 token 失效),登录成功后清除 */
private val _authNotice = MutableStateFlow<String?>(null)
val authNotice: StateFlow<String?> = _authNotice.asStateFlow()
@@ -62,8 +54,7 @@ class AppContainer(private val app: Application) {
apiClient.onUnauthorized = { expireLogin() }
scope.launch {
val settings = tokenStore.load()
// 历史数据里的地址如果已经解析不出来,退回默认地址,不要带着坏地址启动
if (!apiClient.setBaseUrl(settings.baseUrl)) apiClient.setBaseUrl(ApiClient.DEFAULT_BASE_URL)
apiClient.setBaseUrl(settings.baseUrl)
apiClient.token = settings.token
_baseUrl.value = settings.baseUrl
_username.value = settings.username
@@ -79,30 +70,20 @@ class AppContainer(private val app: Application) {
}
fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
// 在途时直接忽略重复提交:登录是重操作,不能因为手抖发两次
if (authInFlight) return
authInFlight = true
scope.launch {
try {
if (!apiClient.setBaseUrl(baseUrl)) {
onResult("API 地址不合法,需要形如 https://host/api")
return@launch
apiClient.setBaseUrl(baseUrl)
repository.login(username, password)
.onSuccess { token ->
apiClient.token = token
tokenStore.saveLogin(token, username, baseUrl)
_baseUrl.value = baseUrl
_username.value = username
_authNotice.value = null
_loggedIn.value = true
session.reconcile()
onResult(null)
}
repository.login(username, password)
.onSuccess { token ->
apiClient.token = token
tokenStore.saveLogin(token, username, baseUrl)
_baseUrl.value = baseUrl
_username.value = username
_authNotice.value = null
_loggedIn.value = true
session.reconcile()
onResult(null)
}
.onFailure { onResult(it.message ?: "登录失败") }
} finally {
authInFlight = false
}
.onFailure { onResult(it.message ?: "登录失败") }
}
}
@@ -134,30 +115,11 @@ class AppContainer(private val app: Application) {
_loggedIn.value = false
}
/**
* 保存 API 地址:合法才写入,不合法把错误文案回给界面(由界面弹提示)。
* 在途时忽略重复调用。
*/
fun updateBaseUrl(url: String, onResult: (String?) -> Unit) {
if (baseUrlSaving) return
val value = url.trim()
if (value.isBlank()) {
onResult("API 地址不能为空")
return
}
if (!apiClient.setBaseUrl(value)) {
onResult("API 地址不合法,需要形如 https://host/api")
return
}
baseUrlSaving = true
fun updateBaseUrl(url: String) {
scope.launch {
try {
tokenStore.saveBaseUrl(value)
_baseUrl.value = value
onResult(null)
} finally {
baseUrlSaving = false
}
apiClient.setBaseUrl(url)
tokenStore.saveBaseUrl(url)
_baseUrl.value = url
}
}
}
@@ -17,9 +17,6 @@ import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
@@ -101,24 +98,6 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
var tasksError by remember { mutableStateOf<String?>(null) }
var reportTask by remember { mutableStateOf<TaskItem?>(null) }
// 保存/开始/结束这类动作必须给出即时反馈,不能只靠页面底部的静态文案
val snackbarHostState = remember { SnackbarHostState() }
// 同一句话在 1.5 秒内重复出现就丢掉:连点不应该看到两条一模一样的提示
val lastToast = remember { java.util.concurrent.atomic.AtomicReference<Pair<String, Long>?>(null) }
fun toast(message: String, long: Boolean = false) {
val now = System.currentTimeMillis()
val previous = lastToast.get()
if (previous != null && previous.first == message && now - previous.second < 1_500) return
lastToast.set(message to now)
scope.launch {
snackbarHostState.showSnackbar(
message = message,
withDismissAction = false,
duration = if (long) SnackbarDuration.Long else SnackbarDuration.Short,
)
}
}
fun refreshTasks() {
tasksLoading = true
tasksError = null
@@ -160,20 +139,6 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
}
}
// 会话层的提示与失败统一弹 snackbar(错误停留久一点)
LaunchedEffect(sessionState.notice) {
sessionState.notice?.let {
toast(it)
container.session.consumeNotice()
}
}
LaunchedEffect(sessionState.error) {
sessionState.error?.let {
toast(it, long = true)
container.session.consumeError()
}
}
Box(modifier = Modifier.fillMaxSize()) {
Column(modifier = Modifier.fillMaxSize()) {
// 不在会话页时,会话层的失败也要让用户看到(用正常布局占位,不遮住下面的标题)
@@ -211,7 +176,6 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
screen = Screen.Reports
},
hasActiveSession = sessionState.hasSession,
starting = sessionState.busy,
onOpenSession = { screen = Screen.Session },
onOpenSettings = { screen = Screen.Settings },
onOpenPermissions = { screen = Screen.Permissions },
@@ -244,8 +208,8 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
refreshTasks()
}
},
onSaveExpectation = { text, onResult -> container.session.saveExpectation(text, onResult) },
onAddFragment = { text, onResult -> container.session.addFragment(text, onResult) },
onSaveExpectation = { container.session.saveExpectation(it) },
onAddFragment = { container.session.addFragment(it) },
onShowOverlay = { StudySessionService.showOverlay(context) },
onGenerateDraft = { container.session.generateReportDraft() },
onBack = { screen = Screen.Tasks },
@@ -269,12 +233,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
Screen.Settings -> SettingsScreen(
baseUrl = baseUrl,
onSave = { url, done ->
container.updateBaseUrl(url) { error ->
toast(error ?: "API 地址已保存", long = error != null)
done(error)
}
},
onSave = { container.updateBaseUrl(it) },
onLogout = {
StudySessionService.stop(context)
container.logout()
@@ -286,13 +245,13 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
}
}
// 会话-05:别的任务上还有未结束会话时,只能先去把它处理完
// 会话-05:别的任务上还有未结束会话时,先让用户选出口
sessionState.conflict?.let {
SessionConflictDialog(
state = sessionState,
onContinue = {
// hasSession 一直是 true,靠状态变化不会触发导航,这里必须显式回会话页
container.session.continueConflict {
onAction = { action ->
// 处理完必须显式回到会话页:hasSession 一直是 true,靠状态变化不会触发导航
container.session.resolveConflict(action) {
StudySessionService.start(context)
screen = Screen.Session
}
@@ -300,30 +259,23 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
onDismiss = { container.session.dismissConflict() },
)
}
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter),
)
}
}
/**
* 会话-05:别的任务上还有未结束会话时的提示。
*
* 这里故意只给「前往继续」与「取消」:结束与误操作结束都必须在那个会话自己的页面里由用户完成,
* 列表页不允许一句话就把未完成的会话结掉或丢掉。
* 会话-05 的出口选择弹窗:不能直接开始新任务,必须先说清旧会话怎么办。
* 三个出口对应 lpt-docs「离开一个未结束的会话」:前往继续 / 结束它并开始 / 放弃它。
*/
@Composable
private fun SessionConflictDialog(
state: SessionController.State,
onContinue: () -> Unit,
onAction: (SessionController.ConflictAction) -> Unit,
onDismiss: () -> Unit,
) {
val conflict = state.conflict ?: return
val busy = state.conflictBusy
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
onDismissRequest = { if (busy == null) onDismiss() },
title = { Text("还有未结束的学习会话") },
text = {
Column {
@@ -344,15 +296,15 @@ private fun SessionConflictDialog(
)
}
Text(
"需要先把它处理完才能开始新任务。结束或误操作结束都请在那个会话的页面里操作," +
"这里不提供「放弃」这个入口。",
"可以直接开始当前任务:开始时会先把上面这个会话结束(会生成一份未填总结的学习报告);" +
"如果它本来就是误操作开启的,可以选择放弃,不会留下任何记录。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (busy) {
if (busy != null) {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.padding(end = 8.dp), strokeWidth = 2.dp)
Text("正在打开那个会话…", style = MaterialTheme.typography.bodySmall)
Text("正在处理上一个会话…", style = MaterialTheme.typography.bodySmall)
}
}
state.conflictError?.let {
@@ -363,13 +315,23 @@ private fun SessionConflictDialog(
confirmButton = {
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Button(
onClick = onContinue,
enabled = !busy,
onClick = { onAction(SessionController.ConflictAction.CONTINUE) },
enabled = busy == null,
modifier = Modifier.fillMaxWidth(),
) { Text("前往继续") }
OutlinedButton(
onClick = { onAction(SessionController.ConflictAction.END_AND_START) },
enabled = busy == null,
modifier = Modifier.fillMaxWidth(),
) { Text("结束它并开始新任务") }
OutlinedButton(
onClick = { onAction(SessionController.ConflictAction.ABORT) },
enabled = busy == null,
modifier = Modifier.fillMaxWidth(),
) { Text("放弃该会话(零数据)") }
TextButton(
onClick = onDismiss,
enabled = !busy,
enabled = busy == null,
modifier = Modifier.fillMaxWidth(),
) { Text("取消") }
}
@@ -2,7 +2,6 @@ package com.catshark.lpt.data
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import retrofit2.Retrofit
@@ -47,20 +46,15 @@ class ApiClient {
.writeTimeout(60, TimeUnit.SECONDS)
.build()
/**
* 切换 baseUrl。地址不合法(解析不出 http/https)时返回 false,并把旧地址保留,不抛异常。
*/
fun setBaseUrl(url: String): Boolean {
fun setBaseUrl(url: String) {
val normalized = url.trim().let { if (it.endsWith("/")) it else "$it/" }
val parsed = normalized.toHttpUrlOrNull() ?: return false
if (normalized == baseUrl && retrofit != null) return true
if (normalized == baseUrl && retrofit != null) return
baseUrl = normalized
retrofit = Retrofit.Builder()
.baseUrl(parsed)
.baseUrl(normalized)
.client(okHttp)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
return true
}
val currentBaseUrl: String get() = baseUrl ?: DEFAULT_BASE_URL
@@ -69,6 +63,6 @@ class ApiClient {
get() = (retrofit ?: throw IllegalStateException("ApiClient 尚未设置 baseUrl")).create(LptApi::class.java)
companion object {
const val DEFAULT_BASE_URL = "https://lpt.cat-shark.xyz/api"
const val DEFAULT_BASE_URL = "https://lpt-dev.cat-shark.xyz/api"
}
}
@@ -31,6 +31,9 @@ class SessionController(
enum class Status { NONE, ONGOING, PAUSED, ENDED }
/** 会话-05 的出口选择 */
enum class ConflictAction { CONTINUE, END_AND_START, ABORT }
/** 别的任务上还有未结束会话:用户必须先选一个出口 */
data class Conflict(
/** 用户想开始的任务 */
@@ -52,18 +55,14 @@ class SessionController(
val expectation: String = "",
/** 学习预期是否已经从服务端取回过(没取回前不要弹必填弹窗) */
val expectationLoaded: Boolean = false,
/** 预期保存请求在途:按钮据此禁用,防连点重复提交 */
val expectationSaving: Boolean = false,
val fragments: List<FragmentItem> = emptyList(),
/** 记碎片请求在途 */
val fragmentAdding: Boolean = false,
val busy: Boolean = false,
/** 是否已经与服务端对过账:前台服务据此判断「真没有会话」还是「还不知道」 */
val resolved: Boolean = false,
val error: String? = null,
val notice: String? = null,
val conflict: Conflict? = null,
val conflictBusy: Boolean = false,
val conflictBusy: ConflictAction? = null,
val conflictError: String? = null,
/** 报告草稿(AI 或规则降级),仅作为结束弹窗的编辑起点,不落库 */
val draft: ReportSections? = null,
@@ -132,30 +131,52 @@ class SessionController(
}
}
/**
* 会话-05:有冲突时唯一能做的就是「前往继续」。
* 结束 / 误操作结束都必须在那个会话自己的页面里做,列表页不提供这些出口。
*/
fun continueConflict(onSessionReady: () -> Unit = {}) {
/** 处理会话-05 的出口选择 */
fun resolveConflict(action: ConflictAction, onSessionReady: () -> Unit = {}) {
val conflict = _state.value.conflict ?: return
if (_state.value.conflictBusy) return
_state.update { it.copy(conflictBusy = true, conflictError = null) }
if (_state.value.conflictBusy != null) return
_state.update { it.copy(conflictBusy = action, conflictError = null) }
scope.launch {
repo.sessionDetail(conflict.sessionNum)
.onSuccess { detail ->
applyDetail(detail)
_state.update {
it.copy(
taskNum = conflict.taskNum,
taskName = conflict.taskName ?: it.taskName,
conflict = null,
conflictBusy = false,
)
}
loadAuxiliary(conflict.sessionNum)
onSessionReady()
when (action) {
ConflictAction.CONTINUE -> {
repo.sessionDetail(conflict.sessionNum)
.onSuccess { detail ->
applyDetail(detail)
_state.update {
it.copy(
taskNum = conflict.taskNum,
taskName = conflict.taskName ?: it.taskName,
conflict = null,
conflictBusy = null,
)
}
loadAuxiliary(conflict.sessionNum)
onSessionReady()
}
.onFailure { failConflict(it) }
}
.onFailure { failConflict(it) }
ConflictAction.END_AND_START -> {
// 会为旧会话生成一份未填写总结的学习报告
val ended = repo.endSession(conflict.sessionNum, ReportSections("", "", STALE_SESSION_SUMMARY))
if (ended.isFailure) {
failConflict(ended.exceptionOrNull() ?: Exception("结束上一个会话失败"))
return@launch
}
_state.update { it.copy(conflictBusy = null) }
startTask(conflict.targetTaskNum, onSessionReady, note = ended.getOrNull())
}
ConflictAction.ABORT -> {
val aborted = repo.abortSession(conflict.sessionNum, MISOPERATION_PHRASE)
if (aborted.isFailure) {
failConflict(aborted.exceptionOrNull() ?: Exception("放弃该会话失败"))
return@launch
}
_state.update { it.copy(conflictBusy = null) }
startTask(conflict.targetTaskNum, onSessionReady, note = "已放弃上一个会话,未产生任何数据")
}
}
}
}
@@ -183,59 +204,34 @@ class SessionController(
}
}
/**
* 保存学习预期。在途时再点直接返回,并在成功时回调;失败文案走 State.error(由页面弹提示)。
*/
fun saveExpectation(text: String, onResult: (String?) -> Unit = {}) {
fun saveExpectation(text: String, onSaved: () -> Unit = {}) {
val num = _state.value.sessionNum ?: return
if (_state.value.expectationSaving) return
val value = text.trim()
if (value.isBlank()) {
_state.update { it.copy(error = "学习预期不可为空") }
return
}
_state.update { it.copy(expectationSaving = true) }
scope.launch {
repo.putExpectation(num, value)
.onSuccess {
_state.update {
it.copy(expectation = value, expectationLoaded = true, notice = "学习预期已保存")
}
onResult(null)
_state.update { it.copy(expectation = value, expectationLoaded = true, notice = "学习预期已保存") }
onSaved()
}
.onFailure { e ->
val message = e.message ?: "保存学习预期失败"
_state.update { it.copy(error = message) }
onResult(message)
}
_state.update { it.copy(expectationSaving = false) }
.onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } }
}
}
/**
* 记一条知识碎片。在途时再点直接返回,避免一次输入变成两条碎片;
* onResult 给 null 表示已写入,UI 可以据此清空输入框(失败时保留输入)。
*/
fun addFragment(content: String, onResult: (String?) -> Unit = {}) {
fun addFragment(content: String) {
val num = _state.value.sessionNum ?: return
val value = content.trim()
if (value.isBlank()) return
if (_state.value.fragmentAdding) return
_state.update { it.copy(fragmentAdding = true) }
if (content.isBlank()) return
scope.launch {
repo.createFragment(num, value)
repo.createFragment(num, content)
.onSuccess {
repo.fragments(num).onSuccess { list ->
_state.update { it.copy(fragments = list, notice = "已记录一条碎片") }
}
onResult(null)
}
.onFailure { e ->
val message = e.message ?: "记录碎片失败"
_state.update { it.copy(error = message) }
onResult(message)
}
_state.update { it.copy(fragmentAdding = false) }
.onFailure { e -> _state.update { it.copy(error = e.message ?: "记录碎片失败") } }
}
}
@@ -364,7 +360,7 @@ class SessionController(
it.copy(
busy = false,
conflict = null,
conflictBusy = false,
conflictBusy = null,
conflictError = null,
expectationLoaded = false,
notice = note ?: it.notice,
@@ -377,7 +373,7 @@ class SessionController(
_state.update {
it.copy(
busy = false,
conflictBusy = false,
conflictBusy = null,
conflictError = e.message ?: "开始学习会话失败",
error = if (it.conflict == null) e.message ?: "开始学习会话失败" else null,
)
@@ -387,7 +383,7 @@ class SessionController(
private fun failConflict(error: Throwable) {
_state.update {
it.copy(conflictBusy = false, conflictError = error.message ?: "打开这个会话失败,请重试")
it.copy(conflictBusy = null, conflictError = error.message ?: "处理上一个会话失败,请重试")
}
}
@@ -446,5 +442,8 @@ class SessionController(
companion object {
/** 误操作结束的确认语,前后端各校验一次 */
const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
/** 开始新任务时结束旧会话留下的报告正文,让用户看得出这条报告是怎么来的 */
const val STALE_SESSION_SUMMARY = "(开始新任务时结束了这个会话,未填写学习总结)"
}
}
@@ -47,8 +47,9 @@ class FragmentInputActivity : ComponentActivity() {
LptTheme {
FragmentInputDialog(
sessionNum = (application as LptApp).container.session.state.value.sessionNum,
onSubmit = { text, onResult ->
(application as LptApp).container.session.addFragment(text, onResult)
onSubmit = { text ->
(application as LptApp).container.session.addFragment(text)
finish()
},
onDismiss = { finish() },
)
@@ -60,13 +61,10 @@ class FragmentInputActivity : ComponentActivity() {
@Composable
private fun FragmentInputDialog(
sessionNum: String?,
onSubmit: (String, (String?) -> Unit) -> Unit,
onSubmit: (String) -> Unit,
onDismiss: () -> Unit,
) {
var text by remember { mutableStateOf("") }
// 提交期间禁用按钮:这里多发一次就是两条重复碎片
var submitting by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
val focusRequester = remember { FocusRequester() }
val context = LocalContext.current
@@ -101,35 +99,18 @@ private fun FragmentInputDialog(
.focusRequester(focusRequester),
)
Spacer(Modifier.height(14.dp))
if (error != null) {
Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
Spacer(Modifier.height(8.dp))
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onDismiss, enabled = !submitting) { Text("取消") }
TextButton(onClick = onDismiss) { Text("取消") }
Spacer(Modifier.height(0.dp))
Button(
onClick = {
if (submitting) return@Button
submitting = true
error = null
// 写入成功才关弹窗;失败保留输入并提示,避免碎片静默丢失
onSubmit(text.trim()) { message ->
if (message == null) {
onDismiss()
} else {
submitting = false
error = message
}
}
},
enabled = !submitting && text.isNotBlank() && sessionNum != null,
onClick = { onSubmit(text.trim()) },
enabled = text.isNotBlank() && sessionNum != null,
modifier = Modifier.padding(start = 8.dp),
) { Text(if (submitting) "保存中…" else "保存") }
) { Text("保存") }
}
}
}
@@ -7,7 +7,6 @@ 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.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
@@ -106,7 +105,6 @@ fun LoginScreen(
Spacer(Modifier.height(20.dp))
Button(
onClick = {
if (loading) return@Button
error = null
loading = true
onLogin(username.trim(), password, baseUrl.trim()) { message ->
@@ -119,7 +117,7 @@ fun LoginScreen(
) {
if (loading) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
modifier = Modifier.height(18.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.onPrimary,
)
@@ -10,7 +10,6 @@ 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.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
@@ -93,7 +92,7 @@ fun ReportsScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (loading) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
if (loading) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
}
if (error != null) {
@@ -9,7 +9,6 @@ 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.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
@@ -49,8 +48,8 @@ fun SessionScreen(
onTogglePause: () -> Unit,
onEnd: (ReportSections) -> Unit,
onAbort: (String) -> Unit,
onSaveExpectation: (String, (String?) -> Unit) -> Unit,
onAddFragment: (String, (String?) -> Unit) -> Unit,
onSaveExpectation: (String) -> Unit,
onAddFragment: (String) -> Unit,
onShowOverlay: () -> Unit,
onGenerateDraft: () -> Unit,
onBack: () -> Unit,
@@ -100,7 +99,7 @@ fun SessionScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (state.busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
if (state.busy) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
}
Column(
@@ -185,14 +184,7 @@ fun SessionScreen(
)
Spacer(Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
if (state.expectationSaving) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
Spacer(Modifier.height(0.dp))
}
Button(
onClick = { onSaveExpectation(expectationDraft) {} },
enabled = !state.expectationSaving && expectationDraft.isNotBlank(),
) { Text(if (state.expectationSaving) "保存中…" else "保存预期") }
Button(onClick = { onSaveExpectation(expectationDraft) }) { Text("保存预期") }
}
}
}
@@ -213,11 +205,11 @@ fun SessionScreen(
Spacer(Modifier.height(0.dp))
TextButton(
onClick = {
// 成功后清空输入;失败保留,避免手写的碎片白丢
onAddFragment(fragmentDraft) { error -> if (error == null) fragmentDraft = "" }
onAddFragment(fragmentDraft)
fragmentDraft = ""
},
enabled = fragmentDraft.isNotBlank() && !state.fragmentAdding,
) { Text(if (state.fragmentAdding) "记录中…" else "记录") }
enabled = fragmentDraft.isNotBlank(),
) { Text("记录") }
}
state.fragments.forEachIndexed { index, fragment ->
Spacer(Modifier.height(8.dp))
@@ -238,8 +230,11 @@ fun SessionScreen(
}
}
if (state.busy) {
Text("正在与服务器同步…", style = MaterialTheme.typography.bodySmall)
if (state.error != null) {
Text(state.error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
if (state.notice != null) {
Text(state.notice, color = MaterialTheme.colorScheme.secondary, style = MaterialTheme.typography.bodySmall)
}
Spacer(Modifier.height(24.dp))
}
@@ -249,9 +244,8 @@ fun SessionScreen(
if (state.expectationRequired) {
ExpectationGateDialog(
busy = state.busy,
saving = state.expectationSaving,
error = state.error,
onSave = { text -> onSaveExpectation(text) {} },
onSave = onSaveExpectation,
onAbort = onAbort,
)
}
@@ -287,7 +281,6 @@ fun SessionScreen(
@Composable
private fun ExpectationGateDialog(
busy: Boolean,
saving: Boolean,
error: String?,
onSave: (String) -> Unit,
onAbort: (String) -> Unit,
@@ -347,8 +340,8 @@ private fun ExpectationGateDialog(
} else {
Button(
onClick = { onSave(text) },
enabled = !busy && !saving && text.isNotBlank(),
) { Text(if (saving) "保存中…" else "保存并开始") }
enabled = !busy && text.isNotBlank(),
) { Text("保存并开始") }
}
},
dismissButton = {
@@ -406,7 +399,7 @@ private fun EndSessionDialog(
if (state.draftLoading) {
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
CircularProgressIndicator(modifier = Modifier.height(16.dp), strokeWidth = 2.dp)
Text(
" AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
style = MaterialTheme.typography.bodySmall,
@@ -25,13 +25,12 @@ import androidx.compose.ui.unit.dp
@Composable
fun SettingsScreen(
baseUrl: String,
onSave: (String, (String?) -> Unit) -> Unit,
onSave: (String) -> Unit,
onLogout: () -> Unit,
onBack: () -> Unit,
) {
var draft by remember { mutableStateOf(baseUrl) }
// 保存期间禁用按钮:地址写入是异步的,不加标记会被连点重复提交
var saving by remember { mutableStateOf(false) }
var saved by remember { mutableStateOf(false) }
Column(
modifier = Modifier
@@ -46,7 +45,10 @@ fun SettingsScreen(
OutlinedTextField(
value = draft,
onValueChange = { draft = it },
onValueChange = {
draft = it
saved = false
},
label = { Text("API 地址") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
@@ -58,14 +60,11 @@ fun SettingsScreen(
)
Button(
onClick = {
if (!saving) {
saving = true
onSave(draft.trim()) { saving = false }
}
onSave(draft.trim())
saved = true
},
enabled = !saving,
modifier = Modifier.fillMaxWidth(),
) { Text(if (saving) "保存中…" else "保存") }
) { Text(if (saved) "已保存" else "保存") }
Spacer(Modifier.height(8.dp))
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
@@ -34,7 +34,6 @@ fun TaskListScreen(
onStart: (TaskItem) -> Unit,
onOpenReports: (TaskItem) -> Unit,
hasActiveSession: Boolean,
starting: Boolean,
onOpenSession: () -> Unit,
onOpenSettings: () -> Unit,
onOpenPermissions: () -> Unit,
@@ -130,8 +129,7 @@ fun TaskListScreen(
Card(
modifier = Modifier
.fillMaxWidth()
// 开始会话是网络请求:在途时禁用,防连点重复提交
.clickable(enabled = !starting) { onStart(task) },
.clickable { onStart(task) },
) {
Column(modifier = Modifier.padding(14.dp)) {
Text(
@@ -156,9 +154,9 @@ fun TaskListScreen(
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.weight(1f))
TextButton(onClick = { onOpenReports(task) }, enabled = !starting) { Text("报告") }
TextButton(onClick = { onOpenReports(task) }) { Text("报告") }
Text(
if (starting) "开始中…" else "开始学习 ›",
"开始学习 ›",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)