Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion backend/app/database.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Database engine and session factory."""

from sqlalchemy import create_engine
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.orm import sessionmaker, DeclarativeBase

from .config import DATABASE_URL
Expand All @@ -22,6 +22,23 @@ def get_db():
db.close()


def _migrate_schema():
"""Apply additive migrations that create_all cannot handle."""
inspector = inspect(engine)
if "focus_sessions" not in inspector.get_table_names():
return
columns = {c["name"] for c in inspector.get_columns("focus_sessions")}
if "client_id" not in columns:
with engine.begin() as conn:
conn.execute(text("ALTER TABLE focus_sessions ADD COLUMN client_id VARCHAR"))
with engine.begin() as conn:
conn.execute(text(
"CREATE UNIQUE INDEX IF NOT EXISTS ix_focus_sessions_client_id "
"ON focus_sessions (client_id)"
))


def init_db():
"""Create all tables. Called on app startup."""
Base.metadata.create_all(bind=engine)
_migrate_schema()
1 change: 1 addition & 0 deletions backend/app/models/focus_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class FocusSession(Base):
__tablename__ = "focus_sessions"

id = Column(Integer, primary_key=True, autoincrement=True)
client_id = Column(String, nullable=True, unique=True, index=True) # idempotency key from client
timer_mode = Column(String, nullable=False) # 'countdown' | 'countup' | 'free'
target_seconds = Column(Integer, nullable=False, default=0)
actual_seconds = Column(Integer, nullable=False)
Expand Down
1 change: 1 addition & 0 deletions backend/app/schemas/focus_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@


class SessionCreate(BaseModel):
client_id: Optional[str] = None
timer_mode: str
target_seconds: int
actual_seconds: int
Expand Down
14 changes: 14 additions & 0 deletions backend/app/services/session_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,22 @@ def create_session(db: Session, data: dict) -> dict:
4. Insert the planted tree
5. Return both records
"""
# 0. Idempotency: a retried request must not plant a second tree
client_id = data.get("client_id")
if client_id:
existing = db.query(FocusSession).filter(FocusSession.client_id == client_id).first()
if existing:
tree = (
db.query(PlantedTree)
.filter(PlantedTree.session_id == existing.id)
.order_by(PlantedTree.id)
.first()
)
return {"session": existing, "tree": tree}

