tedi 0.16.3

Personal productivity CLI for task tracking, time management, and GitHub issue integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::{
	collections::{HashMap, HashSet},
	fs::File,
	hash::{DefaultHasher, Hasher},
	io::BufWriter,
	path::{Path, PathBuf},
	process::Command,
	thread,
	time::Duration,
};

use ask_llm::{ImageContent, Message, Model, Role};
use clap::{Args, Subcommand};
use color_eyre::eyre::{Context, Result, bail};
use jiff::{Timestamp, ToSpan, Zoned, civil};
use libwayshot::WayshotConnection;
use serde::{Deserialize, Serialize};
use v_utils::prelude::*;

use crate::config::LiveSettings;

#[derive(Debug, Subcommand)]
pub enum MonitorsCommands {
	/// Daemon that takes screenshots every 15 minutes, storing up to 24h of history.
	Watch,
	/// Take a fresh screenshot, then annotate all stored screenshots within the given timeframe.
	/// Output: `[HH:MM] <monitor_number> description [path]`
	Annotate {
		/// How far back to look (e.g. "1h", "6h", "24h"). Capped at stored history (24h).
		timeframe: Timeframe,
		/// Model name to pass to ask_llm (e.g. "Fast", "Medium", "Slow").
		#[arg(short, long, default_value = "Fast")]
		model: Model,
	},
	/// Take a screenshot of a specific monitor and remember it with a description.
	/// Next time `annotate` sees a matching screenshot, it will use this description instead of calling the LLM.
	Remember {
		/// Monitor number (0-indexed).
		#[arg(short, long)]
		monitor: usize,
		/// Description to associate with the current screen content.
		description: String,
	},
}
#[derive(Args, Debug)]
pub struct MonitorsArgs {
	#[command(subcommand)]
	pub command: MonitorsCommands,
}

pub async fn main(_settings: &LiveSettings, args: MonitorsArgs) -> Result<()> {
	match args.command {
		MonitorsCommands::Watch => watch_daemon(),
		MonitorsCommands::Annotate { timeframe, model } => annotate(timeframe, model).await,
		MonitorsCommands::Remember { monitor, description } => remember(monitor, description),
	}
}

fn cache_dir() -> PathBuf {
	v_utils::xdg_cache_dir!("watch_monitors")
}

// Watch daemon

/// Query sway for which outputs currently have windows open.
/// Returns a set of output names (e.g. "HDMI-A-1", "eDP-1") that have at least one window.
fn occupied_outputs() -> HashSet<String> {
	let output = match Command::new("swaymsg").args(["-t", "get_tree"]).output() {
		Ok(o) if o.status.success() => o.stdout,
		Ok(o) => {
			tracing::warn!("swaymsg exited with {}", o.status);
			return HashSet::new();
		}
		Err(e) => {
			tracing::warn!("Failed to run swaymsg: {e}");
			return HashSet::new();
		}
	};

	let tree: serde_json::Value = match serde_json::from_slice(&output) {
		Ok(v) => v,
		Err(e) => {
			tracing::warn!("Failed to parse swaymsg output: {e}");
			return HashSet::new();
		}
	};

	fn has_windows(node: &serde_json::Value) -> bool {
		// A node with a pid is a window
		if node.get("pid").is_some_and(|p| p.is_u64()) {
			return true;
		}
		for child in node["nodes"].as_array().into_iter().flatten() {
			if has_windows(child) {
				return true;
			}
		}
		for child in node["floating_nodes"].as_array().into_iter().flatten() {
			if has_windows(child) {
				return true;
			}
		}
		false
	}

	tree["nodes"]
		.as_array()
		.into_iter()
		.flatten()
		.filter(|output| output["name"].as_str().is_some_and(|n| n != "__i3"))
		.filter(|output| has_windows(output))
		.filter_map(|output| output["name"].as_str().map(String::from))
		.collect()
}

