Files
cowork-local/presentation/shell/session_events.py
T
Nam Pham Dinh ThanhandClaude Opus 5 70a0c2fdcf refactor(shell): R08-T10 xong — app.py 1293 -> 128, MainWindow tách thành 11 file
Đây là deliverable còn thiếu duy nhất trong 17 task của Gamma.

    app.py                     128   chỉ còn điểm vào chương trình
    presentation/shell/
      main_window.py           362   __init__ + vòng đời cửa sổ
      nav_rail.py              385   dựng rail + cây điều hướng + thu gọn
      top_bar.py               234   thanh trên + tài khoản + đáy rail
      session_events.py        104   lịch sử, thông báo task xong
      page_registry.py          82   4 màn chính, dựng lười, _goto
      rail_project.py          132   bộ chọn project + RECENTS
      lifecycle_coordinator.py 110   canh màn hình + tắt sạch
      tray_manager.py           76   khay hệ thống
      toast.py                  40   thông báo góc trên trái
      bootstrap.py              42   Composition Root
      branding.py               26   ASSETS + app_icon
      rail_metrics.py           37   kích thước rail + cách vẽ hàng

Mọi file dưới 400 dòng. Đây là ngưỡng CASAN Check 2.

NÓI THẲNG VỀ CÁCH TÁCH: sáu file trong đó là MIXIN, không phải widget rời.
Cả loạt phương thức đọc/ghi state của cửa sổ (self._page_widgets, self.workspace,
self.splitter...). Biến thành đối tượng cộng tác thì phải viết lại từng chỗ
self.X thành self.window.X — gần 800 dòng sửa chỉ để đổi cách gọi, rủi ro cao
mà không đổi hành vi. Mixin cho đúng thứ đang cần: mỗi mảng một file, ai sửa
rail thì mở file rail. Chuyển thành widget thật khi có cửa sổ thứ hai cần dùng
lại — hiện chưa có.

Giữ đường vào cũ: MainWindow, app_icon, _NAV_*, _Toast vẫn import được từ
cowork_local.app, nên 24 checker trong tools/ không phải sửa.

BA LỖI TỰ GÂY TRONG LÚC TÁCH, ĐỀU DO CHECKER BẮT
-------------------------------------------------
1. 12 import lazy nằm trong thân hàm bị thụt lề nên regex đổi mức tương đối
   của tôi bỏ sót -> ModuleNotFoundError khi bấm vào rail.
2. Bộ dò import thiếu của tôi tính cả import cục bộ trong hàm KHÁC, nên tưởng
   QHBoxLayout đã có -> 17 checker đỏ. Bỏ cách dò, cấp thẳng khối import đầy
   đủ rồi cắt phần không dùng.
3. Hằng số ASSETS và _NAV_* nằm ở khối tôi không mang theo -> NameError.

Cả ba đều là lỗi im lặng với bộ test đơn vị (714 vẫn xanh suốt) và chỉ lộ khi
dựng cửa sổ thật. Đó chính là lý do bộ checker trong tools/ tồn tại.

Cập nhật 2 đích đột biến của check_probes_bite: mã nó cần sửa đã dời khỏi
app.py sang rail_project.py và nav_rail.py.

714 test xanh. 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 10:32:22 +09:00

105 lines
5.4 KiB
Python

