feat: 补齐会话冲突出口、预期必填与报告闭环,精简悬浮窗
- 会话冲突出口:开始新任务前查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口,避免同时存在两个进行中的会话 - 学习预期必填:未填预期时用不可关闭弹窗挡住,只能保存预期或走误操作结束 - 收敛提示:把服务端 systemMessage / autoConverged 原样告知用户 - 学习报告:结束会话时取 REPORT_DRAFT 草稿(AI 不可用由后端规则降级)作为编辑起点,可直接手写结束;任务页新增报告查看(三段 + 本会话碎片) - 悬浮窗只保留三件事:展示倒计时、记一条碎片、暂停/继续;结束、报告、预期等一律回到 App 页面 - 修复前台服务在进程被系统拉起时把「还不知道」当成「没有会话」而自杀(以 State.resolved 为准)
This commit is contained in:
@@ -54,7 +54,12 @@ class AppContainer(private val app: Application) {
|
||||
_username.value = settings.username
|
||||
_loggedIn.value = !settings.token.isNullOrBlank()
|
||||
_ready.value = true
|
||||
if (_loggedIn.value) session.reconcile()
|
||||
if (_loggedIn.value) {
|
||||
session.reconcile()
|
||||
} else {
|
||||
// 未登录时没有会话可查:直接标记已知状态,避免前台服务一直等对账
|
||||
session.markResolved()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +87,7 @@ class AppContainer(private val app: Application) {
|
||||
apiClient.token = null
|
||||
session.clear()
|
||||
_loggedIn.value = false
|
||||
session.markResolved()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,21 @@ import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
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.padding
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
@@ -22,10 +31,13 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.data.TaskItem
|
||||
import com.catshark.lpt.service.StudySessionService
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.ui.LoginScreen
|
||||
import com.catshark.lpt.ui.PermissionScreen
|
||||
import com.catshark.lpt.ui.ReportsScreen
|
||||
import com.catshark.lpt.ui.SessionScreen
|
||||
import com.catshark.lpt.ui.SettingsScreen
|
||||
import com.catshark.lpt.ui.TaskListScreen
|
||||
@@ -64,7 +76,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Screen { Tasks, Session, Permissions, Settings }
|
||||
private enum class Screen { Tasks, Session, Reports, Permissions, Settings }
|
||||
|
||||
@Composable
|
||||
private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolean>) {
|
||||
@@ -83,6 +95,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) }
|
||||
var tasksLoading by remember { mutableStateOf(false) }
|
||||
var tasksError by remember { mutableStateOf<String?>(null) }
|
||||
var reportTask by remember { mutableStateOf<TaskItem?>(null) }
|
||||
|
||||
fun refreshTasks() {
|
||||
tasksLoading = true
|
||||
@@ -125,73 +138,213 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
!ready -> LoadingScreen()
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
when {
|
||||
!ready -> LoadingScreen()
|
||||
|
||||
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
|
||||
container.login(user, password, url, onResult)
|
||||
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
|
||||
container.login(user, password, url, onResult)
|
||||
}
|
||||
|
||||
else -> when (screen) {
|
||||
Screen.Tasks -> TaskListScreen(
|
||||
tasks = tasks,
|
||||
loading = tasksLoading,
|
||||
error = tasksError,
|
||||
username = username,
|
||||
onRefresh = { refreshTasks() },
|
||||
onStart = { task ->
|
||||
container.session.startOrContinue(task.taskNum) {
|
||||
StudySessionService.start(context)
|
||||
}
|
||||
},
|
||||
onOpenReports = { task ->
|
||||
reportTask = task
|
||||
screen = Screen.Reports
|
||||
},
|
||||
onOpenSettings = { screen = Screen.Settings },
|
||||
onOpenPermissions = { screen = Screen.Permissions },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
)
|
||||
|
||||
Screen.Session -> SessionScreen(
|
||||
state = sessionState,
|
||||
openEndDialog = openEnd,
|
||||
onConsumeOpenEnd = { openEndRequest.value = false },
|
||||
onTogglePause = {
|
||||
if (sessionState.status == SessionController.Status.ONGOING) {
|
||||
container.session.pause()
|
||||
} else {
|
||||
container.session.resume()
|
||||
}
|
||||
},
|
||||
onEnd = { sections ->
|
||||
container.session.end(sections) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onAbort = { phrase ->
|
||||
container.session.abort(phrase) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onSaveExpectation = { container.session.saveExpectation(it) },
|
||||
onAddFragment = { container.session.addFragment(it) },
|
||||
onShowOverlay = { StudySessionService.showOverlay(context) },
|
||||
onGenerateDraft = { container.session.generateReportDraft() },
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
|
||||
Screen.Reports -> {
|
||||
val task = reportTask
|
||||
if (task == null) {
|
||||
LaunchedEffect(Unit) { screen = Screen.Tasks }
|
||||
} else {
|
||||
ReportsScreen(
|
||||
taskName = task.taskName,
|
||||
onLoadReports = { page -> container.repository.reports(task.taskNum, page) },
|
||||
onLoadFragments = { sessionNum -> container.repository.allFragments(sessionNum) },
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
|
||||
|
||||
Screen.Settings -> SettingsScreen(
|
||||
baseUrl = baseUrl,
|
||||
onSave = { container.updateBaseUrl(it) },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
else -> when (screen) {
|
||||
Screen.Tasks -> TaskListScreen(
|
||||
tasks = tasks,
|
||||
loading = tasksLoading,
|
||||
error = tasksError,
|
||||
username = username,
|
||||
onRefresh = { refreshTasks() },
|
||||
onStart = { task ->
|
||||
container.session.startOrContinue(task.taskNum) {
|
||||
StudySessionService.start(context)
|
||||
}
|
||||
},
|
||||
onOpenSettings = { screen = Screen.Settings },
|
||||
onOpenPermissions = { screen = Screen.Permissions },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
)
|
||||
|
||||
Screen.Session -> SessionScreen(
|
||||
// 会话-05:别的任务上还有未结束会话时,先让用户选出口
|
||||
sessionState.conflict?.let {
|
||||
SessionConflictDialog(
|
||||
state = sessionState,
|
||||
openEndDialog = openEnd,
|
||||
onConsumeOpenEnd = { openEndRequest.value = false },
|
||||
onTogglePause = {
|
||||
if (sessionState.status == com.catshark.lpt.session.SessionController.Status.ONGOING) {
|
||||
container.session.pause()
|
||||
} else {
|
||||
container.session.resume()
|
||||
}
|
||||
onAction = { action ->
|
||||
container.session.resolveConflict(action) { StudySessionService.start(context) }
|
||||
},
|
||||
onEnd = { sections ->
|
||||
container.session.end(sections) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onAbort = { phrase ->
|
||||
container.session.abort(phrase) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onSaveExpectation = { container.session.saveExpectation(it) },
|
||||
onAddFragment = { container.session.addFragment(it) },
|
||||
onShowOverlay = { StudySessionService.showOverlay(context) },
|
||||
onBack = { screen = Screen.Tasks },
|
||||
onDismiss = { container.session.dismissConflict() },
|
||||
)
|
||||
}
|
||||
|
||||
Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
|
||||
// 不在会话页时,会话层的失败也要让用户看到
|
||||
if (screen != Screen.Session) {
|
||||
sessionState.error?.let { message ->
|
||||
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Screen.Settings -> SettingsScreen(
|
||||
baseUrl = baseUrl,
|
||||
onSave = { container.updateBaseUrl(it) },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
onBack = { screen = Screen.Tasks },
|
||||
/**
|
||||
* 会话-05 的出口选择弹窗:不能直接开始新任务,必须先说清旧会话怎么办。
|
||||
* 三个出口对应 lpt-docs「离开一个未结束的会话」:前往继续 / 结束它并开始 / 放弃它。
|
||||
*/
|
||||
@Composable
|
||||
private fun SessionConflictDialog(
|
||||
state: SessionController.State,
|
||||
onAction: (SessionController.ConflictAction) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val conflict = state.conflict ?: return
|
||||
val busy = state.conflictBusy
|
||||
AlertDialog(
|
||||
onDismissRequest = { if (busy == null) onDismiss() },
|
||||
title = { Text("还有未结束的学习会话") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"你已经有一个未结束的学习会话:「${conflict.taskName ?: conflict.taskNum}」",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(
|
||||
conflict.sessionNum,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (conflict.autoConverged) {
|
||||
Text(
|
||||
conflict.systemMessage ?: "这个会话看起来是忘记结束了,服务端已按一个番茄钟自动截止。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"可以直接开始当前任务:开始时会先把上面这个会话结束(会生成一份未填总结的学习报告);" +
|
||||
"如果它本来就是误操作开启的,可以选择放弃,不会留下任何记录。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (busy != null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(modifier = Modifier.padding(end = 8.dp), strokeWidth = 2.dp)
|
||||
Text("正在处理上一个会话…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
state.conflictError?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Button(
|
||||
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 == null,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text("取消") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ErrorBar(message: String, onDismiss: () -> Unit) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(12.dp),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onDismiss) { Text("关闭") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ interface LptApi {
|
||||
@GET("tasks")
|
||||
suspend fun tasks(): ApiEnvelope<TaskPage>
|
||||
|
||||
/** 当前活跃会话;excludeTaskNum 用于把「自己这个任务」排除掉,剩下的就是冲突会话 */
|
||||
@GET("study-sessions/active")
|
||||
suspend fun activeSession(
|
||||
@Query("excludeTaskNum") excludeTaskNum: String? = null,
|
||||
@@ -69,4 +70,24 @@ interface LptApi {
|
||||
|
||||
@GET("report-fragments/session/{sessionNum}")
|
||||
suspend fun fragmentsBySession(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<FragmentItem>>
|
||||
|
||||
/** 某任务的历史报告(按会话生成),报告三段 + 会话预期都在里面 */
|
||||
@GET("study-sessions/tasks/{taskNum}/reports")
|
||||
suspend fun reports(
|
||||
@Path("taskNum") taskNum: String,
|
||||
@Query("page") page: Int = 1,
|
||||
@Query("size") size: Int = 10,
|
||||
@Query("keyword") keyword: String? = null,
|
||||
): ApiEnvelope<ReportPage>
|
||||
|
||||
/** 本次会话产生的所有碎片原文,用于报告页展示 */
|
||||
@GET("study-sessions/{sessionNum}/all-fragments")
|
||||
suspend fun allFragments(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<String>>
|
||||
|
||||
/** 报告草稿:提交 REPORT_DRAFT 任务,随后轮询 GET /ai/tasks/{taskNum} */
|
||||
@POST("ai/tasks")
|
||||
suspend fun submitAiTask(@Body body: SubmitAiTaskRequest): ApiEnvelope<AiTask>
|
||||
|
||||
@GET("ai/tasks/{taskNum}")
|
||||
suspend fun aiTask(@Path("taskNum") taskNum: String): ApiEnvelope<AiTask>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import kotlinx.coroutines.delay
|
||||
import retrofit2.HttpException
|
||||
|
||||
/** 业务错误:把后端的 message 直接带给 UI */
|
||||
class ApiException(message: String) : Exception(message)
|
||||
|
||||
@@ -16,6 +19,18 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
return env.data as T
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 HTTP 层错误换成用户看得懂的话。
|
||||
* 部署环境的 dev 后端比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
|
||||
*/
|
||||
private fun <T> Result<T>.friendly(action: String): Result<T> {
|
||||
val error = exceptionOrNull()
|
||||
return if (error is HttpException) {
|
||||
Result.failure(ApiException("$action 不可用(HTTP ${error.code()}),当前后端可能还没上这个接口"))
|
||||
} else {
|
||||
this
|
||||
}
|
||||
}
|
||||
suspend fun login(username: String, password: String): Result<String> = runCatching {
|
||||
val env = api.login(LoginRequest(username, password))
|
||||
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "登录失败")
|
||||
@@ -28,8 +43,16 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
envelope(api.tasks(), "获取任务").records
|
||||
}
|
||||
|
||||
suspend fun activeSession(): Result<ActiveSession?> = runCatching {
|
||||
api.activeSession().takeIf { it.code == 200 }?.data
|
||||
/**
|
||||
* 当前活跃会话。
|
||||
*
|
||||
* - 传入 `excludeTaskNum` 时,属于该任务的会话不算冲突(后端直接返回 null);
|
||||
* - 业务失败(code != 200)与网络异常一律上抛:调用方需要区分「确实没有会话」和「没问到」。
|
||||
*/
|
||||
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = runCatching {
|
||||
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 {
|
||||
@@ -90,4 +113,43 @@ class LptRepository(private val apiClient: ApiClient) {
|
||||
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = runCatching {
|
||||
api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
|
||||
}
|
||||
|
||||
/** 依次任务的历史报告(按会话生成,分页) */
|
||||
suspend fun reports(taskNum: String, page: Int = 1, size: Int = 10): Result<ReportPage> = runCatching {
|
||||
envelope(api.reports(taskNum, page, size), "获取学习报告")
|
||||
}.friendly("查看学习报告")
|
||||
|
||||
/** 本次会话的全部碎片原文 */
|
||||
suspend fun allFragments(sessionNum: String): Result<List<String>> = runCatching {
|
||||
api.allFragments(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
|
||||
}.friendly("查看本次碎片")
|
||||
|
||||
/**
|
||||
* 报告草稿:提交 REPORT_DRAFT 异步任务后轮询到结束。
|
||||
* 草稿不落库,只作为结束会话弹窗里的编辑起点;AI 不可用时后端自己降级为规则拼接。
|
||||
*/
|
||||
suspend fun reportDraft(sessionNum: String): Result<ReportSections> = runCatching {
|
||||
val submitted = envelope(api.submitAiTask(SubmitAiTaskRequest(AI_TASK_REPORT_DRAFT, sessionNum)), "提交报告草稿任务")
|
||||
val taskNum = submitted.taskNum.takeIf { it.isNotBlank() }
|
||||
?: throw ApiException("报告草稿任务提交失败")
|
||||
var task: AiTask? = null
|
||||
val deadline = System.currentTimeMillis() + DRAFT_TIMEOUT_MS
|
||||
while (task == null) {
|
||||
val current = envelope(api.aiTask(taskNum), "查询报告草稿")
|
||||
when {
|
||||
current.succeeded -> task = current
|
||||
current.failed -> throw ApiException(current.errorMessage?.takeIf { it.isNotBlank() } ?: "生成报告草稿失败")
|
||||
System.currentTimeMillis() > deadline -> throw ApiException("生成报告草稿超时,请直接手写或稍后重试")
|
||||
else -> delay(DRAFT_POLL_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
// 循环出口保证非空
|
||||
task.draftSections()
|
||||
}.friendly("生成学习报告草稿")
|
||||
|
||||
companion object {
|
||||
private const val AI_TASK_REPORT_DRAFT = "REPORT_DRAFT"
|
||||
private const val DRAFT_POLL_INTERVAL_MS = 2_000L
|
||||
private const val DRAFT_TIMEOUT_MS = 180_000L
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.catshark.lpt.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
|
||||
/** lpt-be 的统一响应包装:{ code, message, data } */
|
||||
@Serializable
|
||||
@@ -63,6 +66,8 @@ data class ActiveSession(
|
||||
val taskName: String? = null,
|
||||
val sessionState: String? = null,
|
||||
val autoConverged: Boolean = false,
|
||||
/** 服务端自动收敛时的用户可见文案 */
|
||||
val systemMessage: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
@@ -116,6 +121,10 @@ data class ReportSections(
|
||||
val allBlank: Boolean
|
||||
get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank()
|
||||
|
||||
companion object {
|
||||
val EMPTY = ReportSections("", "", "")
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题,
|
||||
* 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。
|
||||
@@ -130,14 +139,65 @@ data class ReportSections(
|
||||
/** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */
|
||||
fun extractToken(element: JsonElement?): String? {
|
||||
if (element == null) return null
|
||||
return when {
|
||||
element is JsonElement && element.toString().trim().startsWith("\"") ->
|
||||
element.toString().trim().trim('"')
|
||||
else -> {
|
||||
val obj = element as? kotlinx.serialization.json.JsonObject
|
||||
obj?.get("token")?.let { token ->
|
||||
if (token.toString().trim().startsWith("\"")) token.toString().trim().trim('"') else token.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
val text = element.toString().trim()
|
||||
if (text.startsWith("\"")) return text.trim('"')
|
||||
val token = (element as? JsonObject)?.get("token") ?: return null
|
||||
val raw = token.toString().trim()
|
||||
return if (raw.startsWith("\"")) raw.trim('"') else raw
|
||||
}
|
||||
|
||||
/** 某次学习会话产出的学习报告(报告三段 + 该会话的学习预期) */
|
||||
@Serializable
|
||||
data class StudyReport(
|
||||
val id: Int = 0,
|
||||
val sessionNum: String = "",
|
||||
val sessionSummary: String? = null,
|
||||
val expectationVerdict: String? = null,
|
||||
val freeSummary: String? = null,
|
||||
/** 会话对应的学习预期,随报告返回,不落库 */
|
||||
val sessionExpectation: String? = null,
|
||||
val createdTime: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ReportPage(
|
||||
val records: List<StudyReport> = emptyList(),
|
||||
val total: Int = 0,
|
||||
val size: Int = 0,
|
||||
val current: Int = 0,
|
||||
val pages: Int = 0,
|
||||
)
|
||||
|
||||
/** AI 异步任务(AI-02):提交秒级返回,之后轮询拿状态与结果 */
|
||||
@Serializable
|
||||
data class AiTask(
|
||||
val taskNum: String = "",
|
||||
val type: String = "",
|
||||
val targetNum: String = "",
|
||||
val status: String = "",
|
||||
val errorMessage: String? = null,
|
||||
val result: JsonObject? = null,
|
||||
) {
|
||||
val succeeded: Boolean get() = status == "SUCCEEDED"
|
||||
val failed: Boolean get() = status == "FAILED"
|
||||
val inProgress: Boolean get() = status == "PENDING" || status == "RUNNING"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SubmitAiTaskRequest(
|
||||
val type: String,
|
||||
val targetNum: String,
|
||||
)
|
||||
|
||||
/** 取报告草稿三段:REPORT_DRAFT 任务的 result 就是三个同名字段 */
|
||||
fun AiTask.draftSections(): ReportSections = ReportSections(
|
||||
sessionSummary = result.text("sessionSummary"),
|
||||
expectationVerdict = result.text("expectationVerdict"),
|
||||
freeSummary = result.text("freeSummary"),
|
||||
)
|
||||
|
||||
private fun JsonObject?.text(key: String): String {
|
||||
val element = this?.get(key) ?: return ""
|
||||
if (element is JsonNull) return ""
|
||||
return runCatching { element.jsonPrimitive.content }.getOrDefault("")
|
||||
}
|
||||
|
||||
@@ -21,14 +21,21 @@ import kotlin.math.abs
|
||||
/**
|
||||
* 系统级悬浮窗(经典 View 实现)。
|
||||
*
|
||||
* 三种形态:
|
||||
* - 浏览:完整条(任务名 + 计时 + 暂停 + 展开),FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
|
||||
* 职责被刻意压到最小——浮窗只做三件事:
|
||||
* 1. 展示倒计时;
|
||||
* 2. 记一条知识碎片(拉起 FragmentInputActivity,浮窗内不做文本输入);
|
||||
* 3. 暂停 / 继续计时。
|
||||
*
|
||||
* 其余动作(改预期、结束会话、写报告、看历史)一律在 App 页面内完成,不要往浮窗里加。
|
||||
*
|
||||
* 两种形态:
|
||||
* - 常态条:`● 12:34 + 暂停`,FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
|
||||
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
|
||||
*
|
||||
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
|
||||
*
|
||||
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
|
||||
* 所以「+ 记一条碎片」回调给 Service,由它拉起 FragmentInputActivity。
|
||||
* 所以「+」回调给 Service,由它拉起 FragmentInputActivity。
|
||||
*/
|
||||
class OverlayView(private val context: Context) {
|
||||
|
||||
@@ -37,37 +44,25 @@ class OverlayView(private val context: Context) {
|
||||
private var root: LinearLayout? = null
|
||||
private var params: WindowManager.LayoutParams? = null
|
||||
private var shown = false
|
||||
private var expanded = false
|
||||
private var halfHidden = false
|
||||
private var lastState: SessionController.State? = null
|
||||
|
||||
private lateinit var headerRow: LinearLayout
|
||||
private lateinit var barRow: LinearLayout
|
||||
private lateinit var dotView: View
|
||||
private lateinit var nameView: TextView
|
||||
private lateinit var timeView: TextView
|
||||
private lateinit var pauseView: TextView
|
||||
private lateinit var expandView: TextView
|
||||
private lateinit var compactView: LinearLayout
|
||||
private lateinit var fragmentView: TextView
|
||||
private lateinit var toggleView: TextView
|
||||
private lateinit var compactRow: LinearLayout
|
||||
private lateinit var compactDot: View
|
||||
private lateinit var compactTime: TextView
|
||||
private lateinit var expandedPanel: LinearLayout
|
||||
private lateinit var expectationView: TextView
|
||||
private lateinit var fragmentView: TextView
|
||||
private lateinit var latestFragmentView: TextView
|
||||
private lateinit var addFragmentView: TextView
|
||||
private lateinit var endView: TextView
|
||||
private lateinit var openAppView: TextView
|
||||
private lateinit var hideView: TextView
|
||||
|
||||
var onTogglePause: (() -> Unit)? = null
|
||||
var onEnd: (() -> Unit)? = null
|
||||
var onOpenApp: (() -> Unit)? = null
|
||||
var onRequestFragmentInput: (() -> Unit)? = null
|
||||
|
||||
val isShown: Boolean get() = shown
|
||||
|
||||
private val autoHideTask = Runnable {
|
||||
if (shown && !expanded) setHalfHidden(true)
|
||||
if (shown && !halfHidden) setHalfHidden(true)
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
|
||||
@@ -88,14 +83,6 @@ class OverlayView(private val context: Context) {
|
||||
isFocusable = false
|
||||
}
|
||||
|
||||
private fun label(text: String, color: Int, size: Float = 12f): TextView = TextView(context).apply {
|
||||
this.text = text
|
||||
textSize = size
|
||||
setTextColor(color)
|
||||
maxLines = 2
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
}
|
||||
|
||||
fun show() {
|
||||
if (shown) return
|
||||
if (!Settings.canDrawOverlays(context)) return
|
||||
@@ -138,29 +125,15 @@ class OverlayView(private val context: Context) {
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val text = formatDuration(state.effectiveSeconds())
|
||||
|
||||
nameView.text = state.taskName?.takeIf { it.isNotBlank() } ?: "学习会话"
|
||||
timeView.text = text
|
||||
compactTime.text = text
|
||||
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
compactDot.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
pauseView.text = if (ongoing) "暂停" else "继续"
|
||||
pauseView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
|
||||
toggleView.text = if (ongoing) "暂停" else "继续"
|
||||
toggleView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
|
||||
|
||||
expectationView.text =
|
||||
if (state.expectation.isBlank()) "预期:未填写" else "预期:${state.expectation}"
|
||||
fragmentView.text = "本次碎片 ${state.fragments.size} 条"
|
||||
latestFragmentView.text = state.fragments.lastOrNull()?.content?.let { "最新:$it" } ?: ""
|
||||
|
||||
headerRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
|
||||
compactView.visibility = if (halfHidden) View.VISIBLE else View.GONE
|
||||
expandedPanel.visibility = if (!halfHidden && expanded) View.VISIBLE else View.GONE
|
||||
expandView.text = if (expanded) "▴" else "▾"
|
||||
}
|
||||
|
||||
private fun toggleExpanded() {
|
||||
expanded = !expanded
|
||||
lastState?.let { render(it) }
|
||||
scheduleAutoHide()
|
||||
barRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
|
||||
compactRow.visibility = if (halfHidden) View.VISIBLE else View.GONE
|
||||
}
|
||||
|
||||
// ---- 半隐藏 / 自动隐藏 ----
|
||||
@@ -168,9 +141,9 @@ class OverlayView(private val context: Context) {
|
||||
fun setHalfHidden(hidden: Boolean) {
|
||||
val view = root ?: return
|
||||
val p = params ?: return
|
||||
if (hidden) expanded = false
|
||||
halfHidden = hidden
|
||||
view.alpha = if (hidden) 0.6f else 1f
|
||||
// 常态整条 80% 不透明;收起后再压一档,整体约 60%
|
||||
view.alpha = if (hidden) 0.75f else 1f
|
||||
lastState?.let { render(it) }
|
||||
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
@@ -191,7 +164,7 @@ class OverlayView(private val context: Context) {
|
||||
|
||||
private fun scheduleAutoHide() {
|
||||
root?.removeCallbacks(autoHideTask)
|
||||
if (!halfHidden && !expanded) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
|
||||
if (!halfHidden) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
|
||||
}
|
||||
|
||||
private fun cancelAutoHide() {
|
||||
@@ -211,8 +184,8 @@ class OverlayView(private val context: Context) {
|
||||
elevation = dp(10).toFloat()
|
||||
}
|
||||
|
||||
// ---- 完整条 ----
|
||||
headerRow = LinearLayout(context).apply {
|
||||
// ---- 常态条:● 计时 + 暂停/继续 ----
|
||||
barRow = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
}
|
||||
@@ -220,36 +193,31 @@ class OverlayView(private val context: Context) {
|
||||
background = rounded(COLOR_ONGOING, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
|
||||
}
|
||||
nameView = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 13f
|
||||
maxLines = 1
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
|
||||
.apply { marginStart = dp(8) }
|
||||
}
|
||||
timeView = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 16f
|
||||
textSize = 17f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setPadding(dp(8), 0, dp(8), 0)
|
||||
maxLines = 1
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
setPadding(dp(8), 0, dp(10), 0)
|
||||
}
|
||||
pauseView = pill("暂停", COLOR_ACTION)
|
||||
expandView = pill("▾", COLOR_NEUTRAL).apply {
|
||||
fragmentView = pill("+", COLOR_NEUTRAL).apply {
|
||||
contentDescription = "记一条知识碎片"
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(6) }
|
||||
).apply { marginEnd = dp(6) }
|
||||
}
|
||||
headerRow.addView(dotView)
|
||||
headerRow.addView(nameView)
|
||||
headerRow.addView(timeView)
|
||||
headerRow.addView(pauseView)
|
||||
headerRow.addView(expandView)
|
||||
container.addView(headerRow)
|
||||
toggleView = pill("暂停", COLOR_ACTION)
|
||||
|
||||
// ---- 半隐藏小胶囊 ----
|
||||
compactView = LinearLayout(context).apply {
|
||||
barRow.addView(dotView)
|
||||
barRow.addView(timeView)
|
||||
barRow.addView(fragmentView)
|
||||
barRow.addView(toggleView)
|
||||
container.addView(barRow)
|
||||
|
||||
// ---- 半隐藏小胶囊:● 计时 ----
|
||||
compactRow = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
visibility = View.GONE
|
||||
@@ -262,82 +230,27 @@ class OverlayView(private val context: Context) {
|
||||
}
|
||||
compactTime = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 14f
|
||||
textSize = 15f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setPadding(dp(6), 0, 0, 0)
|
||||
setPadding(dp(6), 0, dp(4), 0)
|
||||
}
|
||||
compactView.addView(compactDot)
|
||||
compactView.addView(compactTime)
|
||||
compactView.setOnClickListener { setHalfHidden(false) }
|
||||
container.addView(compactView)
|
||||
compactRow.addView(compactDot)
|
||||
compactRow.addView(compactTime)
|
||||
compactRow.setOnClickListener { setHalfHidden(false) }
|
||||
container.addView(compactRow)
|
||||
|
||||
// ---- 展开面板 ----
|
||||
expandedPanel = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
visibility = View.GONE
|
||||
}
|
||||
expectationView = label("预期:", Color.parseColor("#C9D1D9")).apply {
|
||||
setPadding(0, dp(10), 0, dp(2))
|
||||
}
|
||||
fragmentView = label("本次碎片 0 条", Color.parseColor("#8B949E"), 12f)
|
||||
latestFragmentView = label("", Color.parseColor("#8B949E"), 12f)
|
||||
|
||||
addFragmentView = pill("+ 记一条碎片", COLOR_ACTION).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { topMargin = dp(8) }
|
||||
}
|
||||
addFragmentView.setOnClickListener {
|
||||
fragmentView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
|
||||
setHalfHidden(true)
|
||||
onRequestFragmentInput?.invoke()
|
||||
}
|
||||
|
||||
val actions = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
setPadding(0, dp(10), 0, 0)
|
||||
}
|
||||
endView = pill("结束", COLOR_END)
|
||||
openAppView = pill("打开 App", COLOR_NEUTRAL).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(8) }
|
||||
}
|
||||
hideView = pill("隐藏", COLOR_NEUTRAL).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(8) }
|
||||
}
|
||||
actions.addView(endView)
|
||||
actions.addView(openAppView)
|
||||
actions.addView(hideView)
|
||||
|
||||
expandedPanel.addView(expectationView)
|
||||
expandedPanel.addView(fragmentView)
|
||||
expandedPanel.addView(latestFragmentView)
|
||||
expandedPanel.addView(addFragmentView)
|
||||
expandedPanel.addView(actions)
|
||||
container.addView(expandedPanel)
|
||||
|
||||
pauseView.setOnClickListener {
|
||||
toggleView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onTogglePause?.invoke()
|
||||
}
|
||||
expandView.setOnClickListener { toggleExpanded() }
|
||||
endView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onEnd?.invoke()
|
||||
}
|
||||
openAppView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onOpenApp?.invoke()
|
||||
}
|
||||
hideView.setOnClickListener { setHalfHidden(true) }
|
||||
|
||||
attachDrag(headerRow)
|
||||
attachDrag(barRow)
|
||||
return container
|
||||
}
|
||||
|
||||
@@ -420,7 +333,6 @@ class OverlayView(private val context: Context) {
|
||||
private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
|
||||
private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
|
||||
private const val COLOR_RESUME = 0xFF238636.toInt()
|
||||
private const val COLOR_END = 0xFFB62324.toInt()
|
||||
private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,18 +40,18 @@ class StudySessionService : Service() {
|
||||
controller = container.session
|
||||
overlay = OverlayView(this).apply {
|
||||
onTogglePause = { togglePause() }
|
||||
onEnd = { openApp(openEnd = true) }
|
||||
onOpenApp = { openApp(openEnd = false) }
|
||||
onRequestFragmentInput = { openFragmentInput() }
|
||||
}
|
||||
createChannel()
|
||||
|
||||
// 状态变化:更新通知 / 悬浮窗;会话没了就停服务
|
||||
// 状态变化:更新通知 / 悬浮窗。
|
||||
// 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时
|
||||
// 对账是异步的,早期看到的空状态是「还不知道」,不能据此 stopSelf。
|
||||
scope.launch {
|
||||
controller.state.collect { state ->
|
||||
if (!state.hasSession) {
|
||||
overlay.hide()
|
||||
stopSelf()
|
||||
if (state.resolved) stopSelf()
|
||||
return@collect
|
||||
}
|
||||
ensureForeground(state)
|
||||
@@ -87,6 +87,8 @@ class StudySessionService : Service() {
|
||||
ACTION_SHOW_OVERLAY -> overlay.restore()
|
||||
ACTION_STOP -> stopSelf()
|
||||
}
|
||||
// 进程被系统拉起(intent 为 null)时补一次对账,否则重启后浮窗不会再出现
|
||||
controller.ensureReconciled()
|
||||
// 必须在 5 秒内 startForeground,先用当前状态占位
|
||||
ensureForeground(controller.state.value)
|
||||
return START_STICKY
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.catshark.lpt.data.LptRepository
|
||||
import com.catshark.lpt.data.ReportSections
|
||||
import com.catshark.lpt.data.SessionDetail
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -19,6 +20,9 @@ import java.time.LocalDateTime
|
||||
*
|
||||
* 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。
|
||||
* 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
|
||||
*
|
||||
* 会话-05:开始任务前先看别的任务上有没有未结束会话,有就进 [State.conflict],
|
||||
* 由 UI 给出「前往继续 / 结束它并开始新任务 / 放弃它」三个出口。
|
||||
*/
|
||||
class SessionController(
|
||||
private val repo: LptRepository,
|
||||
@@ -27,6 +31,20 @@ class SessionController(
|
||||
|
||||
enum class Status { NONE, ONGOING, PAUSED, ENDED }
|
||||
|
||||
/** 会话-05 的出口选择 */
|
||||
enum class ConflictAction { CONTINUE, END_AND_START, ABORT }
|
||||
|
||||
/** 别的任务上还有未结束会话:用户必须先选一个出口 */
|
||||
data class Conflict(
|
||||
/** 用户想开始的任务 */
|
||||
val targetTaskNum: String,
|
||||
val sessionNum: String,
|
||||
val taskNum: String,
|
||||
val taskName: String?,
|
||||
val autoConverged: Boolean,
|
||||
val systemMessage: String?,
|
||||
)
|
||||
|
||||
data class State(
|
||||
val sessionNum: String? = null,
|
||||
val taskNum: String? = null,
|
||||
@@ -35,14 +53,30 @@ class SessionController(
|
||||
val baseEffectiveSeconds: Double = 0.0,
|
||||
val anchorRealtimeMs: Long = 0L,
|
||||
val expectation: String = "",
|
||||
/** 学习预期是否已经从服务端取回过(没取回前不要弹必填弹窗) */
|
||||
val expectationLoaded: Boolean = false,
|
||||
val fragments: List<FragmentItem> = emptyList(),
|
||||
val busy: Boolean = false,
|
||||
/** 是否已经与服务端对过账:前台服务据此判断「真没有会话」还是「还不知道」 */
|
||||
val resolved: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
val conflict: Conflict? = null,
|
||||
val conflictBusy: ConflictAction? = null,
|
||||
val conflictError: String? = null,
|
||||
/** 报告草稿(AI 或规则降级),仅作为结束弹窗的编辑起点,不落库 */
|
||||
val draft: ReportSections? = null,
|
||||
val draftLoading: Boolean = false,
|
||||
val draftSeconds: Int = 0,
|
||||
val draftError: String? = null,
|
||||
) {
|
||||
val hasSession: Boolean
|
||||
get() = status == Status.ONGOING || status == Status.PAUSED
|
||||
|
||||
/** 有会话但预期还没填:UI 用不可关闭的弹窗挡住,符合「会话必须有预期才能开始」 */
|
||||
val expectationRequired: Boolean
|
||||
get() = hasSession && expectationLoaded && expectation.isBlank()
|
||||
|
||||
fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
|
||||
if (status == Status.ONGOING) {
|
||||
baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
|
||||
@@ -54,25 +88,95 @@ class SessionController(
|
||||
private val _state = MutableStateFlow(State())
|
||||
val state: StateFlow<State> = _state.asStateFlow()
|
||||
|
||||
private var reconciling = false
|
||||
|
||||
fun consumeError() = _state.update { it.copy(error = null) }
|
||||
|
||||
fun consumeNotice() = _state.update { it.copy(notice = null) }
|
||||
|
||||
/** 启动或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务) */
|
||||
fun dismissConflict() = _state.update { it.copy(conflict = null, conflictError = null) }
|
||||
|
||||
/**
|
||||
* 开始或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务)。
|
||||
*
|
||||
* 先查其他任务上有没有未结束会话:有则只更新 [State.conflict],不开始新会话。
|
||||
*/
|
||||
fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
_state.update { it.copy(busy = true, error = null, conflict = null, conflictError = null) }
|
||||
scope.launch {
|
||||
repo.startOrContinue(taskNum)
|
||||
.onSuccess { detail ->
|
||||
applyDetail(detail)
|
||||
loadAuxiliary(detail.sessionNum)
|
||||
_state.update { it.copy(busy = false) }
|
||||
onSuccess()
|
||||
val active = repo.activeSession(excludeTaskNum = taskNum)
|
||||
val conflict = active.getOrNull()
|
||||
if (conflict != null) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
busy = false,
|
||||
conflict = Conflict(
|
||||
targetTaskNum = taskNum,
|
||||
sessionNum = conflict.sessionNum,
|
||||
taskNum = conflict.taskNum,
|
||||
taskName = conflict.taskName,
|
||||
autoConverged = conflict.autoConverged,
|
||||
systemMessage = conflict.systemMessage,
|
||||
),
|
||||
)
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(busy = false, error = e.message ?: "开始学习会话失败") }
|
||||
return@launch
|
||||
}
|
||||
if (active.isFailure) {
|
||||
// 查不到不等于没有:提示一句再照常开始,不把用户堵在列表页
|
||||
_state.update { it.copy(notice = "未能确认是否存在未结束会话,已按没有冲突处理") }
|
||||
}
|
||||
startTask(taskNum, onSuccess)
|
||||
}
|
||||
}
|
||||
|
||||
/** 处理会话-05 的出口选择 */
|
||||
fun resolveConflict(action: ConflictAction, onSessionReady: () -> Unit = {}) {
|
||||
val conflict = _state.value.conflict ?: return
|
||||
if (_state.value.conflictBusy != null) return
|
||||
_state.update { it.copy(conflictBusy = action, conflictError = null) }
|
||||
scope.launch {
|
||||
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) }
|
||||
}
|
||||
|
||||
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 = "已放弃上一个会话,未产生任何数据")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,12 +204,18 @@ class SessionController(
|
||||
}
|
||||
}
|
||||
|
||||
fun saveExpectation(text: String) {
|
||||
fun saveExpectation(text: String, onSaved: () -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
val value = text.trim()
|
||||
if (value.isBlank()) {
|
||||
_state.update { it.copy(error = "学习预期不可为空") }
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
repo.putExpectation(num, text)
|
||||
repo.putExpectation(num, value)
|
||||
.onSuccess {
|
||||
_state.update { it.copy(expectation = text, notice = "学习预期已保存") }
|
||||
_state.update { it.copy(expectation = value, expectationLoaded = true, notice = "学习预期已保存") }
|
||||
onSaved()
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } }
|
||||
}
|
||||
@@ -132,7 +242,7 @@ class SessionController(
|
||||
scope.launch {
|
||||
repo.endSession(num, sections)
|
||||
.onSuccess { message ->
|
||||
_state.value = State(notice = message ?: "学习会话已结束")
|
||||
_state.value = idle(notice = message ?: "学习会话已结束")
|
||||
onDone()
|
||||
}
|
||||
.onFailure { e ->
|
||||
@@ -148,7 +258,7 @@ class SessionController(
|
||||
scope.launch {
|
||||
repo.abortSession(num, confirmation)
|
||||
.onSuccess {
|
||||
_state.value = State(notice = "已放弃该会话,未产生任何数据")
|
||||
_state.value = idle(notice = "已放弃该会话,未产生任何数据")
|
||||
onDone()
|
||||
}
|
||||
.onFailure { e ->
|
||||
@@ -157,42 +267,135 @@ class SessionController(
|
||||
}
|
||||
}
|
||||
|
||||
/** App 启动时与服务端对账:把未结束的会话恢复出来 */
|
||||
fun reconcile() {
|
||||
/**
|
||||
* 生成报告草稿(有碎片时才有意义)。三段都空时由结束弹窗自动调用,
|
||||
* 用户点「AI 重新生成」也可以再调用一次。
|
||||
*/
|
||||
fun generateReportDraft() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.draftLoading) return
|
||||
if (_state.value.fragments.isEmpty()) {
|
||||
_state.update { it.copy(draftError = "这次学习还没有知识碎片,暂无可聚合的内容") }
|
||||
return
|
||||
}
|
||||
_state.update { it.copy(draftLoading = true, draftSeconds = 0, draftError = null) }
|
||||
scope.launch {
|
||||
repo.activeSession()
|
||||
.onSuccess { active ->
|
||||
if (active == null || active.sessionNum.isBlank()) {
|
||||
if (!_state.value.hasSession) _state.update { it.copy(status = Status.NONE) }
|
||||
return@onSuccess
|
||||
}
|
||||
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
|
||||
val ticker = scope.launch {
|
||||
while (_state.value.draftLoading) {
|
||||
delay(1_000)
|
||||
_state.update { it.copy(draftSeconds = it.draftSeconds + 1) }
|
||||
}
|
||||
}
|
||||
val result = repo.reportDraft(num)
|
||||
ticker.cancel()
|
||||
result
|
||||
.onSuccess { sections ->
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = active.sessionNum,
|
||||
taskNum = active.taskNum.ifBlank { it.taskNum },
|
||||
taskName = active.taskName ?: it.taskName,
|
||||
draftLoading = false,
|
||||
draft = sections,
|
||||
draftError = if (sections.allBlank) "没有可聚合的内容,请手写总结" else null,
|
||||
)
|
||||
}
|
||||
refreshDetail(active.sessionNum)
|
||||
loadAuxiliary(active.sessionNum)
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(draftLoading = false, draftError = e.message ?: "生成报告草稿失败") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
_state.value = State()
|
||||
fun consumeDraftError() = _state.update { it.copy(draftError = null) }
|
||||
|
||||
/** App 启动/登录后与服务端对账:把未结束的会话恢复出来 */
|
||||
fun reconcile() {
|
||||
if (reconciling) return
|
||||
reconciling = true
|
||||
scope.launch {
|
||||
try {
|
||||
repo.activeSession()
|
||||
.onSuccess { active ->
|
||||
if (active == null || active.sessionNum.isBlank()) {
|
||||
_state.update { it.copy(status = if (it.hasSession) it.status else Status.NONE) }
|
||||
return@onSuccess
|
||||
}
|
||||
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = active.sessionNum,
|
||||
taskNum = active.taskNum.ifBlank { it.taskNum },
|
||||
taskName = active.taskName ?: it.taskName,
|
||||
)
|
||||
}
|
||||
refreshDetail(active.sessionNum)
|
||||
loadAuxiliary(active.sessionNum)
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message ?: "恢复会话状态失败") }
|
||||
}
|
||||
} finally {
|
||||
reconciling = false
|
||||
_state.update { it.copy(resolved = true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 前台服务被系统拉起时调用:还没对过账就补一次对账 */
|
||||
fun ensureReconciled() {
|
||||
if (!_state.value.resolved) reconcile()
|
||||
}
|
||||
|
||||
/** 未登录时没有会话可查,直接标记为已知状态,避免服务一直等 */
|
||||
fun markResolved() = _state.update { it.copy(resolved = true) }
|
||||
|
||||
fun clear() = _state.update { State(resolved = true) }
|
||||
|
||||
// ---- 内部 ----
|
||||
|
||||
/** 开始新会话(或继续当前任务上未结束的会话) */
|
||||
private suspend fun startTask(taskNum: String, onSessionReady: () -> Unit, note: String? = null) {
|
||||
repo.startOrContinue(taskNum)
|
||||
.onSuccess { detail ->
|
||||
applyDetail(detail)
|
||||
_state.update {
|
||||
it.copy(
|
||||
busy = false,
|
||||
conflict = null,
|
||||
conflictBusy = null,
|
||||
conflictError = null,
|
||||
expectationLoaded = false,
|
||||
notice = note ?: it.notice,
|
||||
)
|
||||
}
|
||||
loadAuxiliary(detail.sessionNum)
|
||||
onSessionReady()
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update {
|
||||
it.copy(
|
||||
busy = false,
|
||||
conflictBusy = null,
|
||||
conflictError = e.message ?: "开始学习会话失败",
|
||||
error = if (it.conflict == null) e.message ?: "开始学习会话失败" else null,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun failConflict(error: Throwable) {
|
||||
_state.update {
|
||||
it.copy(conflictBusy = null, conflictError = error.message ?: "处理上一个会话失败,请重试")
|
||||
}
|
||||
}
|
||||
|
||||
private fun idle(notice: String? = null) = State(notice = notice, resolved = true)
|
||||
|
||||
private suspend fun refreshDetail(sessionNum: String) {
|
||||
repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
|
||||
}
|
||||
|
||||
private suspend fun loadAuxiliary(sessionNum: String) {
|
||||
repo.getExpectation(sessionNum).onSuccess { text ->
|
||||
_state.update { it.copy(expectation = text) }
|
||||
_state.update { it.copy(expectation = text, expectationLoaded = true) }
|
||||
}
|
||||
repo.fragments(sessionNum).onSuccess { list ->
|
||||
_state.update { it.copy(fragments = list) }
|
||||
@@ -211,6 +414,9 @@ class SessionController(
|
||||
} else {
|
||||
SystemClock.elapsedRealtime()
|
||||
}
|
||||
// 会话-04:被服务端自动收敛过的会话,把服务端文案原样告诉用户
|
||||
val converged = detail.systemMessage?.takeIf { it.isNotBlank() }
|
||||
?: if (detail.autoConverged) "上一次学习疑似忘记结束,已自动截止,本次只计入一个番茄钟的有效学习时间" else null
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
|
||||
@@ -220,6 +426,7 @@ class SessionController(
|
||||
baseEffectiveSeconds = detail.effectiveTime,
|
||||
anchorRealtimeMs = anchor,
|
||||
error = null,
|
||||
notice = converged ?: it.notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -231,4 +438,12 @@ class SessionController(
|
||||
Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
|
||||
}.getOrDefault(0)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 误操作结束的确认语,前后端各校验一次 */
|
||||
const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
|
||||
|
||||
/** 开始新任务时结束旧会话留下的报告正文,让用户看得出这条报告是怎么来的 */
|
||||
const val STALE_SESSION_SUMMARY = "(开始新任务时结束了这个会话,未填写学习总结)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
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.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.data.ReportPage
|
||||
import com.catshark.lpt.data.StudyReport
|
||||
import com.catshark.lpt.util.formatDateTime
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 某任务的历史学习报告:三段文本 + 该会话的学习预期 + 本次会话的碎片原文。
|
||||
*
|
||||
* 报告第四部分「按归属分组的碎片」由复习模块实时聚合(review 前缀的端点),
|
||||
* 本客户端按边界不访问它,所以这里只列本次会话产生的碎片。
|
||||
*/
|
||||
@Composable
|
||||
fun ReportsScreen(
|
||||
taskName: String,
|
||||
onLoadReports: suspend (Int) -> Result<ReportPage>,
|
||||
onLoadFragments: suspend (String) -> Result<List<String>>,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var reports by remember { mutableStateOf<List<StudyReport>>(emptyList()) }
|
||||
var total by remember { mutableIntStateOf(0) }
|
||||
var page by remember { mutableIntStateOf(0) }
|
||||
var loading by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun load(next: Int) {
|
||||
if (loading || next < 1) return
|
||||
loading = true
|
||||
error = null
|
||||
scope.launch {
|
||||
onLoadReports(next)
|
||||
.onSuccess { result ->
|
||||
reports = if (next <= 1) result.records else reports + result.records
|
||||
total = result.total
|
||||
page = next
|
||||
}
|
||||
.onFailure { error = it.message ?: "加载学习报告失败" }
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(taskName) {
|
||||
reports = emptyList()
|
||||
page = 0
|
||||
load(1)
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onBack) { Text("‹ 任务") }
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("学习报告", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
taskName,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (loading) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
error!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = { load(if (page == 0) 1 else page) }) { Text("重试") }
|
||||
}
|
||||
}
|
||||
|
||||
if (reports.isEmpty() && !loading && error == null) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("这个任务还没有学习报告", style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = { load(1) }) { Text("刷新") }
|
||||
}
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(reports, key = { it.id }) { report ->
|
||||
ReportCard(report = report, onLoadFragments = onLoadFragments)
|
||||
}
|
||||
if (reports.size < total) {
|
||||
item {
|
||||
TextButton(onClick = { load(page + 1) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(if (loading) "加载中…" else "加载更多(${reports.size}/$total)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ReportCard(
|
||||
report: StudyReport,
|
||||
onLoadFragments: suspend (String) -> Result<List<String>>,
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var fragments by remember { mutableStateOf<List<String>?>(null) }
|
||||
var fragmentError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"学习报告",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
formatDateTime(report.createdTime),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"会话 ${report.sessionNum}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
if (!report.sessionExpectation.isNullOrBlank()) {
|
||||
Section("本次预期", report.sessionExpectation)
|
||||
}
|
||||
Section("会话摘要", report.sessionSummary)
|
||||
Section("预期达成判断", report.expectationVerdict)
|
||||
Section("自由总结", report.freeSummary)
|
||||
|
||||
TextButton(
|
||||
onClick = {
|
||||
expanded = !expanded
|
||||
if (expanded && fragments == null && fragmentError == null) {
|
||||
scope.launch {
|
||||
onLoadFragments(report.sessionNum)
|
||||
.onSuccess { fragments = it }
|
||||
.onFailure { fragmentError = it.message ?: "加载碎片失败" }
|
||||
}
|
||||
}
|
||||
},
|
||||
) { Text(if (expanded) "收起本次碎片" else "查看本次碎片") }
|
||||
|
||||
if (expanded) {
|
||||
val list = fragments
|
||||
when {
|
||||
fragmentError != null -> Text(
|
||||
fragmentError!!,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
|
||||
list == null -> Text(
|
||||
"加载中…",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
list.isEmpty() -> Text(
|
||||
"这次学习没有记录碎片",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
else -> list.forEachIndexed { index, content ->
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Row {
|
||||
Text(
|
||||
"${index + 1}.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
content,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(label: String, value: String?) {
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
if (value.isNullOrBlank()) {
|
||||
Text(
|
||||
"(未填写)",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package com.catshark.lpt.ui
|
||||
|
||||
import android.os.SystemClock
|
||||
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
|
||||
@@ -39,7 +38,7 @@ import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
|
||||
private val MISOPERATION_PHRASE = SessionController.MISOPERATION_PHRASE
|
||||
|
||||
@Composable
|
||||
fun SessionScreen(
|
||||
@@ -52,6 +51,7 @@ fun SessionScreen(
|
||||
onSaveExpectation: (String) -> Unit,
|
||||
onAddFragment: (String) -> Unit,
|
||||
onShowOverlay: () -> Unit,
|
||||
onGenerateDraft: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
@@ -85,7 +85,8 @@ fun SessionScreen(
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onBack) { Text("‹ 任务") }
|
||||
// 预期还没填时不允许离开:会话必须有预期才能算正式开始
|
||||
TextButton(onClick = onBack, enabled = !state.expectationRequired) { Text("‹ 任务") }
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.taskName ?: "学习会话",
|
||||
@@ -239,15 +240,25 @@ fun SessionScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 会话必须有预期才能正式开始:未填预期时用不可关闭的弹窗挡住
|
||||
if (state.expectationRequired) {
|
||||
ExpectationGateDialog(
|
||||
busy = state.busy,
|
||||
error = state.error,
|
||||
onSave = onSaveExpectation,
|
||||
onAbort = onAbort,
|
||||
)
|
||||
}
|
||||
|
||||
if (showEnd) {
|
||||
EndSessionDialog(
|
||||
defaultSummary = "",
|
||||
busy = state.busy,
|
||||
state = state,
|
||||
onDismiss = { showEnd = false },
|
||||
onConfirm = { sections ->
|
||||
showEnd = false
|
||||
onEnd(sections)
|
||||
},
|
||||
onGenerateDraft = onGenerateDraft,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -263,16 +274,116 @@ fun SessionScreen(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 学习预期必填弹窗。不允许点外部关闭,只能「保存并开始」或走误操作结束:
|
||||
* 否则就会出现一次没有任何预期的会话。
|
||||
*/
|
||||
@Composable
|
||||
private fun ExpectationGateDialog(
|
||||
busy: Boolean,
|
||||
error: String?,
|
||||
onSave: (String) -> Unit,
|
||||
onAbort: (String) -> Unit,
|
||||
) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
var abortMode by remember { mutableStateOf(false) }
|
||||
var phrase by remember { mutableStateOf("") }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = { /* 必须给出预期或误操作结束,不能被关掉 */ },
|
||||
title = { Text(if (abortMode) "误操作结束" else "填写学习预期") },
|
||||
text = {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
if (abortMode) {
|
||||
Text(
|
||||
"此操作会删除本次会话与学习预期,不产生碎片和报告,且不可恢复。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = phrase,
|
||||
onValueChange = { phrase = it },
|
||||
label = { Text("确认语") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
"会话必须有学习预期才能正式开始。写下这次想学会什么,结束时会拿它做达成判断。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
label = { Text("本次学习预期(不可为空)") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (error != null) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
if (abortMode) {
|
||||
Button(
|
||||
onClick = { onAbort(phrase) },
|
||||
enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
|
||||
) { Text("确认放弃") }
|
||||
} else {
|
||||
Button(
|
||||
onClick = { onSave(text) },
|
||||
enabled = !busy && text.isNotBlank(),
|
||||
) { Text("保存并开始") }
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
if (abortMode) {
|
||||
TextButton(onClick = { abortMode = false }) { Text("返回") }
|
||||
} else {
|
||||
TextButton(onClick = { abortMode = true }) { Text("误操作结束") }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束会话:报告为结构化三段。有碎片且三段还空着时,先取一次草稿作为编辑起点;
|
||||
* 草稿生成失败不阻塞手写。用户改过之后再点「AI 重新生成」会先确认再覆盖。
|
||||
*/
|
||||
@Composable
|
||||
private fun EndSessionDialog(
|
||||
defaultSummary: String,
|
||||
busy: Boolean,
|
||||
state: SessionController.State,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (ReportSections) -> Unit,
|
||||
onGenerateDraft: () -> Unit,
|
||||
) {
|
||||
var summary by remember { mutableStateOf(defaultSummary) }
|
||||
var summary by remember { mutableStateOf("") }
|
||||
var verdict by remember { mutableStateOf("") }
|
||||
var free by remember { mutableStateOf("") }
|
||||
var confirmRegenerate by remember { mutableStateOf(false) }
|
||||
val hasFragments = state.fragments.isNotEmpty()
|
||||
|
||||
fun currentSections(): ReportSections = ReportSections(summary, verdict, free)
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
if (currentSections().allBlank && hasFragments) onGenerateDraft()
|
||||
}
|
||||
// 草稿是整段覆盖的:它就是这次生成的编辑起点
|
||||
LaunchedEffect(state.draft) {
|
||||
state.draft?.let {
|
||||
summary = it.sessionSummary
|
||||
verdict = it.expectationVerdict
|
||||
free = it.freeSummary
|
||||
}
|
||||
}
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -280,10 +391,24 @@ private fun EndSessionDialog(
|
||||
text = {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"三段都可留空,但至少要写一段。全空时会记为「未填写总结」。",
|
||||
"三段都可留空,写多少算多少;留空时报告里记「未填写总结」。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (state.draftLoading) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
CircularProgressIndicator(modifier = Modifier.height(16.dp), strokeWidth = 2.dp)
|
||||
Text(
|
||||
" AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
state.draftError?.let {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = summary,
|
||||
@@ -308,23 +433,42 @@ private fun EndSessionDialog(
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
TextButton(
|
||||
onClick = {
|
||||
// 用户已经写过内容时先确认,避免手滑覆盖
|
||||
if (currentSections().allBlank) onGenerateDraft() else confirmRegenerate = true
|
||||
},
|
||||
enabled = !state.draftLoading && hasFragments,
|
||||
) { Text("AI 重新生成") }
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
val sections = if (summary.isBlank() && verdict.isBlank() && free.isBlank()) {
|
||||
ReportSections("", "", "(在手机上结束了本次学习,未填写总结)")
|
||||
} else {
|
||||
ReportSections(summary, verdict, free)
|
||||
}
|
||||
onConfirm(sections)
|
||||
},
|
||||
enabled = !busy,
|
||||
onClick = { onConfirm(currentSections()) },
|
||||
// 草稿只是编辑起点:正在生成时也允许直接手写结束
|
||||
enabled = !state.busy,
|
||||
) { Text("确认结束") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
|
||||
if (confirmRegenerate) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmRegenerate = false },
|
||||
title = { Text("重新生成学习总结") },
|
||||
text = { Text("会用新草稿覆盖当前三段内容(包括你已经编辑的部分),确定继续吗?") },
|
||||
confirmButton = {
|
||||
Button(onClick = {
|
||||
confirmRegenerate = false
|
||||
onGenerateDraft()
|
||||
}) { Text("重新生成") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmRegenerate = false }) { Text("取消") }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -32,6 +32,7 @@ fun TaskListScreen(
|
||||
username: String?,
|
||||
onRefresh: () -> Unit,
|
||||
onStart: (TaskItem) -> Unit,
|
||||
onOpenReports: (TaskItem) -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenPermissions: () -> Unit,
|
||||
onLogout: () -> Unit,
|
||||
@@ -124,6 +125,7 @@ fun TaskListScreen(
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
TextButton(onClick = { onOpenReports(task) }) { Text("报告") }
|
||||
Text(
|
||||
"开始学习 ›",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.catshark.lpt.util
|
||||
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
/** 把秒数格式化成 mm:ss 或 h:mm:ss */
|
||||
fun formatDuration(seconds: Double): String {
|
||||
val total = seconds.toLong().coerceAtLeast(0)
|
||||
@@ -8,3 +11,11 @@ fun formatDuration(seconds: Double): String {
|
||||
val s = total % 60
|
||||
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
|
||||
}
|
||||
|
||||
private val DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
|
||||
|
||||
/** 服务端返回的 LocalDateTime 字符串(无时区),解析失败时原样展示 */
|
||||
fun formatDateTime(iso: String?): String {
|
||||
if (iso.isNullOrBlank()) return ""
|
||||
return runCatching { LocalDateTime.parse(iso).format(DATE_TIME_FORMAT) }.getOrDefault(iso)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user