fn watch_daemon() -> Result<()> {
	let cache_dir = cache_dir();

	tracing::info!("Starting monitor watch daemon. Taking screenshots every 15 minutes.");

	//LOOP: it's a daemon
	loop {
		let now = Zoned::now();
		let date_dir = cache_dir.join(now.strftime("%Y-%m-%d").to_string());

		std::fs::create_dir_all(&date_dir).wrap_err(format!("Failed to create directory: {}", date_dir.display()))?;

		let wayshot = match WayshotConnection::new() {
			Ok(w) => w,
			Err(e) => {
				tracing::error!("Failed to connect to Wayland compositor: {e:?}");
				thread::sleep(Duration::from_secs(900));
				continue;
			}
		};

		let outputs = wayshot.get_all_outputs();

		if outputs.is_empty() {
			tracing::warn!("No outputs found");
			thread::sleep(Duration::from_secs(900));
			continue;
		}

		let occupied = occupied_outputs();
		let timestamp = now.strftime("%H-%M-%S").to_string();

		for (i, output) in outputs.iter().enumerate() {
			if !occupied.contains(&output.name) {
				tracing::debug!("Skipping empty output {i} ({})", output.name);
				continue;
			}

			let filename = format!("{timestamp}-s{i}.png");
			let screenshot_path = date_dir.join(filename);

			match wayshot.screenshot_single_output(output, false) {
				Ok(image_buffer) =>
					if let Err(e) = save_screenshot_png(&image_buffer, &screenshot_path) {
						tracing::error!("Failed to save screenshot to {}: {e:?}", screenshot_path.display());
					} else {
						tracing::debug!("Screenshot saved to: {}", screenshot_path.display());
					},
				Err(e) => {
					tracing::error!("Failed to capture screenshot from output {i}: {e:?}");
				}
			}
		}

		if let Err(e) = cleanup_old_screenshots(&cache_dir) {
			tracing::error!("Failed to cleanup old screenshots: {e:?}");
		}

		thread::sleep(Duration::from_secs(900));
	}
}

fn save_screenshot_png(image_buffer: &image::DynamicImage, path: &Path) -> Result<()> {
	let rgba = image_buffer.to_rgba8();
	let file = File::create(path).wrap_err(format!("Failed to create file: {}", path.display()))?;
	let writer = BufWriter::new(file);

	let mut encoder = png::Encoder::new(writer, rgba.width(), rgba.height());
	encoder.set_color(png::ColorType::Rgba);
	encoder.set_depth(png::BitDepth::Eight);

	let mut writer = encoder.write_header().wrap_err("Failed to write PNG header")?;
	writer.write_image_data(rgba.as_raw()).wrap_err("Failed to write PNG data")?;

	Ok(())
}

fn cleanup_old_screenshots(cache_dir: &Path) -> Result<()> {
	let threshold = Timestamp::now() - 1.day();

	for entry in std::fs::read_dir(cache_dir)? {
		let entry = entry?;
		let path = entry.path();

		if path.is_dir() {
			if let Some(dir_name) = path.file_name().and_then(|n| n.to_str())
				&& let Ok(dir_date) = civil::Date::strptime("%Y-%m-%d", dir_name)
			{
				let dir_timestamp = dir_date.at(0, 0, 0, 0).to_zoned(jiff::tz::TimeZone::UTC)?.timestamp();

				if dir_timestamp < threshold {
					tracing::info!("Removing old screenshot directory: {}", path.display());
					std::fs::remove_dir_all(&path)?;
				}
			}
		}
	}

	Ok(())
}

// Remember command

fn data_dir() -> PathBuf {
	v_utils::xdg_data_dir!("monitors")
}

fn screenshot_hash(png_bytes: &[u8]) -> String {
	let mut hasher = DefaultHasher::new();
	hasher.write(png_bytes);
	format!("{:016x}", hasher.finish())
}

#[derive(Debug, Default, Deserialize, Serialize)]
struct Descriptions(HashMap<String, String>);

impl Descriptions {
	fn load() -> Result<Self> {
		let path = data_dir().join("descriptions.json");
		if !path.exists() {
			return Ok(Self::default());
		}
		let content = std::fs::read_to_string(&path).wrap_err("Failed to read descriptions.json")?;
		serde_json::from_str(&content).wrap_err("Failed to parse descriptions.json")
	}

	fn save(&self) -> Result<()> {
		let path = data_dir().join("descriptions.json");
		let content = serde_json::to_string_pretty(self).wrap_err("Failed to serialize descriptions")?;
		std::fs::write(&path, content).wrap_err("Failed to write descriptions.json")
	}
}

