feat: add energy-aware scheduling and daily insights

- Learn a per-device 7x24 energy profile from completed tasks\n- Constrain high-energy scheduling and expose energy peaks to AI\n- Add ghost-time overlays, daily review dialog, and proactive suggestions\n- Cover energy/insights logic and local OpenAI-compatible providers with tests\n- Update validation docs and screenshots
This commit is contained in:
Misaki
2026-10-26 19:08:09 +08:00
parent 555371a4e0
commit 9bafa71667
42 changed files with 1588 additions and 47 deletions
+31 -6
View File
@@ -2,7 +2,7 @@
细粒度个人日程 + AI 自然语言排程 + 自部署多设备同步。
当前进度:**阶段 0 + 阶段 1 + 界面重构 + TOML 配置 + AI 日程闭环 + AI 增强(更新/删除/涟漪/拆分)+ 多设备同步**。
当前进度:**阶段 0–4(含精力曲线 / 幽灵时间 / 每日复盘 / 主动建议)**。
本地模型 50 条指令回归已完成:完整 49/50(98%),失败项 #42 单独复测通过。
详细计划见 [`docs/PLAN.md`](docs/PLAN.md),验证记录见 [`docs/validation/`](docs/validation/)。
@@ -11,6 +11,7 @@
- **紧凑主窗口**(默认启动):AI 助手 + 今日任务,顶部可打开详细日程或设置。
- **详细日程窗口**:日 / 月 / 年三种视图、选中日期任务面板、新建/编辑/删除、设置;顶部房屋按钮或关闭窗口回到紧凑窗口。
- **系统托盘**:关闭紧凑窗口时最小化到托盘;托盘可显示主窗口、新建日程、退出。
- **智能增强**:今日任务面板显示主动建议;日视图绘制幽灵时间;提供每日复盘对话框。
- **设置**:主题(跟随系统/浅色/深色)、ElaMica 云母效果、AI 接口地址/模型/API Key、同步服务地址/开关。
> 云母效果使用 ElaWidgetTools 的 `ElaMica` 跨平台模拟背景(内置模糊基底图),
@@ -35,10 +36,32 @@
- Word:docx 需要 `unzip`,doc 需要 `catdoc`
- 图片:以 data URL 发送,需要模型支持视觉输入
排程由本地确定性 `SchedulerEngine` 完成:避开已确认日程、优先用户指定时间、回退到 08:00–22:00、按 15 分钟粒度、遵守 deadline。
排程由本地确定性 `SchedulerEngine` 完成:避开已确认日程、优先用户指定时间、回退到 08:00–22:00、按 15 分钟粒度、遵守 deadline,并按学习到的精力曲线约束高精力任务。
> 隐私提示:拖入文件的文本/图片会发送到你配置的 AI 服务。若需完全离线,请配置本地 OpenAI 兼容模型。
## 精力、幽灵时间与复盘
- 客户端从**已完成且带 `energy_req` 的日程**学习 7×24 精力档案(0 低 / 1 中 / 2 高);撤销完成后会回退。
- AI 收到精力高峰摘要;`SchedulerEngine` 会为高精力任务寻找高精力时段,而不是只找最早空档。
- **幽灵时间**:日视图以半透明虚线块显示 08:00–22:00 内的可用空档;复盘对话框列出当天所有 30 分钟以上空档。
- **主动建议**:今日任务面板顶部显示「处理超时日程 / 发现幽灵时间 / 做一次今日复盘」等确定性建议。
- **每日复盘**:点击今日任务标题旁的复盘按钮或按 `Ctrl+R`,查看完成率、专注时长、精力高峰、待办与幽灵时间。
精力档案按设备本地保存,不参与多设备变更流;不同设备的作息差异不会互相覆盖。
### 本地模型
本地模型通过 **OpenAI 兼容端点**接入,与云端使用同一套 Provider:
| 服务 | 接口地址示例 | API Key |
|---|---|---|
| Ollama | `http://127.0.0.1:11434/v1` | 留空 |
| LM Studio | `http://127.0.0.1:1234/v1` | 留空 |
| vLLM / llama.cpp / 其他 | 对应 `/v1` 地址 | 按服务要求 |
在设置中填写接口地址和模型名即可;本地服务不要求 API Key 时留空。模型需要支持流式 SSE 和 OpenAI Chat Completions 格式。
### Linux 中文输入法(fcitx5)
自定义 Qt 安装通常不带 fcitx5 的 Qt6 platform input context 插件;系统包
@@ -162,9 +185,9 @@ cmake --build --preset linux-gcc
ctest --preset linux-gcc
```
当前自动化测试(11 组):存储/服务、网格与详细窗口、紧凑窗口、TOML 配置、SchedulerEngine、
AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
当前自动化测试(12 组):存储/服务、网格与详细窗口、紧凑窗口、TOML 配置、SchedulerEngine、
精力档案 / 幽灵时间 / 每日复盘、AI 编排(15 个用例:流式、修复、更新/删除、涟漪、拆分、冲突保护、多轮历史、文件、删除兜底、无 diff 重试)、
OpenAI 兼容 Provider(本地假 SSE 服务,含无 API Key 的本地模型)、AI 对话到接受落库的 UI 全链路、Go 服务端单元/接口/并发测试、双客户端同步集成(含离线重连)。
本地模型回归(50 条真实中文指令):
@@ -178,7 +201,7 @@ cmake --build --preset linux-gcc --target ai_regression
## 数据与配置
- 数据库:`~/.local/share/Misaki/Schedule/schedule.db`(SQLite WAL)。
- 数据库:`~/.local/share/Misaki/Schedule/schedule.db`(SQLite WAL,包含精力档案;精力档案不参与同步)。
- 配置文件:`~/.config/Misaki/Schedule/config.toml`(TOML,权限 0600)。
- 旧版 `~/.config/Misaki/Schedule.conf` 会在首次启动时自动迁移,原文件保留作备份。
@@ -210,6 +233,7 @@ AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设
|---|---|
| `Ctrl+O` | 打开详细日程 |
| `Ctrl+,` | 打开设置 |
| `Ctrl+R` | 今日复盘 |
### 详细日程窗口
@@ -221,6 +245,7 @@ AI 接口地址、模型、API Key 与同步服务地址/开关可直接在设
| `Alt+←/→` | 上一段 / 下一段(日/月/年自适应) |
| `Ctrl+T` | 回到今天 |
| `Ctrl+,` | 打开设置 |
| `Ctrl+R` | 今日复盘 |
| `Ctrl` + 滚轮 | 时间轴缩放(日视图) |
| `Delete` | 删除选中日程(日视图) |
| `Enter` | 编辑选中日程(日视图) |
+2
View File
@@ -3,6 +3,7 @@
当前本地时间:{CURRENT_TIME}
今天星期:{WEEKDAY}
用户默认可用时间:{WORK_START}–{WORK_END}
用户精力高峰(用于安排高精力任务):{ENERGY_PROFILE}
用户现有日程(每行开头的 [bN] 是引用编号,只能用于 update/delete):
{EXISTING_SCHEDULE}
@@ -29,6 +30,7 @@
15. 现有日程摘要中带“(会议)”标记的条目属于会议类;用户要求删除“所有会议”时,逐个 delete 所有带该标记的条目。
16. 示例:现有 [b2] 团队同步(会议)、[b4] 项目会议(会议)。用户说“删除明天所有会议”时,输出 {"operations":[{"type":"delete","target_ref":"b2"},{"type":"delete","target_ref":"b4"}]}。
17. 示例:用户说“明天之前找时间做两小时长任务,可以拆开”,输出 create 并设置 "splittable":true;不要拆成两个独立任务。
18. energy_req 取值:0=低精力杂务,1=一般沟通/会议,2=高专注深度工作、学习或创作;不确定时填 1。高精力任务应优先放在用户的精力高峰时段。
补充信息:
{EXTRA_CONTEXT}
+6
View File
@@ -1,6 +1,10 @@
add_library(schedule_core STATIC
core/DateTimeUtils.cpp
core/DateTimeUtils.h
core/DailyInsights.cpp
core/DailyInsights.h
core/EnergyProfile.cpp
core/EnergyProfile.h
core/ProposedDiff.h
core/SchedulerEngine.cpp
core/SchedulerEngine.h
@@ -77,6 +81,8 @@ add_library(schedule_ui STATIC
ui/MainWindow.h
ui/dialogs/BlockEditDialog.cpp
ui/dialogs/BlockEditDialog.h
ui/dialogs/DailyReviewDialog.cpp
ui/dialogs/DailyReviewDialog.h
ui/dialogs/SettingsDialog.cpp
ui/dialogs/SettingsDialog.h
ui/panels/ChatPanel.cpp
+5
View File
@@ -476,6 +476,8 @@ QString AIService::buildSystemPrompt()
prompt.replace(QStringLiteral("{WEEKDAY}"), weekdayLabel(now.date()));
prompt.replace(QStringLiteral("{WORK_START}"), QStringLiteral("08:00"));
prompt.replace(QStringLiteral("{WORK_END}"), QStringLiteral("22:00"));
prompt.replace(QStringLiteral("{ENERGY_PROFILE}"),
m_scheduleService.dailyReview(now.date()).energySummary);
prompt.replace(QStringLiteral("{EXISTING_SCHEDULE}"), scheduleSummary());
prompt.replace(QStringLiteral("{EXTRA_CONTEXT}"),
m_filePaths.isEmpty()
@@ -922,6 +924,9 @@ void AIService::buildProposalFromOperations(const QJsonArray& operations, const
}
scheduler::Options options;
options.granularityMinutes = 15;
options.energyAt = [this](scheduler::SysTime value) {
return m_scheduleService.energyLevelFor(fromSysTime(value));
};
struct Busy
{
+273
View File
@@ -0,0 +1,273 @@
#include "DailyInsights.h"
#include <algorithm>
#include <cmath>
#include "core/DateTimeUtils.h"
namespace
{
bool isActiveStatus(const QString& status)
{
return status == QStringLiteral("scheduled") || status == QStringLiteral("in_progress");
}
bool occupiesTime(const QString& status)
{
return status != QStringLiteral("dropped") && status != QStringLiteral("missed");
}
QDateTime dayBoundary(const QDate& date, int hour)
{
if (hour >= 24)
{
return QDateTime(date.addDays(1), QTime(0, 0), Qt::LocalTime);
}
return QDateTime(date, QTime(std::max(0, hour), 0), Qt::LocalTime);
}
QString formatWindow(const FreeWindow& window)
{
return QStringLiteral("%1–%2").arg(window.start.toString(QStringLiteral("HH:mm")),
window.end.toString(QStringLiteral("HH:mm")));
}
} // namespace
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& from,
int workStartHour,
int workEndHour,
int minMinutes)
{
QVector<FreeWindow> result;
if (!date.isValid())
{
return result;
}
QDateTime rangeStart = dayBoundary(date, workStartHour);
const QDateTime rangeEnd = dayBoundary(date, workEndHour);
if (from.isValid() && from > rangeStart)
{
rangeStart = from;
}
if (rangeStart >= rangeEnd || minMinutes <= 0)
{
return result;
}
QVector<QPair<QDateTime, QDateTime>> busy;
for (const ScheduleItem& item : items)
{
if (!occupiesTime(item.block.status))
{
continue;
}
const QDateTime start = std::max(item.block.startAt, rangeStart);
const QDateTime end = std::min(item.block.endAt, rangeEnd);
if (start < end)
{
busy.append({start, end});
}
}
std::sort(busy.begin(), busy.end(), [](const auto& a, const auto& b) {
return a.first < b.first;
});
QDateTime cursor = rangeStart;
for (const auto& interval : busy)
{
if (interval.second <= cursor)
{
continue;
}
if (interval.first > cursor)
{
const int minutes = DateTimeUtils::minutesBetween(cursor, interval.first);
if (minutes >= minMinutes)
{
result.append({cursor, interval.first, minutes});
}
}
cursor = std::max(cursor, interval.second);
}
if (cursor < rangeEnd)
{
const int minutes = DateTimeUtils::minutesBetween(cursor, rangeEnd);
if (minutes >= minMinutes)
{
result.append({cursor, rangeEnd, minutes});
}
}
return result;
}
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
int workStartHour,
int workEndHour,
int minMinutes)
{
return findFreeWindows(items, date, dayBoundary(date, workStartHour), workStartHour, workEndHour, minMinutes);
}
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& now)
{
DailyReview review;
review.date = date;
review.total = items.size();
for (const ScheduleItem& item : items)
{
const QString& status = item.block.status;
if (status == QStringLiteral("done"))
{
++review.done;
review.focusedMinutes +=
std::max(0, DateTimeUtils::minutesBetween(item.block.startAt, item.block.endAt));
}
else if (isActiveStatus(status))
{
++review.active;
if (item.block.endAt < now)
{
++review.overdue;
}
}
else if (status == QStringLiteral("missed"))
{
++review.missed;
}
else if (status == QStringLiteral("dropped"))
{
++review.dropped;
}
}
review.completionPercent =
review.total > 0 ? static_cast<int>(std::lround(review.done * 100.0 / review.total)) : 0;
const QDateTime reviewFrom = date < now.date() ? dayBoundary(date, 8) : now;
review.ghostWindows = findFreeWindows(items, date, reviewFrom, 8, 22, 30);
if (review.total == 0)
{
review.summary = QStringLiteral("今天还没有安排;可以先留出一段专注时间。");
}
else
{
review.summary = QStringLiteral("完成 %1/%2 项(%3%),累计专注 %4。")
.arg(review.done)
.arg(review.total)
.arg(review.completionPercent)
.arg(DateTimeUtils::formatDuration(review.focusedMinutes));
}
if (review.overdue > 0)
{
review.highlights.append(QStringLiteral("%1 项日程已超时").arg(review.overdue));
}
if (review.active > 0)
{
review.highlights.append(QStringLiteral("还有 %1 项待办").arg(review.active));
}
if (review.missed > 0 || review.dropped > 0)
{
review.highlights.append(
QStringLiteral("错过 %1 项,放弃 %2 项").arg(review.missed).arg(review.dropped));
}
if (review.done > 0)
{
review.highlights.append(QStringLiteral("今日专注 %1 分钟").arg(review.focusedMinutes));
}
if (review.ghostWindows.isEmpty())
{
review.highlights.append(QStringLiteral("今天没有 30 分钟以上的幽灵时间"));
}
else
{
review.highlights.append(
QStringLiteral("幽灵时间最早一段:%1").arg(formatWindow(review.ghostWindows.first())));
}
return review;
}
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
const QDateTime& now,
int maxCount)
{
QVector<Suggestion> result;
if (maxCount <= 0)
{
return result;
}
QVector<ScheduleItem> overdue;
for (const ScheduleItem& item : items)
{
if (isActiveStatus(item.block.status) && item.block.endAt < now)
{
overdue.append(item);
}
}
if (!overdue.isEmpty())
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::Overdue;
suggestion.title = QStringLiteral("处理超时日程");
suggestion.detail = QStringLiteral("「%1」%2已超时,建议重新安排或标记完成。")
.arg(overdue.first().task.title)
.arg(overdue.size() > 1
? QStringLiteral("等 %1 项").arg(overdue.size())
: QString());
result.append(suggestion);
}
if (result.size() >= maxCount)
{
return result;
}
const QVector<FreeWindow> ghost =
findFreeWindows(items, now.date(), now, 8, 22, 30);
if (!ghost.isEmpty())
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::GhostTime;
suggestion.title = QStringLiteral("发现幽灵时间");
const FreeWindow& window = ghost.first();
suggestion.detail = QStringLiteral("%1 空出 %2,可安排一件重要的事。")
.arg(formatWindow(window), DateTimeUtils::formatDuration(window.minutes));
suggestion.start = window.start;
suggestion.end = window.end;
result.append(suggestion);
}
if (result.size() >= maxCount)
{
return result;
}
int doneCount = 0;
int activeCount = 0;
for (const ScheduleItem& item : items)
{
if (item.block.status == QStringLiteral("done"))
{
++doneCount;
}
else if (isActiveStatus(item.block.status))
{
++activeCount;
}
}
if (now.time().hour() >= 18 && (doneCount > 0 || activeCount > 0))
{
Suggestion suggestion;
suggestion.kind = Suggestion::Kind::Review;
suggestion.title = QStringLiteral("做一次今日复盘");
suggestion.detail = QStringLiteral("今天完成 %1 项,还有 %2 项待办,花 2 分钟回顾一下。")
.arg(doneCount)
.arg(activeCount);
result.append(suggestion);
}
return result;
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <QDate>
#include <QDateTime>
#include <QString>
#include <QStringList>
#include <QVector>
#include "core/ScheduleItem.h"
struct FreeWindow
{
QDateTime start;
QDateTime end;
int minutes = 0;
};
struct DailyReview
{
QDate date;
int total = 0;
int done = 0;
int active = 0;
int missed = 0;
int dropped = 0;
int overdue = 0;
int focusedMinutes = 0;
int completionPercent = 0;
QVector<FreeWindow> ghostWindows;
QStringList highlights;
QString summary;
QString energySummary;
};
struct Suggestion
{
enum class Kind
{
Overdue,
GhostTime,
Review,
Energy,
};
Kind kind = Kind::Review;
QString title;
QString detail;
QDateTime start;
QDateTime end;
};
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& from,
int workStartHour = 8,
int workEndHour = 22,
int minMinutes = 30);
QVector<FreeWindow> findFreeWindows(const QVector<ScheduleItem>& items,
const QDate& date,
int workStartHour = 8,
int workEndHour = 22,
int minMinutes = 30);
DailyReview buildDailyReview(const QVector<ScheduleItem>& items,
const QDate& date,
const QDateTime& now = QDateTime::currentDateTime());
QVector<Suggestion> buildSuggestions(const QVector<ScheduleItem>& items,
const QDateTime& now,
int maxCount = 3);
+147
View File
@@ -0,0 +1,147 @@
#include "EnergyProfile.h"
#include <algorithm>
#include <cmath>
namespace
{
int clampedLevel(int level)
{
return std::clamp(level, 0, 2);
}
int clampedWeekday(int weekday)
{
return std::clamp(weekday, 1, 7);
}
int clampedHour(int hour)
{
return std::clamp(hour, 0, 23);
}
} // namespace
EnergyProfile EnergyProfile::defaults()
{
EnergyProfile profile;
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
int level = 0;
if (weekday <= 5)
{
if (hour >= 9 && hour <= 11)
{
level = 2;
}
else if (hour == 8 || hour == 12 || hour == 14 || (hour >= 15 && hour <= 18))
{
level = 1;
}
}
else if ((hour >= 10 && hour <= 11) || (hour >= 14 && hour <= 17))
{
level = 1;
}
profile.m_levels[weekday][hour] = level;
}
}
return profile;
}
EnergyProfile EnergyProfile::fromLevels(const QVector<EnergyLevel>& levels)
{
EnergyProfile profile = defaults();
for (const EnergyLevel& level : levels)
{
profile.m_levels[clampedWeekday(level.weekday)][clampedHour(level.hour)] =
clampedLevel(level.level);
}
return profile;
}
QString EnergyProfile::label(int level)
{
switch (clampedLevel(level))
{
case 2:
return QStringLiteral("高");
case 1:
return QStringLiteral("中");
default:
return QStringLiteral("低");
}
}
int EnergyProfile::level(int weekday, int hour) const
{
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
{
return -1;
}
return m_levels[weekday][hour];
}
int EnergyProfile::level(const QDateTime& localDateTime) const
{
if (!localDateTime.isValid())
{
return -1;
}
return level(localDateTime.date().dayOfWeek(), localDateTime.time().hour());
}
bool EnergyProfile::setLevel(int weekday, int hour, int levelValue)
{
if (weekday < 1 || weekday > 7 || hour < 0 || hour > 23)
{
return false;
}
m_levels[weekday][hour] = clampedLevel(levelValue);
return true;
}
QVector<EnergyLevel> EnergyProfile::levels() const
{
QVector<EnergyLevel> result;
result.reserve(7 * 24);
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
result.append({weekday, hour, m_levels[weekday][hour]});
}
}
return result;
}
void EnergyProfile::learn(const QVector<EnergySample>& samples)
{
std::array<std::array<int, 24>, 8> sums{};
std::array<std::array<int, 24>, 8> counts{};
for (const EnergySample& sample : samples)
{
if (sample.weekday < 1 || sample.weekday > 7 || sample.hour < 0 || sample.hour > 23)
{
continue;
}
sums[sample.weekday][sample.hour] += clampedLevel(sample.level);
++counts[sample.weekday][sample.hour];
}
for (int weekday = 1; weekday <= 7; ++weekday)
{
for (int hour = 0; hour < 24; ++hour)
{
if (counts[weekday][hour] == 0)
{
continue;
}
const double average =
static_cast<double>(sums[weekday][hour]) / counts[weekday][hour];
m_levels[weekday][hour] =
std::clamp(static_cast<int>(std::lround(average)), 0, 2);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#include <QDateTime>
#include <QString>
#include <QVector>
#include <array>
/*
* 类名: EnergyProfile
* 功能: 按星期与小时保存精力水平(0 低 / 1 中 / 2 高),并从完成记录学习
* 线程安全: 否(值类型)
*/
struct EnergyLevel
{
int weekday = 1;
int hour = 0;
int level = 1;
};
struct EnergySample
{
int weekday = 1;
int hour = 0;
int level = 1;
};
class EnergyProfile
{
public:
static EnergyProfile defaults();
static EnergyProfile fromLevels(const QVector<EnergyLevel>& levels);
static QString label(int level);
int level(int weekday, int hour) const;
int level(const QDateTime& localDateTime) const;
bool setLevel(int weekday, int hour, int level);
QVector<EnergyLevel> levels() const;
void learn(const QVector<EnergySample>& samples);
private:
std::array<std::array<int, 24>, 8> m_levels{};
};
+43 -19
View File
@@ -65,16 +65,35 @@ std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
SysTime rangeStart,
std::optional<SysTime> deadline,
std::chrono::seconds duration,
int granularityMinutes)
int granularityMinutes,
int energyRequired,
const Options& options)
{
const auto energySatisfied = [&](SysTime start) {
if (energyRequired < 0 || !options.energyAt)
{
return true;
}
const int level = options.energyAt(start);
return level < 0 || level >= energyRequired;
};
const auto nextGrid = [granularityMinutes](SysTime value) {
return ceilToGranularity(value + std::chrono::seconds{std::max(1, granularityMinutes) * 60},
granularityMinutes);
};
for (const TimeRange& window : windows)
{
SysTime cursor = ceilToGranularity(std::max(window.start, rangeStart), granularityMinutes);
if (cursor >= window.end)
while (cursor + duration <= window.end)
{
continue;
if (deadline && cursor + duration > *deadline)
{
break;
}
SysTime occupiedUntil = cursor;
bool conflict = false;
for (const TimeRange& occupied : busy)
{
if (occupied.end <= cursor)
@@ -83,30 +102,26 @@ std::optional<TimeRange> findSlot(const std::vector<TimeRange>& windows,
}
if (occupied.start >= cursor + duration)
{
if (deadline && cursor + duration > *deadline)
{
return std::nullopt;
break;
}
return TimeRange{cursor, cursor + duration};
}
if (occupied.end > cursor)
{
cursor = ceilToGranularity(occupied.end, granularityMinutes);
if (cursor >= window.end)
if (occupied.start < cursor + duration && occupied.end > cursor)
{
occupiedUntil = std::max(occupiedUntil, occupied.end);
conflict = true;
break;
}
}
}
if (cursor + duration <= window.end)
{
if (deadline && cursor + duration > *deadline)
if (conflict)
{
cursor = ceilToGranularity(occupiedUntil, granularityMinutes);
continue;
}
if (energySatisfied(cursor))
{
return TimeRange{cursor, cursor + duration};
}
cursor = nextGrid(cursor);
}
}
return std::nullopt;
}
@@ -212,7 +227,9 @@ Result schedule(const std::vector<TaskInput>& tasks,
rangeStart,
deadline,
duration,
options.granularityMinutes);
options.granularityMinutes,
task.energyRequired,
options);
}
}
@@ -220,7 +237,14 @@ Result schedule(const std::vector<TaskInput>& tasks,
{
const SysTime upper = deadline.value_or(rangeEnd);
const std::vector<TimeRange> generalWindows = intersect(windows, rangeStart, upper);
slot = findSlot(generalWindows, busy, rangeStart, deadline, duration, options.granularityMinutes);
slot = findSlot(generalWindows,
busy,
rangeStart,
deadline,
duration,
options.granularityMinutes,
task.energyRequired,
options);
}
if (!slot.has_value())
+3
View File
@@ -1,6 +1,7 @@
#pragma once
#include <chrono>
#include <functional>
#include <optional>
#include <string>
#include <vector>
@@ -50,6 +51,8 @@ struct Failure
struct Options
{
int granularityMinutes = 15;
// 返回某个开始时刻的精力水平(0 低 / 1 中 / 2 高);返回 -1 表示未知。
std::function<int(SysTime)> energyAt;
};
struct Result
+72
View File
@@ -9,6 +9,7 @@
#include <algorithm>
#include "core/DailyInsights.h"
#include "core/DateTimeUtils.h"
#include "storage/SqliteStore.h"
@@ -21,6 +22,36 @@ QDateTime truncateToMinute(const QDateTime& value)
{
return QDateTime(value.date(), QTime(value.time().hour(), value.time().minute()), value.timeSpec());
}
QString energySummaryForDate(const EnergyProfile& profile, const QDate& date)
{
if (!date.isValid())
{
return {};
}
QStringList windows;
int runStart = -1;
for (int hour = 0; hour <= 24; ++hour)
{
const bool high = hour < 24 && profile.level(date.dayOfWeek(), hour) == 2;
if (high && runStart < 0)
{
runStart = hour;
}
else if (!high && runStart >= 0)
{
windows.append(QStringLiteral("%1:00–%2:00")
.arg(runStart, 2, 10, QLatin1Char('0'))
.arg(hour, 2, 10, QLatin1Char('0')));
runStart = -1;
}
}
if (windows.isEmpty())
{
return QStringLiteral("今天没有明显的高精力时段");
}
return QStringLiteral("精力高峰:%1").arg(windows.join(QStringLiteral("、")));
}
} // namespace
ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject* parent)
@@ -28,6 +59,7 @@ ScheduleService::ScheduleService(SqliteStore& store, QString deviceId, QObject*
, m_store(store)
, m_deviceId(std::move(deviceId))
{
rebuildEnergyProfile();
}
bool ScheduleService::validateRange(const QDateTime& start, const QDateTime& end, QString* error)
@@ -315,6 +347,7 @@ bool ScheduleService::setBlockStatus(const QString& blockId, const QString& stat
return false;
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -404,6 +437,7 @@ bool ScheduleService::deleteBlock(const QString& blockId, QString* error)
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -889,6 +923,7 @@ bool ScheduleService::applyProposedDiff(const ProposedDiff& diff,
}
m_lastError.clear();
rebuildEnergyProfile();
Q_EMIT dataChanged();
return true;
}
@@ -948,5 +983,42 @@ QString ScheduleService::lastError() const
void ScheduleService::notifyDataChanged()
{
rebuildEnergyProfile();
Q_EMIT dataChanged();
}
const EnergyProfile& ScheduleService::energyProfile() const
{
return m_energyProfile;
}
int ScheduleService::energyLevelFor(const QDateTime& localDateTime) const
{
return m_energyProfile.level(localDateTime);
}
DailyReview ScheduleService::dailyReview(const QDate& date) const
{
QDateTime now = QDateTime::currentDateTime();
if (date != now.date())
{
now = date < now.date() ? QDateTime(date, QTime(23, 59), Qt::LocalTime)
: QDateTime(date, QTime(0, 0), Qt::LocalTime);
}
DailyReview review = buildDailyReview(itemsForDay(date), date, now);
review.energySummary = energySummaryForDate(m_energyProfile, date);
return review;
}
QVector<Suggestion> ScheduleService::suggestions(const QDateTime& now) const
{
return buildSuggestions(itemsForDay(now.date()), now);
}
void ScheduleService::rebuildEnergyProfile()
{
EnergyProfile profile = EnergyProfile::defaults();
profile.learn(m_store.completedEnergySamples());
m_energyProfile = profile;
m_store.replaceEnergyLevels(m_energyProfile.levels());
}
+11
View File
@@ -5,6 +5,8 @@
#include <QString>
#include <QVector>
#include "core/DailyInsights.h"
#include "core/EnergyProfile.h"
#include "core/ProposedDiff.h"
#include "core/ScheduleItem.h"
@@ -52,6 +54,14 @@ public:
QVector<ScheduleItem> itemsForRange(const QDate& from, const QDate& to) const;
QVector<ScheduleItem> overdueItems(const QDateTime& now = QDateTime::currentDateTime()) const;
QString lastError() const;
const EnergyProfile& energyProfile() const;
int energyLevelFor(const QDateTime& localDateTime) const;
void rebuildEnergyProfile();
DailyReview dailyReview(const QDate& date) const;
QVector<Suggestion> suggestions(const QDateTime& now = QDateTime::currentDateTime()) const;
// 供同步层在外部写入后通知 UI 刷新。
void notifyDataChanged();
@@ -67,4 +77,5 @@ private:
SqliteStore& m_store;
QString m_deviceId;
QString m_lastError;
EnergyProfile m_energyProfile;
};
+102
View File
@@ -1,5 +1,7 @@
#include "SqliteStore.h"
#include <algorithm>
#include <QDir>
#include <QJsonDocument>
#include <QFileInfo>
@@ -1053,6 +1055,106 @@ bool SqliteStore::applyRemoteChange(const RemoteChange& change, QString* error)
return true;
}
QVector<EnergyLevel> SqliteStore::energyLevels() const
{
m_lastError.clear();
QVector<EnergyLevel> levels;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return levels;
}
QSqlQuery query(m_database);
if (!query.exec(QStringLiteral(
"SELECT weekday, hour_slot, level FROM energy_profile ORDER BY weekday, hour_slot")))
{
setError(QStringLiteral("查询精力档案失败: %1").arg(query.lastError().text()));
return levels;
}
while (query.next())
{
levels.append({query.value(0).toInt(), query.value(1).toInt(), query.value(2).toInt()});
}
return levels;
}
bool SqliteStore::replaceEnergyLevels(const QVector<EnergyLevel>& levels)
{
m_lastError.clear();
if (!isOpenInternal())
{
return setError(QStringLiteral("数据库未打开"));
}
if (!m_database.transaction())
{
return setError(QStringLiteral("开启精力档案事务失败: %1").arg(m_database.lastError().text()));
}
QSqlQuery clear(m_database);
if (!clear.exec(QStringLiteral("DELETE FROM energy_profile")))
{
m_database.rollback();
return setError(QStringLiteral("清理精力档案失败: %1").arg(clear.lastError().text()));
}
QSqlQuery insert(m_database);
insert.prepare(QStringLiteral(
"INSERT OR REPLACE INTO energy_profile(id, weekday, hour_slot, level) "
"VALUES (:id, :weekday, :hour_slot, :level)"));
for (const EnergyLevel& level : levels)
{
insert.bindValue(QStringLiteral(":id"),
QStringLiteral("%1-%2").arg(level.weekday).arg(level.hour));
insert.bindValue(QStringLiteral(":weekday"), level.weekday);
insert.bindValue(QStringLiteral(":hour_slot"), level.hour);
insert.bindValue(QStringLiteral(":level"), std::clamp(level.level, 0, 2));
if (!insert.exec())
{
m_database.rollback();
return setError(QStringLiteral("写入精力档案失败: %1").arg(insert.lastError().text()));
}
}
if (!m_database.commit())
{
m_database.rollback();
return setError(QStringLiteral("提交精力档案失败: %1").arg(m_database.lastError().text()));
}
return true;
}
QVector<EnergySample> SqliteStore::completedEnergySamples() const
{
m_lastError.clear();
QVector<EnergySample> samples;
if (!isOpenInternal())
{
setError(QStringLiteral("数据库未打开"));
return samples;
}
QSqlQuery query(m_database);
if (!query.exec(QStringLiteral(
"SELECT t.energy_req, b.start_at, b.end_at FROM timeblock b "
"JOIN task t ON t.id = b.task_id "
"WHERE b.status = 'done' AND t.energy_req IS NOT NULL")))
{
setError(QStringLiteral("查询精力样本失败: %1").arg(query.lastError().text()));
return samples;
}
while (query.next())
{
const int level = std::clamp(query.value(0).toInt(), 0, 2);
const QDateTime start = DateTimeUtils::fromDb(query.value(1).toString());
const QDateTime end = DateTimeUtils::fromDb(query.value(2).toString());
if (!start.isValid() || !end.isValid() || start >= end)
{
continue;
}
for (QDateTime cursor = start; cursor < end; cursor = cursor.addSecs(3600))
{
samples.append({cursor.date().dayOfWeek(), cursor.time().hour(), level});
}
}
return samples;
}
qint64 SqliteStore::syncCursor(const QString& deviceId, QString* error) const
{
m_lastError.clear();
+5
View File
@@ -7,6 +7,7 @@
#include <atomic>
#include <optional>
#include "core/EnergyProfile.h"
#include "core/ProposedDiff.h"
#include "core/SyncTypes.h"
#include "core/ScheduleItem.h"
@@ -64,6 +65,10 @@ public:
qint64 syncCursor(const QString& deviceId, QString* error = nullptr) const;
bool setSyncCursor(const QString& deviceId, qint64 seq, QString* error = nullptr);
QVector<EnergyLevel> energyLevels() const;
bool replaceEnergyLevels(const QVector<EnergyLevel>& levels);
QVector<EnergySample> completedEnergySamples() const;
private:
bool openDatabase(QString* error);
bool configureConnection(QString* error);
+17 -1
View File
@@ -28,6 +28,7 @@
#include "sync/SyncService.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/DailyReviewDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/ChatPanel.h"
#include "ui/panels/TodayPanel.h"
@@ -175,6 +176,8 @@ void CompactWindow::buildUi()
connect(openShortcut, &QShortcut::activated, this, &CompactWindow::openSchedule);
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &CompactWindow::openSettings);
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
connect(reviewShortcut, &QShortcut::activated, this, &CompactWindow::openDailyReview);
}
void CompactWindow::setupTray()
@@ -244,6 +247,7 @@ void CompactWindow::connectSignals()
m_scheduleWindow->focusBlock(QDate::currentDate(), id);
}
});
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &CompactWindow::openDailyReview);
connect(&m_notificationService,
&NotificationService::overdueListChanged,
@@ -332,8 +336,13 @@ void CompactWindow::reloadToday()
.arg(today.day())
.arg(weekdayLabel(today)));
m_todayItems = m_scheduleService.itemsForDay(today);
const QDateTime now = QDateTime::currentDateTime();
m_todayPanel->setDate(today);
m_todayPanel->setItems(m_todayItems, QDateTime::currentDateTime());
m_todayPanel->setItems(m_todayItems, now);
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
m_todayPanel->setInsightText(
suggestions.isEmpty() ? QString()
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
}
void CompactWindow::openSchedule()
@@ -362,6 +371,13 @@ void CompactWindow::openSettings()
dialog.exec();
}
void CompactWindow::openDailyReview()
{
DailyReviewDialog dialog(m_scheduleService.dailyReview(QDate::currentDate()), m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void CompactWindow::updateSyncStatus(const QString& status)
{
if (!m_syncLabel)
+1
View File
@@ -62,6 +62,7 @@ private:
void reloadToday();
void openSchedule();
void openSettings();
void openDailyReview();
void openEditDialog(const QString& blockId);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
+36 -2
View File
@@ -34,6 +34,7 @@
#include "services/ScheduleService.h"
#include "sync/SyncService.h"
#include "ui/dialogs/BlockEditDialog.h"
#include "ui/dialogs/DailyReviewDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/TodayPanel.h"
#include "ui/theme/ThemeManager.h"
@@ -144,10 +145,10 @@ void MainWindow::buildUi()
m_newButton->setToolTip(QStringLiteral("新建日程 (Ctrl+N)"));
m_searchEdit = new ElaLineEdit(m_toolbar);
m_searchEdit->setPlaceholderText(QStringLiteral("搜索(阶段 4)"));
m_searchEdit->setPlaceholderText(QStringLiteral("搜索(后续版本)"));
m_searchEdit->setFixedSize(140, 30);
m_searchEdit->setEnabled(false);
m_searchEdit->setToolTip(QStringLiteral("搜索将在阶段 4 接入"));
m_searchEdit->setToolTip(QStringLiteral("搜索将在后续版本接入"));
m_snapCombo = new ElaComboBox(m_toolbar);
m_snapCombo->addItems({QStringLiteral("吸附 15 分"),
@@ -310,6 +311,9 @@ void MainWindow::buildUi()
auto* settingsShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+,")), this);
connect(settingsShortcut, &QShortcut::activated, this, &MainWindow::openSettings);
auto* reviewShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+R")), this);
connect(reviewShortcut, &QShortcut::activated, this, &MainWindow::openDailyReview);
auto* compactShortcut = new QShortcut(QKeySequence(QStringLiteral("Ctrl+W")), this);
connect(compactShortcut, &QShortcut::activated, this, &MainWindow::close);
}
@@ -405,6 +409,7 @@ void MainWindow::connectSignals()
m_grid->scrollToBlock(id);
m_grid->setFocus(Qt::OtherFocusReason);
});
connect(m_todayPanel, &TodayPanel::reviewRequested, this, &MainWindow::openDailyReview);
connect(&m_notificationService,
&NotificationService::overdueListChanged,
@@ -590,8 +595,30 @@ void MainWindow::reloadCurrentView()
}
}
if (m_currentView == View::Day)
{
const QDateTime ghostFrom =
m_currentDate == now.date() ? now : QDateTime(m_currentDate, QTime(8, 0), Qt::LocalTime);
m_grid->setGhostWindows(findFreeWindows(agendaItems, m_currentDate, ghostFrom, 8, 22, 30));
}
else
{
m_grid->setGhostWindows({});
}
m_todayPanel->setDate(m_currentDate);
m_todayPanel->setItems(agendaItems, now);
if (m_currentDate == QDate::currentDate())
{
const QVector<Suggestion> suggestions = m_scheduleService.suggestions(now);
m_todayPanel->setInsightText(
suggestions.isEmpty() ? QString()
: QStringLiteral("建议:%1").arg(suggestions.first().detail));
}
else
{
m_todayPanel->setInsightText(QString());
}
}
void MainWindow::navigateToDate(const QDate& date)
@@ -816,6 +843,13 @@ void MainWindow::openSettings()
dialog.exec();
}
void MainWindow::openDailyReview()
{
DailyReviewDialog dialog(m_scheduleService.dailyReview(m_currentDate), m_tokens, this);
dialog.moveToCenter();
dialog.exec();
}
void MainWindow::updateSyncStatus(const QString& status)
{
if (!m_syncLabel)
+1
View File
@@ -89,6 +89,7 @@ private:
void openCreateDialogForNew();
void openEditDialog(const QString& blockId);
void openSettings();
void openDailyReview();
void updateOverdueBanner(const QVector<ScheduleItem>& items);
void showError(const QString& title, const QString& message);
void updateSyncStatus(const QString& status);
+146
View File
@@ -0,0 +1,146 @@
#include "DailyReviewDialog.h"
#include <QGridLayout>
#include <algorithm>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "ElaPushButton.h"
#include "ElaText.h"
namespace
{
QString formatWindow(const FreeWindow& window)
{
return QStringLiteral("%1–%2 · %3")
.arg(window.start.toString(QStringLiteral("HH:mm")),
window.end.toString(QStringLiteral("HH:mm")),
window.minutes >= 60
? QStringLiteral("%1 小时 %2 分").arg(window.minutes / 60).arg(window.minutes % 60)
: QStringLiteral("%1 分钟").arg(window.minutes));
}
} // namespace
DailyReviewDialog::DailyReviewDialog(const DailyReview& review,
const ThemeTokens& tokens,
QWidget* parent)
: ElaDialog(parent)
{
setWindowTitle(QStringLiteral("今日复盘"));
setWindowButtonFlags(ElaAppBarType::CloseButtonHint);
resize(520, 560);
setMinimumWidth(480);
auto* root = new QVBoxLayout(this);
root->setContentsMargins(24, 8, 24, 18);
root->setSpacing(10);
auto* title = new ElaText(QStringLiteral("%1月%2日 · %3复盘")
.arg(review.date.month())
.arg(review.date.day())
.arg(weekdayLabel(review.date)),
17,
this);
QFont titleFont = title->font();
titleFont.setWeight(QFont::DemiBold);
title->setFont(titleFont);
root->addWidget(title);
auto* summary = new ElaText(review.summary, 14, this);
summary->setWordWrap(true);
summary->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.textPrimary.name()));
root->addWidget(summary);
auto* grid = new QGridLayout();
grid->setHorizontalSpacing(28);
grid->setVerticalSpacing(8);
const auto addStat = [this, grid](int row, int column, const QString& label, const QString& value) {
auto* labelText = new ElaText(label, 11, this);
labelText->setTextStyle(ElaTextType::Caption);
auto* valueText = new ElaText(value, 14, this);
QFont valueFont = valueText->font();
valueFont.setWeight(QFont::DemiBold);
valueText->setFont(valueFont);
grid->addWidget(labelText, row, column);
grid->addWidget(valueText, row + 1, column);
};
addStat(0, 0, QStringLiteral("完成"), QStringLiteral("%1 / %2").arg(review.done).arg(review.total));
addStat(0, 1, QStringLiteral("完成率"), QStringLiteral("%1%").arg(review.completionPercent));
addStat(0, 2, QStringLiteral("专注"), QStringLiteral("%1 分钟").arg(review.focusedMinutes));
addStat(2, 0, QStringLiteral("待办"), QString::number(review.active));
addStat(2, 1, QStringLiteral("超时"), QString::number(review.overdue));
addStat(2, 2, QStringLiteral("错过 / 放弃"),
QStringLiteral("%1 / %2").arg(review.missed).arg(review.dropped));
root->addLayout(grid);
if (!review.energySummary.isEmpty())
{
auto* energy = new ElaText(review.energySummary, 12, this);
energy->setWordWrap(true);
energy->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
root->addWidget(energy);
}
auto* highlightsTitle = new ElaText(QStringLiteral("今日概览"), 13, this);
QFont sectionFont = highlightsTitle->font();
sectionFont.setWeight(QFont::DemiBold);
highlightsTitle->setFont(sectionFont);
root->addWidget(highlightsTitle);
for (const QString& highlight : review.highlights)
{
auto* line = new ElaText(QStringLiteral("· %1").arg(highlight), 12, this);
line->setWordWrap(true);
root->addWidget(line);
}
auto* ghostTitle = new ElaText(QStringLiteral("幽灵时间"), 13, this);
ghostTitle->setFont(sectionFont);
root->addWidget(ghostTitle);
if (review.ghostWindows.isEmpty())
{
auto* empty = new ElaText(QStringLiteral("今天没有 30 分钟以上的空档。"), 12, this);
empty->setTextStyle(ElaTextType::Caption);
root->addWidget(empty);
}
else
{
const qsizetype count = std::min<qsizetype>(5, review.ghostWindows.size());
for (int i = 0; i < count; ++i)
{
auto* line = new ElaText(QStringLiteral("· %1").arg(formatWindow(review.ghostWindows.at(i))),
12,
this);
root->addWidget(line);
}
if (review.ghostWindows.size() > count)
{
auto* more = new ElaText(QStringLiteral("还有 %1 段空档")
.arg(review.ghostWindows.size() - count),
11,
this);
more->setTextStyle(ElaTextType::Caption);
root->addWidget(more);
}
}
root->addStretch(1);
auto* buttonRow = new QHBoxLayout();
buttonRow->addStretch(1);
auto* closeButton = new ElaPushButton(QStringLiteral("完成"), this);
closeButton->setFixedSize(88, 34);
closeButton->setDefault(true);
buttonRow->addWidget(closeButton);
root->addLayout(buttonRow);
connect(closeButton, &ElaPushButton::clicked, this, &DailyReviewDialog::accept);
}
QString DailyReviewDialog::weekdayLabel(const QDate& date) const
{
if (!date.isValid())
{
return {};
}
static const char* labels[] = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
return QString::fromUtf8(labels[date.dayOfWeek() - 1]);
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "ElaDialog.h"
#include "core/DailyInsights.h"
#include "ui/theme/ThemeTokens.h"
/*
* 类名: DailyReviewDialog
* 功能: 展示每日完成情况、精力高峰与幽灵时间
* 线程安全: 否;UI 线程
*/
class DailyReviewDialog : public ElaDialog
{
Q_OBJECT
public:
DailyReviewDialog(const DailyReview& review, const ThemeTokens& tokens, QWidget* parent = nullptr);
private:
QString weekdayLabel(const QDate& date) const;
};
+30
View File
@@ -10,6 +10,7 @@
#include "ElaScrollArea.h"
#include "ElaText.h"
#include "ElaToolButton.h"
#include "TodayItemCard.h"
TodayPanel::TodayPanel(QWidget* parent)
@@ -31,11 +32,26 @@ TodayPanel::TodayPanel(QWidget* parent)
m_titleLabel->setFont(titleFont);
m_countLabel = new ElaText(this);
m_countLabel->setTextPixelSize(11);
m_reviewButton = new ElaToolButton(this);
m_reviewButton->setIsTransparent(true);
m_reviewButton->setElaIcon(ElaIconType::ClipboardCheck);
m_reviewButton->setFixedSize(26, 26);
m_reviewButton->setToolTip(QStringLiteral("今日复盘 (Ctrl+R)"));
connect(m_reviewButton, &ElaToolButton::clicked, this, &TodayPanel::reviewRequested);
header->addWidget(m_titleLabel);
header->addStretch(1);
header->addWidget(m_countLabel, 0, Qt::AlignVCenter);
header->addWidget(m_reviewButton, 0, Qt::AlignVCenter);
root->addLayout(header);
m_insightLabel = new ElaText(this);
m_insightLabel->setTextPixelSize(11);
m_insightLabel->setTextStyle(ElaTextType::Caption);
m_insightLabel->setWordWrap(true);
m_insightLabel->setVisible(false);
root->addWidget(m_insightLabel);
m_scrollArea = new ElaScrollArea(this);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setFrameShape(QFrame::NoFrame);
@@ -59,9 +75,23 @@ TodayPanel::TodayPanel(QWidget* parent)
void TodayPanel::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
if (m_insightLabel)
{
m_insightLabel->setStyleSheet(QStringLiteral("color:%1;").arg(tokens.accent.name()));
}
rebuild();
}
void TodayPanel::setInsightText(const QString& text)
{
if (!m_insightLabel)
{
return;
}
m_insightLabel->setText(text);
m_insightLabel->setVisible(!text.trimmed().isEmpty());
}
void TodayPanel::setDate(const QDate& date)
{
if (!m_titleLabel)
+5
View File
@@ -9,6 +9,7 @@
class ElaScrollArea;
class ElaText;
class ElaToolButton;
class QVBoxLayout;
/*
@@ -26,6 +27,7 @@ public:
void setTokens(const ThemeTokens& tokens);
void setDate(const QDate& date);
void setItems(const QVector<ScheduleItem>& items, const QDateTime& now);
void setInsightText(const QString& text);
signals:
void editRequested(const QString& blockId);
@@ -33,6 +35,7 @@ signals:
void postponeRequested(const QString& blockId, int minutes);
void deleteRequested(const QString& blockId);
void focusRequested(const QString& blockId);
void reviewRequested();
private:
void rebuild();
@@ -44,6 +47,8 @@ private:
ElaText* m_titleLabel = nullptr;
ElaText* m_countLabel = nullptr;
ElaText* m_insightLabel = nullptr;
ElaToolButton* m_reviewButton = nullptr;
ElaScrollArea* m_scrollArea = nullptr;
QWidget* m_listWidget = nullptr;
QVBoxLayout* m_listLayout = nullptr;
+48
View File
@@ -102,6 +102,12 @@ const QVector<ScheduleItem>& ScheduleGridView::blocks() const
return m_blocks;
}
void ScheduleGridView::setGhostWindows(const QVector<FreeWindow>& windows)
{
m_ghostWindows = windows;
viewport()->update();
}
void ScheduleGridView::setTokens(const ThemeTokens& tokens)
{
m_tokens = tokens;
@@ -958,12 +964,54 @@ void ScheduleGridView::paintEvent(QPaintEvent* event)
}
const int scroll = verticalScrollBar()->value();
paintGhostWindows(painter, scroll);
paintBlocks(painter, scroll);
paintNowLine(painter, scroll);
paintCreatePreview(painter, scroll);
paintEmptyHint(painter, scroll);
}
void ScheduleGridView::paintGhostWindows(QPainter& painter, int scrollY)
{
if (m_ghostWindows.isEmpty())
{
return;
}
painter.save();
painter.setClipRect(QRectF(m_axisWidth + 1,
0,
viewport()->width() - m_axisWidth - 1,
viewport()->height()));
painter.translate(0, -scrollY);
QColor fill = m_tokens.accent;
fill.setAlpha(m_tokens.dark ? 24 : 18);
QColor border = m_tokens.accent;
border.setAlpha(m_tokens.dark ? 100 : 80);
QFont font = painter.font();
font.setPixelSize(11);
painter.setFont(font);
for (const FreeWindow& window : m_ghostWindows)
{
QRectF rect = rectForTimes(window.start, window.end).adjusted(4, 2, -4, -2);
if (rect.height() < 16)
{
continue;
}
QPainterPath path;
path.addRoundedRect(rect, 6, 6);
painter.fillPath(path, fill);
QPen pen(border, 1.0, Qt::DashLine);
painter.setPen(pen);
painter.setBrush(Qt::NoBrush);
painter.drawPath(path);
painter.setPen(m_tokens.textMuted);
const QString text = QStringLiteral("幽灵时间 · %1")
.arg(DateTimeUtils::formatDuration(window.minutes));
painter.drawText(rect.adjusted(10, 0, -8, 0), Qt::AlignLeft | Qt::AlignVCenter, text);
}
painter.restore();
}
void ScheduleGridView::paintBlocks(QPainter& painter, int scrollY)
{
painter.save();
+4
View File
@@ -7,6 +7,7 @@
#include <QSize>
#include <QVector>
#include "core/DailyInsights.h"
#include "core/ScheduleItem.h"
#include "ui/theme/ThemeTokens.h"
@@ -27,6 +28,7 @@ public:
void setBlocks(const QVector<ScheduleItem>& blocks);
const QVector<ScheduleItem>& blocks() const;
void setGhostWindows(const QVector<FreeWindow>& windows);
void setTokens(const ThemeTokens& tokens);
void setSnapMinutes(int minutes);
@@ -84,6 +86,7 @@ private:
void ensureGridCache();
void invalidateGridCache();
void paintGrid(QPainter& painter);
void paintGhostWindows(QPainter& painter, int scrollY);
void paintBlocks(QPainter& painter, int scrollY);
void paintBlock(QPainter& painter, const VisualBlock& visual);
void paintNowLine(QPainter& painter, int scrollY);
@@ -117,6 +120,7 @@ private:
QDate m_date;
QVector<ScheduleItem> m_blocks;
QVector<FreeWindow> m_ghostWindows;
QVector<VisualBlock> m_visuals;
ThemeTokens m_tokens;
int m_snapMinutes = 15;
+5 -1
View File
@@ -26,6 +26,10 @@ add_executable(test_scheduler test_scheduler.cpp)
target_link_libraries(test_scheduler PRIVATE schedule_core Qt6::Test schedule_warnings)
add_test(NAME scheduler COMMAND test_scheduler)
add_executable(test_energy test_energy.cpp)
target_link_libraries(test_energy PRIVATE schedule_core Qt6::Test schedule_warnings)
add_test(NAME energy COMMAND test_energy)
add_executable(test_ai test_ai.cpp)
target_link_libraries(test_ai PRIVATE schedule_ai Qt6::Test schedule_warnings)
add_test(NAME ai COMMAND test_ai)
@@ -47,7 +51,7 @@ endif()
if(WIN32)
set_target_properties(
test_storage test_services test_grid test_mainwindow test_compactwindow
test_config test_scheduler test_ai test_openai_provider test_sync_integration
test_config test_scheduler test_energy test_ai test_openai_provider test_sync_integration
PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
endif()
+62
View File
@@ -16,6 +16,7 @@
#include "storage/SqliteStore.h"
#include "ui/CompactWindow.h"
#include "ui/MainWindow.h"
#include "ui/dialogs/DailyReviewDialog.h"
#include "ui/dialogs/SettingsDialog.h"
#include "ui/panels/DiffPreviewCard.h"
#include "ui/theme/ThemeManager.h"
@@ -60,6 +61,7 @@ class TestCompactWindow : public QObject
private slots:
void initTestCase();
void compactOpensScheduleAndReturns();
void opensDailyReview();
void aiChatShowsDiffAndAccepts();
void aiChatShowsMultiOperationDiff();
@@ -217,6 +219,13 @@ void TestCompactWindow::compactOpensScheduleAndReturns()
}
saveWindow(scheduleWindow, QStringLiteral("schedule-day.png"));
if (auto* grid = scheduleWindow->findChild<ScheduleGridView*>())
{
grid->scrollToHour(18);
QTest::qWait(80);
}
saveWindow(scheduleWindow, QStringLiteral("schedule-ghost.png"));
scheduleWindow->setView(MainWindow::View::Month);
QTest::qWait(200);
QCOMPARE(scheduleWindow->view(), MainWindow::View::Month);
@@ -266,6 +275,59 @@ void TestCompactWindow::compactOpensScheduleAndReturns()
QTest::mouseClick(settingsButton, Qt::LeftButton);
}
void TestCompactWindow::opensDailyReview()
{
QTemporaryDir databaseDir;
QVERIFY(databaseDir.isValid());
SqliteStore store(databaseDir.filePath(QStringLiteral("schedule.db")));
QString error;
QVERIFY2(store.open(&error), qPrintable(error));
ThemeManager theme(*m_settings);
theme.initialize();
ScheduleService service(store, QStringLiteral("review-test"));
NotificationService notifications(service);
AIService aiService(service, store, *m_settings);
createSampleData(service, QDate::currentDate());
CompactWindow compact(service, notifications, aiService, theme, *m_settings);
compact.show();
QVERIFY(QTest::qWaitForWindowExposed(&compact));
QTest::qWait(300);
ElaToolButton* reviewButton = nullptr;
for (ElaToolButton* button : compact.findChildren<ElaToolButton*>())
{
if (button->toolTip().startsWith(QStringLiteral("今日复盘")))
{
reviewButton = button;
break;
}
}
QVERIFY(reviewButton);
QTimer::singleShot(400, []() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* dialog = qobject_cast<DailyReviewDialog*>(widget))
{
saveWindow(dialog, QStringLiteral("review.png"));
dialog->reject();
}
}
});
QTimer::singleShot(2000, []() {
for (QWidget* widget : QApplication::topLevelWidgets())
{
if (auto* dialog = qobject_cast<DailyReviewDialog*>(widget))
{
dialog->reject();
}
}
});
QTest::mouseClick(reviewButton, Qt::LeftButton);
}
void TestCompactWindow::aiChatShowsDiffAndAccepts()
{
QTemporaryDir databaseDir;
+122
View File
@@ -0,0 +1,122 @@
#include <QtTest>
#include "core/DailyInsights.h"
#include "core/EnergyProfile.h"
class TestEnergy : public QObject
{
Q_OBJECT
private slots:
void defaultProfileHasCurve();
void learnsFromSamples();
void rejectsInvalidCoordinates();
void findsGhostWindows();
void buildsDailyReviewAndSuggestions();
};
void TestEnergy::defaultProfileHasCurve()
{
const EnergyProfile profile = EnergyProfile::defaults();
QCOMPARE(profile.level(1, 9), 2);
QCOMPARE(profile.level(1, 13), 0);
QCOMPARE(profile.level(7, 9), 0);
QCOMPARE(profile.level(7, 10), 1);
QCOMPARE(profile.level(0, 9), -1);
QCOMPARE(EnergyProfile::label(2), QStringLiteral("高"));
QCOMPARE(profile.levels().size(), 7 * 24);
}
void TestEnergy::learnsFromSamples()
{
EnergyProfile profile = EnergyProfile::defaults();
profile.learn({{1, 13, 2}, {1, 13, 2}, {1, 9, 0}});
QCOMPARE(profile.level(1, 13), 2);
QCOMPARE(profile.level(1, 9), 0);
QCOMPARE(profile.level(2, 9), 2);
profile.setLevel(1, 13, 1);
QCOMPARE(profile.level(1, 13), 1);
}
void TestEnergy::rejectsInvalidCoordinates()
{
EnergyProfile profile = EnergyProfile::defaults();
QVERIFY(!profile.setLevel(0, 9, 2));
QVERIFY(!profile.setLevel(8, 9, 2));
QVERIFY(!profile.setLevel(1, 24, 2));
QCOMPARE(profile.level(1, 24), -1);
QCOMPARE(profile.level(QDateTime()), -1);
}
namespace
{
QDate testDate()
{
return QDate(2026, 1, 5);
}
ScheduleItem item(int startHour, int endHour, const QString& status, const QString& title)
{
ScheduleItem result;
result.task.title = title;
result.task.energyReq = 1;
result.block.startAt = QDateTime(testDate(), QTime(startHour, 0), Qt::LocalTime);
result.block.endAt = QDateTime(testDate(), QTime(endHour, 0), Qt::LocalTime);
result.block.status = status;
return result;
}
} // namespace
void TestEnergy::findsGhostWindows()
{
const QVector<ScheduleItem> items = {
item(9, 10, QStringLiteral("done"), QStringLiteral("A")),
item(13, 14, QStringLiteral("scheduled"), QStringLiteral("B")),
item(11, 12, QStringLiteral("dropped"), QStringLiteral("C")),
};
const auto windows = findFreeWindows(items,
testDate(),
QDateTime(testDate(), QTime(8, 0), Qt::LocalTime),
8,
22,
30);
QCOMPARE(windows.size(), 3);
QCOMPARE(windows[0].minutes, 60);
QCOMPARE(windows[0].start.time(), QTime(8, 0));
QCOMPARE(windows[1].minutes, 180);
QCOMPARE(windows[1].start.time(), QTime(10, 0));
QCOMPARE(windows[2].minutes, 8 * 60);
QCOMPARE(windows[2].start.time(), QTime(14, 0));
}
void TestEnergy::buildsDailyReviewAndSuggestions()
{
const QVector<ScheduleItem> items = {
item(9, 10, QStringLiteral("done"), QStringLiteral("完成")),
item(13, 14, QStringLiteral("scheduled"), QStringLiteral("超时")),
};
const QDateTime now(testDate(), QTime(15, 0), Qt::LocalTime);
const DailyReview review = buildDailyReview(items, testDate(), now);
QCOMPARE(review.total, 2);
QCOMPARE(review.done, 1);
QCOMPARE(review.active, 1);
QCOMPARE(review.overdue, 1);
QCOMPARE(review.focusedMinutes, 60);
QCOMPARE(review.completionPercent, 50);
QVERIFY(!review.ghostWindows.isEmpty());
const auto suggestions = buildSuggestions(items, now, 3);
QCOMPARE(suggestions.size(), 2);
QCOMPARE(suggestions[0].kind, Suggestion::Kind::Overdue);
QCOMPARE(suggestions[1].kind, Suggestion::Kind::GhostTime);
const auto evening = buildSuggestions(items,
QDateTime(testDate(), QTime(19, 0), Qt::LocalTime),
3);
QCOMPARE(evening.size(), 3);
QCOMPARE(evening[2].kind, Suggestion::Kind::Review);
}
QTEST_GUILESS_MAIN(TestEnergy)
#include "test_energy.moc"
+40
View File
@@ -47,6 +47,7 @@ class TestOpenAiProvider : public QObject
private slots:
void streamsSseContent();
void streamsLocalWithoutApiKey();
void reportsHttpError();
};
@@ -92,6 +93,45 @@ void TestOpenAiProvider::streamsSseContent()
QCOMPARE(text, QStringLiteral("你好,世界"));
}
void TestOpenAiProvider::streamsLocalWithoutApiKey()
{
FakeSseServer server;
QVERIFY(server.listen(QHostAddress::LocalHost, 0));
server.response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"Connection: close\r\n"
"\r\n"
"data: {\"choices\":[{\"delta\":{\"content\":\"local\"}}]}\n\n"
"data: [DONE]\n\n";
AiConfig config;
config.baseUrl = QStringLiteral("http://127.0.0.1:%1/v1").arg(server.serverPort());
config.model = QStringLiteral("local-model");
QJsonArray messages;
QJsonObject message;
message.insert(QStringLiteral("role"), QStringLiteral("user"));
message.insert(QStringLiteral("content"), QStringLiteral("hi"));
messages.append(message);
OpenAiProvider provider;
QString text;
QString error;
bool finished = false;
provider.streamCompletion(
config,
messages,
{
[&text](const QString& delta) { text += delta; },
[&error](const QString& message) { error = message; },
[&finished]() { finished = true; },
});
QTRY_VERIFY_WITH_TIMEOUT(finished, 5000);
QCOMPARE(error, QString());
QCOMPARE(text, QStringLiteral("local"));
}
void TestOpenAiProvider::reportsHttpError()
{
FakeSseServer server;
+29
View File
@@ -57,6 +57,7 @@ private slots:
void fallsBackWhenPreferredIsFull();
void preferredWindowCanOverrideDefaultHours();
void reportsFailureWhenNoRoom();
void usesEnergyProfile();
};
void TestScheduler::skipsBusyIntervals()
@@ -157,5 +158,33 @@ void TestScheduler::reportsFailureWhenNoRoom()
QCOMPARE(result.failures.size(), std::size_t(1));
}
void TestScheduler::usesEnergyProfile()
{
scheduler::Options options;
options.energyAt = [](SysTime value) {
const int hour = static_cast<int>((value.time_since_epoch().count() / 3600) % 24);
return hour < 14 ? 0 : 2;
};
auto high = task(QStringLiteral("high").toStdString(), 60);
high.energyRequired = 2;
auto result = scheduler::schedule({high}, {}, workWindows(1), at(0, 8), at(0, 22), options);
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 14));
QVERIFY(result.placements[0].end == at(0, 15));
auto medium = task(QStringLiteral("medium").toStdString(), 60);
medium.energyRequired = 1;
result = scheduler::schedule({medium}, {}, workWindows(1), at(0, 8), at(0, 22), options);
QCOMPARE(result.placements.size(), std::size_t(1));
QVERIFY(result.placements[0].start == at(0, 14));
auto strictHigh = task(QStringLiteral("strict-high").toStdString(), 60);
strictHigh.energyRequired = 2;
result = scheduler::schedule({strictHigh}, {}, workWindows(1), at(0, 8), at(0, 13), options);
QVERIFY(result.placements.empty());
QCOMPARE(result.failures.size(), std::size_t(1));
}
QTEST_GUILESS_MAIN(TestScheduler)
#include "test_scheduler.moc"
+49
View File
@@ -25,6 +25,7 @@ private slots:
void overdueAndNotificationDedup();
void invalidRangeRejected();
void applyProposedCreatesOnlySelected();
void energyProfileLearnsFromHistory();
};
namespace
@@ -313,5 +314,53 @@ void TestServices::applyProposedCreatesOnlySelected()
QVERIFY(!context.service->applyProposedCreates(diff, {}, &error));
}
void TestServices::energyProfileLearnsFromHistory()
{
Context context;
QVERIFY(context.open());
const QDate date = QDate::currentDate();
QJsonObject task;
task.insert(QStringLiteral("title"), QStringLiteral("高精力任务"));
task.insert(QStringLiteral("priority"), 2);
task.insert(QStringLiteral("energy_req"), 2);
QJsonObject block;
block.insert(QStringLiteral("start_at"),
DateTimeUtils::toDb(QDateTime(date, QTime(13, 0), Qt::LocalTime)));
block.insert(QStringLiteral("end_at"),
DateTimeUtils::toDb(QDateTime(date, QTime(14, 0), Qt::LocalTime)));
QJsonObject create;
create.insert(QStringLiteral("temp_id"), QStringLiteral("energy"));
create.insert(QStringLiteral("task"), task);
create.insert(QStringLiteral("block"), block);
ProposedDiff diff;
diff.id = QStringLiteral("energy-diff");
diff.createdAt = DateTimeUtils::toDb(QDateTime::currentDateTimeUtc());
diff.state = QStringLiteral("pending");
diff.payload = QJsonObject{
{QStringLiteral("creates"), QJsonArray{create}},
{QStringLiteral("updates"), QJsonArray{}},
{QStringLiteral("deletes"), QJsonArray{}},
};
QString error;
QVERIFY2(context.service->applyProposedCreates(diff, {QStringLiteral("energy")}, &error),
qPrintable(error));
const QVector<ScheduleItem> items = context.service->itemsForDay(date);
QCOMPARE(items.size(), 1);
const QString blockId = items.first().block.id;
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 0);
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("done"), &error), qPrintable(error));
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 2);
QVERIFY(context.service->dailyReview(date).energySummary.contains(QStringLiteral("13:00–14:00")));
ScheduleService reloaded(*context.store, QStringLiteral("test-device"));
QCOMPARE(reloaded.energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 2);
QVERIFY2(context.service->setBlockStatus(blockId, QStringLiteral("scheduled"), &error), qPrintable(error));
QCOMPARE(context.service->energyLevelFor(QDateTime(date, QTime(13, 0), Qt::LocalTime)), 0);
}
QTEST_GUILESS_MAIN(TestServices)
#include "test_services.moc"
+11 -3
View File
@@ -8,6 +8,7 @@
> 阶段 2(AI 日程闭环)已验证:[`validation/phase-2.md`](validation/phase-2.md)。
> 阶段 2.1(更新 / 删除 / 涟漪 / 拆分)已验证:[`validation/phase-2-1.md`](validation/phase-2-1.md)。
> 阶段 3(Go 同步服务端 / 多设备)已验证:[`validation/phase-3.md`](validation/phase-3.md)。
> 阶段 4(精力曲线 / 幽灵时间 / 每日复盘 / 主动建议)已验证:[`validation/phase-4.md`](validation/phase-4.md)。
## 0. 当前环境
@@ -108,7 +109,6 @@ Schedule/
- [x] 长任务拆分(create)
- [x] AI 测试:update/create/delete、涟漪、部分接受冲突、拆分
- [x] 真实本地模型 50 条中文指令回归:完整 49/50 (98%),#42 复测 PASS
- [ ] 精力曲线、幽灵时间、每日复盘(阶段 4)
- [ ] 文件提取内嵌库替换(跨平台 PDF/Word)
### 阶段 3:Go 同步服务端 + 多设备(已完成)
@@ -122,8 +122,16 @@ Schedule/
- [x] 客户端双实例集成:创建 / 更新 / 删除 / 反向同步 / 服务端重启后离线恢复
- 验收:`ctest --preset linux-gcc` 11/11;`go test ./...`、`go vet ./...` 通过;见 [`validation/phase-3.md`](validation/phase-3.md)
### 阶段 4:智能增强(后续)
- 精力曲线学习与排程约束、幽灵时间、每日复盘、主动建议、本地模型 provider
### 阶段 4:智能增强(已完成)
- [x] 精力档案(7 天 × 24 小时,低/中/高)与 SQLite 缓存
- [x] 从已完成日程的 `energy_req` 学习精力曲线;撤销完成后回退
- [x] SchedulerEngine 按 `energy_req` 约束高精力任务的开始时段
- [x] AI 提示词注入精力高峰与 energy_req 语义,AI 排程使用学习后的曲线
- [x] 幽灵时间:工作时段空档计算、日视图半透明覆盖、复盘列表
- [x] 每日复盘:完成率、专注时长、待办/超时/放弃、精力高峰、幽灵时间
- [x] 主动建议:超时提醒、幽灵时间利用、傍晚复盘提示
- [x] 本地模型:Ollama / LM Studio / vLLM 等 OpenAI 兼容端点说明
- 验收:`ctest --preset linux-gcc` 12/12;详见 [`validation/phase-4.md`](validation/phase-4.md)
### 阶段 5:移动端(后续)
- Android 优先,复用同步协议与逻辑层
Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 71 KiB

+29
View File
@@ -0,0 +1,29 @@
Test project /home/misaki/MisakiCodes/Schedule/build/linux-gcc
Start 1: go_server_tests
1/12 Test #1: go_server_tests .................. Passed 0.10 sec
Start 2: storage
2/12 Test #2: storage .......................... Passed 0.02 sec
Start 3: services
3/12 Test #3: services ......................... Passed 0.04 sec
Start 4: grid
4/12 Test #4: grid ............................. Passed 0.38 sec
Start 5: mainwindow
5/12 Test #5: mainwindow ....................... Passed 1.25 sec
Start 6: compactwindow
6/12 Test #6: compactwindow .................... Passed 3.66 sec
Start 7: config
7/12 Test #7: config ........................... Passed 0.01 sec
Start 8: scheduler
8/12 Test #8: scheduler ........................ Passed 0.00 sec
Start 9: energy
9/12 Test #9: energy ........................... Passed 0.01 sec
Start 10: ai
10/12 Test #10: ai ............................... Passed 0.11 sec
Start 11: openai_provider
11/12 Test #11: openai_provider .................. Passed 0.21 sec
Start 12: sync_integration
12/12 Test #12: sync_integration ................. Passed 7.82 sec
100% tests passed, 0 tests failed out of 12
Total Test time (real) = 13.62 sec
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

+103
View File
@@ -0,0 +1,103 @@
# 阶段 4 验证报告:精力曲线 / 幽灵时间 / 每日复盘 / 主动建议
> 日期:2026-10-26
> 环境:Ubuntu 24.04 / GCC 13.3 / Qt 6.6.3
## 1. 本次交付
1. **精力档案**:新增 `EnergyProfile`(7 天 × 24 小时,0 低 / 1 中 / 2 高),默认曲线覆盖工作日与周末;SQLite `energy_profile` 作为本地缓存。
2. **精力学习**:从已完成且带 `energy_req` 的日程学习;按小时聚合完成记录,撤销完成后重新计算并回退。精力档案按设备本地保存,不参与同步。
3. **排程约束**:`SchedulerEngine::Options` 增加 `energyAt` 回调;高精力任务只选择满足要求的开始时段。AI 排程、涟漪与拆分都使用同一约束;用户显式指定的时间仍优先。
4. **AI 上下文**:Prompt 注入当天精力高峰,并明确 `energy_req` 的 0/1/2 语义,让模型在生成建议时优先考虑精力。
5. **幽灵时间**:计算 08:00–22:00 内 30 分钟以上的空档;日视图以半透明虚线块覆盖显示,复盘对话框列出当天全部幽灵时间。
6. **每日复盘**:新增 `DailyReviewDialog`,展示完成率、专注分钟、待办/超时/错过/放弃、精力高峰与幽灵时间;支持紧凑窗口和详细窗口,快捷键 `Ctrl+R`。
7. **主动建议**:今日任务面板顶部展示确定性建议,优先级为超时日程 → 可利用的幽灵时间 → 傍晚复盘提醒。
8. **本地模型**:OpenAI 兼容 Provider 已支持 Ollama / LM Studio / vLLM;新增「无 API Key 的本地端点」测试与 README 配置说明。
## 2. 构建与自动化测试
```bash
cmake --preset linux-gcc
cmake --build --preset linux-gcc --clean-first -j$(nproc)
ctest --preset linux-gcc
cd server
go test ./...
```
| 项目 | 结果 |
|---|---|
| 客户端全量构建 | 成功,项目代码 0 警告(`-Werror`) |
| `ctest --preset linux-gcc` | **12/12 通过**,总耗时约 14s |
| `go test ./...` | 通过(阶段 3 服务端无改动) |
完整输出见 [`ctest-phase-4.txt`](ctest-phase-4.txt)。
新增/扩展测试:
| 用例 | 覆盖 |
|---|---|
| `test_energy::defaultProfileHasCurve` | 默认 7×24 曲线与非法坐标 |
| `test_energy::learnsFromSamples` | 完成样本覆盖默认值、手动设置 |
| `test_energy::findsGhostWindows` | 忙碌/忽略已放弃块、空档合并与最短时长 |
| `test_energy::buildsDailyReviewAndSuggestions` | 完成率、专注时长、超时、幽灵时间、建议优先级 |
| `test_scheduler::usesEnergyProfile` | 高/中精力约束、无匹配时段时失败 |
| `test_services::energyProfileLearnsFromHistory` | 完成后学习、持久化、撤销回退、精力摘要 |
| `test_openai_provider::streamsLocalWithoutApiKey` | 本地 OpenAI 兼容端点无 API Key |
| `test_compactwindow::opensDailyReview` | 紧凑窗口打开复盘对话框并截图 |
## 3. 界面截图
| 截图 | 说明 |
|---|---|
| [`compact-dark.png`](compact-dark.png) / [`compact-light.png`](compact-light.png) | 紧凑窗口:主动建议、复盘入口 |
| [`schedule-ghost.png`](schedule-ghost.png) / [`schedule-ghost-light.png`](schedule-ghost-light.png) | 日视图中的幽灵时间覆盖 |
| [`daily-review-dark.png`](daily-review-dark.png) / [`daily-review-light.png`](daily-review-light.png) | 每日复盘:统计、精力高峰、幽灵时间 |
截图由真实 UI + 临时 SQLite 数据驱动;幽灵时间截图滚动到傍晚时段以展示空档覆盖。
## 4. 行为说明
### 精力曲线
- 默认工作日高峰:09:00–12:00、15:00–19:00;周末高峰较弱。
- 每完成一个带 `energy_req` 的时间块,该块覆盖的小时会作为样本参与聚合。
- 若没有样本,使用默认曲线;撤销完成会移除对应样本并回退。
- `energy_req = 0/1/2` 分别要求低/中/高精力;未指定(-1)不受约束。
- 没有满足要求的时段时,排程器返回失败;AI 会发出「未能安排」提示,而不是静默塞进低精力时段。
### 幽灵时间与建议
- 计算范围为每天 08:00–22:00,最短 30 分钟。
- 日视图从当前时刻开始显示今天的剩余空档;过去日期显示全天空档。
- 建议顺序:超时日程、幽灵时间、傍晚复盘;最多 3 条,界面展示第一条。
- 复盘总是列出当天所有幽灵时间,最多显示 5 条。
### 本地模型
| 服务 | 接口地址 | API Key |
|---|---|---|
| Ollama | `http://127.0.0.1:11434/v1` | 留空 |
| LM Studio | `http://127.0.0.1:1234/v1` | 留空 |
| vLLM / llama.cpp | 对应 `/v1` 地址 | 按服务要求 |
Provider 使用 OpenAI Chat Completions + SSE;本地端点无 Key 时不会发送 Authorization。
## 5. 已知限制
1. 精力学习只使用带 `energy_req` 的已完成日程;手工创建的日程目前没有 energy_req 编辑入口,因此不会贡献样本。
2. 精力档案按设备本地保存,不同设备的精力曲线不会同步或合并。
3. 幽灵时间工作时段固定为 08:00–22:00;尚未提供自定义工作时段。
4. 主动建议是确定性规则,不做模型推理;不主动弹窗,只在今日任务面板展示。
5. 每日复盘是确定性统计,不由 AI 生成叙事;如需 AI 总结,可后续作为可选动作接入。
6. 阶段 2 的 50 条真实模型回归未在阶段 4 重新全量执行;Prompt 增加了精力约束说明,模型行为可能略有波动。
7. 高精力任务在无匹配时段时会失败;显式指定的 preferred 时间不受精力约束。
## 6. 人工验收建议
1. 通过 AI 创建一条 `energy_req=2` 的任务,安排到默认低精力时段,确认排程器把它移到高峰时段。
2. 完成该任务,打开复盘,确认精力高峰包含实际完成时段;再撤销完成,确认曲线回退。
3. 在日视图中查看 08:00–22:00 的空档,确认幽灵时间虚线块和复盘列表一致。
4. 制造一个超时日程,确认今日任务面板出现「处理超时日程」建议;处理后再确认出现幽灵时间或复盘建议。
5. 按 `Ctrl+R` 或点击今日任务标题旁按钮,确认复盘统计(完成率、专注分钟、待办、超时、精力高峰、幽灵时间)正确。
6. 配置 Ollama 本地端点并留空 API Key,确认对话与排程可正常使用。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 140 KiB