# 1. Create session
session = FocusSession(
client_id=client_id,
timer_mode=data["timer_mode"],
target_seconds=data["target_seconds"],
actual_seconds=data["actual_seconds"],
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/test_session_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,36 @@ def test_list_sessions_pagination(client):
resp = client.get("/api/sessions?limit=2&offset=1").json()
assert resp["total"] == 3
assert len(resp["sessions"]) == 2


def test_client_id_is_idempotent(client):
payload = session_payload(25 * 60)
payload["client_id"] = "retry-key-1"

first = client.post("/api/sessions", json=payload)
second = client.post("/api/sessions", json=payload)

assert first.status_code == 201
assert second.status_code == 201
assert first.json()["session"]["id"] == second.json()["session"]["id"]
assert first.json()["tree"]["id"] == second.json()["tree"]["id"]
assert client.get("/api/sessions").json()["total"] == 1
assert client.get("/api/trees?filter=total").json()["stats"]["count"] == 1


def test_distinct_client_ids_plant_distinct_trees(client):
for key in ("a", "b"):
payload = session_payload(600)
payload["client_id"] = key
client.post("/api/sessions", json=payload)

assert client.get("/api/sessions").json()["total"] == 2
assert client.get("/api/trees?filter=total").json()["stats"]["count"] == 2


def test_missing_client_id_is_not_deduplicated(client):
payload = session_payload(600)
client.post("/api/sessions", json=payload)
client.post("/api/sessions", json=payload)

assert client.get("/api/sessions").json()["total"] == 2
45 changes: 28 additions & 17 deletions docs/PROJECT.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ DailyLikeTrees/

### 5.2 种树事务(`backend/app/services/session_service.py`)

0. **`client_id` 幂等(v1.3)**:若该 client_id 已有记录,直接返回原 session/tree,不重复种树(前端失败重放的安全前提)
1. insert FocusSession → `db.flush()` 拿 id
2. `actual_seconds / 60` → `get_growth_stage`(阈值见红线 7)
3. `_assign_grid_position()`:查 today key 下最大 `grid_y`,行内计数,**每行 8 列**,行满换行(顺序分配,但前端忽略)
Expand Down Expand Up @@ -193,7 +194,13 @@ DailyLikeTrees/
- **开关级联**:主开关 OFF → 双子开关都 OFF;主开关 ON → 双子都 ON;双子全 OFF → 主 OFF;任一子 ON → 主 ON
- BGM 同曲不重启(`currentBgmTrack === track && bgmSource` 短路)——修复"切页面音乐从头播"的历史 bug
- 音频文件**已真实存在**(10 个 mp3,见第 3 章目录)——CLAUDE.md 第 6 条「音频是占位符」已过时,勿再误报
- 首次交互前 AudioContext 可能 suspended(浏览器策略),按钮需可重试
- **v1.3.1 资源规格**:环境音 60 s、BGM 90 s 无缝循环,64 kbps 单声道 mp3(LAME),总计 5.3 MB(原 160.8 MB / 15–23 min / 128 kbps)。单层解码 PCM 约 10–15 MB(原 122–303 MB)
- **v1.3.1 引擎约束**(`useAudioEngine.ts`,改动前先读):
- 环境音与 BGM 各有 generation 计数器,`await loadBuffer()` 后必须复核;否则快速切歌/切层会叠音(历史实测 4 源同播)
- `loadBuffer` 用 `inFlightLoads` 去重并发请求;失败必须 `console.warn` 出 URL,禁止静默 `return null`
- 所有层切换走 `fadeOutAndStop`(淡出后 stop + disconnect);新层 0.3 s 淡入
- AudioContext 在 `init()` 时挂 `pointerdown`/`keydown` 一次性手势监听调用 `resume()`;浏览器自动播放策略下否则永久 suspended
- **SW 缓存**:`sw.js` 的 `CACHE_NAME` 每次随静态资源变更递增(当前 `dlt-v2`),且只在 `import.meta.env.PROD` 注册;dev 注册会让 cache-first 长期返回旧音频

### 5.7 悬浮球(三套实现)

Expand Down Expand Up @@ -222,7 +229,7 @@ DailyLikeTrees/

| 表 | 关键字段 | 说明 |
|---|---|---|
| `focus_sessions` | timer_mode, target_seconds, actual_seconds, status, species_id, started_at, ended_at | status 只有 'completed' 实际被写入 |
| `focus_sessions` | timer_mode, target_seconds, actual_seconds, status, species_id, started_at, ended_at, **client_id**(v1.3,唯一,幂等键) | status 只有 'completed' 实际被写入;旧库由 `init_db()` 的 `_migrate_schema()` 自动加列 |
| `planted_trees` | session_id(FK), species_id, growth_stage(0-3), grid_x, grid_y, **time_filter_key(索引)**, planted_at | 每 session 4 行 |
| `todos` | content, completed(0/1), sort_order(Float) | |
| `user_settings` | key(PK), value(String), updated_at | 通用 key-value |
Expand All @@ -237,6 +244,7 @@ DailyLikeTrees/
| `dlt_forest_prefs` | terrain / weather 记忆 |
| `theme` / `weatherEnabled` / `floatingBallEnabled` | settings store(与后端双写) |
| `bgForest` | 背景森林的 filter |
| `dlt_pending_sessions` | 未送达后端的完成会话队列(v1.3) |

### 6.3 IndexedDB(`dlt_local_db` v1,PWA/移动端)

Expand Down Expand Up @@ -276,18 +284,21 @@ DailyLikeTrees/

| # | 问题 | 位置 |
|---|---|---|
| F1 | TreeSpeciesPicker 选中后不自动关闭(`selectAndClose` 未 emit close) | `components/timer/TreeSpeciesPicker.vue` |
| F2 | 背景模式(is-background)下 canvas 仍可被 pointer 拖拽平移(onPointerDown 未拦截) | `IsometricGrid.vue` |
| F3 | 移动端 SettingsPanel 的 `@close` 无消费方(组件未声明 emits) | `components/settings/SettingsPanel.vue` + `mobile/HomeView.vue` |
| F4 | AppShellMobile 底部"设置"tab 事件无人消费(点了没反应) | `AppShellMobile.vue` |
| F5 | FloatingBall 每次开浮窗都注册新 onEvent 订阅(监听器累积) | `components/layout/FloatingBall.vue` |
| F6 | free 模式 running 时无法直接结束(必须先暂停);countdown/countup paused 无"结束"按钮 | `CircularTimer.vue` |
| F7 | 庆祝 toast 的 setTimeout 未清理 | `CircularTimer.vue` |
| F8 | `fetchTrees()` 无重试(todos 有 3 次)→ Electron 启动竞态下森林空加载 | `stores/forest.ts` |
| F9 | `complete()` 网络失败无重试无持久化队列 → 树静默丢失 | `stores/timer.ts` |
| F10 | trees 数组变化(fetchTrees 返回)会全量重排所有树位置(雨天上演瞬移) | `IsometricGrid.vue` watch |
| F11 | `index.html` 的 `/favicon.png` `/manifest.json` `/sw.js` 绝对路径与 `base:'./'` 冲突,Electron file:// 下 404 | `frontend/index.html` |
| F12 | 时间 key 用服务端本地日期 vs 前端本地时区 → 跨时区数据错位;localDb 手写 ISO 周与 Python isocalendar 边界可能不一致 | `backend/routers/trees.py` / `localDb.ts` |
| F1 | TreeSpeciesPicker 选中后不自动关闭(`selectAndClose` 未 emit close)— **已修复 v1.3** | `components/timer/TreeSpeciesPicker.vue` |
| F2 | 背景模式(is-background)下 canvas 仍可被 pointer 拖拽平移(onPointerDown 未拦截)— **已修复 v1.3** | `IsometricGrid.vue` |
| F3 | 移动端 SettingsPanel 的 `@close` 无消费方(组件未声明 emits)— **已修复 v1.3**(`openOnMount` + `close`) | `components/settings/SettingsPanel.vue` + `mobile/HomeView.vue` |
| F4 | AppShellMobile 底部"设置"tab 事件无人消费(点了没反应)— **已修复 v1.3** | `AppShellMobile.vue` |
| F5 | FloatingBall 每次开浮窗都注册新 onEvent 订阅(监听器累积)— **已核查:0a69457 已修复**(`windowOpen` 守卫 + close 时 unlisten) | `components/layout/FloatingBall.vue` |
| F6 | free 模式 running 时无法直接结束(必须先暂停);countdown/countup paused 无"结束"按钮 — **非 bug:§5.1 明确为设计**(中途结束=放弃) | `CircularTimer.vue` |
| F7 | 庆祝 toast 的 setTimeout 未清理 — **已修复 v1.3** | `CircularTimer.vue` |
| F8 | `fetchTrees()` 无重试(todos 有 3 次)→ Electron 启动竞态下森林空加载 — **已修复 v1.3**(3 次 / 1s) | `stores/forest.ts` |
| F9 | `complete()` 网络失败无重试无持久化队列 → 树静默丢失 — **已修复 v1.3**(`client_id` 幂等 + localStorage 队列,启动时重放) | `stores/timer.ts` + `services/pendingSessions.ts` |
| F10 | trees 数组变化(fetchTrees 返回)会全量重排所有树位置(雨天上演瞬移)— **已修复 v1.3**(仅 id 集合/地形变化才重排) | `IsometricGrid.vue` watch |
| F11 | `index.html` 的 `/favicon.png` `/manifest.json` `/sw.js` 绝对路径与 `base:'./'` 冲突,Electron file:// 下 404 — **已修复 v1.3**(构建产物本就相对;SW 注册与 manifest 图标已补相对) | `frontend/index.html` |
| F12 | 时间 key 用服务端本地日期 vs 前端本地时区 → 跨时区数据错位;localDb 手写 ISO 周与 Python isocalendar 边界可能不一致 — **暂不改(v1.3 决定)**:所有端当前都连本机后端,时区一致;作为远程后端的前置条件 | `backend/routers/trees.py` / `localDb.ts` |
| F13 | 音频全量解码 15–23 min mp3:单层 303 MB PCM、解码 2.2–4.7 s、启动长任务 60–124 ms,缓存无淘汰(切地形/天气持续累加)— **已修复 v1.3.1**(短循环资源 + 并发去重 + 淡入淡出) | `useAudioEngine.ts` |
| F14 | BGM 快速切换叠音:`playBgm` 无 generation 守卫,晚到的旧请求照常 start;`stopBgm` 只停最后一个引用 — **已修复 v1.3.1**(实测 5 源启动/1 停止 → 现恒为 1 条 BGM) | `useAudioEngine.ts` |
| F15 | AudioContext 从不 `resume()`(init 在 onMounted,非手势)→ 浏览器首访永久无声;dev 也注册 cache-first SW,资源更新后长期返回旧文件 — **已修复 v1.3.1** | `useAudioEngine.ts` / `main.ts` / `public/sw.js` |

### 8.2 高危代码(动之前必须三思)

Expand All @@ -311,7 +322,7 @@ DailyLikeTrees/

### 8.5 测试基建(2026-08 已建立)

- **后端 pytest**(`backend/tests/`,34 用例):种树事务(1 session → 4 行)、growth 阈值边界、filter key 格式、级联删除、todos CRUD/reorder、settings 默认值与 bool 字符串存储。隔离方案:`conftest.py` 用内存 SQLite(StaticPool)+ `app.dependency_overrides[get_db]`,**绝不触碰真实 data.db**(TestClient 不用 context manager,避免触发 lifespan)
- **后端 pytest**(`backend/tests/`,37 用例):种树事务(1 session → 4 行)、growth 阈值边界、filter key 格式、级联删除、todos CRUD/reorder、settings 默认值与 bool 字符串存储、`client_id` 幂等(同键重放不重复种树)。隔离方案:`conftest.py` 用内存 SQLite(StaticPool)+ `app.dependency_overrides[get_db]`,**绝不触碰真实 data.db**(TestClient 不用 context manager,避免触发 lifespan)
- **前端 vitest**(`frontend/test/`,21 用例):`localDb ↔ treeGrowth ↔ 后端` 三处实现对称性(growth 阈值、filter key 格式、种树事务镜像、级联删除、todos、settings)+ fake-indexeddb 隔离(每个用例全新 IDBFactory)
- **CI**(`.github/workflows/ci.yml`):push main / PR 时跑 frontend(typecheck → build → vitest)+ backend(pytest)
- **已知收益**:对称性测试已抓到并修复一个真实漂移 bug(localDb 首个 todo 的 sort_order 从 1 起、后端从 0 起)
Expand Down Expand Up @@ -375,11 +386,11 @@ npm run android:build # 完整 Gradle debug APK

1. **止血**:修复 8.1 的 F1–F12 功能性 bug(每项改动小、风险可控)
2. **安全**:移除 H1 的 python.exe 全局 kill(改为只杀自己 spawn 的 PID 树)、CORS 收紧、DELETE 加确认参数
3. **可靠**:`complete()` 失败重试/队列、`fetchTrees()` 加重试、后端端口动态探测、settings 双写冲突策略
3. **可靠**:~~`complete()` 失败重试/队列~~、~~`fetchTrees()` 加重试~~(v1.3 已完成)→ 剩余:后端端口动态探测、settings 双写冲突策略
4. **一致性**:三份 growth 阈值与 filter key 计算收敛为单一来源(前端生成 key 传入后端,或后端返回 key);localDb 与后端逻辑对齐测试(测试基建已建立,见 §8.5)
5. **体验**:移动端适配(竖屏布局、设置 tab)
6. **工程质量**:CI 已建立(§8.5);后续可加 Electron 手动触发 release workflow(PyInstaller + electron-builder)

---

*文档版本:v1.2(2026-08-16)。v1.0 重装前盘点;v1.1 彻底移除 Tauri,docs/ 目录建立;v1.2 建立测试基建(后端 pytest 34 用例、前端 vitest 21 用例、CI workflow,详见 §8.5)。本文档随重装进度持续维护,每次重大架构变更必须回写本文档。*
*文档版本:v1.3.1(2026-10-31)。v1.0 重装前盘点;v1.1 彻底移除 Tauri,docs/ 目录建立;v1.2 建立测试基建(后端 pytest 34 用例、前端 vitest 21 用例、CI workflow,详见 §8.5);v1.3 止血 F1–F11(F5 核查为已修,F6 判定非 bug,F12 暂缓),F9 落地 `client_id` 幂等 + localStorage 队列,后端测试增至 37 用例;v1.3.1 修复音频模块 F13–F15(资源重编 160.8 MB → 5.3 MB,单层解码 303 MB → 10 MB,BGM 叠音与 resume/SW 缓存问题)。本文档随重装进度持续维护,每次重大架构变更必须回写本文档。*
Binary file modified frontend/public/assets/audio/ambiance/cloudy.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/creek.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/mountain.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/plain.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/rainny_day.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/sunny.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/ambiance/thunder_rain.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/music/calm-1.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/music/calm-2.mp3
Binary file not shown.
Binary file modified frontend/public/assets/audio/music/calm-3.mp3
Binary file not shown.
2 changes: 1 addition & 1 deletion frontend/public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"orientation": "portrait-primary",
"icons": [
{
"src": "/assets/logo.png",
"src": "./assets/logo.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
Expand Down
4 changes: 3 additions & 1 deletion frontend/public/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
* - API calls → Network First (not cached; local mode uses IndexedDB)
*/

const CACHE_NAME = 'dlt-v1'
// Bump this whenever shipped static assets change, otherwise cache-first
// keeps serving the old files to returning users.
const CACHE_NAME = 'dlt-v2'
const PRECACHE_URLS = [
'./',
'./index.html',
Expand Down
4 changes: 4 additions & 0 deletions frontend/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import { computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useSettingsStore } from './stores/settings'
import { useTimerStore } from './stores/timer'
import { usePlatform } from './composables/usePlatform'
import { useAmbianceController } from './composables/useAmbianceController'
import AppShell from './components/layout/AppShell.vue'
import AppShellMobile from './components/mobile/layout/AppShellMobile.vue'

const route = useRoute()
const settings = useSettingsStore()
const timer = useTimerStore()
const { isMobile } = usePlatform()

// Floating-ball window: render just the view, no shell.
Expand All @@ -29,6 +31,8 @@ if (!isFloating.value) {
onMounted(() => {
if (!isFloating.value) {
settings.loadSettings()
// Retry sessions queued while the backend was unreachable
void timer.flushPendingSessions()
}
})
</script>
Expand Down
12 changes: 11 additions & 1 deletion frontend/src/components/forest/IsometricGrid.vue
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,7 @@ function applyCamera(): void {

// ── Panning ──
function onPointerDown(e: PointerEvent) {
if (props.isBackground) return
if (!(e.target as HTMLElement)?.closest?.('canvas')) return
isPanning = true
panStart = { x: e.clientX - camX, y: e.clientY - camY }
Expand Down Expand Up @@ -1497,10 +1498,13 @@ watch(() => props.forceRefresh, () => {
})

let prevWeather: WeatherType | null = null
let prevTerrain: TerrainType | null = props.terrain
watch(() => [props.trees, props.terrain, props.weather], () => {
if (!app) return
const weatherChanged = props.weather !== prevWeather
prevWeather = props.weather
const terrainChanged = props.terrain !== prevTerrain
prevTerrain = props.terrain

// Only restart weather effects when weather actually changed
if (weatherChanged) {
Expand All @@ -1521,7 +1525,13 @@ watch(() => [props.trees, props.terrain, props.weather], () => {
for (let gx = 0; gx < cols; gx++)
tileKinds[gy][gx] = getTileKind(gx, gy, props.terrain, rows, cols)
}
treePlacements.value = assignTreePositions(props.trees, tileKinds, rows, cols)
const idsChanged =
props.trees.length !== treePlacements.value.size ||
props.trees.some(t => !treePlacements.value.has(t.id))

// Keep positions stable when only weather/object identity (fetchTrees) changes
if (idsChanged || terrainChanged || treePlacements.value.size === 0)
treePlacements.value = assignTreePositions(props.trees, tileKinds, rows, cols)

centerCamera()
fullRender()
Expand Down
14 changes: 6 additions & 8 deletions frontend/src/components/mobile/layout/AppShellMobile.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,22 @@
<IconSvg name="tree" :size="20" />
<span class="tab-label">森林</span>
</router-link>
<button class="tab-item" @click="toggleSettings">
<button class="tab-item" @click="showSettings = true">
<IconSvg name="settings" :size="20" />
<span class="tab-label">设置</span>
</button>
</nav>

<SettingsPanel v-if="showSettings" open-on-mount @close="showSettings = false" />
</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import IconSvg from '../../icons/IconSvg.vue'
import SettingsPanel from '../../settings/SettingsPanel.vue'

const emit = defineEmits<{
(e: 'toggle-settings'): void
}>()

function toggleSettings() {
emit('toggle-settings')
}
const showSettings = ref(false)
</script>

<style scoped>
Expand Down
Loading