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
21 changed files with 1551 additions and 364 deletions
+102 -8
View File
@@ -19,6 +19,11 @@ env:
DEV_API: https://lpt-dev.cat-shark.xyz/api
PROD_API: https://lpt.cat-shark.xyz/api
# 上传 Release 附件需要写权限。Gitea 会给每个 job 注入一个仓库范围的 GITEA_TOKEN,
# 它的权限由这里声明(再受实例最大值限制)。
permissions:
contents: write
jobs:
build:
runs-on: ubuntu-latest
@@ -100,11 +105,100 @@ jobs:
ls -l "$NAME"
sha256sum "$NAME" | tee apk-sha256.txt
- name: 归档 APK
uses: actions/upload-artifact@v4
with:
name: lpt-android-${{ inputs.environment }}-apk
path: |
*.apk
apk-sha256.txt
if-no-files-found: error
- name: 上传 APK 到 Release 附件
env:
TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_REF: ${{ gitea.ref }}
ENV_NAME: ${{ inputs.environment }}
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
fi
API="https://git.cat-shark.xyz/api/v1/repos/cat-shark/lpt-android"
BRANCH="${GITEA_REF#refs/heads/}"
TAG="android-${ENV_NAME}"
ASSET="lpt-android-${ENV_NAME}.apk"
SHORT="$(echo "$SHA" | cut -c1-8)"
APK="lpt-android-${ENV_NAME}-${SHORT}.apk"
test -f "$APK"
AUTH=(-H "Authorization: token ${TOKEN}")
# 纯 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)"
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 见对应构建日志。\"}" \
-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)"
curl -fsS "${AUTH[@]}" "$API/releases/$RID/assets" -o "$ASSETS_JSON"
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
fi
done
# 3) 上传新附件
curl -fsS "${AUTH[@]}" -X POST "$API/releases/$RID/assets?name=$ASSET" \
-F "attachment=@${APK}" > /dev/null
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})"
+14 -4
View File
@@ -23,21 +23,28 @@
| `data/` | 网络与本地存储;`LptApi` 是唯一接口定义处,`LptRepository` 负责 `code != 200 → ApiException` |
| `session/` | `SessionController` 是会话状态机唯一入口;UI 与服务都只读它的 `StateFlow` |
| `service/` | 前台服务与悬浮窗;不承载业务逻辑,只渲染状态并转发动作 |
| `ui/` | Compose 页面;不直接调 Retrofit,只调 `SessionController` / `AppContainer` |
| `ui/` | Compose 页面(含 `ReportsScreen`);不直接调 Retrofit,只调 `SessionController` / `AppContainer` |
## 必须遵守的约定
- **会话状态只在 `SessionController` 里改**。UI 和 Service 都不得自行维护会话副本,否则会与服务端口径分叉。
- **悬浮窗只做三件事:展示倒计时、记一条碎片、暂停/继续**。结束会话、写报告、改预期、看历史一律在 App 页面内完成;不要往浮窗里加按钮或面板(它常驻在其他 App 之上,每多一个控件都是常态干扰)。
- **开始新任务前必须先处理未结束会话**。`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`),不要假设源码与部署一致——两者已经分叉过一次。
## 后端
- dev:`https://lpt-dev.cat-shark.xyz/api`
- 认证:Sa-Token,token 放请求头 `satoken`(不用 Cookie)
- 只使用学习会话相关端点,**不碰 `review/*`**
- 只使用学习会话相关端点(含报告与 `POST /ai/tasks` 的 `REPORT_DRAFT`),**不碰复习端点**(`review` 前缀)
## 分支与发布
@@ -53,8 +60,11 @@
- 构建在 Gitea 手动触发 `.gitea/workflows/build.yml`(dev/prod 二选一),不需要签本地环境:
1. 校验「分支 ↔ 环境」(从 dev 发 prod 直接被拒);
2. 校验代码里的 `DEFAULT_BASE_URL` 是否与本环境一致,不一致直接失败;
3. 容器内构建 APK(`ci/Dockerfile` 固定 JDK 17 / cmdline-tools / android-36),产物归档为 Actions artifact 并打印 sha256。
- APK 不入 Git(`.gitignore` 已忽略 `*.apk`),分发走 Actions artifact。
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**,也不得依赖 `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` 预检)。
## 提交规范
+20 -13
View File
@@ -8,18 +8,23 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
- 浮窗常驻在其他 App 之上,学习计时不因切走而中断。
- 不抢输入法焦点、不挡住下层 App 的触摸(`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL`)。
- 12 秒无操作自动收成贴边小胶囊,点一下恢复;常态 80% 不透明,收起后 60%。
- 12 秒无操作自动收成贴边小胶囊,点一下恢复;常态 80% 不透明,收起后约 60%。
- 可在浮窗里直接记一条知识碎片(拉起轻量输入弹窗)。
浮窗的职责被刻意压到最小:**只展示倒计时、记碎片、暂停/继续**。其余动作(结束会话、写报告、改预期、看历史)都在 App 页面内完成。
## 功能范围
| 模块 | 内容 |
|------|------|
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头 |
| 登录 | `POST /login` 拿 token,DataStore 持久化,OkHttp 拦截器注入 `satoken` 请求头;服务端返回 401 时自动退出登录并在登录页说明原因 |
| 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
| 任务列表 | `GET /tasks` |
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期、知识碎片、结束报告三段 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;暂停/继续/结束/记碎片/半隐藏 |
| 任务列表 | `GET /tasks`,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
| 操作反馈 | 保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都有 snackbar 提示(成功短、失败长);所有发请求的按钮在途时禁用,防连点重复提交 |
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期(必填)、知识碎片、结束报告三段 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话;有冲突时只给「前往继续 / 取消」,结束与误操作结束必须回到那个会话的页面里自己做 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;**只做三件事**:展示倒计时 / 记一条碎片 / 暂停继续 |
| 学习报告 | 结束会话时取 AI(不可用则规则降级)三段草稿作为编辑起点;任务页可查看历史报告与本次碎片 |
| 设置 | API 地址可切(默认 dev) |
**不做**:复习(`review/*`)、思维导图、回忆对比、学习录音。
@@ -55,7 +60,7 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
两个分支**只差 `ApiClient.DEFAULT_BASE_URL` 一行**;安装后仍可在「设置」页临时改地址(调试用)。
打包走 Gitea Actions 的 `lpt-android Build`(手动触发,选 `dev` 或 `prod`),它会先校验「分支 ↔ 默认地址」是否匹配,再把 APK 归档成 artifact——本地不需要配签名环境。
打包走 Gitea Actions 的 `lpt-android Build`(手动触发,选 `dev` 或 `prod`):先校验「分支 ↔ 默认地址」是否匹配,再在容器里构建,最后把 APK 传到该环境的**滚动 Release**(`android-dev` / `android-prod`,附件每次覆盖)——本地不需要配签名环境。
## 构建与安装
@@ -88,7 +93,8 @@ gradle :app:assembleDebug
- **计时口径**:显示值 = 服务端 `effectiveTime`(基准)+ 以 `SystemClock.elapsedRealtime()` 为锚点的增量。**不用 tick 累加**,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时用服务端 `lastStartTime` 重新对锚。
- **窗口必须带 `FLAG_LAYOUT_NO_LIMITS`**:否则 WindowManager 会把越界位置夹回屏幕内,半隐藏会失效(实测 `mAttrs x=-651` 但 `mFrame` 仍是 `[0,...]`)。
- **浮窗内不做文本输入**:App 不在前台时,系统不允许后台窗口弹软键盘——实测浮窗的 `EditText` 能拿到输入连接(`mServedView=EditText`),但 IME 窗口 `mViewVisibility=0x8`(GONE)。因此「记碎片」改为拉起 `FragmentInputActivity`(带 `SYSTEM_ALERT_WINDOW` 的 App 有后台启动 Activity 豁免),并给它独立 `taskAffinity`,保存后回到用户原本在用的 App。
- **服务自恢复**:App 启动时 `GET /study-sessions/active` 对账,恢复未结束的会话;只要状态里有活跃会话就拉起前台服务,权限是后来才授予的也会每秒兜底重试 `overlay.show()`。
- **服务自恢复**:App 启动时 `GET /study-sessions/active` 对账,恢复未结束的会话;只要状态里有活跃会话就拉起前台服务,权限是后来才授予的也会每秒兜底重试 `overlay.show()`。进程被系统拉起时(`START_STICKY`)服务自己会补一次对账,**只有「对过账且确实没有会话」才停服务**,否则会先自杀而没人再拉起来。
- **浮窗职责固定为三件事**:展示倒计时、记一条碎片、暂停/继续。结束、写报告、改预期、看历史都必须在 App 页面内完成(详见 `AGENTS.md`)。
## 后端契约兼容(重要)
@@ -98,7 +104,7 @@ gradle :app:assembleDebug
|------|--------------|----------------|-----------|
| `POST /report-fragments` | `{sessionNum, content}` | `{contextNum, content}` | 两个字段都发 |
| `POST .../study-sessions/ended` | `{content}`(单段,必填) | `{sessionSummary, expectationVerdict, freeSummary}` | 发 `content`(三段拼接)+ 三段字段 |
| 报告草稿 | `GET .../report-draft`(同步 AI) | `POST /ai/tasks`(异步) | 暂未接入,报告由用户手写 |
| 报告草稿 | `GET .../report-draft`(同步 AI) | `POST /ai/tasks`(`REPORT_DRAFT` 异步任务) | 走新契约:提交后轮询 `GET /ai/tasks/{taskNum}`,失败不阻塞手写 |
| `DELETE /report-fragments/{id}` | 不存在 | 存在 | 未使用 |
排查这类问题的可靠手段:直接拉部署环境的 OpenAPI —— `GET {baseUrl}/v3/api-docs`。
@@ -108,19 +114,20 @@ gradle :app:assembleDebug
```text
app/src/main/java/com/catshark/lpt/
├── LptApp.kt Application + 手写依赖容器
├── MainActivity.kt 导航(任务列表 / 会话 / 权限 / 设置)
├── MainActivity.kt 导航(任务列表 / 会话 / 报告 / 权限 / 设置)+ 会话冲突出口弹窗
├── data/ Models / LptApi / ApiClient / TokenStore / LptRepository
├── session/SessionController.kt 会话状态机(Application 级单例,StateFlow)
├── service/
│ ├── StudySessionService.kt 前台服务 + 通知 + 调度浮窗与输入弹窗
│ └── OverlayView.kt 悬浮窗(完整条 / 半隐藏胶囊)
├── ui/ Compose 页面 + FragmentInputActivity
│ └── OverlayView.kt 悬浮窗(只做倒计时 / 记碎片 / 暂停继续)
├── ui/ Compose 页面(含 ReportsScreen)+ FragmentInputActivity
└── util/Format.kt
```
## 已知限制
- 浮窗依赖悬浮窗权限,被系统回收后需要 App 进程还活着才能自动恢复(`START_STICKY` + 启动时对账)。
- 浮窗依赖悬浮窗权限;进程被杀后靠 `START_STICKY` + 启动时对账恢复。实测 **MIUI(Android 12)不会重启被杀的进程**:进程没了浮窗就没了,需要用户打开一次 App 才恢复(打开后的对账是可靠的)。
- 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。
- 报告草稿的 AI 生成未接入(旧后端同步接口慢、新后端是异步任务,两者差异大),报告目前由用户手写。
- 报告第四部分「按归属分组的碎片」由复习模块实时聚合,本客户端按仓库边界不访问复习端点,报告页只列本次会话产生的碎片。
- 没有自动化测试;`.gitea/workflows/build.yml` 只构建不跑测试。
- 学习录音(系统混音采集)未做,属于二期。
+89 -21
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,51 +46,118 @@ 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
_loggedIn.value = !settings.token.isNullOrBlank()
_ready.value = true
if (_loggedIn.value) session.reconcile()
if (_loggedIn.value) {
session.reconcile()
} else {
// 未登录时没有会话可查:直接标记已知状态,避免前台服务一直等对账
session.markResolved()
}
}
}
fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
// 在途时直接忽略重复提交:登录是重操作,不能因为手抖发两次
if (authInFlight) return
authInFlight = true
scope.launch {
apiClient.setBaseUrl(baseUrl)
repository.login(username, password)
.onSuccess { token ->
apiClient.token = token
tokenStore.saveLogin(token, username, baseUrl)
_baseUrl.value = baseUrl
_username.value = username
_loggedIn.value = true
session.reconcile()
onResult(null)
try {
if (!apiClient.setBaseUrl(baseUrl)) {
onResult("API 地址不合法,需要形如 https://host/api")
return@launch
}
.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() {
scope.launch {
repository.logout()
tokenStore.clearLogin()
apiClient.token = null
session.clear()
_loggedIn.value = false
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
}
}
}
}
@@ -5,12 +5,24 @@ import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.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
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
@@ -22,10 +34,13 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.catshark.lpt.data.TaskItem
import com.catshark.lpt.service.StudySessionService
import com.catshark.lpt.session.SessionController
import com.catshark.lpt.ui.LoginScreen
import com.catshark.lpt.ui.PermissionScreen
import com.catshark.lpt.ui.ReportsScreen
import com.catshark.lpt.ui.SessionScreen
import com.catshark.lpt.ui.SettingsScreen
import com.catshark.lpt.ui.TaskListScreen
@@ -64,7 +79,7 @@ class MainActivity : ComponentActivity() {
}
}
private enum class Screen { Tasks, Session, Permissions, Settings }
private enum class Screen { Tasks, Session, Reports, Permissions, Settings }
@Composable
private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolean>) {
@@ -77,12 +92,32 @@ 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) }
var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) }
var tasksLoading by remember { mutableStateOf(false) }
var tasksError by remember { mutableStateOf<String?>(null) }
var reportTask by remember { mutableStateOf<TaskItem?>(null) }
// 保存/开始/结束这类动作必须给出即时反馈,不能只靠页面底部的静态文案
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
@@ -125,73 +160,243 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
}
}
when {
!ready -> LoadingScreen()
// 会话层的提示与失败统一弹 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()
}
}
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
container.login(user, password, url, onResult)
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,
notice = authNotice,
) { user, password, url, onResult ->
container.login(user, password, url, onResult)
}
else -> when (screen) {
Screen.Tasks -> TaskListScreen(
tasks = tasks,
loading = tasksLoading,
error = tasksError,
username = username,
onRefresh = { refreshTasks() },
onStart = { task ->
container.session.startOrContinue(task.taskNum) {
StudySessionService.start(context)
}
},
onOpenReports = { task ->
reportTask = task
screen = Screen.Reports
},
hasActiveSession = sessionState.hasSession,
starting = sessionState.busy,
onOpenSession = { screen = Screen.Session },
onOpenSettings = { screen = Screen.Settings },
onOpenPermissions = { screen = Screen.Permissions },
onLogout = {
StudySessionService.stop(context)
container.logout()
},
)
Screen.Session -> SessionScreen(
state = sessionState,
openEndDialog = openEnd,
onConsumeOpenEnd = { openEndRequest.value = false },
onTogglePause = {
if (sessionState.status == SessionController.Status.ONGOING) {
container.session.pause()
} else {
container.session.resume()
}
},
onEnd = { sections ->
container.session.end(sections) {
StudySessionService.stop(context)
refreshTasks()
}
},
onAbort = { phrase ->
container.session.abort(phrase) {
StudySessionService.stop(context)
refreshTasks()
}
},
onSaveExpectation = { 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 },
)
Screen.Reports -> {
val task = reportTask
if (task == null) {
LaunchedEffect(Unit) { screen = Screen.Tasks }
} else {
ReportsScreen(
taskName = task.taskName,
onLoadReports = { page -> container.repository.reports(task.taskNum, page) },
onLoadFragments = { sessionNum -> container.repository.allFragments(sessionNum) },
onBack = { screen = Screen.Tasks },
)
}
}
Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
Screen.Settings -> SettingsScreen(
baseUrl = baseUrl,
onSave = { url, done ->
container.updateBaseUrl(url) { error ->
toast(error ?: "API 地址已保存", long = error != null)
done(error)
}
},
onLogout = {
StudySessionService.stop(context)
container.logout()
},
onBack = { screen = Screen.Tasks },
)
}
}
}
}
else -> when (screen) {
Screen.Tasks -> TaskListScreen(
tasks = tasks,
loading = tasksLoading,
error = tasksError,
username = username,
onRefresh = { refreshTasks() },
onStart = { task ->
container.session.startOrContinue(task.taskNum) {
StudySessionService.start(context)
}
},
onOpenSettings = { screen = Screen.Settings },
onOpenPermissions = { screen = Screen.Permissions },
onLogout = {
StudySessionService.stop(context)
container.logout()
},
)
Screen.Session -> SessionScreen(
// 会话-05:别的任务上还有未结束会话时,只能先去把它处理完
sessionState.conflict?.let {
SessionConflictDialog(
state = sessionState,
openEndDialog = openEnd,
onConsumeOpenEnd = { openEndRequest.value = false },
onTogglePause = {
if (sessionState.status == com.catshark.lpt.session.SessionController.Status.ONGOING) {
container.session.pause()
} else {
container.session.resume()
onContinue = {
// hasSession 一直是 true,靠状态变化不会触发导航,这里必须显式回会话页
container.session.continueConflict {
StudySessionService.start(context)
screen = Screen.Session
}
},
onEnd = { sections ->
container.session.end(sections) {
StudySessionService.stop(context)
refreshTasks()
}
},
onAbort = { phrase ->
container.session.abort(phrase) {
StudySessionService.stop(context)
refreshTasks()
}
},
onSaveExpectation = { container.session.saveExpectation(it) },
onAddFragment = { container.session.addFragment(it) },
onShowOverlay = { StudySessionService.showOverlay(context) },
onBack = { screen = Screen.Tasks },
onDismiss = { container.session.dismissConflict() },
)
}
Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter),
)
}
}
Screen.Settings -> SettingsScreen(
baseUrl = baseUrl,
onSave = { container.updateBaseUrl(it) },
onLogout = {
StudySessionService.stop(context)
container.logout()
},
onBack = { screen = Screen.Tasks },
/**
* 会话-05:别的任务上还有未结束会话时的提示。
*
* 这里故意只给「前往继续」与「取消」:结束与误操作结束都必须在那个会话自己的页面里由用户完成,
* 列表页不允许一句话就把未完成的会话结掉或丢掉。
*/
@Composable
private fun SessionConflictDialog(
state: SessionController.State,
onContinue: () -> Unit,
onDismiss: () -> Unit,
) {
val conflict = state.conflict ?: return
val busy = state.conflictBusy
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
title = { Text("还有未结束的学习会话") },
text = {
Column {
Text(
"你已经有一个未结束的学习会话:「${conflict.taskName ?: conflict.taskNum}」",
style = MaterialTheme.typography.bodyMedium,
)
Text(
conflict.sessionNum,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (conflict.autoConverged) {
Text(
conflict.systemMessage ?: "这个会话看起来是忘记结束了,服务端已按一个番茄钟自动截止。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.secondary,
)
}
Text(
"需要先把它处理完才能开始新任务。结束或误操作结束都请在那个会话的页面里操作," +
"这里不提供「放弃」这个入口。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (busy) {
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.padding(end = 8.dp), strokeWidth = 2.dp)
Text("正在打开那个会话…", style = MaterialTheme.typography.bodySmall)
}
}
state.conflictError?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
}
},
confirmButton = {
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Button(
onClick = onContinue,
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
) { Text("前往继续") }
TextButton(
onClick = onDismiss,
enabled = !busy,
modifier = Modifier.fillMaxWidth(),
) { Text("取消") }
}
},
)
}
@Composable
private fun ErrorBar(message: String, onDismiss: () -> Unit) {
Surface(
color = MaterialTheme.colorScheme.errorContainer,
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
shape = MaterialTheme.shapes.medium,
) {
Row(
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer,
modifier = Modifier.weight(1f),
)
TextButton(onClick = onDismiss) { Text("关闭") }
}
}
}
@@ -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
@@ -23,6 +23,7 @@ interface LptApi {
@GET("tasks")
suspend fun tasks(): ApiEnvelope<TaskPage>
/** 当前活跃会话;excludeTaskNum 用于把「自己这个任务」排除掉,剩下的就是冲突会话 */
@GET("study-sessions/active")
suspend fun activeSession(
@Query("excludeTaskNum") excludeTaskNum: String? = null,
@@ -69,4 +70,24 @@ interface LptApi {
@GET("report-fragments/session/{sessionNum}")
suspend fun fragmentsBySession(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<FragmentItem>>
/** 某任务的历史报告(按会话生成),报告三段 + 会话预期都在里面 */
@GET("study-sessions/tasks/{taskNum}/reports")
suspend fun reports(
@Path("taskNum") taskNum: String,
@Query("page") page: Int = 1,
@Query("size") size: Int = 10,
@Query("keyword") keyword: String? = null,
): ApiEnvelope<ReportPage>
/** 本次会话产生的所有碎片原文,用于报告页展示 */
@GET("study-sessions/{sessionNum}/all-fragments")
suspend fun allFragments(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<String>>
/** 报告草稿:提交 REPORT_DRAFT 任务,随后轮询 GET /ai/tasks/{taskNum} */
@POST("ai/tasks")
suspend fun submitAiTask(@Body body: SubmitAiTaskRequest): ApiEnvelope<AiTask>
@GET("ai/tasks/{taskNum}")
suspend fun aiTask(@Path("taskNum") taskNum: String): ApiEnvelope<AiTask>
}
@@ -1,5 +1,8 @@
package com.catshark.lpt.data
import kotlinx.coroutines.delay
import retrofit2.HttpException
/** 业务错误:把后端的 message 直接带给 UI */
class ApiException(message: String) : Exception(message)
@@ -16,51 +19,84 @@ class LptRepository(private val apiClient: ApiClient) {
return env.data as T
}
suspend fun login(username: String, password: String): Result<String> = runCatching {
/** 统一的请求包装:网络/HTTP 层错误都换成用户看得懂的话 */
private inline fun <T> call(block: () -> T): Result<T> = runCatching(block).friendly()
/**
* 把网络/HTTP 层错误换成用户看得懂的话。
* 部署环境的 dev 后端可能比源码旧,新加的接口在它上面会是 404/405,这类失败要说清楚。
*/
private fun <T> Result<T>.friendly(action: String? = null): Result<T> {
val error = exceptionOrNull()
return when {
error is HttpException -> {
val detail = "HTTP ${error.code()}"
val message = if (action != null) {
"$action 不可用($detail),当前后端可能还没上这个接口"
} else {
"请求失败($detail),请稍后重试"
}
Result.failure(ApiException(message))
}
error is java.io.IOException -> Result.failure(ApiException("网络不可用,请检查网络或设置里的 API 地址"))
else -> this
}
}
suspend fun login(username: String, password: String): Result<String> = 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
}
suspend fun activeSession(): Result<ActiveSession?> = runCatching {
api.activeSession().takeIf { it.code == 200 }?.data
/**
* 当前活跃会话。
*
* - 传入 `excludeTaskNum` 时,属于该任务的会话不算冲突(后端直接返回 null);
* - 业务失败(code != 200)与网络异常一律上抛:调用方需要区分「确实没有会话」和「没问到」。
*/
suspend fun activeSession(excludeTaskNum: String? = null): Result<ActiveSession?> = 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(
@@ -74,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)),
"记录碎片",
@@ -87,7 +123,46 @@ 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()
}
/** 依次任务的历史报告(按会话生成,分页) */
suspend fun reports(taskNum: String, page: Int = 1, size: Int = 10): Result<ReportPage> = runCatching {
envelope(api.reports(taskNum, page, size), "获取学习报告")
}.friendly("查看学习报告")
/** 本次会话的全部碎片原文 */
suspend fun allFragments(sessionNum: String): Result<List<String>> = runCatching {
api.allFragments(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
}.friendly("查看本次碎片")
/**
* 报告草稿:提交 REPORT_DRAFT 异步任务后轮询到结束。
* 草稿不落库,只作为结束会话弹窗里的编辑起点;AI 不可用时后端自己降级为规则拼接。
*/
suspend fun reportDraft(sessionNum: String): Result<ReportSections> = runCatching {
val submitted = envelope(api.submitAiTask(SubmitAiTaskRequest(AI_TASK_REPORT_DRAFT, sessionNum)), "提交报告草稿任务")
val taskNum = submitted.taskNum.takeIf { it.isNotBlank() }
?: throw ApiException("报告草稿任务提交失败")
var task: AiTask? = null
val deadline = System.currentTimeMillis() + DRAFT_TIMEOUT_MS
while (task == null) {
val current = envelope(api.aiTask(taskNum), "查询报告草稿")
when {
current.succeeded -> task = current
current.failed -> throw ApiException(current.errorMessage?.takeIf { it.isNotBlank() } ?: "生成报告草稿失败")
System.currentTimeMillis() > deadline -> throw ApiException("生成报告草稿超时,请直接手写或稍后重试")
else -> delay(DRAFT_POLL_INTERVAL_MS)
}
}
// 循环出口保证非空
task.draftSections()
}.friendly("生成学习报告草稿")
companion object {
private const val AI_TASK_REPORT_DRAFT = "REPORT_DRAFT"
private const val DRAFT_POLL_INTERVAL_MS = 2_000L
private const val DRAFT_TIMEOUT_MS = 180_000L
}
}
@@ -2,6 +2,9 @@ package com.catshark.lpt.data
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive
/** lpt-be 的统一响应包装:{ code, message, data } */
@Serializable
@@ -63,6 +66,8 @@ data class ActiveSession(
val taskName: String? = null,
val sessionState: String? = null,
val autoConverged: Boolean = false,
/** 服务端自动收敛时的用户可见文案 */
val systemMessage: String? = null,
)
@Serializable
@@ -116,6 +121,10 @@ data class ReportSections(
val allBlank: Boolean
get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank()
companion object {
val EMPTY = ReportSections("", "", "")
}
/**
* 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题,
* 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。
@@ -130,14 +139,65 @@ data class ReportSections(
/** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */
fun extractToken(element: JsonElement?): String? {
if (element == null) return null
return when {
element is JsonElement && element.toString().trim().startsWith("\"") ->
element.toString().trim().trim('"')
else -> {
val obj = element as? kotlinx.serialization.json.JsonObject
obj?.get("token")?.let { token ->
if (token.toString().trim().startsWith("\"")) token.toString().trim().trim('"') else token.toString()
}
}
}
val text = element.toString().trim()
if (text.startsWith("\"")) return text.trim('"')
val token = (element as? JsonObject)?.get("token") ?: return null
val raw = token.toString().trim()
return if (raw.startsWith("\"")) raw.trim('"') else raw
}
/** 某次学习会话产出的学习报告(报告三段 + 该会话的学习预期) */
@Serializable
data class StudyReport(
val id: Int = 0,
val sessionNum: String = "",
val sessionSummary: String? = null,
val expectationVerdict: String? = null,
val freeSummary: String? = null,
/** 会话对应的学习预期,随报告返回,不落库 */
val sessionExpectation: String? = null,
val createdTime: String? = null,
)
@Serializable
data class ReportPage(
val records: List<StudyReport> = emptyList(),
val total: Int = 0,
val size: Int = 0,
val current: Int = 0,
val pages: Int = 0,
)
/** AI 异步任务(AI-02):提交秒级返回,之后轮询拿状态与结果 */
@Serializable
data class AiTask(
val taskNum: String = "",
val type: String = "",
val targetNum: String = "",
val status: String = "",
val errorMessage: String? = null,
val result: JsonObject? = null,
) {
val succeeded: Boolean get() = status == "SUCCEEDED"
val failed: Boolean get() = status == "FAILED"
val inProgress: Boolean get() = status == "PENDING" || status == "RUNNING"
}
@Serializable
data class SubmitAiTaskRequest(
val type: String,
val targetNum: String,
)
/** 取报告草稿三段:REPORT_DRAFT 任务的 result 就是三个同名字段 */
fun AiTask.draftSections(): ReportSections = ReportSections(
sessionSummary = result.text("sessionSummary"),
expectationVerdict = result.text("expectationVerdict"),
freeSummary = result.text("freeSummary"),
)
private fun JsonObject?.text(key: String): String {
val element = this?.get(key) ?: return ""
if (element is JsonNull) return ""
return runCatching { element.jsonPrimitive.content }.getOrDefault("")
}
@@ -21,14 +21,21 @@ import kotlin.math.abs
/**
* 系统级悬浮窗(经典 View 实现)。
*
* 三种形态:
* - 浏览:完整条(任务名 + 计时 + 暂停 + 展开),FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
* 职责被刻意压到最小——浮窗只做三件事:
* 1. 展示倒计时;
* 2. 记一条知识碎片(拉起 FragmentInputActivity,浮窗内不做文本输入);
* 3. 暂停 / 继续计时。
*
* 其余动作(改预期、结束会话、写报告、看历史)一律在 App 页面内完成,不要往浮窗里加。
*
* 两种形态:
* - 常态条:`● 12:34 + 暂停`,FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
*
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
*
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
* 所以「+ 记一条碎片」回调给 Service,由它拉起 FragmentInputActivity。
* 所以「+」回调给 Service,由它拉起 FragmentInputActivity。
*/
class OverlayView(private val context: Context) {
@@ -37,37 +44,25 @@ class OverlayView(private val context: Context) {
private var root: LinearLayout? = null
private var params: WindowManager.LayoutParams? = null
private var shown = false
private var expanded = false
private var halfHidden = false
private var lastState: SessionController.State? = null
private lateinit var headerRow: LinearLayout
private lateinit var barRow: LinearLayout
private lateinit var dotView: View
private lateinit var nameView: TextView
private lateinit var timeView: TextView
private lateinit var pauseView: TextView
private lateinit var expandView: TextView
private lateinit var compactView: LinearLayout
private lateinit var fragmentView: TextView
private lateinit var toggleView: TextView
private lateinit var compactRow: LinearLayout
private lateinit var compactDot: View
private lateinit var compactTime: TextView
private lateinit var expandedPanel: LinearLayout
private lateinit var expectationView: TextView
private lateinit var fragmentView: TextView
private lateinit var latestFragmentView: TextView
private lateinit var addFragmentView: TextView
private lateinit var endView: TextView
private lateinit var openAppView: TextView
private lateinit var hideView: TextView
var onTogglePause: (() -> Unit)? = null
var onEnd: (() -> Unit)? = null
var onOpenApp: (() -> Unit)? = null
var onRequestFragmentInput: (() -> Unit)? = null
val isShown: Boolean get() = shown
private val autoHideTask = Runnable {
if (shown && !expanded) setHalfHidden(true)
if (shown && !halfHidden) setHalfHidden(true)
}
private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
@@ -88,14 +83,6 @@ class OverlayView(private val context: Context) {
isFocusable = false
}
private fun label(text: String, color: Int, size: Float = 12f): TextView = TextView(context).apply {
this.text = text
textSize = size
setTextColor(color)
maxLines = 2
ellipsize = TextUtils.TruncateAt.END
}
fun show() {
if (shown) return
if (!Settings.canDrawOverlays(context)) return
@@ -138,29 +125,15 @@ class OverlayView(private val context: Context) {
val ongoing = state.status == SessionController.Status.ONGOING
val text = formatDuration(state.effectiveSeconds())
nameView.text = state.taskName?.takeIf { it.isNotBlank() } ?: "学习会话"
timeView.text = text
compactTime.text = text
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
compactDot.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
pauseView.text = if (ongoing) "暂停" else "继续"
pauseView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
toggleView.text = if (ongoing) "暂停" else "继续"
toggleView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
expectationView.text =
if (state.expectation.isBlank()) "预期:未填写" else "预期:${state.expectation}"
fragmentView.text = "本次碎片 ${state.fragments.size} 条"
latestFragmentView.text = state.fragments.lastOrNull()?.content?.let { "最新:$it" } ?: ""
headerRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
compactView.visibility = if (halfHidden) View.VISIBLE else View.GONE
expandedPanel.visibility = if (!halfHidden && expanded) View.VISIBLE else View.GONE
expandView.text = if (expanded) "▴" else "▾"
}
private fun toggleExpanded() {
expanded = !expanded
lastState?.let { render(it) }
scheduleAutoHide()
barRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
compactRow.visibility = if (halfHidden) View.VISIBLE else View.GONE
}
// ---- 半隐藏 / 自动隐藏 ----
@@ -168,9 +141,9 @@ class OverlayView(private val context: Context) {
fun setHalfHidden(hidden: Boolean) {
val view = root ?: return
val p = params ?: return
if (hidden) expanded = false
halfHidden = hidden
view.alpha = if (hidden) 0.6f else 1f
// 常态整条 80% 不透明;收起后再压一档,整体约 60%
view.alpha = if (hidden) 0.75f else 1f
lastState?.let { render(it) }
val screenWidth = context.resources.displayMetrics.widthPixels
@@ -191,7 +164,7 @@ class OverlayView(private val context: Context) {
private fun scheduleAutoHide() {
root?.removeCallbacks(autoHideTask)
if (!halfHidden && !expanded) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
if (!halfHidden) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
}
private fun cancelAutoHide() {
@@ -211,8 +184,8 @@ class OverlayView(private val context: Context) {
elevation = dp(10).toFloat()
}
// ---- 完整条 ----
headerRow = LinearLayout(context).apply {
// ---- 常态条:● 计时 + 暂停/继续 ----
barRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
@@ -220,36 +193,31 @@ class OverlayView(private val context: Context) {
background = rounded(COLOR_ONGOING, 4)
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
}
nameView = TextView(context).apply {
setTextColor(Color.WHITE)
textSize = 13f
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
.apply { marginStart = dp(8) }
}
timeView = TextView(context).apply {
setTextColor(Color.WHITE)
textSize = 16f
textSize = 17f
typeface = Typeface.MONOSPACE
setPadding(dp(8), 0, dp(8), 0)
maxLines = 1
ellipsize = TextUtils.TruncateAt.END
setPadding(dp(8), 0, dp(10), 0)
}
pauseView = pill("暂停", COLOR_ACTION)
expandView = pill("▾", COLOR_NEUTRAL).apply {
fragmentView = pill("+", COLOR_NEUTRAL).apply {
contentDescription = "记一条知识碎片"
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { marginStart = dp(6) }
).apply { marginEnd = dp(6) }
}
headerRow.addView(dotView)
headerRow.addView(nameView)
headerRow.addView(timeView)
headerRow.addView(pauseView)
headerRow.addView(expandView)
container.addView(headerRow)
toggleView = pill("暂停", COLOR_ACTION)
// ---- 半隐藏小胶囊 ----
compactView = LinearLayout(context).apply {
barRow.addView(dotView)
barRow.addView(timeView)
barRow.addView(fragmentView)
barRow.addView(toggleView)
container.addView(barRow)
// ---- 半隐藏小胶囊:● 计时 ----
compactRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
visibility = View.GONE
@@ -262,82 +230,27 @@ class OverlayView(private val context: Context) {
}
compactTime = TextView(context).apply {
setTextColor(Color.WHITE)
textSize = 14f
textSize = 15f
typeface = Typeface.MONOSPACE
setPadding(dp(6), 0, 0, 0)
setPadding(dp(6), 0, dp(4), 0)
}
compactView.addView(compactDot)
compactView.addView(compactTime)
compactView.setOnClickListener { setHalfHidden(false) }
container.addView(compactView)
compactRow.addView(compactDot)
compactRow.addView(compactTime)
compactRow.setOnClickListener { setHalfHidden(false) }
container.addView(compactRow)
// ---- 展开面板 ----
expandedPanel = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
visibility = View.GONE
}
expectationView = label("预期:", Color.parseColor("#C9D1D9")).apply {
setPadding(0, dp(10), 0, dp(2))
}
fragmentView = label("本次碎片 0 条", Color.parseColor("#8B949E"), 12f)
latestFragmentView = label("", Color.parseColor("#8B949E"), 12f)
addFragmentView = pill("+ 记一条碎片", COLOR_ACTION).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { topMargin = dp(8) }
}
addFragmentView.setOnClickListener {
fragmentView.setOnClickListener {
scheduleAutoHide()
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
setHalfHidden(true)
onRequestFragmentInput?.invoke()
}
val actions = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
setPadding(0, dp(10), 0, 0)
}
endView = pill("结束", COLOR_END)
openAppView = pill("打开 App", COLOR_NEUTRAL).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { marginStart = dp(8) }
}
hideView = pill("隐藏", COLOR_NEUTRAL).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { marginStart = dp(8) }
}
actions.addView(endView)
actions.addView(openAppView)
actions.addView(hideView)
expandedPanel.addView(expectationView)
expandedPanel.addView(fragmentView)
expandedPanel.addView(latestFragmentView)
expandedPanel.addView(addFragmentView)
expandedPanel.addView(actions)
container.addView(expandedPanel)
pauseView.setOnClickListener {
toggleView.setOnClickListener {
scheduleAutoHide()
onTogglePause?.invoke()
}
expandView.setOnClickListener { toggleExpanded() }
endView.setOnClickListener {
scheduleAutoHide()
onEnd?.invoke()
}
openAppView.setOnClickListener {
scheduleAutoHide()
onOpenApp?.invoke()
}
hideView.setOnClickListener { setHalfHidden(true) }
attachDrag(headerRow)
attachDrag(barRow)
return container
}
@@ -420,7 +333,6 @@ class OverlayView(private val context: Context) {
private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
private const val COLOR_RESUME = 0xFF238636.toInt()
private const val COLOR_END = 0xFFB62324.toInt()
private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
}
}
@@ -40,18 +40,18 @@ class StudySessionService : Service() {
controller = container.session
overlay = OverlayView(this).apply {
onTogglePause = { togglePause() }
onEnd = { openApp(openEnd = true) }
onOpenApp = { openApp(openEnd = false) }
onRequestFragmentInput = { openFragmentInput() }
}
createChannel()
// 状态变化:更新通知 / 悬浮窗;会话没了就停服务
// 状态变化:更新通知 / 悬浮窗。
// 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时
// 对账是异步的,早期看到的空状态是「还不知道」,不能据此 stopSelf。
scope.launch {
controller.state.collect { state ->
if (!state.hasSession) {
overlay.hide()
stopSelf()
if (state.resolved) stopSelf()
return@collect
}
ensureForeground(state)
@@ -87,6 +87,8 @@ class StudySessionService : Service() {
ACTION_SHOW_OVERLAY -> overlay.restore()
ACTION_STOP -> stopSelf()
}
// 进程被系统拉起(intent 为 null)时补一次对账,否则重启后浮窗不会再出现
controller.ensureReconciled()
// 必须在 5 秒内 startForeground,先用当前状态占位
ensureForeground(controller.state.value)
return START_STICKY
@@ -6,6 +6,7 @@ import com.catshark.lpt.data.LptRepository
import com.catshark.lpt.data.ReportSections
import com.catshark.lpt.data.SessionDetail
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -19,6 +20,9 @@ import java.time.LocalDateTime
*
* 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。
* 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
*
* 会话-05:开始任务前先看别的任务上有没有未结束会话,有就进 [State.conflict],
* 由 UI 给出「前往继续 / 结束它并开始新任务 / 放弃它」三个出口。
*/
class SessionController(
private val repo: LptRepository,
@@ -27,6 +31,17 @@ class SessionController(
enum class Status { NONE, ONGOING, PAUSED, ENDED }
/** 别的任务上还有未结束会话:用户必须先选一个出口 */
data class Conflict(
/** 用户想开始的任务 */
val targetTaskNum: String,
val sessionNum: String,
val taskNum: String,
val taskName: String?,
val autoConverged: Boolean,
val systemMessage: String?,
)
data class State(
val sessionNum: String? = null,
val taskNum: String? = null,
@@ -35,14 +50,34 @@ class SessionController(
val baseEffectiveSeconds: Double = 0.0,
val anchorRealtimeMs: Long = 0L,
val expectation: String = "",
/** 学习预期是否已经从服务端取回过(没取回前不要弹必填弹窗) */
val expectationLoaded: Boolean = false,
/** 预期保存请求在途:按钮据此禁用,防连点重复提交 */
val expectationSaving: Boolean = false,
val fragments: List<FragmentItem> = emptyList(),
/** 记碎片请求在途 */
val fragmentAdding: Boolean = false,
val busy: Boolean = false,
/** 是否已经与服务端对过账:前台服务据此判断「真没有会话」还是「还不知道」 */
val resolved: Boolean = false,
val error: String? = null,
val notice: String? = null,
val conflict: Conflict? = null,
val conflictBusy: Boolean = false,
val conflictError: String? = null,
/** 报告草稿(AI 或规则降级),仅作为结束弹窗的编辑起点,不落库 */
val draft: ReportSections? = null,
val draftLoading: Boolean = false,
val draftSeconds: Int = 0,
val draftError: String? = null,
) {
val hasSession: Boolean
get() = status == Status.ONGOING || status == Status.PAUSED
/** 有会话但预期还没填:UI 用不可关闭的弹窗挡住,符合「会话必须有预期才能开始」 */
val expectationRequired: Boolean
get() = hasSession && expectationLoaded && expectation.isBlank()
fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
if (status == Status.ONGOING) {
baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
@@ -54,25 +89,73 @@ class SessionController(
private val _state = MutableStateFlow(State())
val state: StateFlow<State> = _state.asStateFlow()
private var reconciling = false
fun consumeError() = _state.update { it.copy(error = null) }
fun consumeNotice() = _state.update { it.copy(notice = null) }
/** 启动或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务) */
fun dismissConflict() = _state.update { it.copy(conflict = null, conflictError = null) }
/**
* 开始或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务)。
*
* 先查其他任务上有没有未结束会话:有则只更新 [State.conflict],不开始新会话。
*/
fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
if (_state.value.busy) return
_state.update { it.copy(busy = true, error = null) }
_state.update { it.copy(busy = true, error = null, conflict = null, conflictError = null) }
scope.launch {
repo.startOrContinue(taskNum)
val active = repo.activeSession(excludeTaskNum = taskNum)
val conflict = active.getOrNull()
if (conflict != null) {
_state.update {
it.copy(
busy = false,
conflict = Conflict(
targetTaskNum = taskNum,
sessionNum = conflict.sessionNum,
taskNum = conflict.taskNum,
taskName = conflict.taskName,
autoConverged = conflict.autoConverged,
systemMessage = conflict.systemMessage,
),
)
}
return@launch
}
if (active.isFailure) {
// 查不到不等于没有:提示一句再照常开始,不把用户堵在列表页
_state.update { it.copy(notice = "未能确认是否存在未结束会话,已按没有冲突处理") }
}
startTask(taskNum, onSuccess)
}
}
/**
* 会话-05:有冲突时唯一能做的就是「前往继续」。
* 结束 / 误操作结束都必须在那个会话自己的页面里做,列表页不提供这些出口。
*/
fun continueConflict(onSessionReady: () -> Unit = {}) {
val conflict = _state.value.conflict ?: return
if (_state.value.conflictBusy) return
_state.update { it.copy(conflictBusy = true, conflictError = null) }
scope.launch {
repo.sessionDetail(conflict.sessionNum)
.onSuccess { detail ->
applyDetail(detail)
loadAuxiliary(detail.sessionNum)
_state.update { it.copy(busy = false) }
onSuccess()
}
.onFailure { e ->
_state.update { it.copy(busy = false, error = e.message ?: "开始学习会话失败") }
_state.update {
it.copy(
taskNum = conflict.taskNum,
taskName = conflict.taskName ?: it.taskName,
conflict = null,
conflictBusy = false,
)
}
loadAuxiliary(conflict.sessionNum)
onSessionReady()
}
.onFailure { failConflict(it) }
}
}
@@ -100,28 +183,59 @@ class SessionController(
}
}
fun saveExpectation(text: String) {
/**
* 保存学习预期。在途时再点直接返回,并在成功时回调;失败文案走 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, text)
repo.putExpectation(num, value)
.onSuccess {
_state.update { it.copy(expectation = text, notice = "学习预期已保存") }
_state.update {
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
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) }
}
}
@@ -132,7 +246,7 @@ class SessionController(
scope.launch {
repo.endSession(num, sections)
.onSuccess { message ->
_state.value = State(notice = message ?: "学习会话已结束")
_state.value = idle(notice = message ?: "学习会话已结束")
onDone()
}
.onFailure { e ->
@@ -148,7 +262,7 @@ class SessionController(
scope.launch {
repo.abortSession(num, confirmation)
.onSuccess {
_state.value = State(notice = "已放弃该会话,未产生任何数据")
_state.value = idle(notice = "已放弃该会话,未产生任何数据")
onDone()
}
.onFailure { e ->
@@ -157,42 +271,135 @@ class SessionController(
}
}
/** App 启动时与服务端对账:把未结束的会话恢复出来 */
fun reconcile() {
/**
* 生成报告草稿(有碎片时才有意义)。三段都空时由结束弹窗自动调用,
* 用户点「AI 重新生成」也可以再调用一次。
*/
fun generateReportDraft() {
val num = _state.value.sessionNum ?: return
if (_state.value.draftLoading) return
if (_state.value.fragments.isEmpty()) {
_state.update { it.copy(draftError = "这次学习还没有知识碎片,暂无可聚合的内容") }
return
}
_state.update { it.copy(draftLoading = true, draftSeconds = 0, draftError = null) }
scope.launch {
repo.activeSession()
.onSuccess { active ->
if (active == null || active.sessionNum.isBlank()) {
if (!_state.value.hasSession) _state.update { it.copy(status = Status.NONE) }
return@onSuccess
}
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
val ticker = scope.launch {
while (_state.value.draftLoading) {
delay(1_000)
_state.update { it.copy(draftSeconds = it.draftSeconds + 1) }
}
}
val result = repo.reportDraft(num)
ticker.cancel()
result
.onSuccess { sections ->
_state.update {
it.copy(
sessionNum = active.sessionNum,
taskNum = active.taskNum.ifBlank { it.taskNum },
taskName = active.taskName ?: it.taskName,
draftLoading = false,
draft = sections,
draftError = if (sections.allBlank) "没有可聚合的内容,请手写总结" else null,
)
}
refreshDetail(active.sessionNum)
loadAuxiliary(active.sessionNum)
}
.onFailure { e ->
_state.update { it.copy(draftLoading = false, draftError = e.message ?: "生成报告草稿失败") }
}
}
}
fun clear() {
_state.value = State()
fun consumeDraftError() = _state.update { it.copy(draftError = null) }
/** App 启动/登录后与服务端对账:把未结束的会话恢复出来 */
fun reconcile() {
if (reconciling) return
reconciling = true
scope.launch {
try {
repo.activeSession()
.onSuccess { active ->
if (active == null || active.sessionNum.isBlank()) {
_state.update { it.copy(status = if (it.hasSession) it.status else Status.NONE) }
return@onSuccess
}
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
_state.update {
it.copy(
sessionNum = active.sessionNum,
taskNum = active.taskNum.ifBlank { it.taskNum },
taskName = active.taskName ?: it.taskName,
)
}
refreshDetail(active.sessionNum)
loadAuxiliary(active.sessionNum)
}
.onFailure { e ->
_state.update { it.copy(error = e.message ?: "恢复会话状态失败") }
}
} finally {
reconciling = false
_state.update { it.copy(resolved = true) }
}
}
}
/** 前台服务被系统拉起时调用:还没对过账就补一次对账 */
fun ensureReconciled() {
if (!_state.value.resolved) reconcile()
}
/** 未登录时没有会话可查,直接标记为已知状态,避免服务一直等 */
fun markResolved() = _state.update { it.copy(resolved = true) }
fun clear() = _state.update { State(resolved = true) }
// ---- 内部 ----
/** 开始新会话(或继续当前任务上未结束的会话) */
private suspend fun startTask(taskNum: String, onSessionReady: () -> Unit, note: String? = null) {
repo.startOrContinue(taskNum)
.onSuccess { detail ->
applyDetail(detail)
_state.update {
it.copy(
busy = false,
conflict = null,
conflictBusy = false,
conflictError = null,
expectationLoaded = false,
notice = note ?: it.notice,
)
}
loadAuxiliary(detail.sessionNum)
onSessionReady()
}
.onFailure { e ->
_state.update {
it.copy(
busy = false,
conflictBusy = false,
conflictError = e.message ?: "开始学习会话失败",
error = if (it.conflict == null) e.message ?: "开始学习会话失败" else null,
)
}
}
}
private fun failConflict(error: Throwable) {
_state.update {
it.copy(conflictBusy = false, conflictError = error.message ?: "打开这个会话失败,请重试")
}
}
private fun idle(notice: String? = null) = State(notice = notice, resolved = true)
private suspend fun refreshDetail(sessionNum: String) {
repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
}
private suspend fun loadAuxiliary(sessionNum: String) {
repo.getExpectation(sessionNum).onSuccess { text ->
_state.update { it.copy(expectation = text) }
_state.update { it.copy(expectation = text, expectationLoaded = true) }
}
repo.fragments(sessionNum).onSuccess { list ->
_state.update { it.copy(fragments = list) }
@@ -211,6 +418,9 @@ class SessionController(
} else {
SystemClock.elapsedRealtime()
}
// 会话-04:被服务端自动收敛过的会话,把服务端文案原样告诉用户
val converged = detail.systemMessage?.takeIf { it.isNotBlank() }
?: if (detail.autoConverged) "上一次学习疑似忘记结束,已自动截止,本次只计入一个番茄钟的有效学习时间" else null
_state.update {
it.copy(
sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
@@ -220,6 +430,7 @@ class SessionController(
baseEffectiveSeconds = detail.effectiveTime,
anchorRealtimeMs = anchor,
error = null,
notice = converged ?: it.notice,
)
}
}
@@ -231,4 +442,9 @@ class SessionController(
Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
}.getOrDefault(0)
}
companion object {
/** 误操作结束的确认语,前后端各校验一次 */
const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
}
}
@@ -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,
)
@@ -0,0 +1,257 @@
package com.catshark.lpt.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.catshark.lpt.data.ReportPage
import com.catshark.lpt.data.StudyReport
import com.catshark.lpt.util.formatDateTime
import kotlinx.coroutines.launch
/**
* 某任务的历史学习报告:三段文本 + 该会话的学习预期 + 本次会话的碎片原文。
*
* 报告第四部分「按归属分组的碎片」由复习模块实时聚合(review 前缀的端点),
* 本客户端按边界不访问它,所以这里只列本次会话产生的碎片。
*/
@Composable
fun ReportsScreen(
taskName: String,
onLoadReports: suspend (Int) -> Result<ReportPage>,
onLoadFragments: suspend (String) -> Result<List<String>>,
onBack: () -> Unit,
) {
val scope = rememberCoroutineScope()
var reports by remember { mutableStateOf<List<StudyReport>>(emptyList()) }
var total by remember { mutableIntStateOf(0) }
var page by remember { mutableIntStateOf(0) }
var loading by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
fun load(next: Int) {
if (loading || next < 1) return
loading = true
error = null
scope.launch {
onLoadReports(next)
.onSuccess { result ->
reports = if (next <= 1) result.records else reports + result.records
total = result.total
page = next
}
.onFailure { error = it.message ?: "加载学习报告失败" }
loading = false
}
}
LaunchedEffect(taskName) {
reports = emptyList()
page = 0
load(1)
}
Column(modifier = Modifier.fillMaxSize()) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onBack) { Text("‹ 任务") }
Column(modifier = Modifier.weight(1f)) {
Text("学习报告", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
Text(
taskName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (loading) CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
}
if (error != null) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
error!!,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f),
)
TextButton(onClick = { load(if (page == 0) 1 else page) }) { Text("重试") }
}
}
if (reports.isEmpty() && !loading && error == null) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text("这个任务还没有学习报告", style = MaterialTheme.typography.bodyLarge)
Spacer(Modifier.height(8.dp))
TextButton(onClick = { load(1) }) { Text("刷新") }
}
}
return@Column
}
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(reports, key = { it.id }) { report ->
ReportCard(report = report, onLoadFragments = onLoadFragments)
}
if (reports.size < total) {
item {
TextButton(onClick = { load(page + 1) }, modifier = Modifier.fillMaxWidth()) {
Text(if (loading) "加载中…" else "加载更多(${reports.size}/$total)")
}
}
}
}
}
}
@Composable
private fun ReportCard(
report: StudyReport,
onLoadFragments: suspend (String) -> Result<List<String>>,
) {
val scope = rememberCoroutineScope()
var expanded by remember { mutableStateOf(false) }
var fragments by remember { mutableStateOf<List<String>?>(null) }
var fragmentError by remember { mutableStateOf<String?>(null) }
Card(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(14.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
"学习报告",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f),
)
Text(
formatDateTime(report.createdTime),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Text(
"会话 ${report.sessionNum}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (!report.sessionExpectation.isNullOrBlank()) {
Section("本次预期", report.sessionExpectation)
}
Section("会话摘要", report.sessionSummary)
Section("预期达成判断", report.expectationVerdict)
Section("自由总结", report.freeSummary)
TextButton(
onClick = {
expanded = !expanded
if (expanded && fragments == null && fragmentError == null) {
scope.launch {
onLoadFragments(report.sessionNum)
.onSuccess { fragments = it }
.onFailure { fragmentError = it.message ?: "加载碎片失败" }
}
}
},
) { Text(if (expanded) "收起本次碎片" else "查看本次碎片") }
if (expanded) {
val list = fragments
when {
fragmentError != null -> Text(
fragmentError!!,
color = MaterialTheme.colorScheme.error,
style = MaterialTheme.typography.bodySmall,
)
list == null -> Text(
"加载中…",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
list.isEmpty() -> Text(
"这次学习没有记录碎片",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
else -> list.forEachIndexed { index, content ->
Spacer(Modifier.height(6.dp))
Row {
Text(
"${index + 1}.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Text(
content,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(start = 6.dp),
)
}
}
}
}
}
}
}
@Composable
private fun Section(label: String, value: String?) {
Spacer(Modifier.height(10.dp))
Text(
label,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.height(2.dp))
if (value.isNullOrBlank()) {
Text(
"(未填写)",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
} else {
Text(value, style = MaterialTheme.typography.bodyMedium)
}
}
@@ -2,7 +2,6 @@ package com.catshark.lpt.ui
import android.os.SystemClock
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -10,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
@@ -39,7 +39,7 @@ import com.catshark.lpt.session.SessionController
import com.catshark.lpt.util.formatDuration
import kotlinx.coroutines.delay
private const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
private val MISOPERATION_PHRASE = SessionController.MISOPERATION_PHRASE
@Composable
fun SessionScreen(
@@ -49,9 +49,10 @@ 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,
) {
var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
@@ -85,7 +86,8 @@ fun SessionScreen(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(onClick = onBack) { Text("‹ 任务") }
// 预期还没填时不允许离开:会话必须有预期才能算正式开始
TextButton(onClick = onBack, enabled = !state.expectationRequired) { Text("‹ 任务") }
Column(modifier = Modifier.weight(1f)) {
Text(
state.taskName ?: "学习会话",
@@ -98,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(
@@ -183,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 "保存预期") }
}
}
}
@@ -204,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))
@@ -229,25 +238,33 @@ 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))
}
}
// 会话必须有预期才能正式开始:未填预期时用不可关闭的弹窗挡住
if (state.expectationRequired) {
ExpectationGateDialog(
busy = state.busy,
saving = state.expectationSaving,
error = state.error,
onSave = { text -> onSaveExpectation(text) {} },
onAbort = onAbort,
)
}
if (showEnd) {
EndSessionDialog(
defaultSummary = "",
busy = state.busy,
state = state,
onDismiss = { showEnd = false },
onConfirm = { sections ->
showEnd = false
onEnd(sections)
},
onGenerateDraft = onGenerateDraft,
)
}
@@ -263,16 +280,118 @@ fun SessionScreen(
}
}
/**
* 学习预期必填弹窗。不允许点外部关闭,只能「保存并开始」或走误操作结束:
* 否则就会出现一次没有任何预期的会话。
*/
@Composable
private fun ExpectationGateDialog(
busy: Boolean,
saving: Boolean,
error: String?,
onSave: (String) -> Unit,
onAbort: (String) -> Unit,
) {
var text by remember { mutableStateOf("") }
var abortMode by remember { mutableStateOf(false) }
var phrase by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = { /* 必须给出预期或误操作结束,不能被关掉 */ },
title = { Text(if (abortMode) "误操作结束" else "填写学习预期") },
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
if (abortMode) {
Text(
"此操作会删除本次会话与学习预期,不产生碎片和报告,且不可恢复。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
Spacer(Modifier.height(10.dp))
Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = phrase,
onValueChange = { phrase = it },
label = { Text("确认语") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
} else {
Text(
"会话必须有学习预期才能正式开始。写下这次想学会什么,结束时会拿它做达成判断。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(Modifier.height(10.dp))
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("本次学习预期(不可为空)") },
minLines = 2,
modifier = Modifier.fillMaxWidth(),
)
if (error != null) {
Spacer(Modifier.height(8.dp))
Text(error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
}
}
},
confirmButton = {
if (abortMode) {
Button(
onClick = { onAbort(phrase) },
enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
) { Text("确认放弃") }
} else {
Button(
onClick = { onSave(text) },
enabled = !busy && !saving && text.isNotBlank(),
) { Text(if (saving) "保存中…" else "保存并开始") }
}
},
dismissButton = {
if (abortMode) {
TextButton(onClick = { abortMode = false }) { Text("返回") }
} else {
TextButton(onClick = { abortMode = true }) { Text("误操作结束") }
}
},
)
}
/**
* 结束会话:报告为结构化三段。有碎片且三段还空着时,先取一次草稿作为编辑起点;
* 草稿生成失败不阻塞手写。用户改过之后再点「AI 重新生成」会先确认再覆盖。
*/
@Composable
private fun EndSessionDialog(
defaultSummary: String,
busy: Boolean,
state: SessionController.State,
onDismiss: () -> Unit,
onConfirm: (ReportSections) -> Unit,
onGenerateDraft: () -> Unit,
) {
var summary by remember { mutableStateOf(defaultSummary) }
var summary by remember { mutableStateOf("") }
var verdict by remember { mutableStateOf("") }
var free by remember { mutableStateOf("") }
var confirmRegenerate by remember { mutableStateOf(false) }
val hasFragments = state.fragments.isNotEmpty()
fun currentSections(): ReportSections = ReportSections(summary, verdict, free)
LaunchedEffect(Unit) {
// 已经有缓存草稿时直接用它,不要为了重开弹窗再化一次 AI
if (currentSections().allBlank && hasFragments && state.draft == null) onGenerateDraft()
}
// 草稿是整段覆盖的:它就是这次生成的编辑起点
LaunchedEffect(state.draft) {
state.draft?.let {
summary = it.sessionSummary
verdict = it.expectationVerdict
free = it.freeSummary
}
}
AlertDialog(
onDismissRequest = onDismiss,
@@ -280,10 +399,24 @@ private fun EndSessionDialog(
text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Text(
"三段都可留空,但至少要写一段。全空时会记为「未填写总结」。",
"三段都可留空,写多少算多少;留空时报告里记「未填写总结」。",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
if (state.draftLoading) {
Spacer(Modifier.height(8.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
Text(
" AI 正在根据 ${state.fragments.size} 条碎片生成草稿,已等待 ${state.draftSeconds} 秒",
style = MaterialTheme.typography.bodySmall,
)
}
}
state.draftError?.let {
Spacer(Modifier.height(8.dp))
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
Spacer(Modifier.height(10.dp))
OutlinedTextField(
value = summary,
@@ -308,23 +441,42 @@ private fun EndSessionDialog(
minLines = 2,
modifier = Modifier.fillMaxWidth(),
)
Spacer(Modifier.height(6.dp))
TextButton(
onClick = {
// 用户已经写过内容时先确认,避免手滑覆盖
if (currentSections().allBlank) onGenerateDraft() else confirmRegenerate = true
},
enabled = !state.draftLoading && hasFragments,
) { Text("AI 重新生成") }
}
},
confirmButton = {
Button(
onClick = {
val sections = if (summary.isBlank() && verdict.isBlank() && free.isBlank()) {
ReportSections("", "", "(在手机上结束了本次学习,未填写总结)")
} else {
ReportSections(summary, verdict, free)
}
onConfirm(sections)
},
enabled = !busy,
onClick = { onConfirm(currentSections()) },
// 草稿只是编辑起点:正在生成时也允许直接手写结束
enabled = !state.busy,
) { Text("确认结束") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
)
if (confirmRegenerate) {
AlertDialog(
onDismissRequest = { confirmRegenerate = false },
title = { Text("重新生成学习总结") },
text = { Text("会用新草稿覆盖当前三段内容(包括你已经编辑的部分),确定继续吗?") },
confirmButton = {
Button(onClick = {
confirmRegenerate = false
onGenerateDraft()
}) { Text("重新生成") }
},
dismissButton = {
TextButton(onClick = { confirmRegenerate = false }) { Text("取消") }
},
)
}
}
@Composable
@@ -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()) {
@@ -32,6 +32,10 @@ fun TaskListScreen(
username: String?,
onRefresh: () -> Unit,
onStart: (TaskItem) -> Unit,
onOpenReports: (TaskItem) -> Unit,
hasActiveSession: Boolean,
starting: Boolean,
onOpenSession: () -> Unit,
onOpenSettings: () -> Unit,
onOpenPermissions: () -> Unit,
onLogout: () -> Unit,
@@ -55,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
@@ -99,7 +130,8 @@ fun TaskListScreen(
Card(
modifier = Modifier
.fillMaxWidth()
.clickable { onStart(task) },
// 开始会话是网络请求:在途时禁用,防连点重复提交
.clickable(enabled = !starting) { onStart(task) },
) {
Column(modifier = Modifier.padding(14.dp)) {
Text(
@@ -124,8 +156,9 @@ fun TaskListScreen(
color = MaterialTheme.colorScheme.primary,
)
Spacer(Modifier.weight(1f))
TextButton(onClick = { onOpenReports(task) }, enabled = !starting) { Text("报告") }
Text(
"开始学习 ›",
if (starting) "开始中…" else "开始学习 ›",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
)
@@ -1,5 +1,8 @@
package com.catshark.lpt.util
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/** 把秒数格式化成 mm:ss 或 h:mm:ss */
fun formatDuration(seconds: Double): String {
val total = seconds.toLong().coerceAtLeast(0)
@@ -8,3 +11,11 @@ fun formatDuration(seconds: Double): String {
val s = total % 60
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
}
private val DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
/** 服务端返回的 LocalDateTime 字符串(无时区),解析失败时原样展示 */
fun formatDateTime(iso: String?): String {
if (iso.isNullOrBlank()) return ""
return runCatching { LocalDateTime.parse(iso).format(DATE_TIME_FORMAT) }.getOrDefault(iso)
}
+12
View File
@@ -32,6 +32,18 @@ RUN yes | sdkmanager --licenses > /dev/null \
WORKDIR /workspace
COPY . .
# 先把 Gradle 分发包(约 140 MB)下下来,带重试;
# 后面真正的构建就直接用缓存,不会因为一次网络抖动整条流水线重跑。
RUN set -e; \
ok=0; \
for i in 1 2 3; do \
if ./gradlew --no-daemon --version > /tmp/gradle-wrapper.log 2>&1; then ok=1; break; fi; \
echo "Gradle 分发包获取失败(第 $i 次),5 秒后重试"; \
tail -5 /tmp/gradle-wrapper.log; \
sleep 5; \
done; \
if [ "$ok" != "1" ]; then echo "三次都失败,日志:"; tail -30 /tmp/gradle-wrapper.log; exit 1; fi
# 容器内没有 daemon 需要常驻,显式关掉
RUN ./gradlew --no-daemon :app:assembleDebug
+8 -2
View File
@@ -1,7 +1,13 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip
networkTimeout=10000
# 官方 services.gradle.org 会 302 跳到 release-assets.githubusercontent.com,
# 国内网络下大文件经常 10s 读超时(CI 上已复现:Read timed out)。
# 改用腾讯云镜像——与官方 zip 逐字节一致,sha256 已核对(见下面的 distributionSha256Sum)。
# 如需换回官方源:distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.14.6-bin.zip
distributionSha256Sum=7988ed071b2a07900e2ec715fca15c6ab72bce6db433af301fa7fa7e9407bd24
# 140 MB 的分发包:10s 太短,慢速链路上必然超时
networkTimeout=120000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists