Author SHA1 Message Date
cat-shark c894025d83 feat: 同步 dev 的会话冲突、报告闭环与真机修复到生产包
内容与 dev 完全一致,只有 ApiClient.DEFAULT_BASE_URL 指向生产环境(流水线第一步会逐字校验这一行)。

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