"""Lịch sử hội thoại và thông báo khi task chạy xong — R08-T10.
Gom những gì phản ứng với việc **có chuyện xảy ra ở nơi khác**: một task đã lên
lịch chạy xong, một phiên được lưu, danh sách project đổi.
Điểm dễ sai đã ghi lại trong ``_on_scheduled_task_done``: tín hiệu
``task_started`` bắn TRƯỚC khi luồng chạy bắt đầu, lúc đó phiên chưa có trên
đĩa — làm mới Lịch sử ở đó thì không thấy gì. Phải bám ``history_ready``.
Cùng kiểu mixin, xem ghi chú ở đầu ``nav_rail.py``.
"""
from __future__ import annotations
from pathlib import Path
from PySide6.QtCore import Qt, QTimer
from ... import DISPLAY_NAME
from ...i18n import tr
from ...ui.workspace_tab import WorkspaceTab
class SessionEventsMixin:
def _running_session_ids(self):
"""All conversation ids currently running — interactive Cowork/Code
chat tab AgentWorkers, plus Schedule Task runs (their own session,
tracked by the scheduler), so a task's live run gets the same
"running" marker in History an interactive chat gets."""
return set(self.cowork.running_session_ids()) | self.task_scheduler.running_session_ids()
def _refresh_history(self) -> None:
"""Rebuild the History list with the current conversation highlighted and
the running ones marked. Deferred to the next event-loop tick: this is often
triggered (via load_conversation) from inside the sidebar's own item-click
handler, and clearing the tree there would delete the item mid-click."""
from PySide6.QtCore import QTimer
def _do() -> None:
current = self.cowork.session_id
self.sidebar.set_view_state(current, self._running_session_ids())
self.sidebar.refresh()
self._refresh_rail_recents() # the rail shortcut follows the panel
QTimer.singleShot(0, _do)
def _on_scheduled_task_done(self, task_id: str, ok: bool) -> None:
"""Desktop notification for a finished scheduled task (toast always,
tray balloon when the window isn't focused), then refresh History —
cowork/co4e task runs just saved themselves as new sessions there."""
from ...core.tasks import load_task
task = load_task(task_id) or {}
title = task.get("title", "")
msg = (tr("app.toast.task_done", title=title) if ok
else tr("app.toast.task_failed", title=title))
self.toast.show_message(msg, ok=ok)
if (self.tray is not None
and self.ctx.config.data.get("tray", {}).get("notify_on_done", True)
and not self.isActiveWindow()):
self._tray.show_message(DISPLAY_NAME, msg, error=not ok)
self._refresh_history()
def _notify_task(self, tab, kind: str, result: dict) -> None:
"""Notify when a task finishes/fails (skip if more stages queued)."""
if tab.composer.has_queue():
return # a flow / queue is still running — notify only at the end
name = tr(f"app.tab.{kind}")
err = (result or {}).get("error")
# In-app popup at the top-left (shown whether or not the window is focused).
self.toast.show_message(
tr("app.toast.error", name=name) if err else tr("app.toast.done", name=name), ok=not err)
# System-tray balloon only when the window isn't the active one.
if self.tray is None:
return
if not self.ctx.config.data.get("tray", {}).get("notify_on_done", True):
return
if self.isActiveWindow():
return # user is looking at the window already
err = (result or {}).get("error")
title = tr("app.toast.error", name=name) if err else tr("app.toast.done", name=name)
body = (err if err else (tab._last_assistant_text() or "Task completed."))[:140]
self._tray.show_message(title, body, error=bool(err))
def _restore_sessions(self) -> None:
"""Reopen the last conversation per tab (recover after a crash/abrupt exit)."""
from pathlib import Path
from ...core.history import load_conversation
last = self.ctx.config.data.get("last_session", {})
path = last.get("cowork", "")
if path and Path(path).exists():
try:
self.cowork.load_conversation(load_conversation(path))
# Reflect the restored thread's project in the Workspace home
# (selecting the matching row won't wipe it — the project id
# already matches, so _bind_project starts no new session).
# Skip forcing the Cowork tab open for a project that no
# longer exists (deleted since this session was saved) — that
# would show the Cowork page while the tab strip still says
# "no project selected" (see WorkspaceTab._on_sidebar_open).
pid = self.cowork.project_id
if pid in ("", "default") or self.workspace._select_project_row(pid):
self.workspace._show_cowork_tab()
except Exception:
pass
def _on_projects_changed(self) -> None:
self.sidebar.refresh() # History regroups by project
self.cowork._apply_output_folder_label() # project may have been renamed
self.structure._refresh_project_combo() # GraphRAG's project lock list follows too