feat(energy): Phase 3 — match-my-energy task sort + tri-state tag column
Closes Phase 3 of the 2026-04-23 feature-complete roadmap. Incorporates the Codex plan-review fixes from this session: profile-free index, tri- state update command, and de-prioritise-not-hide semantics. Storage (kon-storage): - Migration v11 adds `energy TEXT` to `tasks` with a CHECK constraint on `high | medium | brain_dead | NULL`. Index `(energy, created_at DESC)` — deliberately not per-profile because the tasks table carries no profile_id column yet (tracked as a separate gap in HANDOVER). - `TaskRow.energy: Option<String>` plus `task_row_from` read. - `insert_task` signature grows by one optional arg (`energy`). Allowed `too_many_arguments` with a rationale comment — the positional shape matches the column order and flipping to a params struct would have rippled through every caller for cosmetic benefit only. - New `set_task_energy(pool, id, Option<&str>) -> TaskRow`. Lives as its own function because `update_task` uses COALESCE to let `None` mean "preserve" — which would make clearing the tag impossible. - Two new tests: round-trip including explicit NULL clear, and CHECK constraint rejection of unknown values. - Tests updated for the v10 → v11 version bump. Tauri (src-tauri): - `TaskDto.energy`. `CreateTaskRequest.energy` (optional). Inline validation against the allowed set before hitting the DB, so frontend bugs surface as friendly errors instead of CHECK-constraint failures. - New `set_task_energy_cmd` command mirroring the storage tri-state API. Frontend (svelte): - `EnergyLevel` type added to `types/app.ts`. `TaskDto`, `TaskEntry`, and `TaskDraft` grow an `energy` field. - `SettingsState.currentEnergy` (persisted) + `matchMyEnergy` (persisted toggle). Defaults: null + false — no surface change until user opts in. - `setTaskEnergy(id, EnergyLevel | null)` action on the task store. Calls the dedicated Tauri command, updates local state, broadcasts to sibling windows. - `EnergyChip.svelte` — new component. Cycles unset → High → Medium → Brain-Dead → unset on click. Colour tokens: accent / warning / text-tertiary (deliberately not danger-red for Brain-Dead — the brief is explicit that this state must not feel pathologised). - Chip rendered on every task row in TasksPage and every row in WipTaskList. Hidden-until-hover when energy is unset so untagged rows stay calm; always visible once tagged because the colour is the signal. - Tasks page header gains a "I feel" segmented control and a "Match my energy" toggle. When both are active, matching tasks sort to the top — unset tasks are treated as Medium-equivalent. Nothing is ever hidden; this is a de-prioritisation, not a filter. Deferred / out of scope: - LLM-driven surfacing (brief says "The AI surfaces...") — deterministic client-side sort is v1; LLM layer is a later phase. - tasks.profile_id + per-profile energy sort — separate migration. All green: cargo build + 251 tests + clippy -D warnings (0 warnings) + fmt + svelte-check (0/0) + npm run build.
This commit is contained in:
@@ -270,6 +270,11 @@ pub async fn search_transcripts(
|
||||
/// Insert a task. `list_id` and `effort` are nullable (schema predates their
|
||||
/// UI surfacing); `notes` defaults to '' at the column level. Callers that
|
||||
/// want to set metadata at creation time pass `Some(...)`; omit for defaults.
|
||||
///
|
||||
/// Positional signature is deliberately flat — it mirrors the `tasks`
|
||||
/// schema columns one-to-one. Refactor to a params struct only if another
|
||||
/// nullable is added after `energy`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn insert_task(
|
||||
pool: &SqlitePool,
|
||||
id: &str,
|
||||
@@ -278,10 +283,11 @@ pub async fn insert_task(
|
||||
source_transcript_id: Option<&str>,
|
||||
list_id: Option<&str>,
|
||||
effort: Option<&str>,
|
||||
energy: Option<&str>,
|
||||
) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO tasks (id, text, bucket, source_transcript_id, list_id, effort) \
|
||||
VALUES (?, ?, ?, ?, ?, ?)",
|
||||
"INSERT INTO tasks (id, text, bucket, source_transcript_id, list_id, effort, energy) \
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(text)
|
||||
@@ -289,6 +295,7 @@ pub async fn insert_task(
|
||||
.bind(source_transcript_id)
|
||||
.bind(list_id)
|
||||
.bind(effort)
|
||||
.bind(energy)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| KonError::StorageError(format!("Insert task failed: {e}")))?;
|
||||
@@ -298,7 +305,7 @@ pub async fn insert_task(
|
||||
pub async fn list_tasks(pool: &SqlitePool) -> Result<Vec<TaskRow>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT id, text, bucket, list_id, effort, notes, done, done_at, created_at, \
|
||||
source_transcript_id, parent_task_id \
|
||||
source_transcript_id, parent_task_id, energy \
|
||||
FROM tasks WHERE parent_task_id IS NULL ORDER BY created_at DESC",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
@@ -311,7 +318,7 @@ pub async fn list_tasks(pool: &SqlitePool) -> Result<Vec<TaskRow>> {
|
||||
pub async fn get_task_by_id(pool: &SqlitePool, id: &str) -> Result<Option<TaskRow>> {
|
||||
let row = sqlx::query(
|
||||
"SELECT id, text, bucket, list_id, effort, notes, done, done_at, created_at, \
|
||||
source_transcript_id, parent_task_id FROM tasks WHERE id = ?",
|
||||
source_transcript_id, parent_task_id, energy FROM tasks WHERE id = ?",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
@@ -361,6 +368,27 @@ pub async fn update_task(
|
||||
})
|
||||
}
|
||||
|
||||
/// Dedicated tri-state energy setter. Exists as its own function because
|
||||
/// `update_task` uses `COALESCE(?, col)` to let `None` mean "preserve" —
|
||||
/// which makes it impossible to explicitly clear energy back to NULL.
|
||||
/// `set_task_energy` always writes exactly the value passed, including
|
||||
/// `None` to clear. Returns the refreshed row.
|
||||
///
|
||||
/// Caller is responsible for validating `energy` is one of the allowed
|
||||
/// values; the CHECK constraint will reject anything else at commit time.
|
||||
pub async fn set_task_energy(pool: &SqlitePool, id: &str, energy: Option<&str>) -> Result<TaskRow> {
|
||||
sqlx::query("UPDATE tasks SET energy = ? WHERE id = ?")
|
||||
.bind(energy)
|
||||
.bind(id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| KonError::StorageError(format!("set_task_energy failed: {e}")))?;
|
||||
|
||||
get_task_by_id(pool, id).await?.ok_or_else(|| {
|
||||
KonError::StorageError(format!("set_task_energy: task {id} not found after update"))
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn insert_subtask(
|
||||
pool: &SqlitePool,
|
||||
id: &str,
|
||||
@@ -380,7 +408,7 @@ pub async fn insert_subtask(
|
||||
pub async fn list_subtasks(pool: &SqlitePool, parent_id: &str) -> Result<Vec<TaskRow>> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT id, text, bucket, list_id, effort, notes, done, done_at, created_at, \
|
||||
source_transcript_id, parent_task_id \
|
||||
source_transcript_id, parent_task_id, energy \
|
||||
FROM tasks WHERE parent_task_id = ? ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(parent_id)
|
||||
@@ -577,6 +605,11 @@ pub struct TaskRow {
|
||||
pub created_at: String,
|
||||
pub source_transcript_id: Option<String>,
|
||||
pub parent_task_id: Option<String>,
|
||||
/// Phase 3 energy tagging: one of `"high"`, `"medium"`, `"brain_dead"`,
|
||||
/// or `None`. Enforced at the DB layer via a CHECK constraint (see
|
||||
/// migration v11). Unset is the expected normal case — the match-my-
|
||||
/// energy sort treats unset as Medium-equivalent.
|
||||
pub energy: Option<String>,
|
||||
}
|
||||
|
||||
fn transcript_row_from(r: &sqlx::sqlite::SqliteRow) -> TranscriptRow {
|
||||
@@ -639,6 +672,7 @@ fn task_row_from(r: sqlx::sqlite::SqliteRow) -> TaskRow {
|
||||
created_at: r.get("created_at"),
|
||||
source_transcript_id: r.get("source_transcript_id"),
|
||||
parent_task_id: r.get("parent_task_id"),
|
||||
energy: r.get("energy"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1158,7 +1192,16 @@ mod tests {
|
||||
async fn task_crud_roundtrip() {
|
||||
let pool = test_pool().await;
|
||||
|
||||
insert_task(&pool, "task1", "Buy groceries", "today", None, None, None)
|
||||
insert_task(
|
||||
&pool,
|
||||
"task1",
|
||||
"Buy groceries",
|
||||
"today",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1179,7 +1222,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn subtask_crud_roundtrip() {
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "p1", "Write report", "inbox", None, None, None)
|
||||
insert_task(&pool, "p1", "Write report", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_subtask(&pool, "s1", "Open document", "p1")
|
||||
@@ -1224,7 +1267,7 @@ mod tests {
|
||||
// child must also reopen the parent so "parent is done iff
|
||||
// every child is done" holds in both directions.
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "p1", "Ship release", "inbox", None, None, None)
|
||||
insert_task(&pool, "p1", "Ship release", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_subtask(&pool, "s1", "Final test", "p1")
|
||||
@@ -1258,10 +1301,10 @@ mod tests {
|
||||
// Sanity: tasks without a parent must not trigger the parent-
|
||||
// reopen branch (it should no-op cleanly).
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "a", "A", "inbox", None, None, None)
|
||||
insert_task(&pool, "a", "A", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
insert_task(&pool, "b", "B", "inbox", None, None, None)
|
||||
insert_task(&pool, "b", "B", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
complete_task(&pool, "a").await.unwrap();
|
||||
@@ -1385,7 +1428,7 @@ mod tests {
|
||||
async fn update_task_overwrites_provided_fields() {
|
||||
// Task 2.6 — happy path: insert, update bucket + effort, read back.
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "u1", "Draft post", "inbox", None, None, None)
|
||||
insert_task(&pool, "u1", "Draft post", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1402,7 +1445,16 @@ mod tests {
|
||||
async fn update_task_partial_leaves_others_unchanged() {
|
||||
// Task 2.6 — partial update: only notes changes; text/bucket intact.
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "u2", "Prep slides", "today", None, None, Some("30m"))
|
||||
insert_task(
|
||||
&pool,
|
||||
"u2",
|
||||
"Prep slides",
|
||||
"today",
|
||||
None,
|
||||
None,
|
||||
Some("30m"),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -1433,6 +1485,52 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// --- Energy tagging (Phase 3) ---
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_task_energy_round_trip_includes_explicit_clear() {
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "e1", "Write report", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Fresh task: energy must be NULL.
|
||||
let t = get_task_by_id(&pool, "e1").await.unwrap().unwrap();
|
||||
assert!(t.energy.is_none(), "new task must start with energy unset");
|
||||
|
||||
// Set High.
|
||||
let t = set_task_energy(&pool, "e1", Some("high")).await.unwrap();
|
||||
assert_eq!(t.energy.as_deref(), Some("high"));
|
||||
|
||||
// Change to Medium.
|
||||
let t = set_task_energy(&pool, "e1", Some("medium")).await.unwrap();
|
||||
assert_eq!(t.energy.as_deref(), Some("medium"));
|
||||
|
||||
// Explicit clear back to NULL — the whole reason this function
|
||||
// exists separately from update_task's COALESCE semantics.
|
||||
let t = set_task_energy(&pool, "e1", None).await.unwrap();
|
||||
assert!(
|
||||
t.energy.is_none(),
|
||||
"set_task_energy(None) must explicitly clear the column"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_task_energy_rejects_unknown_value_via_check_constraint() {
|
||||
// Migration v11 defines a CHECK constraint; invalid values must
|
||||
// be rejected at the DB layer even if a caller bypasses frontend
|
||||
// validation.
|
||||
let pool = test_pool().await;
|
||||
insert_task(&pool, "e2", "Task", "inbox", None, None, None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let res = set_task_energy(&pool, "e2", Some("turbo")).await;
|
||||
assert!(
|
||||
res.is_err(),
|
||||
"CHECK constraint must reject energy values outside the enum"
|
||||
);
|
||||
}
|
||||
|
||||
// --- Profile CRUD tests (Task 11) ---
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -12,9 +12,9 @@ pub use database::{
|
||||
get_profile, get_setting, get_task_by_id, get_transcript, init, insert_subtask, insert_task,
|
||||
insert_transcript, list_feedback_examples, list_profile_terms, list_profiles,
|
||||
list_recent_errors, list_subtasks, list_tasks, list_transcripts, list_transcripts_paged,
|
||||
log_error, record_feedback, search_transcripts, set_setting, uncomplete_task, update_profile,
|
||||
update_task, update_transcript, update_transcript_meta, ErrorLogRow, FeedbackRow,
|
||||
FeedbackTargetType, InsertTranscriptParams, ProfileRow, ProfileTermRow, RecordFeedbackParams,
|
||||
TaskRow, TranscriptRow,
|
||||
log_error, record_feedback, search_transcripts, set_setting, set_task_energy, uncomplete_task,
|
||||
update_profile, update_task, update_transcript, update_transcript_meta, ErrorLogRow,
|
||||
FeedbackRow, FeedbackTargetType, InsertTranscriptParams, ProfileRow, ProfileTermRow,
|
||||
RecordFeedbackParams, TaskRow, TranscriptRow,
|
||||
};
|
||||
pub use file_storage::{app_data_dir, crashes_dir, database_path, logs_dir, recordings_dir};
|
||||
|
||||
@@ -377,6 +377,29 @@ const MIGRATIONS: &[(i64, &str, &str)] = &[
|
||||
ON feedback(profile_id, target_type, created_at DESC);
|
||||
"#,
|
||||
),
|
||||
(
|
||||
11,
|
||||
"tasks: energy tagging for match-my-energy sort",
|
||||
r#"
|
||||
-- Phase 3 of the feature-complete roadmap: replaces the cut
|
||||
-- temptation-bundling feature with a deterministic client-side
|
||||
-- sort that matches tasks to the user's current energy state.
|
||||
-- NULL is the expected normal case — users who never tag get
|
||||
-- Medium-equivalent treatment at sort time (see Match-my-energy
|
||||
-- logic in src/lib/pages/TasksPage.svelte).
|
||||
--
|
||||
-- profile_id is deliberately absent from the index: tasks
|
||||
-- currently carry no profile_id column, so a per-profile index
|
||||
-- is out of scope until the broader task → profile migration
|
||||
-- lands. See HANDOVER deferred list.
|
||||
ALTER TABLE tasks
|
||||
ADD COLUMN energy TEXT
|
||||
CHECK (energy IS NULL OR energy IN ('high', 'medium', 'brain_dead'));
|
||||
|
||||
CREATE INDEX idx_tasks_energy_created
|
||||
ON tasks(energy, created_at DESC);
|
||||
"#,
|
||||
),
|
||||
];
|
||||
|
||||
/// Split SQL into individual statements, respecting BEGIN...END trigger blocks.
|
||||
@@ -526,7 +549,7 @@ mod tests {
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 10);
|
||||
assert_eq!(count, 11);
|
||||
|
||||
sqlx::query("INSERT INTO settings (key, value) VALUES ('test', 'value')")
|
||||
.execute(&pool)
|
||||
@@ -545,7 +568,7 @@ mod tests {
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 10);
|
||||
assert_eq!(count, 11);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -12,8 +12,9 @@ use kon_storage::{
|
||||
delete_task as db_delete_task, get_task_by_id as db_get_task,
|
||||
insert_subtask as db_insert_subtask, insert_task as db_insert_task,
|
||||
list_feedback_examples as db_list_feedback_examples, list_subtasks as db_list_subtasks,
|
||||
list_tasks as db_list_tasks, uncomplete_task as db_uncomplete_task,
|
||||
update_task as db_update_task, FeedbackRow, FeedbackTargetType, TaskRow,
|
||||
list_tasks as db_list_tasks, set_task_energy as db_set_task_energy,
|
||||
uncomplete_task as db_uncomplete_task, update_task as db_update_task, FeedbackRow,
|
||||
FeedbackTargetType, TaskRow,
|
||||
};
|
||||
|
||||
use crate::AppState;
|
||||
@@ -33,6 +34,7 @@ pub struct TaskDto {
|
||||
pub created_at: String,
|
||||
pub source_transcript_id: Option<String>,
|
||||
pub parent_task_id: Option<String>,
|
||||
pub energy: Option<String>,
|
||||
}
|
||||
|
||||
impl From<TaskRow> for TaskDto {
|
||||
@@ -49,10 +51,27 @@ impl From<TaskRow> for TaskDto {
|
||||
created_at: r.created_at,
|
||||
source_transcript_id: r.source_transcript_id,
|
||||
parent_task_id: r.parent_task_id,
|
||||
energy: r.energy,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepted energy tag values. Kept as a const so frontend and storage
|
||||
/// validate against the same list. Migration v11 enforces the same
|
||||
/// set via a CHECK constraint.
|
||||
const ENERGY_LEVELS: &[&str] = &["high", "medium", "brain_dead"];
|
||||
|
||||
fn validate_energy(raw: Option<&str>) -> Result<Option<&str>, String> {
|
||||
match raw {
|
||||
None => Ok(None),
|
||||
Some(s) if ENERGY_LEVELS.contains(&s) => Ok(Some(s)),
|
||||
Some(other) => Err(format!(
|
||||
"energy must be one of {:?} or null, got {:?}",
|
||||
ENERGY_LEVELS, other
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateTaskRequest {
|
||||
@@ -65,6 +84,8 @@ pub struct CreateTaskRequest {
|
||||
pub list_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub effort: Option<String>,
|
||||
#[serde(default)]
|
||||
pub energy: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -72,6 +93,7 @@ pub async fn create_task_cmd(
|
||||
state: tauri::State<'_, AppState>,
|
||||
request: CreateTaskRequest,
|
||||
) -> Result<TaskDto, String> {
|
||||
let energy = validate_energy(request.energy.as_deref())?;
|
||||
db_insert_task(
|
||||
&state.db,
|
||||
&request.id,
|
||||
@@ -80,6 +102,7 @@ pub async fn create_task_cmd(
|
||||
request.source_transcript_id.as_deref(),
|
||||
request.list_id.as_deref(),
|
||||
request.effort.as_deref(),
|
||||
energy,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -168,6 +191,24 @@ pub async fn uncomplete_task_cmd(
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Phase 3: set or clear the `energy` tag on a task. Dedicated command
|
||||
/// rather than a field on `update_task_cmd` because the existing update
|
||||
/// path uses `COALESCE` semantics where `None` means "preserve" — which
|
||||
/// makes clearing the tag impossible. This command always writes exactly
|
||||
/// what you send, including `None` to explicitly clear.
|
||||
#[tauri::command]
|
||||
pub async fn set_task_energy_cmd(
|
||||
state: tauri::State<'_, AppState>,
|
||||
id: String,
|
||||
energy: Option<String>,
|
||||
) -> Result<TaskDto, String> {
|
||||
let validated = validate_energy(energy.as_deref())?;
|
||||
let row = db_set_task_energy(&state.db, &id, validated)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(TaskDto::from(row))
|
||||
}
|
||||
|
||||
/// Convert HITL feedback rows fetched from storage into the few-shot
|
||||
/// exemplar shape the LLM crate consumes. We reconstruct the `input`
|
||||
/// (parent task text, transcript chunk) from `context_json` where the
|
||||
|
||||
@@ -284,6 +284,7 @@ pub fn run() {
|
||||
commands::tasks::complete_task_cmd,
|
||||
commands::tasks::delete_task_cmd,
|
||||
commands::tasks::uncomplete_task_cmd,
|
||||
commands::tasks::set_task_energy_cmd,
|
||||
commands::tasks::decompose_and_store,
|
||||
commands::tasks::extract_tasks_from_transcript_cmd,
|
||||
commands::tasks::list_subtasks_cmd,
|
||||
|
||||
106
src/lib/components/EnergyChip.svelte
Normal file
106
src/lib/components/EnergyChip.svelte
Normal file
@@ -0,0 +1,106 @@
|
||||
<script lang="ts">
|
||||
// Phase 3 — Energy tag chip. Cycles a task's energy level through
|
||||
// the spec's four states: unset → High → Medium → Brain-Dead → unset.
|
||||
//
|
||||
// Visual discipline: when energy is unset, the chip renders at
|
||||
// `group-hover` opacity only so untagged rows stay calm. Once set,
|
||||
// the chip is always visible because the colour IS the signal for
|
||||
// the match-my-energy sort.
|
||||
//
|
||||
// Colour choices borrow the existing design tokens:
|
||||
// High → accent (warm, on-brand, attention-ready)
|
||||
// Medium → warning (amber, unforced)
|
||||
// Brain-Dead → text-tertiary (low-energy grey, not danger red —
|
||||
// the brief is explicit that this state must not feel
|
||||
// pathologised)
|
||||
//
|
||||
// Callers pass the task's current energy and a setter. This component
|
||||
// owns no state — the task store is the source of truth.
|
||||
|
||||
import type { EnergyLevel } from "$lib/types/app";
|
||||
import { Zap } from "lucide-svelte";
|
||||
|
||||
let {
|
||||
energy = null as EnergyLevel | null,
|
||||
onSelect,
|
||||
size = "sm",
|
||||
reduceMotion = false,
|
||||
}: {
|
||||
energy: EnergyLevel | null;
|
||||
onSelect: (next: EnergyLevel | null) => void;
|
||||
size?: "sm" | "md";
|
||||
reduceMotion?: boolean;
|
||||
} = $props();
|
||||
|
||||
// Cycle order lives here so the chip is the single authority on what
|
||||
// "next" means. Tap once to tag, tap again to move up, tap past
|
||||
// Brain-Dead to clear. Keyboard-equivalent via the <button> element.
|
||||
const CYCLE: (EnergyLevel | null)[] = [null, "high", "medium", "brain_dead"];
|
||||
|
||||
function next(): EnergyLevel | null {
|
||||
const idx = CYCLE.indexOf(energy);
|
||||
return CYCLE[(idx + 1) % CYCLE.length];
|
||||
}
|
||||
|
||||
function labelFor(level: EnergyLevel | null): string {
|
||||
switch (level) {
|
||||
case "high": return "High";
|
||||
case "medium": return "Medium";
|
||||
case "brain_dead": return "Brain-Dead";
|
||||
default: return "No energy set";
|
||||
}
|
||||
}
|
||||
|
||||
let tooltip = $derived(
|
||||
energy === null
|
||||
? "Tag energy (click to set)"
|
||||
: `Energy: ${labelFor(energy)} — click to change`
|
||||
);
|
||||
|
||||
// Icon dimensions. `md` is the one used on the Tasks-page main rows;
|
||||
// `sm` is for the compact WIP list rows and micro-step children.
|
||||
let iconSize = $derived(size === "md" ? 13 : 10);
|
||||
let chipSize = $derived(size === "md" ? "h-5" : "h-4");
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="energy-chip inline-flex items-center justify-center rounded-md border px-1 {chipSize} text-[10px] font-medium
|
||||
{energy === null
|
||||
? 'opacity-0 group-hover:opacity-100 text-text-tertiary border-border-subtle hover:border-accent hover:text-text-secondary'
|
||||
: ''}
|
||||
{energy === 'high'
|
||||
? 'text-accent border-accent bg-accent/10'
|
||||
: ''}
|
||||
{energy === 'medium'
|
||||
? 'text-warning border-warning bg-warning/10'
|
||||
: ''}
|
||||
{energy === 'brain_dead'
|
||||
? 'text-text-tertiary border-border bg-hover'
|
||||
: ''}"
|
||||
onclick={() => onSelect(next())}
|
||||
aria-label={tooltip}
|
||||
title={tooltip}
|
||||
data-energy={energy ?? 'unset'}
|
||||
style={reduceMotion
|
||||
? ''
|
||||
: 'transition: opacity var(--duration-ui), color var(--duration-ui), border-color var(--duration-ui), background-color var(--duration-ui)'}
|
||||
>
|
||||
<Zap size={iconSize} aria-hidden="true" />
|
||||
{#if energy !== null && size === "md"}
|
||||
<span class="ml-1">{labelFor(energy)}</span>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<style>
|
||||
.energy-chip {
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
font-family: var(--font-family-body);
|
||||
}
|
||||
|
||||
.energy-chip:focus-visible {
|
||||
outline: 2px solid var(--color-accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { tasks, addTask, completeTask, uncompleteTask, deleteTask } from '$lib/stores/page.svelte.js';
|
||||
import { tasks, addTask, completeTask, uncompleteTask, deleteTask, setTaskEnergy } from '$lib/stores/page.svelte.js';
|
||||
import MicroSteps from '$lib/components/MicroSteps.svelte';
|
||||
import EnergyChip from '$lib/components/EnergyChip.svelte';
|
||||
import { ChevronDown, ChevronRight, Timer } from 'lucide-svelte';
|
||||
|
||||
function startFocusTimer(task: { id: string; text: string }) {
|
||||
@@ -74,6 +75,12 @@
|
||||
aria-label="Complete task"
|
||||
></button>
|
||||
<span class="text-[13px] text-text flex-1 min-w-0 truncate">{task.text}</span>
|
||||
<!-- Energy chip (Phase 3) — compact, reveals on hover when unset -->
|
||||
<EnergyChip
|
||||
energy={task.energy}
|
||||
onSelect={(next) => setTaskEnergy(task.id, next)}
|
||||
size="sm"
|
||||
/>
|
||||
<!-- 5-min focus timer — the "just-start" button from the brief -->
|
||||
<button
|
||||
class="opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-accent"
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { tick } from "svelte";
|
||||
import type { TaskBucket, TaskList } from "$lib/types/app";
|
||||
import type { EnergyLevel, TaskBucket, TaskEntry, TaskList } from "$lib/types/app";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
tasks, addTask, completeTask, uncompleteTask, deleteTask, updateTask,
|
||||
setTaskEnergy,
|
||||
taskLists, addTaskList, renameTaskList, deleteTaskList,
|
||||
settings, saveSettings,
|
||||
} from "$lib/stores/page.svelte.js";
|
||||
import WipTaskList from '$lib/components/WipTaskList.svelte';
|
||||
import EmptyState from '$lib/components/EmptyState.svelte';
|
||||
import { SquareCheck, Search, ExternalLink, ChevronLeft, ArrowUpDown, Plus, X, ChevronRight } from 'lucide-svelte';
|
||||
import EnergyChip from '$lib/components/EnergyChip.svelte';
|
||||
import { SquareCheck, Search, ExternalLink, ChevronLeft, ArrowUpDown, Plus, X, ChevronRight, Zap } from 'lucide-svelte';
|
||||
import Card from "$lib/components/Card.svelte";
|
||||
import { formatTimestamp } from "$lib/utils/time.js";
|
||||
import { BUCKET_COLORS, EFFORT_LABELS, EFFORT_ORDER } from "$lib/utils/constants.js";
|
||||
@@ -47,6 +50,17 @@
|
||||
return EFFORT_LABELS[effort as keyof typeof EFFORT_LABELS] || effort;
|
||||
}
|
||||
|
||||
// Phase 3 energy sort: when the user has opted in and declared a
|
||||
// current energy, tasks matching that energy sort to the top. Tasks
|
||||
// with no energy tag are treated as Medium-equivalent, per the brief's
|
||||
// framing that unset is the normal case. Nothing is ever hidden —
|
||||
// "reserves" in the spec means de-prioritise, not filter.
|
||||
function energyMatchRank(task: TaskEntry, currentEnergy: EnergyLevel | null): number {
|
||||
if (!currentEnergy) return 0;
|
||||
const effective = task.energy ?? "medium";
|
||||
return effective === currentEnergy ? 0 : 1;
|
||||
}
|
||||
|
||||
let filteredTasks = $derived.by(() => {
|
||||
let list = tasks.filter((t) => !t.done);
|
||||
if (activeBucket !== "all") {
|
||||
@@ -68,9 +82,34 @@
|
||||
} else if (sortMode === "deep-first") {
|
||||
list.sort((a, b) => effortRank(b.effort) - effortRank(a.effort));
|
||||
}
|
||||
// Match-my-energy sort runs last (stable) so it reorders the result
|
||||
// of the effort-based sort rather than replacing it.
|
||||
if (settings.matchMyEnergy && settings.currentEnergy) {
|
||||
const energy = settings.currentEnergy;
|
||||
list.sort((a, b) => energyMatchRank(a, energy) - energyMatchRank(b, energy));
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
function cycleCurrentEnergy(next: EnergyLevel | null) {
|
||||
settings.currentEnergy = next;
|
||||
saveSettings();
|
||||
}
|
||||
|
||||
function toggleMatchMyEnergy() {
|
||||
settings.matchMyEnergy = !settings.matchMyEnergy;
|
||||
saveSettings();
|
||||
}
|
||||
|
||||
function energyLabel(level: EnergyLevel | null): string {
|
||||
switch (level) {
|
||||
case "high": return "High";
|
||||
case "medium": return "Medium";
|
||||
case "brain_dead": return "Brain-Dead";
|
||||
default: return "Not set";
|
||||
}
|
||||
}
|
||||
|
||||
let completedTasks = $derived.by(() => {
|
||||
let list = tasks.filter((t) => t.done);
|
||||
if (activeBucket !== "all") {
|
||||
@@ -199,6 +238,49 @@
|
||||
<p class="text-[11px] text-text-tertiary mt-1">Add tasks manually. Automatic extraction from your transcripts is coming.</p>
|
||||
</div>
|
||||
<div class="flex-1"></div>
|
||||
|
||||
<!-- Phase 3 match-my-energy control. Three-state energy selector +
|
||||
toggle for the sort. Sits in the header so it is always visible
|
||||
from any bucket / list context. -->
|
||||
<div class="flex items-center gap-2 mr-2">
|
||||
<span class="text-[10px] text-text-tertiary hidden sm:inline" aria-hidden="true">I feel</span>
|
||||
<div class="flex items-center gap-0.5 bg-bg-input border border-border-subtle rounded-lg p-0.5"
|
||||
role="radiogroup"
|
||||
aria-label="My current energy">
|
||||
{#each [
|
||||
{ value: null, label: '—' },
|
||||
{ value: 'high' as EnergyLevel, label: 'High' },
|
||||
{ value: 'medium' as EnergyLevel, label: 'Med' },
|
||||
{ value: 'brain_dead' as EnergyLevel, label: 'Low' },
|
||||
] as opt}
|
||||
<button
|
||||
class="text-[10px] px-2 py-0.5 rounded-md
|
||||
{settings.currentEnergy === opt.value
|
||||
? 'bg-accent/15 text-accent'
|
||||
: 'text-text-tertiary hover:text-text-secondary'}"
|
||||
role="radio"
|
||||
aria-checked={settings.currentEnergy === opt.value}
|
||||
aria-label={opt.value ? `Set current energy to ${energyLabel(opt.value)}` : 'Clear current energy'}
|
||||
onclick={() => cycleCurrentEnergy(opt.value)}
|
||||
>{opt.label}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<button
|
||||
class="flex items-center gap-1 btn-md rounded-lg text-[10px]
|
||||
{settings.matchMyEnergy
|
||||
? 'bg-accent/15 text-accent border border-accent/30'
|
||||
: 'text-text-tertiary hover:bg-hover hover:text-text border border-transparent'}"
|
||||
style="transition-duration: var(--duration-ui)"
|
||||
onclick={toggleMatchMyEnergy}
|
||||
aria-pressed={settings.matchMyEnergy}
|
||||
aria-label={settings.matchMyEnergy ? 'Match my energy is on — click to turn off' : 'Match my energy is off — click to turn on'}
|
||||
title="Sort matching tasks to the top (unset counts as Medium)"
|
||||
>
|
||||
<Zap size={12} aria-hidden="true" />
|
||||
Match my energy
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
class="flex items-center gap-1.5 btn-md rounded-lg text-text-secondary hover:bg-hover hover:text-text"
|
||||
style="transition-duration: var(--duration-ui)"
|
||||
@@ -451,6 +533,13 @@
|
||||
onclick={() => setEffort(task.id, e)}
|
||||
>{effortLabel(e)}</button>
|
||||
{/each}
|
||||
<span class="text-border-subtle">·</span>
|
||||
<!-- Energy chip (Phase 3) -->
|
||||
<EnergyChip
|
||||
energy={task.energy}
|
||||
onSelect={(next) => setTaskEnergy(task.id, next)}
|
||||
size="md"
|
||||
/>
|
||||
<!-- Timestamp -->
|
||||
{#if task.createdAt}
|
||||
<span class="text-[10px] text-text-tertiary ml-auto">{formatTimestamp(task.createdAt)}</span>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type {
|
||||
EnergyLevel,
|
||||
PageState,
|
||||
Profile,
|
||||
Segment,
|
||||
@@ -68,6 +69,8 @@ const defaults: SettingsState = {
|
||||
globalHotkey: "Ctrl+Shift+R",
|
||||
sidebarCollapsed: false,
|
||||
microphoneDevice: "",
|
||||
currentEnergy: null,
|
||||
matchMyEnergy: false,
|
||||
};
|
||||
|
||||
function canUseStorage(): boolean {
|
||||
@@ -314,6 +317,7 @@ function mapTaskRow(row: TaskDto): TaskEntry {
|
||||
createdAt: row.createdAt ?? new Date().toISOString(),
|
||||
sourceTranscriptId: row.sourceTranscriptId ?? null,
|
||||
parentTaskId: row.parentTaskId ?? null,
|
||||
energy: row.energy ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -352,6 +356,7 @@ export async function addTask(task: TaskDraft) {
|
||||
sourceTranscriptId: task.sourceTranscriptId || null,
|
||||
listId: task.listId ?? null,
|
||||
effort: task.effort ?? null,
|
||||
energy: task.energy ?? null,
|
||||
},
|
||||
});
|
||||
tasks.unshift(mapTaskRow(row));
|
||||
@@ -396,6 +401,29 @@ export async function updateTask(id: string, updates: TaskUpdate) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 3: explicit tri-state energy setter. Lives outside `updateTask`
|
||||
* because the backend uses a dedicated command for clearing — see
|
||||
* `set_task_energy_cmd` in src-tauri/src/commands/tasks.rs. Pass `null`
|
||||
* to clear the tag entirely; pass an `EnergyLevel` string to set it.
|
||||
*/
|
||||
export async function setTaskEnergy(id: string, energy: EnergyLevel | null) {
|
||||
if (!hasTauriRuntime()) {
|
||||
applyLocalTaskUpdate(id, { energy });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const row = await invoke<TaskDto>("set_task_energy_cmd", { id, energy });
|
||||
const idx = tasks.findIndex((task) => task.id === id);
|
||||
if (idx >= 0) {
|
||||
tasks[idx] = mapTaskRow(row);
|
||||
broadcastTasks();
|
||||
}
|
||||
} catch (err) {
|
||||
toasts.error("Couldn't change energy", errorMessage(err));
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteTask(id: string) {
|
||||
if (!hasTauriRuntime()) return;
|
||||
|
||||
|
||||
@@ -56,6 +56,20 @@ export interface SettingsState {
|
||||
globalHotkey: string;
|
||||
sidebarCollapsed: boolean;
|
||||
microphoneDevice: string;
|
||||
/**
|
||||
* Phase 3 match-my-energy: the user's self-reported current energy
|
||||
* level. `null` means "not stated" — the sort falls back to created_at
|
||||
* order. Persists across sessions because energy tracks the person,
|
||||
* not the work.
|
||||
*/
|
||||
currentEnergy: EnergyLevel | null;
|
||||
/**
|
||||
* Phase 3 match-my-energy: when true, the Tasks page sorts tasks
|
||||
* matching `currentEnergy` to the top (with unset tasks treated as
|
||||
* Medium). Off by default so the list reads chronologically until
|
||||
* the user explicitly opts in.
|
||||
*/
|
||||
matchMyEnergy: boolean;
|
||||
}
|
||||
|
||||
export interface Profile {
|
||||
@@ -150,6 +164,14 @@ export interface TranscriptMetaPatch {
|
||||
segments?: Segment[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 3: energy level tag on a task. `null` means unset — the sort
|
||||
* treats unset as Medium-equivalent. Three tagged values match the
|
||||
* brief's "High / Medium / Brain-Dead" language; `brain_dead` is the
|
||||
* stored form because SQL enums don't love hyphens.
|
||||
*/
|
||||
export type EnergyLevel = "high" | "medium" | "brain_dead";
|
||||
|
||||
export interface TaskDto {
|
||||
id: string;
|
||||
text: string;
|
||||
@@ -162,6 +184,7 @@ export interface TaskDto {
|
||||
createdAt: string;
|
||||
sourceTranscriptId: string | null;
|
||||
parentTaskId: string | null;
|
||||
energy: EnergyLevel | null;
|
||||
}
|
||||
|
||||
export interface TaskEntry {
|
||||
@@ -176,6 +199,7 @@ export interface TaskEntry {
|
||||
createdAt: string;
|
||||
sourceTranscriptId: string | null;
|
||||
parentTaskId: string | null;
|
||||
energy: EnergyLevel | null;
|
||||
}
|
||||
|
||||
export interface TaskDraft {
|
||||
@@ -184,6 +208,7 @@ export interface TaskDraft {
|
||||
listId?: string | null;
|
||||
effort?: string | null;
|
||||
sourceTranscriptId?: string | null;
|
||||
energy?: EnergyLevel | null;
|
||||
}
|
||||
|
||||
export interface TaskUpdate {
|
||||
|
||||
Reference in New Issue
Block a user