Skip to content
Merged
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
48 changes: 29 additions & 19 deletions docs/PROJECT.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

## 1. 项目定位

**DailyLikeTrees(如树日常)**:Forest 专注森林的开源替代品 —— 设专注计时 → 完成 → 在等距森林种一棵树。数据全部本地(无账号、无云同步),强调视觉精致(包豪斯 + 自然动效)与多端一致性。
**DailyLikeTrees(如树日常)**:Forest 专注森林的开源替代品 —— 设专注计时 → 完成 → 在等距森林种一棵树。数据全部本地(无账号、无云同步;真实天气显示会请求第三方接口,见 §5.4),强调视觉精致(包豪斯 + 自然动效)与多端一致性。

## 2. 平台矩阵与运行时检测

Expand Down 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 @@ -173,10 +174,17 @@ DailyLikeTrees/
| 系统 | 来源 | 用途 |
|---|---|---|
| **模拟天气** | `stores/forest.ts` 的 `weather`(sunny/cloudy/rainy/thunderstorm) | 森林渲染 + 环境音选层 + 背景森林天气覆盖 |
| **真实天气** | Open-Meteo(`useWeatherInfo.ts`:权限 → 定位 6s 超时 → IP 双 API 竞速 → 北京兜底) | Header 左上角天气/温度/时间显示(`settings.weatherEnabled` 控制,默认关) |
| **真实天气** | Open-Meteo(`useWeatherInfo.ts`:权限 → 定位 6s 超时 → IP 双 API 并行 → 北京兜底) | Header 左上角天气/温度/时间显示(`settings.weatherEnabled`,**默认开**) |

两者**完全无关**。改天气相关功能时先确认改的是哪套。

**真实天气的联网与隐私(v1.3.2 核实)**:
- `WeatherStatus.vue` 在 Header 中常驻,`useWeatherInfo()` 在 `onMounted` 无条件执行——**即使关闭“显示天气”,请求照发**,`weatherEnabled` 只控制 UI 是否渲染
- 定位链:`navigator.permissions` 查询 → 已拒绝则直接走 IP;否则 `getCurrentPosition`(8 s 超时 + 6 s 安全兜底)
- IP 定位是 **两个 API 并行**(`Promise.allSettled`):`ipapi.co`(HTTPS)与 `ip-api.com`(**HTTP 明文**,免费版限制),两个请求都会发出,先成功者生效
- 天气与城市名:`api.open-meteo.com`、`geocoding-api.open-meteo.com`(仅浏览器定位成功时查城市名)
- 结论:核心功能(计时/森林/音频/待办/设置)完全离线可用;天气显示是唯一的第三方依赖,失败时静默降级到北京坐标

### 5.5 背景森林(BackgroundForest.vue + HomeView)

- `localStorage['bgForest']` 存 filter(today/week/month/total);HomeView 首次启动若非法则默认 `'today'`
Expand Down Expand Up @@ -222,7 +230,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 +245,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 +285,19 @@ 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 | 真实天气默认开启且忽略 `weatherEnabled`(关闭只隐藏 UI,请求照发);IP 定位使用 `ip-api.com` 明文 HTTP — **未修复(v1.3.2 仅文档化)**:应改为仅开启时请求、移除明文源、加缓存 | `useWeatherInfo.ts` / `WeatherStatus.vue` |

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

Expand All @@ -311,7 +321,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 @@ -374,12 +384,12 @@ npm run android:build # 完整 Gradle debug APK
## 10. 重装建议路线图(按优先级)

1. **止血**:修复 8.1 的 F1–F12 功能性 bug(每项改动小、风险可控)
2. **安全**:移除 H1 的 python.exe 全局 kill(改为只杀自己 spawn 的 PID 树)、CORS 收紧、DELETE 加确认参数
3. **可靠**:`complete()` 失败重试/队列、`fetchTrees()` 加重试、后端端口动态探测、settings 双写冲突策略
2. **安全**:移除 H1 的 python.exe 全局 kill(改为只杀自己 spawn 的 PID 树)、CORS 收紧、DELETE 加确认参数;真实天气仅在开启时请求并移除 `ip-api.com` 明文源(F13)
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.2(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.2 核实并更正真实天气的联网与隐私说明(默认开、关闭仍请求、ip-api.com 明文),登记 F13。本文档随重装进度持续维护,每次重大架构变更必须回写本文档。*
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: 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
Loading