fn remember(monitor: usize, description: String) -> Result<()> {
	let wayshot = WayshotConnection::new().wrap_err("Failed to connect to Wayland compositor")?;
	let outputs = wayshot.get_all_outputs();

	if monitor >= outputs.len() {
		bail!("Monitor {monitor} not found (have {} monitors: 0..{})", outputs.len(), outputs.len() - 1);
	}

	let image_buffer = wayshot
		.screenshot_single_output(&outputs[monitor], false)
		.wrap_err(format!("Failed to capture screenshot from monitor {monitor}"))?;

	// Save to a temp path first to get the PNG bytes
	let data_dir = data_dir();
	let tmp_path = data_dir.join("_tmp.png");
	save_screenshot_png(&image_buffer, &tmp_path)?;
	let png_bytes = std::fs::read(&tmp_path).wrap_err("Failed to read temp screenshot")?;
	let hash = screenshot_hash(&png_bytes);

	// Move to final location
	let screenshot_path = data_dir.join(format!("{hash}.png"));
	std::fs::rename(&tmp_path, &screenshot_path).wrap_err("Failed to move screenshot")?;

	// Update descriptions
	let mut descriptions = Descriptions::load()?;
	descriptions.0.insert(hash.clone(), description.clone());
	descriptions.save()?;

	println!("Remembered monitor {monitor} as \"{description}\" [{hash}]");
	Ok(())
}

// Annotated command

/// Take a fresh screenshot, then collect all screenshots within the timeframe and annotate them via LLM.
async fn annotate(timeframe: Timeframe, model: Model) -> Result<()> {
	let cache_dir = cache_dir();

	// Take a fresh screenshot right now
	capture_screenshots_now(&cache_dir)?;

	// Collect all screenshots within the timeframe
	let cutoff = Timestamp::now() - timeframe.signed_duration();
	let screenshots = collect_screenshots(&cache_dir, cutoff)?;

	if screenshots.is_empty() {
		bail!("No screenshots found within the requested timeframe");
	}

	// Check remembered descriptions
	let descriptions = Descriptions::load()?;
	let mut results: Vec<(usize, String)> = Vec::with_capacity(screenshots.len());
	let mut needs_llm: Vec<(usize, &ScreenshotEntry, Vec<u8>)> = Vec::new();

	for (i, s) in screenshots.iter().enumerate() {
		let png_bytes = std::fs::read(&s.path).wrap_err(format!("Failed to read screenshot: {}", s.path.display()))?;
		if png_bytes.is_empty() {
			tracing::warn!("Skipping empty screenshot: {}", s.path.display());
			continue;
		}
		let hash = screenshot_hash(&png_bytes);
		if let Some(desc) = descriptions.0.get(&hash) {
			results.push((i, format!("[{}] {} {desc}", s.time_str, s.monitor_index)));
		} else {
			needs_llm.push((i, s, png_bytes));
		}
	}

	if !needs_llm.is_empty() {
		let mut images = Vec::new();
		let mut llm_screenshots: Vec<(usize, &ScreenshotEntry)> = Vec::new();

		for (i, s, png_bytes) in &needs_llm {
			let base64_data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, png_bytes);
			images.push(ImageContent {
				base64_data,
				media_type: "image/png".to_string(),
			});
			llm_screenshots.push((*i, s));
		}

		let image_listing = llm_screenshots
			.iter()
			.enumerate()
			.map(|(img_idx, (_, s))| format!("Image {}: [{}] monitor {} ({})", img_idx + 1, s.time_str, s.monitor_index, s.path.display()))
			.collect::<Vec<_>>()
			.join("\n");

		let prompt = format!(
			r#"You are annotating workspace screenshots. Each image corresponds to a specific timestamp and monitor.

Here are the screenshots in chronological order:
{image_listing}

For EACH screenshot, provide a concise description of what is visible on the screen (e.g. "VSCode editing Rust file", "Firefox on GitHub PR", "terminal running tests", "Discord chat").

Format your response as one line per screenshot, EXACTLY matching this format:
<annotations>
[HH:MM] <monitor_number> description
</annotations>

Where HH:MM is the UTC time, monitor_number is the monitor index, and description is your brief annotation. One line per image, in the same order as the images above."#
		);

		let message = Message::new_with_text_and_images(Role::User, prompt, images);
		let mut conv = ask_llm::Conversation::new();
		conv.0.push(message);

		let response = ask_llm::conversation::<&str>(&conv, model, Some(4096), None).await?;

		let annotations_raw = response.extract_html_tag("annotations").inspect_err(|_| {
			eprintln!("Failed to extract <annotations> tag. Full response:\n{}\n", response.text);
		})?;

		let annotation_lines: Vec<&str> = annotations_raw.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect();

		if annotation_lines.len() != llm_screenshots.len() {
			tracing::warn!(
				"LLM returned {} annotations but we sent {} screenshots — printing raw",
				annotation_lines.len(),
				llm_screenshots.len()
			);
			for line in &annotation_lines {
				results.push((usize::MAX, line.to_string()));
			}
		} else {
			for (line, (orig_idx, _)) in annotation_lines.iter().zip(llm_screenshots.iter()) {
				results.push((*orig_idx, line.to_string()));
			}
		}

		tracing::info!("Cost: {:.4} cents", response.cost_cents);
	}

	// Sort by original index to maintain chronological order
	results.sort_by_key(|(idx, _)| *idx);

	let mut prev_time_str: Option<&str> = None;
	for (idx, line) in &results {
		if *idx < screenshots.len() {
			let time_str = &screenshots[*idx].time_str;
			if prev_time_str.is_some_and(|prev| prev != time_str) {
				println!();
			}
			prev_time_str = Some(time_str);
			println!("{line} [{}]", screenshots[*idx].path.display());
		} else {
			println!("{line}");
		}
	}

	Ok(())
}

