10 Commits
Author SHA1 Message Date
cat-shark d71bfe2139 fix: 补齐设置保存/登录的中间层在途守卫,并去重同文案提示
- 真机双击验证发现:设置页「保存」两次点击都会真的写一遍(DataStore 写太快,UI 标记在第二次点击前就已复位),会看到两条一样的提示
- AppContainer 增加 authInFlight / baseUrlSaving 在途标记,重复调用直接忽略
- snackbar 增加同文案 1.5 秒去重,连点不再堆两条相同提示
2026-11-08 22:44:28 +08:00
cat-shark 27d4bcc774 fix: 所有发请求的按钮加防连点
- SessionController 新增在途标记 expectationSaving / fragmentAdding,入口早退 + 按钮禁用(文案改「保存中…」「记录中…」)
- 记碎片改为「成功才清空输入、失败保留」;浮窗拉起的碎片输入页同样防连点,且写入成功才关弹窗
- 设置页保存 API 地址期间禁用按钮;登录按钮补显式重入保护
- 任务列表开始会话在途时禁用卡片(文案改「开始中…」),不再能连点重复开始
2026-11-08 22:37:57 +08:00
cat-shark 267570dcab fix: 修复加载动画变形、补动作反馈,并收紧冲突弹窗
- CircularProgressIndicator 误用 Modifier.height() 会拿到非方形画布,圆环被压扁且旋转中心偏;四处统一改为 Modifier.size()
- 保存预期 / 保存 API 地址 / 开始暂停结束 / 记碎片都有 snackbar 反馈(成功短、失败长),不再只靠页面底部静态文案
- API 地址改为先校验再写入(不合法保留旧地址并提示),登录页同样校验;启动时遇到坏地址退回默认,不再抛异常
- 冲突弹窗只保留「前往继续 / 取消」:结束与误操作结束必须回到会话页面里用户自己做,列表页不再提供放弃/结束入口
2026-11-08 22:21:45 +08:00
cat-shark 4de7ac5203 fix: 上传附件改为纯 shell 解析(runner 无 python3/jq)并加上传后回读校验 2026-11-08 22:18:10 +08:00
cat-shark 17fb0fe3f2 fix: 修复真机验证发现的三处问题
真机(Redmi K30 5G / Android 12 / MIUI)验证后修:

