5 Commits
Author SHA1 Message Date
cat-shark d71bfe2139 fix: 补齐设置保存/登录的中间层在途守卫,并去重同文案提示
- 真机双击验证发现:设置页「保存」两次点击都会真的写一遍(DataStore 写太快,UI 标记在第二次点击前就已复位),会看到两条一样的提示
- AppContainer 增加 authInFlight / baseUrlSaving 在途标记,重复调用直接忽略
- snackbar 增加同文案 1.5 秒去重,连点不再堆两条相同提示
2026-11-08 22:44:28 +08:00
cat-shark 27d4bcc774 fix: 所有发请求的按钮加防连点
- SessionController 新增在途标记 expectationSaving / fragmentAdding,入口早退 + 按钮禁用(文案改「保存中…」「记录中…」)
- 记碎片改为「成功才清空输入、失败保留」;浮窗拉起的碎片输入页同样防连点,且写入成功才关弹窗
- 设置页保存 API 地址期间禁用按钮;登录按钮补显式重入保护
- 任务列表开始会话在途时禁用卡片(文案改「开始中…」),不再能连点重复开始
2026-11-08 22:37:57 +08:00
cat-shark 267570dcab fix: 修复加载动画变形、补动作反馈,并收紧冲突弹窗
- CircularProgressIndicator 误用 Modifier.height() 会拿到非方形画布,圆环被压扁且旋转中心偏;四处统一改为 Modifier.size()
- 保存预期 / 保存 API 地址 / 开始暂停结束 / 记碎片都有 snackbar 反馈(成功短、失败长),不再只靠页面底部静态文案
- API 地址改为先校验再写入(不合法保留旧地址并提示),登录页同样校验;启动时遇到坏地址退回默认,不再抛异常
- 冲突弹窗只保留「前往继续 / 取消」:结束与误操作结束必须回到会话页面里用户自己做,列表页不再提供放弃/结束入口
2026-11-08 22:21:45 +08:00
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
14 changed files with 461 additions and 198 deletions
+54 -9
View File
@@ -113,6 +113,12 @@ jobs:
SHA: ${{ gitea.sha }}
run: |
set -euo pipefail
# runner 上只有 coreutils / grep / curl:不得依赖 python3、jq、node
# (历史上这三个都缺过:JS action 报 node,本步曾报 python3)
for t in curl grep cut head sed mktemp; do
command -v "$t" > /dev/null || { echo "ERROR: runner 缺少命令 $t"; exit 1; }
done
if [ -z "${TOKEN:-}" ]; then
echo "ERROR: GITEA_TOKEN 为空——本步骤依赖 Gitea 为每个 job 自动注入的仓库令牌"
exit 1
@@ -127,26 +133,50 @@ jobs:
test -f "$APK"
AUTH=(-H "Authorization: token ${TOKEN}")
# 1) 找滚动 release;不存在就创建(tag 不存在时 Gitea 会按 target_commitish 建)
RID="$(curl -sS "${AUTH[@]}" "$API/releases/tags/$TAG" \
| python3 -c 'import sys,json;print(json.load(sys.stdin).get("id",""))' 2>/dev/null || true)"
# 纯 shell 取 JSON 字段(不依赖 python3/jq)。
# 正则对空白宽容(Gitea 默认是紧凑 JSON,但保留容错以便任何重编码都不影响)。
# 找不到时返回空(`|| true`),否则 set -e 会直接中断。
name_re() { printf '%s' "$1" | sed 's/[.[\*^$()+?{}|]/\\&/g'; }
first_id() { grep -oE '"id"[[:space:]]*:[[:space:]]*[0-9]+' | head -1 | grep -oE '[0-9]+' | head -1 || true; }
asset_id() {
grep -oE '\{[[:space:]]*"id"[[:space:]]*:[[:space:]]*[0-9]+[[:space:]]*,[[:space:]]*"name"[[:space:]]*:[[:space:]]*"[^"]*"' \
| grep -E "\"name\"[[:space:]]*:[[:space:]]*\"$(name_re "$1")\"" \
| head -1 \
| sed -E 's/^\{[[:space:]]*"id"[[:space:]]*:[[:space:]]*([0-9]+).*/\1/' || true
}
# 1) 找滚动 release(看状态码而不是解析错误体);不存在就创建
REL_JSON="$(mktemp)"
CODE="$(curl -sS -o "$REL_JSON" -w '%{http_code}' "${AUTH[@]}" "$API/releases/tags/$TAG")"
echo "查 $TAG: HTTP $CODE"
if [ "$CODE" = "200" ]; then
RID="$(cat "$REL_JSON" | first_id)"
else
RID=""
fi
if [ -z "$RID" ]; then
echo "创建滚动 release: $TAG(分支 $BRANCH)"
RID="$(curl -fsS "${AUTH[@]}" -H 'Content-Type: application/json' -X POST "$API/releases" \
curl -fsS "${AUTH[@]}" -H 'Content-Type: application/json' -X POST "$API/releases" \
-d "{\"tag_name\":\"$TAG\",\"target_commitish\":\"$BRANCH\",\"name\":\"LPT Android ${ENV_NAME}(滚动发布)\",\"body\":\"附件始终是该环境最新一次构建,每次覆盖;sha256 见对应构建日志。\"}" \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')"
-o "$REL_JSON"
RID="$(cat "$REL_JSON" | first_id)"
if [ -z "$RID" ]; then
echo "ERROR: 创建 release 后拿不到 id,响应前 300 字节:"
head -c 300 "$REL_JSON"; echo
exit 1
fi
fi
echo "release id=$RID"
# 2) 同名附件先删,保证下载链接稳定
ASSETS_JSON="$(mktemp)"
for NAME in "$ASSET" "${ASSET}.sha256"; do
curl -fsS "${AUTH[@]}" "$API/releases/$RID/assets" -o "$ASSETS_JSON"
OLD_IDS="$(ASSET_NAME="$NAME" python3 -c 'import json,os,sys;print("\n".join(str(a["id"]) for a in json.load(open(sys.argv[1])) if a["name"]==os.environ["ASSET_NAME"]))' "$ASSETS_JSON")"
for AID in $OLD_IDS; do
for NAME in "$ASSET" "${ASSET}.sha256"; do
AID="$(cat "$ASSETS_JSON" | asset_id "$NAME")"
if [ -n "$AID" ]; then
echo "删除旧附件 $NAME (id=$AID)"
curl -fsS "${AUTH[@]}" -X DELETE "$API/releases/assets/$AID" > /dev/null
done
fi
done
# 3) 上传新附件
@@ -155,5 +185,20 @@ jobs:
curl -fsS "${AUTH[@]}" -X POST "$API/releases/$RID/assets?name=${ASSET}.sha256" \
-F "attachment=@apk-sha256.txt" > /dev/null
# 4) 回读校验:两个附件名都能在 release 上找到(不依赖任何外部工具)
curl -fsS "${AUTH[@]}" "$API/releases/$RID/assets" -o "$ASSETS_JSON"
MISSING=0
for NAME in "$ASSET" "${ASSET}.sha256"; do
if grep -qE "\"name\"[[:space:]]*:[[:space:]]*\"$(name_re "$NAME")\"" "$ASSETS_JSON"; then
echo "OK: 已上传 $NAME"
else
echo "ERROR: 附件 $NAME 上传后读不到"; MISSING=1
fi
done
if [ "$MISSING" != "0" ]; then
echo "release 附件列表响应:"; head -c 500 "$ASSETS_JSON"; echo
exit 1
fi
echo "OK: https://git.cat-shark.xyz/cat-shark/lpt-android/releases/tag/$TAG"
echo "附件: $ASSET / ${ASSET}.sha256(本次 sha=${SHORT})"
+6 -3
View File
@@ -29,12 +29,15 @@
- **会话状态只在 `SessionController` 里改**。UI 和 Service 都不得自行维护会话副本,否则会与服务端口径分叉。
- **悬浮窗只做三件事:展示倒计时、记一条碎片、暂停/继续**。结束会话、写报告、改预期、看历史一律在 App 页面内完成;不要往浮窗里加按钮或面板(它常驻在其他 App 之上,每多一个控件都是常态干扰)。
- **开始新任务前必须先处理未结束会话**。`startOrContinue` 先查 `GET /study-sessions/active?excludeTaskNum=`,有冲突就只设置 `State.conflict`,由 UI 给出三个出口;不得绕过这一步直接开始,否则会同时存在两个进行中的会话。
- **开始新任务前必须先处理未结束会话**。`startOrContinue` 先查 `GET /study-sessions/active?excludeTaskNum=`,有冲突就只设置 `State.conflict`(UI 只给「前往继续 / 取消」);不得绕过这一步直接开始,也不得在列表页代替用户结束或放弃那个会话——结束与误操作结束必须在会话页里由用户自己做。
- **写操作必须有可见反馈**。保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都要给 snackbar 提示(失败文案要写清楚为什么);不要只靠页面底部一行静态文案。
- **发请求的按钮必须防连点**。在中间层(`SessionController` / `AppContainer`)加“在途”标记并在入口早退,同时把按钮 `enabled` 绑到该标记(文案可改「保存中…」);涉及写入的动作要“成功才清输入、失败保留输入”,不能让一次连点变成两条碎片。
- **学习预期不可为空**。`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`),不要假设源码与部署一致——两者已经分叉过一次。
## 后端
@@ -60,8 +63,8 @@
3. 容器内构建 APK(`ci/Dockerfile` 固定 JDK 17 / cmdline-tools / android-36),产物上传到该环境的**滚动 Release** 并在日志打印 sha256。
- APK 不入 Git(`.gitignore` 已忽略 `*.apk`),分发走 Release 附件:
`https://git.cat-shark.xyz/cat-shark/lpt-android/releases/tag/android-dev`(生产为 `android-prod`),每次构建覆盖同名附件。
- **本仓库的流水线不使用任何 `uses:` action**:runner 上没有 `node`,JS action(含 `actions/upload-artifact`)会报 `Cannot find: node in PATH`。
归档改用 Gitea 的 Release API + `curl`,凭据用 Gitea 为每个 job 自动注入的 `secrets.GITEA_TOKEN`(权限由 workflow 的 `permissions: contents: write` 声明)。新增步骤时同样优先纯 shell。
- **本仓库的流水线不使用任何 `uses:` action**,也不得依赖 `python3` / `jq`(runner 上都没有,历史报错:`Cannot find: node in PATH`、`python3: command not found`)。
归档改用 Gitea 的 Release API + `curl`,只用 `grep`/`sed`/`cut` 解析 JSON,凭据用 Gitea 为每个 job 自动注入的 `secrets.GITEA_TOKEN`(权限由 workflow 的 `permissions: contents: write` 声明)。新增步骤前先确认工具在 runner 上存在(脚本开头有 `command -v` 预检)。
## 提交规范
+5 -4
View File
@@ -17,11 +17,12 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
| 模块 | 内容 |
|------|------|
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头 |
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头;服务端返回 401 时自动退出登录并在登录页说明原因 |
| 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
| 任务列表 | `GET /tasks`,每个任务带「报告」入口 |
| 任务列表 | `GET /tasks`,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
| 操作反馈 | 保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都有 snackbar 提示(成功短、失败长);所有发请求的按钮在途时禁用,防连点重复提交 |
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期(必填)、知识碎片、结束报告三段 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话;有冲突时只给「前往继续 / 取消」,结束与误操作结束必须回到那个会话的页面里自己做 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;**只做三件事**:展示倒计时 / 记一条碎片 / 暂停继续 |
| 学习报告 | 结束会话时取 AI(不可用则规则降级)三段草稿作为编辑起点;任务页可查看历史报告与本次碎片 |
| 设置 | API 地址可切(默认 dev) |
@@ -125,7 +126,7 @@ app/src/main/java/com/catshark/lpt/
## 已知限制
- 浮窗依赖悬浮窗权限;进程被杀后靠 `START_STICKY` + 启动时对账恢复,被系统彻底禁止后台启动时(部分国内 ROM)仍需用户手动打开一次 App。
- 浮窗依赖悬浮窗权限;进程被杀后靠 `START_STICKY` + 启动时对账恢复。实测 **MIUI(Android 12)不会重启被杀的进程**:进程没了浮窗就没了,需要用户打开一次 App 才恢复(打开后的对账是可靠的)。
- 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。
- 报告第四部分「按归属分组的碎片」由复习模块实时聚合,本客户端按仓库边界不访问复习端点,报告页只列本次会话产生的碎片。
- 没有自动化测试;`.gitea/workflows/build.yml` 只构建不跑测试。
+73 -11
View File
@@ -4,6 +4,7 @@ import android.app.Application
import com.catshark.lpt.data.ApiClient
import com.catshark.lpt.data.LptRepository
import com.catshark.lpt.data.TokenStore
import com.catshark.lpt.service.StudySessionService
import com.catshark.lpt.session.SessionController
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -45,10 +46,24 @@ 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()
init {
apiClient.onUnauthorized = { expireLogin() }
scope.launch {
val settings = tokenStore.load()
apiClient.setBaseUrl(settings.baseUrl)
// 历史数据里的地址如果已经解析不出来,退回默认地址,不要带着坏地址启动
if (!apiClient.setBaseUrl(settings.baseUrl)) apiClient.setBaseUrl(ApiClient.DEFAULT_BASE_URL)
apiClient.token = settings.token
_baseUrl.value = settings.baseUrl
_username.value = settings.username
@@ -64,38 +79,85 @@ class AppContainer(private val app: Application) {
}
fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
// 在途时直接忽略重复提交:登录是重操作,不能因为手抖发两次
if (authInFlight) return
authInFlight = true
scope.launch {
apiClient.setBaseUrl(baseUrl)
try {
if (!apiClient.setBaseUrl(baseUrl)) {
onResult("API 地址不合法,需要形如 https://host/api")
return@launch
}
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
}
}
}
fun logout() {
scope.launch {
repository.logout()
tokenStore.clearLogin()
apiClient.token = null
session.clear()
_loggedIn.value = false
session.markResolved()
clearLoginState()
}
}
fun updateBaseUrl(url: String) {
/**
* token 失效:本地直接退出登录并回登录页。
* 不调 /logout(这个 token 已经无效了),也不再发请求,避免递归。
*/
private fun expireLogin() {
if (!_loggedIn.value) return
scope.launch {
apiClient.setBaseUrl(url)
tokenStore.saveBaseUrl(url)
_baseUrl.value = url
_authNotice.value = "登录已失效,请重新登录"
StudySessionService.stop(app)
clearLoginState()
}
}
private suspend fun clearLoginState() {
tokenStore.clearLogin()
apiClient.token = null
session.clear()
session.markResolved()
_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
scope.launch {
try {
tokenStore.saveBaseUrl(value)
_baseUrl.value = value
onResult(null)
} finally {
baseUrlSaving = false
}
}
}
}
@@ -17,6 +17,9 @@ 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
@@ -89,6 +92,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
val username by container.username.collectAsState()
val baseUrl by container.baseUrl.collectAsState()
val sessionState by container.session.state.collectAsState()
val authNotice by container.authNotice.collectAsState()
val openEnd by openEndRequest
var screen by remember { mutableStateOf(Screen.Tasks) }
@@ -97,6 +101,24 @@ 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
@@ -138,11 +160,37 @@ 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()) {
// 不在会话页时,会话层的失败也要让用户看到(用正常布局占位,不遮住下面的标题)
if (screen != Screen.Session) {
sessionState.error?.let { message ->
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
}
}
Box(modifier = Modifier.weight(1f)) {
when {
!ready -> LoadingScreen()
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
!loggedIn -> LoginScreen(
initialBaseUrl = baseUrl,
notice = authNotice,
) { user, password, url, onResult ->
container.login(user, password, url, onResult)
}
@@ -162,6 +210,9 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
reportTask = task
screen = Screen.Reports
},
hasActiveSession = sessionState.hasSession,
starting = sessionState.busy,
onOpenSession = { screen = Screen.Session },
onOpenSettings = { screen = Screen.Settings },
onOpenPermissions = { screen = Screen.Permissions },
onLogout = {
@@ -193,8 +244,8 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
refreshTasks()
}
},
onSaveExpectation = { container.session.saveExpectation(it) },
onAddFragment = { container.session.addFragment(it) },
onSaveExpectation = { text, onResult -> container.session.saveExpectation(text, onResult) },
onAddFragment = { text, onResult -> container.session.addFragment(text, onResult) },
onShowOverlay = { StudySessionService.showOverlay(context) },
onGenerateDraft = { container.session.generateReportDraft() },
onBack = { screen = Screen.Tasks },
@@ -218,7 +269,12 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
Screen.Settings -> SettingsScreen(
baseUrl = baseUrl,
onSave = { container.updateBaseUrl(it) },
onSave = { url, done ->
container.updateBaseUrl(url) { error ->
toast(error ?: "API 地址已保存", long = error != null)
done(error)
}
},
onLogout = {
StudySessionService.stop(context)
container.logout()
@@ -227,41 +283,47 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
)
}
}
}
}
// 会话-05:别的任务上还有未结束会话时,先让用户选出口
// 会话-05:别的任务上还有未结束会话时,只能先去把它处理完
sessionState.conflict?.let {
SessionConflictDialog(
state = sessionState,
onAction = { action ->
container.session.resolveConflict(action) { StudySessionService.start(context) }
onContinue = {
// hasSession 一直是 true,靠状态变化不会触发导航,这里必须显式回会话页
container.session.continueConflict {
StudySessionService.start(context)
screen = Screen.Session
}
},
onDismiss = { container.session.dismissConflict() },
)
}
// 不在会话页时,会话层的失败也要让用户看到
if (screen != Screen.Session) {
sessionState.error?.let { message ->
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
}
}
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter),
)
}
}
/**
* 会话-05 的出口选择弹窗:不能直接开始新任务,必须先说清旧会话怎么办。
* 三个出口对应 lpt-docs「离开一个未结束的会话」:前往继续 / 结束它并开始 / 放弃它。
* 会话-05:别的任务上还有未结束会话时的提示。
*
* 这里故意只给「前往继续」与「取消」:结束与误操作结束都必须在那个会话自己的页面里由用户完成,
* 列表页不允许一句话就把未完成的会话结掉或丢掉。
*/
@Composable
private fun SessionConflictDialog(
state: SessionController.State,
onAction: (SessionController.ConflictAction) -> Unit,
onContinue: () -> Unit,
onDismiss: () -> Unit,
) {
val conflict = state.conflict ?: return
val busy = state.conflictBusy
AlertDialog(
onDismissRequest = { if (busy == null) onDismiss() },
onDismissRequest = { if (!busy) onDismiss() },
title = { Text("还有未结束的学习会话") },
text = {
Column {
@@ -282,15 +344,15 @@ private fun SessionConflictDialog(
)
}
Text(
"可以直接开始当前任务:开始时会先把上面这个会话结束(会生成一份未填总结的学习报告);" +
"如果它本来就是误操作开启的,可以选择放弃,不会留下任何记录。",
"需要先把它处理完才能开始新任务。结束或误操作结束都请在那个会话的页面里操作," +
"这里不提供「放弃」这个入口。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (busy != null) {
if (busy) {
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 {
@@ -301,23 +363,13 @@ private fun SessionConflictDialog(
confirmButton = {
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Button(
onClick = { onAction(SessionController.ConflictAction.CONTINUE) },
enabled = busy == null,
onClick = onContinue,
enabled = !busy,
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,
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
) { Text("取消") }
}
@@ -2,6 +2,7 @@ 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
@@ -16,6 +17,10 @@ class ApiClient {
@Volatile
var token: String? = null
/** 服务端返回 401(token 失效)时的回调,由 AppContainer 接管成“退出登录” */
@Volatile
var onUnauthorized: (() -> Unit)? = null
@Volatile
private var baseUrl: String? = null
@@ -32,22 +37,30 @@ class ApiClient {
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
token?.takeIf { it.isNotBlank() }?.let { builder.header("satoken", it) }
chain.proceed(builder.build())
val response = chain.proceed(builder.build())
// token 失效:登录接口本身的 401 由登录页自己处理,这里只处理已登录后的失效
if (response.code == 401) onUnauthorized?.invoke()
response
}
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
fun setBaseUrl(url: String) {
/**
* 切换 baseUrl。地址不合法(解析不出 http/https)时返回 false,并把旧地址保留,不抛异常。
*/
fun setBaseUrl(url: String): Boolean {
val normalized = url.trim().let { if (it.endsWith("/")) it else "$it/" }
if (normalized == baseUrl && retrofit != null) return
val parsed = normalized.toHttpUrlOrNull() ?: return false
if (normalized == baseUrl && retrofit != null) return true
baseUrl = normalized
retrofit = Retrofit.Builder()
.baseUrl(normalized)
.baseUrl(parsed)
.client(okHttp)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
return true
}
val currentBaseUrl: String get() = baseUrl ?: DEFAULT_BASE_URL
@@ -19,27 +19,40 @@ class LptRepository(private val apiClient: ApiClient) {
return env.data as T
}
/** 统一的请求包装:网络/HTTP 层错误都换成用户看得懂的话 */
private inline fun <T> call(block: () -> T): Result<T> = runCatching(block).friendly()
/**
* 把 HTTP 层错误换成用户看得懂的话。
* 部署环境的 dev 后端比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
* 把网络/HTTP 层错误换成用户看得懂的话。
* 部署环境的 dev 后端可能比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
*/
private fun <T> Result<T>.friendly(action: String): Result<T> {
private fun <T> Result<T>.friendly(action: String? = null): Result<T> {
val error = exceptionOrNull()
return if (error is HttpException) {
Result.failure(ApiException("$action 不可用(HTTP ${error.code()}),当前后端可能还没上这个接口"))
return when {
error is HttpException -> {
val detail = "HTTP ${error.code()}"
val message = if (action != null) {
"$action 不可用($detail),当前后端可能还没上这个接口"
} else {
this
"请求失败($detail),请稍后重试"
}
Result.failure(ApiException(message))
}
error is java.io.IOException -> Result.failure(ApiException("网络不可用,请检查网络或设置里的 API 地址"))
else -> this
}
}
suspend fun login(username: String, password: String): Result<String> = runCatching {
suspend fun login(username: String, password: String): Result<String> = call {
val env = api.login(LoginRequest(username, password))
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "登录失败")
extractToken(env.data)?.takeIf { it.isNotBlank() } ?: throw ApiException("登录响应缺少 token")
}
suspend fun logout(): Result<Unit> = runCatching { api.logout() }
suspend fun logout(): Result<Unit> = call { api.logout() }
suspend fun tasks(): Result<List<TaskItem>> = runCatching {
suspend fun tasks(): Result<List<TaskItem>> = call {
envelope(api.tasks(), "获取任务").records
}
@@ -49,41 +62,41 @@ class LptRepository(private val apiClient: ApiClient) {
* - 传入 `excludeTaskNum` 时,属于该任务的会话不算冲突(后端直接返回 null);
* - 业务失败(code != 200)与网络异常一律上抛:调用方需要区分「确实没有会话」和「没问到」。
*/
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = runCatching {
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = call {
val env = api.activeSession(excludeTaskNum)
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "查询未结束会话失败")
env.data?.takeIf { it.sessionNum.isNotBlank() }
}
suspend fun startOrContinue(taskNum: String): Result<SessionDetail> = runCatching {
suspend fun startOrContinue(taskNum: String): Result<SessionDetail> = call {
envelope(api.startOrContinue(taskNum), "开始学习会话")
}
suspend fun sessionDetail(sessionNum: String): Result<SessionDetail> = runCatching {
suspend fun sessionDetail(sessionNum: String): Result<SessionDetail> = call {
envelope(api.sessionDetail(sessionNum), "获取会话")
}
suspend fun getExpectation(sessionNum: String): Result<String> = runCatching {
suspend fun getExpectation(sessionNum: String): Result<String> = call {
api.getExpectation(sessionNum).takeIf { it.code == 200 }?.data?.description.orEmpty()
}
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = runCatching {
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = call {
envelope(api.putExpectation(sessionNum, ExpectationRequest(description)), "保存学习预期")
Unit
}
suspend fun continueSession(sessionNum: String): Result<Unit> = runCatching {
suspend fun continueSession(sessionNum: String): Result<Unit> = call {
envelope(api.continueSession(sessionNum), "继续学习会话")
Unit
}
suspend fun pauseSession(sessionNum: String): Result<Unit> = runCatching {
suspend fun pauseSession(sessionNum: String): Result<Unit> = call {
envelope(api.pauseSession(sessionNum), "暂停学习会话")
Unit
}
/** 结束会话;后端可能返回一条提示(如有效时间不足),作为 message 带回 */
suspend fun endSession(sessionNum: String, sections: ReportSections): Result<String?> = runCatching {
suspend fun endSession(sessionNum: String, sections: ReportSections): Result<String?> = call {
val env = api.endSession(
sessionNum,
EndSessionRequest(
@@ -97,12 +110,12 @@ class LptRepository(private val apiClient: ApiClient) {
env.message
}
suspend fun abortSession(sessionNum: String, confirmation: String): Result<Unit> = runCatching {
suspend fun abortSession(sessionNum: String, confirmation: String): Result<Unit> = call {
envelope(api.abortSession(sessionNum, AbortRequest(confirmation)), "误操作结束")
Unit
}
suspend fun createFragment(sessionNum: String, content: String): Result<Unit> = runCatching {
suspend fun createFragment(sessionNum: String, content: String): Result<Unit> = call {
envelope(
api.createFragment(CreateFragmentRequest(contextNum = sessionNum, sessionNum = sessionNum, content = content)),
"记录碎片",
@@ -110,7 +123,7 @@ class LptRepository(private val apiClient: ApiClient) {
Unit
}
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = runCatching {
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = call {
api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
}
@@ -31,9 +31,6 @@ class SessionController(
enum class Status { NONE, ONGOING, PAUSED, ENDED }
/** 会话-05 的出口选择 */
enum class ConflictAction { CONTINUE, END_AND_START, ABORT }
/** 别的任务上还有未结束会话:用户必须先选一个出口 */
data class Conflict(
/** 用户想开始的任务 */
@@ -55,14 +52,18 @@ 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: ConflictAction? = null,
val conflictBusy: Boolean = false,
val conflictError: String? = null,
/** 报告草稿(AI 或规则降级),仅作为结束弹窗的编辑起点,不落库 */
val draft: ReportSections? = null,
@@ -131,14 +132,15 @@ class SessionController(
}
}
/** 处理会话-05 的出口选择 */
fun resolveConflict(action: ConflictAction, onSessionReady: () -> Unit = {}) {
/**
* 会话-05:有冲突时唯一能做的就是「前往继续」。
* 结束 / 误操作结束都必须在那个会话自己的页面里做,列表页不提供这些出口。
*/
fun continueConflict(onSessionReady: () -> Unit = {}) {
val conflict = _state.value.conflict ?: return
if (_state.value.conflictBusy != null) return
_state.update { it.copy(conflictBusy = action, conflictError = null) }
if (_state.value.conflictBusy) return
_state.update { it.copy(conflictBusy = true, conflictError = null) }
scope.launch {
when (action) {
ConflictAction.CONTINUE -> {
repo.sessionDetail(conflict.sessionNum)
.onSuccess { detail ->
applyDetail(detail)
@@ -147,7 +149,7 @@ class SessionController(
taskNum = conflict.taskNum,
taskName = conflict.taskName ?: it.taskName,
conflict = null,
conflictBusy = null,
conflictBusy = false,
)
}
loadAuxiliary(conflict.sessionNum)
@@ -155,29 +157,6 @@ class SessionController(
}
.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 = "已放弃上一个会话,未产生任何数据")
}
}
}
}
fun pause() {
@@ -204,34 +183,59 @@ class SessionController(
}
}
fun saveExpectation(text: String, onSaved: () -> Unit = {}) {
/**
* 保存学习预期。在途时再点直接返回,并在成功时回调;失败文案走 State.error(由页面弹提示)。
*/
fun saveExpectation(text: String, onResult: (String?) -> 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 = "学习预期已保存") }
onSaved()
_state.update {
it.copy(expectation = value, expectationLoaded = true, notice = "学习预期已保存")
}
.onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } }
onResult(null)
}
.onFailure { e ->
val message = e.message ?: "保存学习预期失败"
_state.update { it.copy(error = message) }
onResult(message)
}
_state.update { it.copy(expectationSaving = false) }
}
}
fun addFragment(content: String) {
/**
* 记一条知识碎片。在途时再点直接返回,避免一次输入变成两条碎片;
* onResult 给 null 表示已写入,UI 可以据此清空输入框(失败时保留输入)。
*/
fun addFragment(content: String, onResult: (String?) -> Unit = {}) {
val num = _state.value.sessionNum ?: return
if (content.isBlank()) return
val value = content.trim()
if (value.isBlank()) return
if (_state.value.fragmentAdding) return
_state.update { it.copy(fragmentAdding = true) }
scope.launch {
repo.createFragment(num, content)
repo.createFragment(num, value)
.onSuccess {
repo.fragments(num).onSuccess { list ->
_state.update { it.copy(fragments = list, notice = "已记录一条碎片") }
}
onResult(null)
}
.onFailure { e -> _state.update { it.copy(error = e.message ?: "记录碎片失败") } }
.onFailure { e ->
val message = e.message ?: "记录碎片失败"
_state.update { it.copy(error = message) }
onResult(message)
}
_state.update { it.copy(fragmentAdding = false) }
}
}
@@ -360,7 +364,7 @@ class SessionController(
it.copy(
busy = false,
conflict = null,
conflictBusy = null,
conflictBusy = false,
conflictError = null,
expectationLoaded = false,
notice = note ?: it.notice,
@@ -373,7 +377,7 @@ class SessionController(
_state.update {
it.copy(
busy = false,
conflictBusy = null,
conflictBusy = false,
conflictError = e.message ?: "开始学习会话失败",
error = if (it.conflict == null) e.message ?: "开始学习会话失败" else null,
)
@@ -383,7 +387,7 @@ class SessionController(
private fun failConflict(error: Throwable) {
_state.update {
it.copy(conflictBusy = null, conflictError = error.message ?: "处理上一个会话失败,请重试")
it.copy(conflictBusy = false, conflictError = error.message ?: "打开这个会话失败,请重试")
}
}
@@ -442,8 +446,5 @@ class SessionController(
companion object {
/** 误操作结束的确认语,前后端各校验一次 */
const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
/** 开始新任务时结束旧会话留下的报告正文,让用户看得出这条报告是怎么来的 */
const val STALE_SESSION_SUMMARY = "(开始新任务时结束了这个会话,未填写学习总结)"
}
}
@@ -47,9 +47,8 @@ class FragmentInputActivity : ComponentActivity() {
LptTheme {
FragmentInputDialog(
sessionNum = (application as LptApp).container.session.state.value.sessionNum,
onSubmit = { text ->
(application as LptApp).container.session.addFragment(text)
finish()
onSubmit = { text, onResult ->
(application as LptApp).container.session.addFragment(text, onResult)
},
onDismiss = { finish() },
)
@@ -61,10 +60,13 @@ class FragmentInputActivity : ComponentActivity() {
@Composable
private fun FragmentInputDialog(
sessionNum: String?,
onSubmit: (String) -> Unit,
onSubmit: (String, (String?) -> Unit) -> 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
@@ -99,18 +101,35 @@ 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) { Text("取消") }
TextButton(onClick = onDismiss, enabled = !submitting) { Text("取消") }
Spacer(Modifier.height(0.dp))
Button(
onClick = { onSubmit(text.trim()) },
enabled = text.isNotBlank() && sessionNum != null,
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,
modifier = Modifier.padding(start = 8.dp),
) { Text("保存") }
) { Text(if (submitting) "保存中…" else "保存") }
}
}
}
@@ -7,6 +7,7 @@ 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
@@ -30,6 +31,7 @@ import androidx.compose.ui.unit.dp
@Composable
fun LoginScreen(
initialBaseUrl: String,
notice: String? = null,
onLogin: (username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) -> Unit,
) {
var username by remember { mutableStateOf("") }
@@ -55,6 +57,16 @@ fun LoginScreen(
)
Spacer(Modifier.height(24.dp))
if (notice != null) {
// 一直留到下次登录成功:否则用户回到登录页时已经看不到原因了
Text(
notice,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
Spacer(Modifier.height(8.dp))
}
OutlinedTextField(
value = username,
onValueChange = { username = it },
@@ -94,6 +106,7 @@ fun LoginScreen(
Spacer(Modifier.height(20.dp))
Button(
onClick = {
if (loading) return@Button
error = null
loading = true
onLogin(username.trim(), password, baseUrl.trim()) { message ->
@@ -106,7 +119,7 @@ fun LoginScreen(
) {
if (loading) {
CircularProgressIndicator(
modifier = Modifier.height(18.dp),
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.onPrimary,
)
@@ -10,6 +10,7 @@ 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
@@ -92,7 +93,7 @@ fun ReportsScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (loading) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
if (loading) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
}
if (error != null) {
@@ -9,6 +9,7 @@ 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
@@ -48,8 +49,8 @@ fun SessionScreen(
onTogglePause: () -> Unit,
onEnd: (ReportSections) -> Unit,
onAbort: (String) -> Unit,
onSaveExpectation: (String) -> Unit,
onAddFragment: (String) -> Unit,
onSaveExpectation: (String, (String?) -> Unit) -> Unit,
onAddFragment: (String, (String?) -> Unit) -> Unit,
onShowOverlay: () -> Unit,
onGenerateDraft: () -> Unit,
onBack: () -> Unit,
@@ -99,7 +100,7 @@ fun SessionScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (state.busy) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
if (state.busy) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
}
Column(
@@ -184,7 +185,14 @@ fun SessionScreen(
)
Spacer(Modifier.height(8.dp))
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
Button(onClick = { onSaveExpectation(expectationDraft) }) { Text("保存预期") }
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 "保存预期") }
}
}
}
@@ -205,11 +213,11 @@ fun SessionScreen(
Spacer(Modifier.height(0.dp))
TextButton(
onClick = {
onAddFragment(fragmentDraft)
fragmentDraft = ""
// 成功后清空输入;失败保留,避免手写的碎片白丢
onAddFragment(fragmentDraft) { error -> if (error == null) fragmentDraft = "" }
},
enabled = fragmentDraft.isNotBlank(),
) { Text("记录") }
enabled = fragmentDraft.isNotBlank() && !state.fragmentAdding,
) { Text(if (state.fragmentAdding) "记录中…" else "记录") }
}
state.fragments.forEachIndexed { index, fragment ->
Spacer(Modifier.height(8.dp))
@@ -230,11 +238,8 @@ fun SessionScreen(
}
}
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)
if (state.busy) {
Text("正在与服务器同步…", style = MaterialTheme.typography.bodySmall)
}
Spacer(Modifier.height(24.dp))
}
@@ -244,8 +249,9 @@ fun SessionScreen(
if (state.expectationRequired) {
ExpectationGateDialog(
busy = state.busy,
saving = state.expectationSaving,
error = state.error,
onSave = onSaveExpectation,
onSave = { text -> onSaveExpectation(text) {} },
onAbort = onAbort,
)
}
@@ -281,6 +287,7 @@ fun SessionScreen(
@Composable
private fun ExpectationGateDialog(
busy: Boolean,
saving: Boolean,
error: String?,
onSave: (String) -> Unit,
onAbort: (String) -> Unit,
@@ -340,8 +347,8 @@ private fun ExpectationGateDialog(
} else {
Button(
onClick = { onSave(text) },
enabled = !busy && text.isNotBlank(),
) { Text("保存并开始") }
enabled = !busy && !saving && text.isNotBlank(),
) { Text(if (saving) "保存中…" else "保存并开始") }
}
},
dismissButton = {
@@ -374,7 +381,8 @@ private fun EndSessionDialog(
fun currentSections(): ReportSections = ReportSections(summary, verdict, free)
LaunchedEffect(Unit) {
if (currentSections().allBlank && hasFragments) onGenerateDraft()
// 已经有缓存草稿时直接用它,不要为了重开弹窗再化一次 AI
if (currentSections().allBlank && hasFragments && state.draft == null) onGenerateDraft()
}
// 草稿是整段覆盖的:它就是这次生成的编辑起点
LaunchedEffect(state.draft) {
@@ -398,7 +406,7 @@ private fun EndSessionDialog(
if (state.draftLoading) {
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.height(16.dp), strokeWidth = 2.dp)
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
Text(
" AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
style = MaterialTheme.typography.bodySmall,
@@ -25,12 +25,13 @@ import androidx.compose.ui.unit.dp
@Composable
fun SettingsScreen(
baseUrl: String,
onSave: (String) -> Unit,
onSave: (String, (String?) -> Unit) -> Unit,
onLogout: () -> Unit,
onBack: () -> Unit,
) {
var draft by remember { mutableStateOf(baseUrl) }
var saved by remember { mutableStateOf(false) }
// 保存期间禁用按钮:地址写入是异步的,不加标记会被连点重复提交
var saving by remember { mutableStateOf(false) }
Column(
modifier = Modifier
@@ -45,10 +46,7 @@ fun SettingsScreen(
OutlinedTextField(
value = draft,
onValueChange = {
draft = it
saved = false
},
onValueChange = { draft = it },
label = { Text("API 地址") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
@@ -60,11 +58,14 @@ fun SettingsScreen(
)
Button(
onClick = {
onSave(draft.trim())
saved = true
if (!saving) {
saving = true
onSave(draft.trim()) { saving = false }
}
},
enabled = !saving,
modifier = Modifier.fillMaxWidth(),
) { Text(if (saved) "已保存" else "保存") }
) { Text(if (saving) "保存中…" else "保存") }
Spacer(Modifier.height(8.dp))
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
@@ -33,6 +33,9 @@ fun TaskListScreen(
onRefresh: () -> Unit,
onStart: (TaskItem) -> Unit,
onOpenReports: (TaskItem) -> Unit,
hasActiveSession: Boolean,
starting: Boolean,
onOpenSession: () -> Unit,
onOpenSettings: () -> Unit,
onOpenPermissions: () -> Unit,
onLogout: () -> Unit,
@@ -56,6 +59,33 @@ fun TaskListScreen(
TextButton(onClick = onOpenSettings) { Text("设置") }
}
if (hasActiveSession) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp)
.clickable { onOpenSession() },
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
"有一次学习正在进行",
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
)
Text(
"回到会话 ›",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
}
}
}
if (error != null) {
Row(
modifier = Modifier
@@ -100,7 +130,8 @@ fun TaskListScreen(
Card(
modifier = Modifier
.fillMaxWidth()
.clickable { onStart(task) },
// 开始会话是网络请求:在途时禁用,防连点重复提交
.clickable(enabled = !starting) { onStart(task) },
) {
Column(modifier = Modifier.padding(14.dp)) {
Text(
@@ -125,9 +156,9 @@ fun TaskListScreen(
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.weight(1f))
TextButton(onClick = { onOpenReports(task) }) { Text("报告") }
TextButton(onClick = { onOpenReports(task) }, enabled = !starting) { Text("报告") }
Text(
"开始学习 ›",
if (starting) "开始中…" else "开始学习 ›",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)