-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtask_tray.py
More file actions
2376 lines (2127 loc) · 90.2 KB
/
task_tray.py
File metadata and controls
2376 lines (2127 loc) · 90.2 KB
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Task Tray — SQLite Task Manager.
System tray widget with dual mode: compact popup + full window.
Reads/writes directly to ~/.claude/memory/memory.db.
"""
# ruff: noqa: E402
import atexit
import copy
import faulthandler
import json
import logging
import logging.handlers
import os
import socket as _socket
import sqlite3
import sys
import tempfile
import threading
import uuid
import time
from datetime import datetime, timedelta, timezone
def _resolve_log_dir() -> str:
for path in (
os.path.expanduser("~/.claude/mcp_servers/sqlite_kb"),
os.path.join(tempfile.gettempdir(), "sqlite-memory-mcp"),
):
try:
os.makedirs(path, exist_ok=True)
return path
except OSError:
continue
return tempfile.gettempdir()
def _open_log_file(path: str):
try:
return open(path, "a", encoding="utf-8", errors="replace")
except OSError:
return open(os.devnull, "a")
_log_dir = _resolve_log_dir()
_crash_log = _open_log_file(os.path.join(_log_dir, "crash.log"))
atexit.register(_crash_log.close)
try:
faulthandler.enable(file=_crash_log)
except (OSError, RuntimeError, ValueError):
pass
try:
_handler = logging.handlers.RotatingFileHandler(
os.path.join(_log_dir, "task_tray.log"),
maxBytes=2 * 1024 * 1024,
backupCount=5,
encoding="utf-8",
)
_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
_root_logger = logging.getLogger()
_root_logger.addHandler(_handler)
_root_logger.setLevel(logging.WARNING)
except OSError:
logging.basicConfig(
filename=os.devnull,
level=logging.WARNING,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger("task_tray")
_OPTIONAL_VECTOR_ERRORS = (
ImportError,
sqlite3.Error,
OSError,
RuntimeError,
ValueError,
)
_OPTIONAL_PIPELINE_ERRORS = (
ImportError,
sqlite3.Error,
OSError,
RuntimeError,
ValueError,
)
from task_search import TaskSearchEngine
from db_utils import (
DB_PATH,
TaskDAO,
add_task_attachment,
apply_task_mutation,
create_task_with_ledger,
get_conn,
is_overdue,
normalize_project_filter_values,
now_iso,
priority_sort_key,
remove_task_attachment,
resolve_task_attachment_path,
)
from schema import init_db
# Page size cap for "All" and "Done" tabs to keep QListWidget responsive
_TAB_PAGE_SIZE = 200
class TaskDB:
"""Direct sqlite3 wrapper for tasks table."""
def __init__(self, db_path=None):
self.db_path = db_path or DB_PATH
self.on_change = None
# Run shared schema migrations before opening the long-lived GUI connection.
init_db(self.db_path)
self._conn = sqlite3.connect(self.db_path, isolation_level=None, timeout=10)
self._conn.row_factory = sqlite3.Row
self._conn.execute("PRAGMA journal_mode=WAL")
self._conn.execute("PRAGMA foreign_keys=ON")
self._conn.execute("PRAGMA busy_timeout=10000")
self._repair_fts_if_needed()
self._last_promote_time: float = 0.0
self.search_engine = TaskSearchEngine()
# Entity enrichment cache — pre-loaded obs preview + task count
self._enrich_cache_obs: dict[int, str] = {}
self._enrich_cache_tc: dict[int, int] = {}
self._enrich_cache_lock = threading.Lock()
self._enrich_refresh_lock = threading.Lock()
threading.Thread(target=self._refresh_enrich_cache, daemon=True).start()
self._wal_timer = QTimer(QApplication.instance())
self._wal_timer.timeout.connect(self._wal_checkpoint)
self._wal_timer.start(300_000) # 5 minutes
class _transact:
"""Explicit transaction block for multi-statement atomic writes.
In autocommit mode (isolation_level=None), each execute() auto-commits.
This context manager groups multiple statements into a single transaction.
"""
def __init__(self, conn):
self._conn = conn
def __enter__(self):
self._conn.execute("BEGIN")
return self._conn
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._conn.execute("COMMIT")
else:
try:
self._conn.execute("ROLLBACK")
except sqlite3.Error:
pass
return False
def _wal_checkpoint(self):
try:
self._conn.execute("PRAGMA wal_checkpoint(PASSIVE)")
except sqlite3.Error:
pass
def _repair_fts_if_needed(self):
"""Check FTS5 indexes and rebuild if corrupted."""
for fts_table in ("tasks_fts", "memory_fts"):
try:
self._conn.execute(
f"INSERT INTO {fts_table}({fts_table}, rank) VALUES('integrity-check', 1)"
)
except sqlite3.Error:
try:
self._conn.execute(
f"INSERT INTO {fts_table}({fts_table}) VALUES('rebuild')"
)
self._conn.commit()
logging.getLogger("task_tray").warning(
"Repaired corrupted FTS index: %s", fts_table
)
except sqlite3.Error as e:
logger.warning("FTS rebuild failed: %s", e)
def close(self):
self._wal_timer.stop()
self._conn.close()
def promote_due_today(self):
"""Auto-move tasks with due_date <= today (throttled to 60s)."""
now = time.monotonic()
if now - self._last_promote_time < 60:
return 0
self._last_promote_time = now
return TaskDAO.promote_due_today(self._conn)
def get_all_active(self):
"""Return all active tasks (excludes done, archived, cancelled)."""
return TaskDAO.get_active(self._conn, columns=_UI_COLS)
def get_done_tasks(self):
"""Return completed tasks, newest first."""
return TaskDAO.get_done(self._conn, columns=_UI_COLS)
def purge_old_done(self, days=30):
"""Delete done tasks older than `days` days. Returns count deleted."""
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
return TaskDAO.purge_done(self._conn, cutoff)
def get_suggested_tasks(self, limit=20):
"""Return prioritized mix: overdue + high/critical + nearest due."""
return TaskDAO.get_suggested(self._conn, limit)
def get_all_notes(self):
"""Visible open notes. Excludes done/archived/cancelled."""
return TaskDAO.get_notes(self._conn)
def get_project_names(self):
"""Return project names sorted by active task count (most first)."""
return TaskDAO.get_project_names(self._conn)
def get_summary(self, tasks=None):
"""Return dict with total, overdue counts. Accepts pre-fetched tasks."""
if tasks is None:
tasks = self.get_all_active()
overdue = sum(1 for t in tasks if is_overdue(t["due_date"]))
return {"total": len(tasks), "overdue": overdue}
def get_tasks(self, section=None):
"""Return tasks excluding archived/cancelled, optionally filtered by section."""
if section:
rows = self._conn.execute(
f"SELECT {_UI_COLS} FROM tasks "
"WHERE status NOT IN ('archived', 'cancelled') "
"AND section = ? "
"ORDER BY created_at",
(section,),
).fetchall()
else:
rows = self._conn.execute(
f"SELECT {_UI_COLS} FROM tasks "
"WHERE status NOT IN ('archived', 'cancelled') "
"ORDER BY created_at"
).fetchall()
return [dict(r) for r in rows]
def get_overdue(self):
"""Return active tasks with past due_date."""
rows = self._conn.execute(
f"SELECT {_UI_COLS} FROM tasks "
"WHERE due_date < date('now') "
"AND due_date IS NOT NULL "
"AND status NOT IN ('done', 'archived', 'cancelled') "
"ORDER BY due_date"
).fetchall()
return [dict(r) for r in rows]
def add_task(
self,
title,
section="inbox",
priority="medium",
due_date=None,
project=None,
status="not_started",
description=None,
notes=None,
type="task",
attachments=None,
):
"""Insert new task, return its ID."""
task_id = str(uuid.uuid4())
now = now_iso()
with self._transact(self._conn):
create_task_with_ledger(
self._conn,
task_id,
title,
now,
description=description,
status=status,
section=section,
priority=priority,
due_date=due_date,
project=project,
notes=notes,
type=type,
tool_name="task_tray.add_task",
)
for file_path in attachments or []:
add_task_attachment(
self._conn,
task_id,
file_path,
tool_name="task_tray.add_task_attachment",
)
if self.on_change:
self.on_change()
return task_id
@staticmethod
def _recurring_series_key(raw: str | None) -> str | None:
"""Normalize recurring config for sibling matching."""
if not raw:
return None
try:
config = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return raw
if not isinstance(config, dict):
return raw
config = dict(config)
config.pop("last_spawned", None)
return json.dumps(config, sort_keys=True, separators=(",", ":"))
def mark_done(self, task_id):
"""Set status=done."""
now = now_iso()
with self._transact(self._conn):
result = apply_task_mutation(
self._conn,
task_id,
{"status": "done"},
timestamp=now,
tool_name="task_tray.mark_done",
)
if result.get("updated", 0) == 0:
return False
if self.on_change:
self.on_change()
return True
def update_task(self, task_id, **fields):
"""Update arbitrary fields on a task."""
if not fields:
return False
now = now_iso()
with self._transact(self._conn):
result = apply_task_mutation(
self._conn,
task_id,
fields,
timestamp=now,
tool_name="task_tray.update_task",
)
if result.get("updated", 0) == 0:
return False
if self.on_change:
self.on_change()
return True
def get_task_attachments(self, task_id, include_removed=False):
"""Return attachment metadata for a task."""
return TaskDAO.get_attachments(
self._conn,
task_id,
include_removed=include_removed,
)
def resolve_attachment_path(self, attachment):
"""Resolve best local path for an attachment."""
return resolve_task_attachment_path(attachment)
def apply_attachment_changes(self, task_id, add_paths=None, remove_ids=None):
"""Apply attachment additions/removals atomically for a task."""
add_paths = [p for p in (add_paths or []) if p]
remove_ids = [aid for aid in (remove_ids or []) if aid]
if not add_paths and not remove_ids:
return False
changed = False
with self._transact(self._conn):
for file_path in add_paths:
add_task_attachment(
self._conn,
task_id,
file_path,
tool_name="task_tray.add_task_attachment",
)
changed = True
for attachment_id in remove_ids:
changed = (
remove_task_attachment(
self._conn,
attachment_id,
tool_name="task_tray.remove_task_attachment",
)
or changed
)
if changed and self.on_change:
self.on_change()
return changed
def delete_task(self, task_id):
"""Soft-delete: cancel task (creates tombstone for bridge sync).
For recurring tasks, also cancel done siblings to stop respawn cycle."""
now = now_iso()
with self._transact(self._conn):
# Read task metadata before cancelling
row = TaskDAO.get_by_id(
self._conn,
task_id,
"title, recurring, project, parent_id, type, status",
)
# Cancel the target task
result = apply_task_mutation(
self._conn,
task_id,
{"status": "cancelled"},
timestamp=now,
tool_name="task_tray.delete_task",
)
if result.get("updated", 0) == 0:
return False
# For recurring tasks: cancel all done siblings to break spawn cycle
if row and row["recurring"]:
series_key = self._recurring_series_key(row["recurring"])
sibling_ids = [
s["id"]
for s in self._conn.execute(
"SELECT id, recurring FROM tasks WHERE title=? AND status='done' "
"AND recurring IS NOT NULL AND id!=? AND project IS ? "
"AND parent_id IS ? AND type=?",
(
row["title"],
task_id,
row["project"],
row["parent_id"],
row["type"],
),
).fetchall()
if self._recurring_series_key(s["recurring"]) == series_key
]
if sibling_ids:
for sid in sibling_ids:
apply_task_mutation(
self._conn,
sid,
{"status": "cancelled"},
timestamp=now,
tool_name="task_tray.delete_task",
)
if self.on_change:
self.on_change()
return True
# ── Entity Link helpers (v2.2.0) ─────────────────────────────────
def search_entities(self, query: str, limit: int = 10) -> list[dict]:
"""FTS5 search for entities (for autocomplete in link dialog)."""
if not query or len(query.strip()) < 2:
return []
words = query.strip().split()
fts_q = " OR ".join('"' + w.replace('"', '""') + '"' for w in words if w)
if not fts_q:
return []
rows = self._conn.execute(
"SELECT rowid, name, entity_type, "
"(SELECT COUNT(*) FROM observations WHERE entity_id = memory_fts.rowid) AS obs_count "
"FROM memory_fts WHERE memory_fts MATCH ? LIMIT ?",
(fts_q, limit),
).fetchall()
return [dict(r) for r in rows]
def search_entities_hybrid(
self, query: str, limit: int = 10, use_vector: bool = True
) -> list[dict]:
"""Hybrid entity search: FTS5 + optional vector, enriched with obs preview + task count."""
fts_results = self.search_entities(query, limit)
if not fts_results:
return []
# Optional vector search via vec_search module
if use_vector:
try:
from vec_search import vector_search, rrf_merge
vec_results = vector_search(self._conn, query, limit)
if vec_results:
# Normalize FTS results to match rrf_merge expected format (eid key)
fts_for_rrf = [
{
"eid": r["rowid"],
"name": r["name"],
"entity_type": r.get("entity_type", ""),
"project": None,
}
for r in fts_results
]
merged = rrf_merge(fts_for_rrf, vec_results, k=60)
# Rebuild result list from merged ranking
by_id = {r["rowid"]: r for r in fts_results}
for vr in vec_results:
if vr["eid"] not in by_id:
by_id[vr["eid"]] = {
"rowid": vr["eid"],
"name": vr["name"],
"entity_type": vr.get("entity_type", ""),
"obs_count": 0,
}
fts_results = [
by_id[m["eid"]] for m in merged if m["eid"] in by_id
][:limit]
except _OPTIONAL_VECTOR_ERRORS as exc:
logger.debug("Entity vector search unavailable: %s", exc)
# Batch enrich: obs preview + task count
eids = [r["rowid"] for r in fts_results]
if not eids:
return []
placeholders = ",".join("?" * len(eids))
obs_map = {}
for row in self._conn.execute(
f"SELECT entity_id, content FROM observations WHERE entity_id IN ({placeholders}) "
"GROUP BY entity_id",
eids,
).fetchall():
obs_map[row["entity_id"]] = row["content"][:80]
tc_map = {}
try:
for row in self._conn.execute(
f"SELECT entity_id, COUNT(*) as cnt FROM task_entity_links "
f"WHERE entity_id IN ({placeholders}) GROUP BY entity_id",
eids,
).fetchall():
tc_map[row["entity_id"]] = row["cnt"]
except sqlite3.OperationalError as exc:
logger.debug("Entity task link counts unavailable: %s", exc)
return [
{
"entity_id": r["rowid"],
"name": r["name"],
"entity_type": r.get("entity_type", ""),
"obs_preview": obs_map.get(r["rowid"], ""),
"obs_count": r.get("obs_count", 0),
"task_count": tc_map.get(r["rowid"], 0),
"_is_entity": True,
}
for r in fts_results
]
def _refresh_enrich_cache(self):
"""Bulk-load obs preview + task count for all entities. Thread-safe."""
if not self._enrich_refresh_lock.acquire(blocking=False):
return
try:
with get_conn(self.db_path) as conn:
obs = {}
for row in conn.execute(
"SELECT entity_id, content FROM observations GROUP BY entity_id"
).fetchall():
obs[row["entity_id"]] = row["content"][:80]
tc = {}
try:
for row in conn.execute(
"SELECT entity_id, COUNT(*) as cnt FROM task_entity_links GROUP BY entity_id"
).fetchall():
tc[row["entity_id"]] = row["cnt"]
except sqlite3.OperationalError as exc:
logger.debug("Entity enrich task counts unavailable: %s", exc)
with self._enrich_cache_lock:
self._enrich_cache_obs = obs
self._enrich_cache_tc = tc
except sqlite3.Error as e:
logger.warning("Enrich cache refresh failed: %s", e)
finally:
self._enrich_refresh_lock.release()
def _get_enrich(self, entity_id: int) -> tuple[str, int]:
"""Get cached (obs_preview, task_count). Returns ("", 0) on miss."""
with self._enrich_cache_lock:
return (
self._enrich_cache_obs.get(entity_id, ""),
self._enrich_cache_tc.get(entity_id, 0),
)
def search_entities_fast(self, query: str, limit: int = 10) -> list[dict]:
"""FTS5 + vector search with cached enrichment. Thread-safe (own connection)."""
if not query or len(query.strip()) < 2:
return []
words = query.strip().split()
fts_q = " OR ".join('"' + w.replace('"', '""') + '"' for w in words if w)
if not fts_q:
return []
with get_conn(self.db_path) as conn:
try:
rows = conn.execute(
"SELECT rowid, name, entity_type, "
"(SELECT COUNT(*) FROM observations WHERE entity_id = memory_fts.rowid) AS obs_count "
"FROM memory_fts WHERE memory_fts MATCH ? LIMIT ?",
(fts_q, limit),
).fetchall()
except sqlite3.Error as exc:
logger.warning("Entity FTS search failed: %s", exc)
return []
fts_results = [dict(r) for r in rows]
# Vector search (ALWAYS enabled) — graceful degradation if deps missing
try:
from vec_search import vector_search, rrf_merge, load_vec
if load_vec(conn):
vec_results = vector_search(conn, query, limit)
if vec_results and fts_results:
fts_for_rrf = [
{
"eid": r["rowid"],
"name": r["name"],
"entity_type": r.get("entity_type", ""),
"project": None,
}
for r in fts_results
]
merged = rrf_merge(fts_for_rrf, vec_results, k=60)
by_id = {r["rowid"]: r for r in fts_results}
for vr in vec_results:
if vr["eid"] not in by_id:
by_id[vr["eid"]] = {
"rowid": vr["eid"],
"name": vr["name"],
"entity_type": vr.get("entity_type", ""),
"obs_count": 0,
}
fts_results = [
by_id[m["eid"]] for m in merged if m["eid"] in by_id
][:limit]
elif vec_results and not fts_results:
fts_results = [
{
"rowid": vr["eid"],
"name": vr["name"],
"entity_type": vr.get("entity_type", ""),
"obs_count": 0,
}
for vr in vec_results[:limit]
]
except _OPTIONAL_VECTOR_ERRORS as exc:
logger.debug("Fast entity vector search unavailable: %s", exc)
# Apply cached enrichment (zero SQL queries)
results = []
for r in fts_results:
eid = r["rowid"]
obs_preview, task_count = self._get_enrich(eid)
results.append(
{
"entity_id": eid,
"name": r["name"],
"entity_type": r.get("entity_type", ""),
"obs_preview": obs_preview,
"obs_count": r.get("obs_count", 0),
"task_count": task_count,
"_is_entity": True,
}
)
return results
def link_task_entity(
self, task_id: str, entity_id: int, link_type: str = "manual"
) -> bool:
"""Create a manual link between a task and an entity."""
now = now_iso()
try:
with self._transact(self._conn) as conn:
TaskDAO.link_entity(conn, task_id, entity_id, link_type, created_at=now)
return True
except (sqlite3.OperationalError, sqlite3.IntegrityError):
return False
def get_task_links(self, task_id: str) -> list[dict]:
"""Get all entities linked to a task."""
try:
return TaskDAO.get_task_links(self._conn, task_id)
except sqlite3.OperationalError:
return []
def unlink_task_entity(self, task_id: str, entity_id: int) -> bool:
"""Remove a link between a task and an entity."""
with self._transact(self._conn) as conn:
removed = TaskDAO.unlink_entity(conn, task_id, entity_id)
return removed > 0
# ── UI Layer ────────────────────────────────────────────────────────
from PyQt6.QtWidgets import (
QApplication,
QSystemTrayIcon,
QMenu,
QLabel,
QLineEdit,
QMainWindow,
QTabWidget,
QListWidgetItem,
QToolBar,
QToolButton,
QStatusBar,
QDialog,
QProgressBar,
)
from PyQt6.QtGui import QIcon, QAction, QActionGroup, QColor
from PyQt6.QtCore import (
QFileSystemWatcher,
QObject,
QSettings,
Qt,
QTimer,
pyqtSignal,
)
from pathlib import Path
from tray_filters import FilterMixin
from premium_task_tray import maybe_load_task_tray_extension
from tray_sync import BridgeSyncMixin
import tray_dialogs as _td
from tray_dialogs import (
# Theme system
_THEMES,
_theme_name,
_font_size,
_bold,
_T,
_update_theme_colors,
_build_main_style,
_build_filter_style,
_build_list_style,
_REFRESH_INTERVAL_MS,
# Constants
_UI_COLS,
# Dialog classes + TaskListWidget
TrayPopup,
CustomDesignDialog,
EditTaskDialog,
ReminderPopupDialog,
TaskListWidget,
create_tray_icon_pixmap,
_suggested_sort_key,
)
_PURGE_INTERVAL_MS = 3_600_000 # 1 hour
def _run_recurring_maintenance(db_path):
"""Process recurring tasks silently (idempotent)."""
try:
from recurring_tasks import process_recurring
with get_conn(db_path) as conn:
return process_recurring(conn, dry_run=False)
except _OPTIONAL_PIPELINE_ERRORS as exc:
logging.getLogger("task_tray").warning("recurring: %s", exc)
return []
class _BridgeSignalBus(QObject):
progress = pyqtSignal(int, str)
done = pyqtSignal(str)
class _TrayStatusProxy:
"""Status sink for app-level sync ownership without a permanent status bar."""
def __init__(self, app):
self._app = app
def showMessage(self, message, timeout):
logger.info("tray_status message=%r timeout_ms=%s", message, timeout)
full_window = getattr(self._app, "full_window", None)
if full_window and full_window.isVisible():
full_window.status.showMessage(message, timeout)
return
if message.startswith(("Sync error", "Sync blocked", "Sync incomplete")):
self._app.tray.showMessage(
"SQLite Memory Tray",
message,
QSystemTrayIcon.MessageIcon.Warning,
timeout,
)
# Per-tab sort/filter constants
_FIXED_VIEW_TABS = frozenset({"suggested", "projects"})
_DEFAULT_TAB_VIEW = {
"sort": "priority",
"active": {"priority": set(), "due": set(), "project": set()},
"excluded": {"priority": set(), "due": set(), "project": set()},
"params": {},
}
def _normalize_filter_payload(filter_payload):
"""Normalize persisted include/exclude filter payloads."""
payload = filter_payload or {}
return {
"priority": set(payload.get("priority", [])),
"due": set(payload.get("due", [])),
"project": normalize_project_filter_values(payload.get("project", [])),
}
class FullWindow(QMainWindow, BridgeSyncMixin, FilterMixin):
"""Full task manager window with tabs, search, sort, and suggested view."""
_bridge_done = pyqtSignal(str)
_bridge_progress = pyqtSignal(int, str) # (percent, step_label)
_enrich_done = pyqtSignal(str)
_enrich_running = pyqtSignal(str)
_entity_search_done = pyqtSignal(list, int) # (entity_results, seq_id)
# Sort modes cycle: priority → due → created → priority ...
_SORT_MODES = ("priority", "due", "created", "project")
_SORT_LABELS = {
"priority": "Sort: Priority",
"due": "Sort: Due Date",
"created": "Sort: Created",
"project": "Sort: Project",
}
def __init__(self, db, sync_host=None, parent=None):
super().__init__(parent)
self.db = db
self._sync_host = sync_host
self._sort_mode = "priority"
self._search_text = ""
self._entity_results: list[dict] = []
self._entity_seq_id = 0
self._entity_search_lock = threading.Lock()
self._entity_search_running = False
self._pending_entity_search: tuple[int, str] | None = None
self._pre_search_tab: int | None = None # tab to restore after search clears
self._active_filters = {"priority": set(), "due": set(), "project": set()}
self._excluded_filters = {"priority": set(), "due": set(), "project": set()}
self._minus_mode = False
self._filter_chips = {}
self._last_projects = None
self._project_cache_time: float = 0.0 # monotonic time of last project query
self._filtered_cache: dict[str, list] = {} # lazy tab rendering cache
self._search_engine = db.search_engine
self._premium_tray_extension = maybe_load_task_tray_extension(
server_name="sqlite-task-tray"
)
self._design_button_visible = False
self.setWindowTitle("Task Manager \u2014 SQLite Memory")
self.resize(800, 600)
primary = QApplication.primaryScreen()
if primary:
screen = primary.availableGeometry()
self.move(screen.center() - self.rect().center())
self._settings = QSettings("TaskTray", "FullWindow")
geometry = self._settings.value("geometry")
if geometry:
self.restoreGeometry(geometry)
# Restore appearance settings (mutate tray_dialogs module globals)
_td._theme_name = self._settings.value("theme", "blue")
if _td._theme_name not in _THEMES:
_td._theme_name = "blue"
_td._font_size = int(self._settings.value("font_size", 13))
_td._bold = self._settings.value("bold", "false") == "true"
_update_theme_colors()
self.setStyleSheet(_build_main_style())
# Central widget with tabs
self.tabs = QTabWidget()
self.setCentralWidget(self.tabs)
self._SORT_MODES = tuple(self._SORT_MODES)
self._SORT_LABELS = dict(self._SORT_LABELS)
if self._premium_tray_extension:
for mode, label in self._premium_tray_extension.extra_sort_modes.items():
if mode not in self._SORT_LABELS:
self._SORT_MODES = (*self._SORT_MODES, mode)
self._SORT_LABELS[mode] = label
# Tab order: Suggested, Today, Inbox, Next, Notes, All, Done
self._tab_keys = [
"suggested",
"today",
"inbox",
"next",
"projects",
"notes",
"all",
"done",
]
if self._premium_tray_extension:
self._tab_keys.insert(1, self._premium_tray_extension.tab_key)
self._tab_labels = {
"suggested": "Suggested",
"today": "Today",
"inbox": "Inbox",
"next": "Next",
"projects": "Projects",
"notes": "Notes",
"all": "All",
"done": "Done",
}
if self._premium_tray_extension:
self._tab_labels[self._premium_tray_extension.tab_key] = (
self._premium_tray_extension.tab_label
)
self.tab_lists = {}
for key in self._tab_keys:
lw = TaskListWidget(self.db)
lw._search_engine = self._search_engine
lw.itemChanged.connect(lambda item, k=key: self._on_item_changed(item))
self.tab_lists[key] = lw
self.tabs.addTab(lw, self._tab_labels[key])
# B1: Per-tab view state dict (sort + filters per tab)
self._tab_views = {
key: copy.deepcopy(_DEFAULT_TAB_VIEW) for key in self._tab_keys
}
if self._premium_tray_extension:
premium_key = self._premium_tray_extension.tab_key
if premium_key in self._tab_views:
self._tab_views[premium_key]["params"] = self._normalize_tab_params(
premium_key,
self._premium_tray_extension.default_params,
)
self._current_tab_idx = 0 # track for state swapping on tab change
# B2: Restore per-tab state from QSettings
parsed = {}
try:
raw_views = self._settings.value("tab_views", "{}")
parsed = json.loads(raw_views) if isinstance(raw_views, str) else {}
for key, view in parsed.items():
if key in self._tab_views:
if view.get("sort") in self._SORT_MODES:
self._tab_views[key]["sort"] = view["sort"]
self._tab_views[key]["active"] = _normalize_filter_payload(
view.get("active", {})
)
self._tab_views[key]["excluded"] = _normalize_filter_payload(
view.get("excluded", {})
)
self._tab_views[key]["params"] = self._normalize_tab_params(
key, view.get("params", {})
)
except (json.JSONDecodeError, TypeError, ValueError, AttributeError):
pass
# Set working state from the initial tab
self._saved_active_tab = int(self._settings.value("active_tab", 0))
initial_key = self._tab_keys[
min(self._saved_active_tab, len(self._tab_keys) - 1)
]
if initial_key in self._tab_views:
v = self._tab_views[initial_key]
self._sort_mode = v["sort"]
self._active_filters = v["active"]
self._excluded_filters = v["excluded"]
# First-run recovery: if QSettings has no tab_views, try bridge profile
if self._settings.value("tab_views") is None:
self._restore_profile_from_bridge()
# Restore saved active tab
self.tabs.setCurrentIndex(min(self._saved_active_tab, len(self._tab_keys) - 1))
self._current_tab_idx = self.tabs.currentIndex()
self.tabs.currentChanged.connect(self._on_tab_changed)
# Toolbar: actions + search + sort
toolbar = QToolBar()
toolbar.setMovable(False)
add_action = QAction("+ Add Task", self)
add_action.triggered.connect(self._add_task)
toolbar.addAction(add_action)
refresh_action = QAction("Refresh + Sync", self)
refresh_action.triggered.connect(self._refresh_and_sync)
toolbar.addAction(refresh_action)
toolbar.addSeparator()
# ── Intelligence v2 enrich buttons (amber→orange→red gradient) ──
for obj_name, label, depth in [
("enrich_quick", "\u26a1 Quick", "quick"),
("enrich_standard", "\U0001f52c Std", "standard"),
("enrich_deep", "\U0001f9e0 Deep", "deep"),
]:
btn = QToolButton()
btn.setText(label)
btn.setObjectName(obj_name)
btn.setToolTip(f"Enrich context: {depth}")
btn.clicked.connect(lambda checked, d=depth: self._run_enrich(d))
toolbar.addWidget(btn)
toolbar.addSeparator()
# Instant search bar (debounced 300ms)
self._search_input = QLineEdit()
self._search_input.setObjectName("search")
self._search_input.setPlaceholderText("Search tasks...")
self._search_input.setClearButtonEnabled(True)