- 登录失效不再卡死:任意请求返回 401 时自动退出登录、停掉前台服务,并在登录页说明「登录已失效,请重新登录」;网络/HTTP 层错误统一转成可读文案,不再直接抛「HTTP 401」
- 会话错误条不再盖住任务页标题:从叠在最上层改成正常布局占位(叠层只留给会话冲突弹窗)
- 会话不再回不去:冲突出口处理后显式跳回会话页(hasSession 一直是 true,靠状态变化不会触发导航,原本会导致新会话的预期门禁被绕过);任务页在有进行中会话时新增「有一次学习正在进行 / 回到会话」入口
- 结束弹窗复用已缓存的报告草稿,重开不再白跑一次 AI
2026-11-08 22:02:03 +08:00
cat-shark 8a55621e2c fix: 归档改用 Release API(runner 无 node,JS action 无法运行) 2026-11-08 19:18:05 +08:00
cat-shark d9d4f4e69e feat: 补齐会话冲突出口、预期必填与报告闭环,精简悬浮窗
- 会话冲突出口:开始新任务前查其他任务上的未结束会话,给出「前往继续 / 结束它并开始 / 放弃它」三个出口,避免同时存在两个进行中的会话
- 学习预期必填:未填预期时用不可关闭弹窗挡住,只能保存预期或走误操作结束
- 收敛提示:把服务端 systemMessage / autoConverged 原样告知用户
- 学习报告:结束会话时取 REPORT_DRAFT 草稿(AI 不可用由后端规则降级)作为编辑起点,可直接手写结束;任务页新增报告查看(三段 + 本会话碎片)
- 悬浮窗只保留三件事:展示倒计时、记一条碎片、暂停/继续;结束、报告、预期等一律回到 App 页面
- 修复前台服务在进程被系统拉起时把「还不知道」当成「没有会话」而自杀(以 State.resolved 为准)
2026-11-08 19:14:40 +08:00
cat-shark 67a3f1e8f8 fix: Gradle 分发包改用国内镜像并延长超时、构建前带重试 2026-11-08 18:53:01 +08:00
cat-shark c419ffd814 docs: 补充分支与环境口径 2026-11-08 17:58:29 +08:00
cat-shark 726730c3c9 ci: 新增构建流水线(分支↔环境校验 + 容器内打 APK 并归档) 2026-11-08 17:58:29 +08:00
22 changed files with 1728 additions and 353 deletions
+10
View File
@@ -0,0 +1,10 @@
# 构建上下文瘦身:CI 里是全新 clone,这里主要防止把本地产物/仓库元数据塞进镜像
.git/
.gradle/
build/
app/build/
.idea/
*.iml
*.apk
*.aab
local.properties
+204
View File
@@ -0,0 +1,204 @@
name: lpt-android Build
on:
workflow_dispatch:
inputs:
environment:
description: '构建环境(dev 仅允许 dev 分支;prod 仅允许 master 分支)'
required: true
type: choice
options:
- dev
- prod
env:
APP: lpt-android
REPO_URL: https://git.cat-shark.xyz/cat-shark/lpt-android.git
# 各环境的默认 API 地址。必须与 app/src/main/java/com/catshark/lpt/data/ApiClient.kt
# 里的 DEFAULT_BASE_URL 保持一致——第二步会逐字比对。
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
steps:
- name: 校验分支 ↔ 环境
run: |
set -euo pipefail
REF="${{ gitea.ref }}"
BRANCH="${REF#refs/heads/}"
if [[ "$REF" == refs/tags/* ]]; then
echo "ERROR: 请从分支触发构建,不要用 tag。当前 ref=$REF"
exit 1
fi
ENV="${{ inputs.environment }}"
echo "branch=$BRANCH environment=$ENV sha=${{ gitea.sha }}"
case "$ENV" in
prod)
case "$BRANCH" in
master) echo "OK: prod 允许从 $BRANCH 构建" ;;
*)
echo "ERROR: prod 只能从 master 构建,当前分支是 '$BRANCH'"
echo "请切换到 master 后再 Run workflow,并选择 environment=prod"
exit 1
;;
esac
;;
dev)
case "$BRANCH" in
dev) echo "OK: dev 允许从 $BRANCH 构建" ;;
*)
echo "ERROR: dev 只能从 dev 分支构建,当前分支是 '$BRANCH'"
echo "请切换到 dev 后再 Run workflow,并选择 environment=dev"
exit 1
;;
esac
;;
*)
echo "ERROR: 未知 environment=$ENV"
exit 1
;;
esac
- name: Checkout code
run: |
set -euo pipefail
git clone "$REPO_URL" .
git checkout "${{ gitea.sha }}"
- name: 校验代码里的默认环境地址
run: |
set -euo pipefail
ENV="${{ inputs.environment }}"
ACTUAL="$(grep -oE 'DEFAULT_BASE_URL = "[^"]+"' app/src/main/java/com/catshark/lpt/data/ApiClient.kt \
| head -1 | sed 's/.*= "//; s/"$//')"
if [ "$ENV" = "prod" ]; then EXPECT="$PROD_API"; else EXPECT="$DEV_API"; fi
echo "代码里的分支默认地址 = $ACTUAL"
echo "本环境期望的地址 = $EXPECT"
if [ "$ACTUAL" != "$EXPECT" ]; then
echo "ERROR: $ENV 的默认 API 地址与分支不匹配。"
echo "这两个分支只允许差这一行:dev 指向 dev 环境、master 指向生产环境。"
exit 1
fi
echo "OK: 默认地址与环境匹配"
- name: 构建 APK(容器内完成,JDK/SDK 版本固化)
run: |
set -euo pipefail
docker build -f ci/Dockerfile -t lpt-android-apk:ci .
- name: 取出 APK 并打印校验值
run: |
set -euo pipefail
ENV="${{ inputs.environment }}"
SHORT="$(echo "${{ gitea.sha }}" | cut -c1-8)"
NAME="lpt-android-${ENV}-${SHORT}.apk"
docker create --name lpt-apk-out lpt-android-apk:ci > /dev/null
docker cp lpt-apk-out:/out/app-debug.apk "$NAME"
docker rm -f lpt-apk-out > /dev/null
ls -l "$NAME"
sha256sum "$NAME" | tee apk-sha256.txt
- 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})"
+29 -2
View File
@@ -23,21 +23,48 @@
| `data/` | 网络与本地存储;`LptApi` 是唯一接口定义处,`LptRepository` 负责 `code != 200 → ApiException` | | `data/` | 网络与本地存储;`LptApi` 是唯一接口定义处,`LptRepository` 负责 `code != 200 → ApiException` |
| `session/` | `SessionController` 是会话状态机唯一入口;UI 与服务都只读它的 `StateFlow` | | `session/` | `SessionController` 是会话状态机唯一入口;UI 与服务都只读它的 `StateFlow` |
| `service/` | 前台服务与悬浮窗;不承载业务逻辑,只渲染状态并转发动作 | | `service/` | 前台服务与悬浮窗;不承载业务逻辑,只渲染状态并转发动作 |
| `ui/` | Compose 页面;不直接调 Retrofit,只调 `SessionController` / `AppContainer` | | `ui/` | Compose 页面(含 `ReportsScreen`);不直接调 Retrofit,只调 `SessionController` / `AppContainer` |
## 必须遵守的约定 ## 必须遵守的约定
- **会话状态只在 `SessionController` 里改**。UI 和 Service 都不得自行维护会话副本,否则会与服务端口径分叉。 - **会话状态只在 `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()`。 - **计时不得用 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`),不要假设源码与部署一致——两者已经分叉过一次。
## 后端 ## 后端
- dev:`https://lpt-dev.cat-shark.xyz/api` - dev:`https://lpt-dev.cat-shark.xyz/api`
- 认证:Sa-Token,token 放请求头 `satoken`(不用 Cookie) - 认证:Sa-Token,token 放请求头 `satoken`(不用 Cookie)
- 只使用学习会话相关端点,**不碰 `review/*`** - 只使用学习会话相关端点(含报告与 `POST /ai/tasks` 的 `REPORT_DRAFT`),**不碰复习端点**(`review` 前缀)
## 分支与发布
与 `lpt-be` / `lpt-fe` / `lpt-ai` 同规则:**一个分支对一个环境**(本仓库没有服务端部署,环境差异落在“默认 API 地址”上)。
| 分支 | 环境 | 默认 API 地址 |
|------|------|----------------|
| `dev` | 开发 | `https://lpt-dev.cat-shark.xyz/api` |
| `master` | 生产 | `https://lpt.cat-shark.xyz/api` |
- 两个分支的代码**只允许差 `ApiClient.DEFAULT_BASE_URL` 这一行**(其余全部一致)。改这一行时必须确认自己在哪个分支上,改完只提本分支。
- 不要跨分支合并:`dev` 的功能要上生产时,只把常规代码改动同步过去,并保持 master 的默认地址不变。
- 构建在 Gitea 手动触发 `.gitea/workflows/build.yml`(dev/prod 二选一),不需要签本地环境:
1. 校验「分支 ↔ 环境」(从 dev 发 prod 直接被拒);
2. 校验代码里的 `DEFAULT_BASE_URL` 是否与本环境一致,不一致直接失败;
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` 预检)。
## 提交规范 ## 提交规范
+30 -12
View File
@@ -8,18 +8,23 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
- 浮窗常驻在其他 App 之上,学习计时不因切走而中断。 - 浮窗常驻在其他 App 之上,学习计时不因切走而中断。
- 不抢输入法焦点、不挡住下层 App 的触摸(`FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL`)。 - 不抢输入法焦点、不挡住下层 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 自启动与后台弹出 | | 权限引导 | 悬浮窗权限 / 通知权限 / 电池优化白名单 / MIUI 自启动与后台弹出 |
| 任务列表 | `GET /tasks` | | 任务列表 | `GET /tasks`,每个任务带「报告」入口;有进行中的会话时顶部带「回到会话」入口 |
| 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期、知识碎片、结束报告三段 | | 操作反馈 | 保存预期、保存 API 地址、开始/暂停/结束、记碎片等动作都有 snackbar 提示(成功短、失败长);所有发请求的按钮在途时禁用,防连点重复提交 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;暂停/继续/结束/记碎片/半隐藏 | | 学习会话 | 开始/继续、暂停、结束、误操作结束(零数据)、学习预期(必填)、知识碎片、结束报告三段 |
| 会话冲突出口 | 开始新任务前先查其他任务上的未结束会话;有冲突时只给「前往继续 / 取消」,结束与误操作结束必须回到那个会话的页面里自己做 |
| 悬浮窗 | 前台服务(`specialUse`)托管,跨应用常驻;**只做三件事**:展示倒计时 / 记一条碎片 / 暂停继续 |
| 学习报告 | 结束会话时取 AI(不可用则规则降级)三段草稿作为编辑起点;任务页可查看历史报告与本次碎片 |
| 设置 | API 地址可切(默认 dev) | | 设置 | API 地址可切(默认 dev) |
**不做**:复习(`review/*`)、思维导图、回忆对比、学习录音。 **不做**:复习(`review/*`)、思维导图、回忆对比、学习录音。
@@ -46,6 +51,17 @@ LPT 的学习计时原本只能在电脑浏览器里进行;而真实的学习
> ⚠️ Compose BOM ≥ 2026.04(compose 1.11+)要求 **AGP 9.1+ 与 compileSdk 37**,配 AGP 8.13.2 会报 `requires Android Gradle plugin 9.1.0 or higher`。要么整体升 AGP 9,要么锁在 2026.03.01。 > ⚠️ Compose BOM ≥ 2026.04(compose 1.11+)要求 **AGP 9.1+ 与 compileSdk 37**,配 AGP 8.13.2 会报 `requires Android Gradle plugin 9.1.0 or higher`。要么整体升 AGP 9,要么锁在 2026.03.01。
### 分支与环境
| 分支 | 环境 | 默认 API 地址 | 用途 |
|------|------|----------------|------|
| `dev` | 开发 | `https://lpt-dev.cat-shark.xyz/api` | 日常开发与验证 |
| `master` | 生产 | `https://lpt.cat-shark.xyz/api` | 给真实使用打的生产包 |
两个分支**只差 `ApiClient.DEFAULT_BASE_URL` 一行**;安装后仍可在「设置」页临时改地址(调试用)。
打包走 Gitea Actions 的 `lpt-android Build`(手动触发,选 `dev` 或 `prod`):先校验「分支 ↔ 默认地址」是否匹配,再在容器里构建,最后把 APK 传到该环境的**滚动 Release**(`android-dev` / `android-prod`,附件每次覆盖)——本地不需要配签名环境。
## 构建与安装 ## 构建与安装
```bash ```bash
@@ -77,7 +93,8 @@ gradle :app:assembleDebug
- **计时口径**:显示值 = 服务端 `effectiveTime`(基准)+ 以 `SystemClock.elapsedRealtime()` 为锚点的增量。**不用 tick 累加**,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时用服务端 `lastStartTime` 重新对锚。 - **计时口径**:显示值 = 服务端 `effectiveTime`(基准)+ 以 `SystemClock.elapsedRealtime()` 为锚点的增量。**不用 tick 累加**,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时用服务端 `lastStartTime` 重新对锚。
- **窗口必须带 `FLAG_LAYOUT_NO_LIMITS`**:否则 WindowManager 会把越界位置夹回屏幕内,半隐藏会失效(实测 `mAttrs x=-651` 但 `mFrame` 仍是 `[0,...]`)。 - **窗口必须带 `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 不在前台时,系统不允许后台窗口弹软键盘——实测浮窗的 `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`)。
## 后端契约兼容(重要) ## 后端契约兼容(重要)
@@ -87,7 +104,7 @@ gradle :app:assembleDebug
|------|--------------|----------------|-----------| |------|--------------|----------------|-----------|
| `POST /report-fragments` | `{sessionNum, content}` | `{contextNum, content}` | 两个字段都发 | | `POST /report-fragments` | `{sessionNum, content}` | `{contextNum, content}` | 两个字段都发 |
| `POST .../study-sessions/ended` | `{content}`(单段,必填) | `{sessionSummary, expectationVerdict, freeSummary}` | 发 `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}` | 不存在 | 存在 | 未使用 | | `DELETE /report-fragments/{id}` | 不存在 | 存在 | 未使用 |
排查这类问题的可靠手段:直接拉部署环境的 OpenAPI —— `GET {baseUrl}/v3/api-docs`。 排查这类问题的可靠手段:直接拉部署环境的 OpenAPI —— `GET {baseUrl}/v3/api-docs`。
@@ -97,19 +114,20 @@ gradle :app:assembleDebug
```text ```text
app/src/main/java/com/catshark/lpt/ app/src/main/java/com/catshark/lpt/
├── LptApp.kt Application + 手写依赖容器 ├── LptApp.kt Application + 手写依赖容器
├── MainActivity.kt 导航(任务列表 / 会话 / 权限 / 设置) ├── MainActivity.kt 导航(任务列表 / 会话 / 报告 / 权限 / 设置)+ 会话冲突出口弹窗
├── data/ Models / LptApi / ApiClient / TokenStore / LptRepository ├── data/ Models / LptApi / ApiClient / TokenStore / LptRepository
├── session/SessionController.kt 会话状态机(Application 级单例,StateFlow) ├── session/SessionController.kt 会话状态机(Application 级单例,StateFlow)
├── service/ ├── service/
│ ├── StudySessionService.kt 前台服务 + 通知 + 调度浮窗与输入弹窗 │ ├── StudySessionService.kt 前台服务 + 通知 + 调度浮窗与输入弹窗
│ └── OverlayView.kt 悬浮窗(完整条 / 半隐藏胶囊) │ └── OverlayView.kt 悬浮窗(只做倒计时 / 记碎片 / 暂停继续)
├── ui/ Compose 页面 + FragmentInputActivity ├── ui/ Compose 页面(含 ReportsScreen)+ FragmentInputActivity
└── util/Format.kt └── util/Format.kt
``` ```
## 已知限制 ## 已知限制
- 浮窗依赖悬浮窗权限,被系统回收后需要 App 进程还活着才能自动恢复(`START_STICKY` + 启动时对账)。 - 浮窗依赖悬浮窗权限;进程被杀后靠 `START_STICKY` + 启动时对账恢复。实测 **MIUI(Android 12)不会重启被杀的进程**:进程没了浮窗就没了,需要用户打开一次 App 才恢复(打开后的对账是可靠的)。
- 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。 - 国内 OEM 的省电策略可能杀掉前台服务,需要用户手动白名单。
- 报告草稿的 AI 生成未接入(旧后端同步接口慢、新后端是异步任务,两者差异大),报告目前由用户手写。 - 报告第四部分「按归属分组的碎片」由复习模块实时聚合,本客户端按仓库边界不访问复习端点,报告页只列本次会话产生的碎片。
- 没有自动化测试;`.gitea/workflows/build.yml` 只构建不跑测试。
- 学习录音(系统混音采集)未做,属于二期。 - 学习录音(系统混音采集)未做,属于二期。
+79 -11
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,51 +46,118 @@ 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
_loggedIn.value = !settings.token.isNullOrBlank() _loggedIn.value = !settings.token.isNullOrBlank()
_ready.value = true _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) { fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
// 在途时直接忽略重复提交:登录是重操作,不能因为手抖发两次
if (authInFlight) return
authInFlight = true
scope.launch { scope.launch {
apiClient.setBaseUrl(baseUrl) try {
if (!apiClient.setBaseUrl(baseUrl)) {
onResult("API 地址不合法,需要形如 https://host/api")
return@launch
}
repository.login(username, password) repository.login(username, password)
.onSuccess { token -> .onSuccess { token ->
apiClient.token = token apiClient.token = token
tokenStore.saveLogin(token, username, baseUrl) tokenStore.saveLogin(token, username, baseUrl)
_baseUrl.value = baseUrl _baseUrl.value = baseUrl
_username.value = username _username.value = username
_authNotice.value = null
_loggedIn.value = true _loggedIn.value = true
session.reconcile() session.reconcile()
onResult(null) onResult(null)
} }
.onFailure { onResult(it.message ?: "登录失败") } .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
} }
} }
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
}
} }
} }
} }
@@ -5,12 +5,24 @@ import android.os.Bundle
import android.provider.Settings import android.provider.Settings
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box 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.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.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme 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.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
@@ -22,10 +34,13 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.catshark.lpt.data.TaskItem import com.catshark.lpt.data.TaskItem
import com.catshark.lpt.service.StudySessionService import com.catshark.lpt.service.StudySessionService
import com.catshark.lpt.session.SessionController
import com.catshark.lpt.ui.LoginScreen import com.catshark.lpt.ui.LoginScreen
import com.catshark.lpt.ui.PermissionScreen import com.catshark.lpt.ui.PermissionScreen
import com.catshark.lpt.ui.ReportsScreen
import com.catshark.lpt.ui.SessionScreen import com.catshark.lpt.ui.SessionScreen
import com.catshark.lpt.ui.SettingsScreen import com.catshark.lpt.ui.SettingsScreen
import com.catshark.lpt.ui.TaskListScreen 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 @Composable
private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolean>) { 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 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) }
var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) } var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) }
var tasksLoading by remember { mutableStateOf(false) } var tasksLoading by remember { mutableStateOf(false) }
var tasksError by remember { mutableStateOf<String?>(null) } 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() { fun refreshTasks() {
tasksLoading = true tasksLoading = true
@@ -125,10 +160,37 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
} }
} }
// 会话层的提示与失败统一弹 snackbar(错误停留久一点)
LaunchedEffect(sessionState.notice) {
sessionState.notice?.let {
toast(it)
container.session.consumeNotice()
}
}
LaunchedEffect(sessionState.error) {
sessionState.error?.let {
toast(it, long = true)
container.session.consumeError()
}
}
Box(modifier = Modifier.fillMaxSize()) {
Column(modifier = Modifier.fillMaxSize()) {
// 不在会话页时,会话层的失败也要让用户看到(用正常布局占位,不遮住下面的标题)
if (screen != Screen.Session) {
sessionState.error?.let { message ->
ErrorBar(message = message, onDismiss = { container.session.consumeError() })
}
}
Box(modifier = Modifier.weight(1f)) {
when { 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)
} }
@@ -144,6 +206,13 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
StudySessionService.start(context) StudySessionService.start(context)
} }
}, },
onOpenReports = { task ->
reportTask = task
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 = {
@@ -157,7 +226,7 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
openEndDialog = openEnd, openEndDialog = openEnd,
onConsumeOpenEnd = { openEndRequest.value = false }, onConsumeOpenEnd = { openEndRequest.value = false },
onTogglePause = { onTogglePause = {
if (sessionState.status == com.catshark.lpt.session.SessionController.Status.ONGOING) { if (sessionState.status == SessionController.Status.ONGOING) {
container.session.pause() container.session.pause()
} else { } else {
container.session.resume() container.session.resume()
@@ -175,17 +244,37 @@ 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() },
onBack = { screen = Screen.Tasks }, 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.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
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()
@@ -195,6 +284,122 @@ private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolea
} }
} }
} }
}
// 会话-05:别的任务上还有未结束会话时,只能先去把它处理完
sessionState.conflict?.let {
SessionConflictDialog(
state = sessionState,
onContinue = {
// hasSession 一直是 true,靠状态变化不会触发导航,这里必须显式回会话页
container.session.continueConflict {
StudySessionService.start(context)
screen = Screen.Session
}
},
onDismiss = { container.session.dismissConflict() },
)
}
SnackbarHost(
hostState = snackbarHostState,
modifier = Modifier.align(Alignment.BottomCenter),
)
}
}
/**
* 会话-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("关闭") }
}
}
}
@Composable @Composable
private fun LoadingScreen() { private fun LoadingScreen() {
@@ -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
@@ -23,6 +23,7 @@ interface LptApi {
@GET("tasks") @GET("tasks")
suspend fun tasks(): ApiEnvelope<TaskPage> suspend fun tasks(): ApiEnvelope<TaskPage>
/** 当前活跃会话;excludeTaskNum 用于把「自己这个任务」排除掉,剩下的就是冲突会话 */
@GET("study-sessions/active") @GET("study-sessions/active")
suspend fun activeSession( suspend fun activeSession(
@Query("excludeTaskNum") excludeTaskNum: String? = null, @Query("excludeTaskNum") excludeTaskNum: String? = null,
@@ -69,4 +70,24 @@ interface LptApi {
@GET("report-fragments/session/{sessionNum}") @GET("report-fragments/session/{sessionNum}")
suspend fun fragmentsBySession(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<FragmentItem>> 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 package com.catshark.lpt.data
import kotlinx.coroutines.delay
import retrofit2.HttpException
/** 业务错误:把后端的 message 直接带给 UI */ /** 业务错误:把后端的 message 直接带给 UI */
class ApiException(message: String) : Exception(message) class ApiException(message: String) : Exception(message)
@@ -16,51 +19,84 @@ class LptRepository(private val apiClient: ApiClient) {
return env.data as T 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)) 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
} }
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), "开始学习会话") 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(
@@ -74,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)),
"记录碎片", "记录碎片",
@@ -87,7 +123,46 @@ 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()
} }
/** 依次任务的历史报告(按会话生成,分页) */
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.Serializable
import kotlinx.serialization.json.JsonElement 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 } */ /** lpt-be 的统一响应包装:{ code, message, data } */
@Serializable @Serializable
@@ -63,6 +66,8 @@ data class ActiveSession(
val taskName: String? = null, val taskName: String? = null,
val sessionState: String? = null, val sessionState: String? = null,
val autoConverged: Boolean = false, val autoConverged: Boolean = false,
/** 服务端自动收敛时的用户可见文案 */
val systemMessage: String? = null,
) )
@Serializable @Serializable
@@ -116,6 +121,10 @@ data class ReportSections(
val allBlank: Boolean val allBlank: Boolean
get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank() get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank()
companion object {
val EMPTY = ReportSections("", "", "")
}
/** /**
* 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题, * 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题,
* 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。 * 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。
@@ -130,14 +139,65 @@ data class ReportSections(
/** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */ /** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */
fun extractToken(element: JsonElement?): String? { fun extractToken(element: JsonElement?): String? {
if (element == null) return null if (element == null) return null
return when { val text = element.toString().trim()
element is JsonElement && element.toString().trim().startsWith("\"") -> if (text.startsWith("\"")) return text.trim('"')
element.toString().trim().trim('"') val token = (element as? JsonObject)?.get("token") ?: return null
else -> { val raw = token.toString().trim()
val obj = element as? kotlinx.serialization.json.JsonObject return if (raw.startsWith("\"")) raw.trim('"') else raw
obj?.get("token")?.let { token ->
if (token.toString().trim().startsWith("\"")) token.toString().trim().trim('"') else token.toString()
}
} }
/** 某次学习会话产出的学习报告(报告三段 + 该会话的学习预期) */
@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 实现)。 * 系统级悬浮窗(经典 View 实现)。
* *
* 三种形态: * 职责被刻意压到最小——浮窗只做三件事:
* - 浏览:完整条(任务名 + 计时 + 暂停 + 展开),FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。 * 1. 展示倒计时;
* 2. 记一条知识碎片(拉起 FragmentInputActivity,浮窗内不做文本输入);
* 3. 暂停 / 继续计时。
*
* 其余动作(改预期、结束会话、写报告、看历史)一律在 App 页面内完成,不要往浮窗里加。
*
* 两种形态:
* - 常态条:`● 12:34 + 暂停`,FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。 * - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
* *
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。 * 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
* *
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘, * 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
* 所以「+ 记一条碎片」回调给 Service,由它拉起 FragmentInputActivity。 * 所以「+」回调给 Service,由它拉起 FragmentInputActivity。
*/ */
class OverlayView(private val context: Context) { class OverlayView(private val context: Context) {
@@ -37,37 +44,25 @@ class OverlayView(private val context: Context) {
private var root: LinearLayout? = null private var root: LinearLayout? = null
private var params: WindowManager.LayoutParams? = null private var params: WindowManager.LayoutParams? = null
private var shown = false private var shown = false
private var expanded = false
private var halfHidden = false private var halfHidden = false
private var lastState: SessionController.State? = null private var lastState: SessionController.State? = null
private lateinit var headerRow: LinearLayout private lateinit var barRow: LinearLayout
private lateinit var dotView: View private lateinit var dotView: View
private lateinit var nameView: TextView
private lateinit var timeView: TextView private lateinit var timeView: TextView
private lateinit var pauseView: TextView private lateinit var fragmentView: TextView
private lateinit var expandView: TextView private lateinit var toggleView: TextView
private lateinit var compactView: LinearLayout private lateinit var compactRow: LinearLayout
private lateinit var compactDot: View private lateinit var compactDot: View
private lateinit var compactTime: TextView 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 onTogglePause: (() -> Unit)? = null
var onEnd: (() -> Unit)? = null
var onOpenApp: (() -> Unit)? = null
var onRequestFragmentInput: (() -> Unit)? = null var onRequestFragmentInput: (() -> Unit)? = null
val isShown: Boolean get() = shown val isShown: Boolean get() = shown
private val autoHideTask = Runnable { 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() private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
@@ -88,14 +83,6 @@ class OverlayView(private val context: Context) {
isFocusable = false 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() { fun show() {
if (shown) return if (shown) return
if (!Settings.canDrawOverlays(context)) return if (!Settings.canDrawOverlays(context)) return
@@ -138,29 +125,15 @@ class OverlayView(private val context: Context) {
val ongoing = state.status == SessionController.Status.ONGOING val ongoing = state.status == SessionController.Status.ONGOING
val text = formatDuration(state.effectiveSeconds()) val text = formatDuration(state.effectiveSeconds())
nameView.text = state.taskName?.takeIf { it.isNotBlank() } ?: "学习会话"
timeView.text = text timeView.text = text
compactTime.text = text compactTime.text = text
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4) dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
compactDot.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 "继续" toggleView.text = if (ongoing) "暂停" else "继续"
pauseView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10) toggleView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
expectationView.text = barRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
if (state.expectation.isBlank()) "预期:未填写" else "预期:${state.expectation}" compactRow.visibility = if (halfHidden) View.VISIBLE else View.GONE
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()
} }
// ---- 半隐藏 / 自动隐藏 ---- // ---- 半隐藏 / 自动隐藏 ----
@@ -168,9 +141,9 @@ class OverlayView(private val context: Context) {
fun setHalfHidden(hidden: Boolean) { fun setHalfHidden(hidden: Boolean) {
val view = root ?: return val view = root ?: return
val p = params ?: return val p = params ?: return
if (hidden) expanded = false
halfHidden = hidden halfHidden = hidden
view.alpha = if (hidden) 0.6f else 1f // 常态整条 80% 不透明;收起后再压一档,整体约 60%
view.alpha = if (hidden) 0.75f else 1f
lastState?.let { render(it) } lastState?.let { render(it) }
val screenWidth = context.resources.displayMetrics.widthPixels val screenWidth = context.resources.displayMetrics.widthPixels
@@ -191,7 +164,7 @@ class OverlayView(private val context: Context) {
private fun scheduleAutoHide() { private fun scheduleAutoHide() {
root?.removeCallbacks(autoHideTask) 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() { private fun cancelAutoHide() {
@@ -211,8 +184,8 @@ class OverlayView(private val context: Context) {
elevation = dp(10).toFloat() elevation = dp(10).toFloat()
} }
// ---- 完整条 ---- // ---- 常态条:● 计时 + 暂停/继续 ----
headerRow = LinearLayout(context).apply { barRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL gravity = Gravity.CENTER_VERTICAL
} }
@@ -220,36 +193,31 @@ class OverlayView(private val context: Context) {
background = rounded(COLOR_ONGOING, 4) background = rounded(COLOR_ONGOING, 4)
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8)) 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 { timeView = TextView(context).apply {
setTextColor(Color.WHITE) setTextColor(Color.WHITE)
textSize = 16f textSize = 17f
typeface = Typeface.MONOSPACE 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) fragmentView = pill("+", COLOR_NEUTRAL).apply {
expandView = pill("▾", COLOR_NEUTRAL).apply { contentDescription = "记一条知识碎片"
layoutParams = LinearLayout.LayoutParams( layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,
).apply { marginStart = dp(6) } ).apply { marginEnd = dp(6) }
} }
headerRow.addView(dotView) toggleView = pill("暂停", COLOR_ACTION)
headerRow.addView(nameView)
headerRow.addView(timeView)
headerRow.addView(pauseView)
headerRow.addView(expandView)
container.addView(headerRow)
// ---- 半隐藏小胶囊 ---- barRow.addView(dotView)
compactView = LinearLayout(context).apply { barRow.addView(timeView)
barRow.addView(fragmentView)
barRow.addView(toggleView)
container.addView(barRow)
// ---- 半隐藏小胶囊:● 计时 ----
compactRow = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL gravity = Gravity.CENTER_VERTICAL
visibility = View.GONE visibility = View.GONE
@@ -262,82 +230,27 @@ class OverlayView(private val context: Context) {
} }
compactTime = TextView(context).apply { compactTime = TextView(context).apply {
setTextColor(Color.WHITE) setTextColor(Color.WHITE)
textSize = 14f textSize = 15f
typeface = Typeface.MONOSPACE typeface = Typeface.MONOSPACE
setPadding(dp(6), 0, 0, 0) setPadding(dp(6), 0, dp(4), 0)
} }
compactView.addView(compactDot) compactRow.addView(compactDot)
compactView.addView(compactTime) compactRow.addView(compactTime)
compactView.setOnClickListener { setHalfHidden(false) } compactRow.setOnClickListener { setHalfHidden(false) }
container.addView(compactView) container.addView(compactRow)
// ---- 展开面板 ---- fragmentView.setOnClickListener {
expandedPanel = LinearLayout(context).apply { scheduleAutoHide()
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 {
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡 // 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
setHalfHidden(true) setHalfHidden(true)
onRequestFragmentInput?.invoke() onRequestFragmentInput?.invoke()
} }
toggleView.setOnClickListener {
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 {
scheduleAutoHide() scheduleAutoHide()
onTogglePause?.invoke() 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 return container
} }
@@ -420,7 +333,6 @@ class OverlayView(private val context: Context) {
private const val COLOR_PAUSED = 0xFFF59E0B.toInt() private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
private const val COLOR_ACTION = 0xFF1F6FEB.toInt() private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
private const val COLOR_RESUME = 0xFF238636.toInt() private const val COLOR_RESUME = 0xFF238636.toInt()
private const val COLOR_END = 0xFFB62324.toInt()
private const val COLOR_NEUTRAL = 0xFF30363D.toInt() private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
} }
} }
@@ -40,18 +40,18 @@ class StudySessionService : Service() {
controller = container.session controller = container.session
overlay = OverlayView(this).apply { overlay = OverlayView(this).apply {
onTogglePause = { togglePause() } onTogglePause = { togglePause() }
onEnd = { openApp(openEnd = true) }
onOpenApp = { openApp(openEnd = false) }
onRequestFragmentInput = { openFragmentInput() } onRequestFragmentInput = { openFragmentInput() }
} }
createChannel() createChannel()
// 状态变化:更新通知 / 悬浮窗;会话没了就停服务 // 状态变化:更新通知 / 悬浮窗。
// 只有「已经与服务端对过账且确实没有会话」才能停服务——进程被系统拉起时
// 对账是异步的,早期看到的空状态是「还不知道」,不能据此 stopSelf。
scope.launch { scope.launch {
controller.state.collect { state -> controller.state.collect { state ->
if (!state.hasSession) { if (!state.hasSession) {
overlay.hide() overlay.hide()
stopSelf() if (state.resolved) stopSelf()
return@collect return@collect
} }
ensureForeground(state) ensureForeground(state)
@@ -87,6 +87,8 @@ class StudySessionService : Service() {
ACTION_SHOW_OVERLAY -> overlay.restore() ACTION_SHOW_OVERLAY -> overlay.restore()
ACTION_STOP -> stopSelf() ACTION_STOP -> stopSelf()
} }
// 进程被系统拉起(intent 为 null)时补一次对账,否则重启后浮窗不会再出现
controller.ensureReconciled()
// 必须在 5 秒内 startForeground,先用当前状态占位 // 必须在 5 秒内 startForeground,先用当前状态占位
ensureForeground(controller.state.value) ensureForeground(controller.state.value)
return START_STICKY return START_STICKY
@@ -6,6 +6,7 @@ import com.catshark.lpt.data.LptRepository
import com.catshark.lpt.data.ReportSections import com.catshark.lpt.data.ReportSections
import com.catshark.lpt.data.SessionDetail import com.catshark.lpt.data.SessionDetail
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
@@ -19,6 +20,9 @@ import java.time.LocalDateTime
* *
* 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。 * 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。
* 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。 * 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
*
* 会话-05:开始任务前先看别的任务上有没有未结束会话,有就进 [State.conflict],
* 由 UI 给出「前往继续 / 结束它并开始新任务 / 放弃它」三个出口。
*/ */
class SessionController( class SessionController(
private val repo: LptRepository, private val repo: LptRepository,
@@ -27,6 +31,17 @@ class SessionController(
enum class Status { NONE, ONGOING, PAUSED, ENDED } 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( data class State(
val sessionNum: String? = null, val sessionNum: String? = null,
val taskNum: String? = null, val taskNum: String? = null,
@@ -35,14 +50,34 @@ class SessionController(
val baseEffectiveSeconds: Double = 0.0, val baseEffectiveSeconds: Double = 0.0,
val anchorRealtimeMs: Long = 0L, val anchorRealtimeMs: Long = 0L,
val expectation: String = "", val expectation: String = "",
/** 学习预期是否已经从服务端取回过(没取回前不要弹必填弹窗) */
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 error: String? = null, val error: String? = null,
val notice: 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 val hasSession: Boolean
get() = status == Status.ONGOING || status == Status.PAUSED get() = status == Status.ONGOING || status == Status.PAUSED
/** 有会话但预期还没填:UI 用不可关闭的弹窗挡住,符合「会话必须有预期才能开始」 */
val expectationRequired: Boolean
get() = hasSession && expectationLoaded && expectation.isBlank()
fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double = fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
if (status == Status.ONGOING) { if (status == Status.ONGOING) {
baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0 baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
@@ -54,25 +89,73 @@ class SessionController(
private val _state = MutableStateFlow(State()) private val _state = MutableStateFlow(State())
val state: StateFlow<State> = _state.asStateFlow() val state: StateFlow<State> = _state.asStateFlow()
private var reconciling = false
fun consumeError() = _state.update { it.copy(error = null) } fun consumeError() = _state.update { it.copy(error = null) }
fun consumeNotice() = _state.update { it.copy(notice = 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 = {}) { fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
if (_state.value.busy) return 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 { 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 -> .onSuccess { detail ->
applyDetail(detail) applyDetail(detail)
loadAuxiliary(detail.sessionNum) _state.update {
_state.update { it.copy(busy = false) } it.copy(
onSuccess() taskNum = conflict.taskNum,
taskName = conflict.taskName ?: it.taskName,
conflict = null,
conflictBusy = false,
)
} }
.onFailure { e -> loadAuxiliary(conflict.sessionNum)
_state.update { it.copy(busy = false, error = e.message ?: "开始学习会话失败") } 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 val num = _state.value.sessionNum ?: return
scope.launch { if (_state.value.expectationSaving) return
repo.putExpectation(num, text) val value = text.trim()
.onSuccess { if (value.isBlank()) {
_state.update { it.copy(expectation = text, notice = "学习预期已保存") } _state.update { it.copy(error = "学习预期不可为空") }
return
} }
.onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } } _state.update { it.copy(expectationSaving = true) }
scope.launch {
repo.putExpectation(num, value)
.onSuccess {
_state.update {
it.copy(expectation = value, expectationLoaded = true, notice = "学习预期已保存")
}
onResult(null)
}
.onFailure { e ->
val message = e.message ?: "保存学习预期失败"
_state.update { it.copy(error = message) }
onResult(message)
}
_state.update { it.copy(expectationSaving = false) }
} }
} }
fun addFragment(content: String) { /**
* 记一条知识碎片。在途时再点直接返回,避免一次输入变成两条碎片;
* onResult 给 null 表示已写入,UI 可以据此清空输入框(失败时保留输入)。
*/
fun addFragment(content: String, onResult: (String?) -> Unit = {}) {
val num = _state.value.sessionNum ?: return 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) }
} }
} }
@@ -132,7 +246,7 @@ class SessionController(
scope.launch { scope.launch {
repo.endSession(num, sections) repo.endSession(num, sections)
.onSuccess { message -> .onSuccess { message ->
_state.value = State(notice = message ?: "学习会话已结束") _state.value = idle(notice = message ?: "学习会话已结束")
onDone() onDone()
} }
.onFailure { e -> .onFailure { e ->
@@ -148,7 +262,7 @@ class SessionController(
scope.launch { scope.launch {
repo.abortSession(num, confirmation) repo.abortSession(num, confirmation)
.onSuccess { .onSuccess {
_state.value = State(notice = "已放弃该会话,未产生任何数据") _state.value = idle(notice = "已放弃该会话,未产生任何数据")
onDone() onDone()
} }
.onFailure { e -> .onFailure { e ->
@@ -157,13 +271,55 @@ 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 { scope.launch {
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(
draftLoading = false,
draft = sections,
draftError = if (sections.allBlank) "没有可聚合的内容,请手写总结" else null,
)
}
}
.onFailure { e ->
_state.update { it.copy(draftLoading = false, draftError = e.message ?: "生成报告草稿失败") }
}
}
}
fun consumeDraftError() = _state.update { it.copy(draftError = null) }
/** App 启动/登录后与服务端对账:把未结束的会话恢复出来 */
fun reconcile() {
if (reconciling) return
reconciling = true
scope.launch {
try {
repo.activeSession() repo.activeSession()
.onSuccess { active -> .onSuccess { active ->
if (active == null || active.sessionNum.isBlank()) { if (active == null || active.sessionNum.isBlank()) {
if (!_state.value.hasSession) _state.update { it.copy(status = Status.NONE) } _state.update { it.copy(status = if (it.hasSession) it.status else Status.NONE) }
return@onSuccess return@onSuccess
} }
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底 // 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
@@ -177,22 +333,73 @@ class SessionController(
refreshDetail(active.sessionNum) refreshDetail(active.sessionNum)
loadAuxiliary(active.sessionNum) loadAuxiliary(active.sessionNum)
} }
.onFailure { e ->
_state.update { it.copy(error = e.message ?: "恢复会话状态失败") }
}
} finally {
reconciling = false
_state.update { it.copy(resolved = true) }
}
} }
} }
fun clear() { /** 前台服务被系统拉起时调用:还没对过账就补一次对账 */
_state.value = State() 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) { private suspend fun refreshDetail(sessionNum: String) {
repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) } repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
} }
private suspend fun loadAuxiliary(sessionNum: String) { private suspend fun loadAuxiliary(sessionNum: String) {
repo.getExpectation(sessionNum).onSuccess { text -> repo.getExpectation(sessionNum).onSuccess { text ->
_state.update { it.copy(expectation = text) } _state.update { it.copy(expectation = text, expectationLoaded = true) }
} }
repo.fragments(sessionNum).onSuccess { list -> repo.fragments(sessionNum).onSuccess { list ->
_state.update { it.copy(fragments = list) } _state.update { it.copy(fragments = list) }
@@ -211,6 +418,9 @@ class SessionController(
} else { } else {
SystemClock.elapsedRealtime() SystemClock.elapsedRealtime()
} }
// 会话-04:被服务端自动收敛过的会话,把服务端文案原样告诉用户
val converged = detail.systemMessage?.takeIf { it.isNotBlank() }
?: if (detail.autoConverged) "上一次学习疑似忘记结束,已自动截止,本次只计入一个番茄钟的有效学习时间" else null
_state.update { _state.update {
it.copy( it.copy(
sessionNum = detail.sessionNum.ifBlank { it.sessionNum }, sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
@@ -220,6 +430,7 @@ class SessionController(
baseEffectiveSeconds = detail.effectiveTime, baseEffectiveSeconds = detail.effectiveTime,
anchorRealtimeMs = anchor, anchorRealtimeMs = anchor,
error = null, error = null,
notice = converged ?: it.notice,
) )
} }
} }
@@ -231,4 +442,9 @@ class SessionController(
Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0) Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
}.getOrDefault(0) }.getOrDefault(0)
} }
companion object {
/** 误操作结束的确认语,前后端各校验一次 */
const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
}
} }
@@ -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,
) )
@@ -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 android.os.SystemClock
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer 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.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
@@ -39,7 +39,7 @@ import com.catshark.lpt.session.SessionController
import com.catshark.lpt.util.formatDuration import com.catshark.lpt.util.formatDuration
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
private const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习" private val MISOPERATION_PHRASE = SessionController.MISOPERATION_PHRASE
@Composable @Composable
fun SessionScreen( fun SessionScreen(
@@ -49,9 +49,10 @@ 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,
onBack: () -> Unit, onBack: () -> Unit,
) { ) {
var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) } var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
@@ -85,7 +86,8 @@ fun SessionScreen(
.padding(horizontal = 16.dp, vertical = 12.dp), .padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
) { ) {
TextButton(onClick = onBack) { Text("‹ 任务") } // 预期还没填时不允许离开:会话必须有预期才能算正式开始
TextButton(onClick = onBack, enabled = !state.expectationRequired) { Text("‹ 任务") }
Column(modifier = Modifier.weight(1f)) { Column(modifier = Modifier.weight(1f)) {
Text( Text(
state.taskName ?: "学习会话", state.taskName ?: "学习会话",
@@ -98,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(
@@ -183,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 "保存预期") }
} }
} }
} }
@@ -204,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))
@@ -229,25 +238,33 @@ 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))
} }
} }
// 会话必须有预期才能正式开始:未填预期时用不可关闭的弹窗挡住
if (state.expectationRequired) {
ExpectationGateDialog(
busy = state.busy,
saving = state.expectationSaving,
error = state.error,
onSave = { text -> onSaveExpectation(text) {} },
onAbort = onAbort,
)
}
if (showEnd) { if (showEnd) {
EndSessionDialog( EndSessionDialog(
defaultSummary = "", state = state,
busy = state.busy,
onDismiss = { showEnd = false }, onDismiss = { showEnd = false },
onConfirm = { sections -> onConfirm = { sections ->
showEnd = false showEnd = false
onEnd(sections) 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 @Composable
private fun EndSessionDialog( private fun EndSessionDialog(
defaultSummary: String, state: SessionController.State,
busy: Boolean,
onDismiss: () -> Unit, onDismiss: () -> Unit,
onConfirm: (ReportSections) -> Unit, onConfirm: (ReportSections) -> Unit,
onGenerateDraft: () -> Unit,
) { ) {
var summary by remember { mutableStateOf(defaultSummary) } var summary by remember { mutableStateOf("") }
var verdict by remember { mutableStateOf("") } var verdict by remember { mutableStateOf("") }
var free 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( AlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
@@ -280,10 +399,24 @@ private fun EndSessionDialog(
text = { text = {
Column(modifier = Modifier.verticalScroll(rememberScrollState())) { Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
Text( Text(
"三段都可留空,但至少要写一段。全空时会记为「未填写总结」。", "三段都可留空,写多少算多少;留空时报告里记「未填写总结」。",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant, 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)) Spacer(Modifier.height(10.dp))
OutlinedTextField( OutlinedTextField(
value = summary, value = summary,
@@ -308,23 +441,42 @@ private fun EndSessionDialog(
minLines = 2, minLines = 2,
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
) )
Spacer(Modifier.height(6.dp))
TextButton(
onClick = {
// 用户已经写过内容时先确认,避免手滑覆盖
if (currentSections().allBlank) onGenerateDraft() else confirmRegenerate = true
},
enabled = !state.draftLoading && hasFragments,
) { Text("AI 重新生成") }
} }
}, },
confirmButton = { confirmButton = {
Button( Button(
onClick = { onClick = { onConfirm(currentSections()) },
val sections = if (summary.isBlank() && verdict.isBlank() && free.isBlank()) { // 草稿只是编辑起点:正在生成时也允许直接手写结束
ReportSections("", "", "(在手机上结束了本次学习,未填写总结)") enabled = !state.busy,
} else {
ReportSections(summary, verdict, free)
}
onConfirm(sections)
},
enabled = !busy,
) { Text("确认结束") } ) { Text("确认结束") }
}, },
dismissButton = { TextButton(onClick = onDismiss) { 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 @Composable
@@ -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()) {
@@ -32,6 +32,10 @@ fun TaskListScreen(
username: String?, username: String?,
onRefresh: () -> Unit, onRefresh: () -> Unit,
onStart: (TaskItem) -> Unit, onStart: (TaskItem) -> Unit,
onOpenReports: (TaskItem) -> Unit,
hasActiveSession: Boolean,
starting: Boolean,
onOpenSession: () -> Unit,
onOpenSettings: () -> Unit, onOpenSettings: () -> Unit,
onOpenPermissions: () -> Unit, onOpenPermissions: () -> Unit,
onLogout: () -> Unit, onLogout: () -> Unit,
@@ -55,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
@@ -99,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(
@@ -124,8 +156,9 @@ fun TaskListScreen(
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.primary,
) )
Spacer(Modifier.weight(1f)) Spacer(Modifier.weight(1f))
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,
) )
@@ -1,5 +1,8 @@
package com.catshark.lpt.util package com.catshark.lpt.util
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/** 把秒数格式化成 mm:ss 或 h:mm:ss */ /** 把秒数格式化成 mm:ss 或 h:mm:ss */
fun formatDuration(seconds: Double): String { fun formatDuration(seconds: Double): String {
val total = seconds.toLong().coerceAtLeast(0) val total = seconds.toLong().coerceAtLeast(0)
@@ -8,3 +11,11 @@ fun formatDuration(seconds: Double): String {
val s = total % 60 val s = total % 60
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s) 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)
}
+52
View File
@@ -0,0 +1,52 @@
# CI 专用:在容器里完成 Android 构建。
#
# 采用容器构建的原因与 lpt-be / lpt-fe / lpt-ai 一致:版本(JDK 17 / Android SDK 36)
# 固化在镜像里,不依赖 runner 上碰巧装了什么;Docker 层缓存让重复构建不必重下 SDK。
#
# 产物固定在 /out,由流水线用 `docker cp` 取出后归档为 Actions artifact。
FROM eclipse-temurin:17-jdk
ENV ANDROID_HOME=/opt/android-sdk \
ANDROID_SDK_ROOT=/opt/android-sdk \
GRADLE_USER_HOME=/root/.gradle \
PATH=/opt/android-sdk/cmdline-tools/latest/bin:/opt/android-sdk/platform-tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 固定版本,避免 Google 换文件名导致构建随机失败
ARG CMDLINE_TOOLS=commandlinetools-linux-13114758_latest.zip
RUN apt-get update \
&& apt-get install -y --no-install-recommends unzip curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p "${ANDROID_HOME}/cmdline-tools" \
&& curl -fsSL -o /tmp/cmdline-tools.zip "https://dl.google.com/android/repository/${CMDLINE_TOOLS}" \
&& unzip -q /tmp/cmdline-tools.zip -d /tmp/cmdline-tools \
&& mv /tmp/cmdline-tools/cmdline-tools "${ANDROID_HOME}/cmdline-tools/latest" \
&& rm -rf /tmp/cmdline-tools /tmp/cmdline-tools.zip
# 与 app/build.gradle.kts 对齐:compileSdk / targetSdk = 36
# build-tools 装 35 与 36 两版,避免 AGP 默认版本落在哪个上不确定
RUN yes | sdkmanager --licenses > /dev/null \
&& sdkmanager --install "platform-tools" "platforms;android-36" "build-tools;36.0.0" "build-tools;35.0.0" > /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
RUN mkdir -p /out && cp app/build/outputs/apk/debug/*.apk /out/
CMD ["true"]
+8 -2
View File
@@ -1,7 +1,13 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip # 官方 services.gradle.org 会 302 跳到 release-assets.githubusercontent.com,
networkTimeout=10000 # 国内网络下大文件经常 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 validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists