Team Hoa, EPIC R08 (UI/Application Separation) - Team Hoa scope only
(R08-T11 -> T14; R08-T01->T10 belong to Team Duy/Team Nam).
- R08-T11: ui/schedule_task_tab.py (795 lines) -> presentation/scheduling/
{kanban_board_widget,calendar_view_widget,ai_task_creator_dialog,
ai_task_import_dialog,run_history_dialog}.py + schedule_task_tab.py
shell. Kanban CRUD/drag-drop now goes through
application/scheduling/task_application_service.py (R07-T04) instead of
~30 lines of inline if/elif per drag target.
- R08-T12: ui/folder_tab.py (1587 lines, the largest of the four) ->
presentation/folder/{workspace_file_tree,document_preview_manager,
code_editor,office_document_renderer,ai_file_editor_dialog,
ai_edit_model_resolver,ai_edit_pipeline}.py + folder_tab.py shell.
Closes the R06-T05 loop: FileWorkspaceService existed since R06 with
zero production call sites (confirmed by grep); every plain-text write
(save/create/write_content) now goes through it, gaining path
containment and a Python-syntax warning the original code never had.
Pure helpers (_read_text, _is_probably_text, _pptx_available,
_split_code_block, _parse_ai_output) moved to
application/workspaces/{file_preview_helpers,ai_edit_output}.py.
- R08-T13: ui/dashboard_tab.py (437 lines) -> presentation/dashboard/
{token_usage_card_widget,usage_chart_widget,habits_widget}.py +
dashboard_tab.py shell, backed by a new
application/monitoring/dashboard_query_service.py (pricing/period/
summary queries the three widgets used to each recompute separately).
Directory-ownership note left in the checklist for Team Nam.
- R08-T14: ui/structure_graph_view.py (1035 lines) ->
presentation/graph/{graph_scene_items,graph_renderer,
graph_messages_view,graph_qa_widget}.py + structure_graph_view.py
shell. Extraction helpers (_pdf_to_markdown, _extract_file_contents)
moved to application/workspaces/graph_index_service.py (pure Python).
Renderer and Q&A panel talk only through signals
(node_selected/graph_rendered/raw_json_ready/project_changed) - neither
imports the other.
- presentation/shared/web_engine_support.py: HAS_WEB_ENGINE, previously
duplicated (folder_tab imported it FROM structure_graph_view.py) - now
one shared flag instead of one screen importing another screen's module.
All four old ui/*.py files deleted; app.py and ui/workspace_tab.py updated
to the new import paths (each god-file only had 1-2 real construction
sites, so import sites were updated directly rather than kept as a
strangler-fig shim - unlike core/tools.py at R05, which had dozens).
pytest: 377 pass (+94 vs the R07 baseline of 328; same 4 pre-existing
failures as the R05/R06 baseline, unrelated to this work).
scripts/check_imports.py: PASS. python -c "import cowork_local.app": OK.
Every new file < 400 lines (largest: graph_renderer.py, 391).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
180 lines
7.9 KiB
Python
180 lines
7.9 KiB
Python
"""UsageChartWidget — the period pager + granularity/metric/currency
|
|
controls + spline chart of the Dashboard (R08-T13, extracted from
|
|
``ui/dashboard_tab.py::DashboardTab``, lines 53-114/143-152/201-207/
|
|
263-323 of the original 437-line file).
|
|
|
|
Owns the period SELECTOR (granularity + prev/next offset) that the whole
|
|
screen follows — ``token_usage_card_widget.py`` and ``habits_widget.py``
|
|
read :meth:`period_range`/:meth:`granularity` rather than keeping their own
|
|
copy, and the shell re-refreshes them on :attr:`period_changed`.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Tuple
|
|
|
|
from PySide6.QtCore import Qt, Signal
|
|
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
|
|
|
|
from cowork_local.application.monitoring import DashboardQueryService
|
|
from cowork_local.i18n import tr
|
|
from cowork_local.theme import current_palette
|
|
from cowork_local.ui.icons import icon
|
|
from cowork_local.ui.spline_chart import SplineChart
|
|
from cowork_local.ui.widgets import fmt_tokens
|
|
|
|
|
|
class UsageChartWidget(QWidget):
|
|
period_changed = Signal() # granularity or offset changed — re-run every widget
|
|
currency_changed = Signal() # display currency changed — same, cost text depends on it
|
|
|
|
def __init__(self, ctx, query: DashboardQueryService, parent=None):
|
|
super().__init__(parent)
|
|
self.ctx = ctx
|
|
self._query = query
|
|
self._chart_offset = 0 # 0 = current period; <0 = a past period
|
|
|
|
root = QVBoxLayout(self)
|
|
root.setContentsMargins(0, 0, 0, 0)
|
|
controls = QHBoxLayout()
|
|
controls.setSpacing(6)
|
|
self.chart_prev_btn = QPushButton()
|
|
self.chart_prev_btn.setIcon(icon("chevron-left"))
|
|
self.chart_prev_btn.setFixedWidth(30)
|
|
self.chart_prev_btn.clicked.connect(self._chart_prev)
|
|
controls.addWidget(self.chart_prev_btn)
|
|
self._chart_period_lbl = QLabel()
|
|
self._chart_period_lbl.setObjectName("hint")
|
|
self._chart_period_lbl.setAlignment(Qt.AlignCenter)
|
|
self._chart_period_lbl.setMinimumWidth(170)
|
|
controls.addWidget(self._chart_period_lbl)
|
|
self.chart_next_btn = QPushButton()
|
|
self.chart_next_btn.setIcon(icon("chevron-right"))
|
|
self.chart_next_btn.setFixedWidth(30)
|
|
self.chart_next_btn.clicked.connect(self._chart_next)
|
|
controls.addWidget(self.chart_next_btn)
|
|
controls.addSpacing(12)
|
|
self.gran_combo = QComboBox()
|
|
for g in ("week", "month", "year"):
|
|
self.gran_combo.addItem(tr(f"dashboard.gran_{g}"), g)
|
|
self.gran_combo.currentIndexChanged.connect(self._on_gran_changed)
|
|
controls.addWidget(self.gran_combo)
|
|
self.metric_combo = QComboBox()
|
|
for m in ("cost", "tokens"):
|
|
self.metric_combo.addItem(tr(f"dashboard.metric_{m}"), m)
|
|
self.metric_combo.currentIndexChanged.connect(self.refresh)
|
|
controls.addWidget(self.metric_combo)
|
|
controls.addStretch(1)
|
|
# Display-currency picker — both Dashboard and Monitoring read/write
|
|
# the same usage.currency config key, so changing it here updates
|
|
# cost text everywhere.
|
|
self.currency_lbl = QLabel()
|
|
self.currency_lbl.setObjectName("hint")
|
|
controls.addWidget(self.currency_lbl)
|
|
self.currency_combo = QComboBox()
|
|
from cowork_local.core import usage_tracker as ut
|
|
for cur in ut.SUPPORTED_CURRENCIES:
|
|
self.currency_combo.addItem(cur, cur)
|
|
idx = self.currency_combo.findData(
|
|
(self.ctx.config.data.get("usage") or {}).get("currency", "USD"))
|
|
self.currency_combo.setCurrentIndex(max(0, idx))
|
|
self.currency_combo.currentIndexChanged.connect(self._on_currency_changed)
|
|
controls.addWidget(self.currency_combo)
|
|
root.addLayout(controls)
|
|
|
|
chart_head = QHBoxLayout()
|
|
self._chart_title = QLabel()
|
|
self._chart_title.setStyleSheet("font-weight:600;")
|
|
chart_head.addWidget(self._chart_title, 1)
|
|
root.addLayout(chart_head)
|
|
self.chart = SplineChart()
|
|
root.addWidget(self.chart)
|
|
|
|
self.retranslate()
|
|
|
|
def retranslate(self) -> None:
|
|
self.currency_lbl.setText(tr("monitoring.overview_currency"))
|
|
self.currency_combo.setToolTip(tr("dashboard.currency_tooltip"))
|
|
self._chart_title.setText(tr("dashboard.chart_title"))
|
|
self.chart_prev_btn.setToolTip(tr("dashboard.chart_prev"))
|
|
self.chart_next_btn.setToolTip(tr("dashboard.chart_next"))
|
|
|
|
# ---- public: the period selector every other widget follows ------------- #
|
|
def granularity(self) -> str:
|
|
return self.gran_combo.currentData() or "week"
|
|
|
|
@property
|
|
def chart_offset(self) -> int:
|
|
return self._chart_offset
|
|
|
|
def period_range(self) -> Tuple:
|
|
return self._query.period_range(self.granularity(), self._chart_offset)
|
|
|
|
# ---- navigation ------------------------------------------------------------ #
|
|
def _on_gran_changed(self, *_a) -> None:
|
|
self._chart_offset = 0 # period size changed → back to current
|
|
self.period_changed.emit()
|
|
|
|
def _chart_prev(self) -> None:
|
|
self._chart_offset -= 1
|
|
self.period_changed.emit()
|
|
|
|
def _chart_next(self) -> None:
|
|
self._chart_offset = min(0, self._chart_offset + 1) # never past the present
|
|
self.period_changed.emit()
|
|
|
|
def _on_currency_changed(self, _idx: int) -> None:
|
|
cur = self.currency_combo.currentData()
|
|
if not cur:
|
|
return
|
|
self.ctx.config.data.setdefault("usage", {})["currency"] = cur
|
|
self.ctx.save()
|
|
self.currency_changed.emit()
|
|
|
|
@staticmethod
|
|
def _delta_txt(cur: float, prev: float) -> str:
|
|
"""▲/▼ percent change of ``cur`` vs ``prev`` (empty if no baseline)."""
|
|
if not prev:
|
|
return ""
|
|
pct = (cur - prev) / prev * 100
|
|
arrow = "▲" if pct > 0.5 else ("▼" if pct < -0.5 else "•")
|
|
return f"{arrow}{abs(pct):.0f}%"
|
|
|
|
# ---- rendering --------------------------------------------------------------- #
|
|
def refresh(self, *_a) -> None:
|
|
"""Break the SELECTED period into its parts: WEEK -> 7 days (Mon-Sun)
|
|
- MONTH -> weeks W1..Wn - YEAR -> 12 months. A dashed line marks the
|
|
previous same-granularity period's average per point with the %
|
|
change of the totals."""
|
|
from cowork_local.core import usage_tracker as ut
|
|
|
|
gran = self.granularity()
|
|
metric = self.metric_combo.currentData() or "cost"
|
|
pts = self._query.chart_series(gran, self._chart_offset, metric)
|
|
pricing = self._query.pricing()
|
|
mi = 0 if metric == "tokens" else 1
|
|
# Compact cost format (2 decimals, K/M above 1,000/1,000,000) — the
|
|
# chart's y-axis label box is narrow; format_cost's full precision
|
|
# overflowed it, clipping/obscuring the amount.
|
|
fmt = fmt_tokens if metric == "tokens" else (lambda v: ut.format_cost_compact(v, pricing))
|
|
|
|
cur = self._query.period_totals(gran, self._chart_offset)
|
|
prev = self._query.period_totals(gran, self._chart_offset - 1)
|
|
ref_key = {"week": "dashboard.ref_last_week",
|
|
"month": "dashboard.ref_last_month",
|
|
"year": "dashboard.ref_last_year"}.get(gran, "dashboard.ref_last_week")
|
|
n_points = max(1, len(pts))
|
|
refs = []
|
|
if prev[mi] > 0:
|
|
# Muted on purpose: the comparison line is a reference, not the
|
|
# series — it must not compete with the accent-coloured spline.
|
|
refs.append((prev[mi] / n_points,
|
|
f"{tr(ref_key)} {self._delta_txt(cur[mi], prev[mi])}",
|
|
current_palette().text_muted))
|
|
self.chart.set_reference_lines(refs)
|
|
self.chart.set_data(pts, fmt, tr(f"dashboard.metric_{metric}"))
|
|
self._chart_period_lbl.setText(self._query.period_range_label(gran, self._chart_offset))
|
|
self.chart_next_btn.setEnabled(self._chart_offset < 0)
|
|
|
|
|
|
__all__ = ["UsageChartWidget"]
|