struct ScreenshotEntry {
	path: PathBuf,
	timestamp: Timestamp,
	time_str: String,
	monitor_index: usize,
}

/// Capture screenshots from all monitors right now and save them to the cache dir.
fn capture_screenshots_now(cache_dir: &Path) -> Result<()> {
	let now = Zoned::now();
	let date_dir = cache_dir.join(now.strftime("%Y-%m-%d").to_string());
	std::fs::create_dir_all(&date_dir).wrap_err(format!("Failed to create directory: {}", date_dir.display()))?;

	let wayshot = WayshotConnection::new().wrap_err("Failed to connect to Wayland compositor")?;
	let outputs = wayshot.get_all_outputs();

	if outputs.is_empty() {
		bail!("No monitor outputs found");
	}

	let timestamp = now.strftime("%H-%M-%S").to_string();

	for (i, output) in outputs.iter().enumerate() {
		let filename = format!("{timestamp}-s{i}.png");
		let screenshot_path = date_dir.join(filename);

		let image_buffer = wayshot
			.screenshot_single_output(output, false)
			.wrap_err(format!("Failed to capture screenshot from output {i}"))?;
		save_screenshot_png(&image_buffer, &screenshot_path)?;
		tracing::debug!("Fresh screenshot saved to: {}", screenshot_path.display());
	}

	Ok(())
}

/// Collect all screenshots from the cache that are newer than `cutoff`, sorted chronologically.
fn collect_screenshots(cache_dir: &Path, cutoff: Timestamp) -> Result<Vec<ScreenshotEntry>> {
	let mut entries = Vec::new();

	for dir_entry in std::fs::read_dir(cache_dir)? {
		let dir_entry = dir_entry?;
		let dir_path = dir_entry.path();

		if !dir_path.is_dir() {
			continue;
		}

		let dir_name = match dir_path.file_name().and_then(|n| n.to_str()) {
			Some(n) => n.to_string(),
			None => continue,
		};

		let date = match civil::Date::strptime("%Y-%m-%d", &dir_name) {
			Ok(d) => d,
			Err(_) => continue,
		};

		for file_entry in std::fs::read_dir(&dir_path)? {
			let file_entry = file_entry?;
			let file_path = file_entry.path();

			if file_path.extension().and_then(|s| s.to_str()) != Some("png") {
				continue;
			}

			let file_name = match file_path.file_stem().and_then(|s| s.to_str()) {
				Some(n) => n.to_string(),
				None => continue,
			};

			// Parse "HH-MM-SS-sN" format
			let (time_part, monitor_part) = match file_name.rsplit_once("-s") {
				Some((t, m)) => (t, m),
				None => continue,
			};

			let monitor_index: usize = match monitor_part.parse() {
				Ok(m) => m,
				Err(_) => continue,
			};

			let time = match civil::Time::strptime("%H-%M-%S", time_part) {
				Ok(t) => t,
				Err(_) => continue,
			};

			let zoned = date.at(time.hour(), time.minute(), time.second(), 0).to_zoned(jiff::tz::TimeZone::system())?;
			let timestamp = zoned.timestamp();

			if timestamp < cutoff {
				continue;
			}

			let time_str = format!("{:02}:{:02}", zoned.hour(), zoned.minute());

			entries.push(ScreenshotEntry {
				path: file_path,
				timestamp,
				time_str,
				monitor_index,
			});
		}
	}

	entries.sort_by_key(|e| (e.timestamp, e.monitor_index));

	Ok(entries)
}