Files
cowork-local/app.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

129 lines
5.3 KiB
Python

"""
pages (Dashboard / Schedule / Workspace / Cowork / Structure) and top bar."""
from __future__ import annotations
import sys
from pathlib import Path
from typing import List
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QColor, QGuiApplication, QIcon
from PySide6.QtWidgets import (
QStyledItemDelegate,
QApplication, QComboBox, QHBoxLayout, QLabel, QMainWindow, QMenu,
QPushButton, QScrollArea, QSizePolicy, QSplitter, QStackedWidget,
QSystemTrayIcon, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout,
QWidget,
)
from . import APP_NAME, DISPLAY_NAME, __version__
from .config import PROVIDER_LABELS, AppConfig
from .i18n import LANGUAGE_SHORT, LANGUAGES, get_language, on_language_changed, set_language, tr
from .presentation.shell.bootstrap import build_context
from .presentation.shell.branding import app_icon
from .presentation.shell.main_window import MainWindow
# Các checker trong tools/ và mã cũ vẫn import mấy tên này từ cowork_local.app.
# Giữ đường vào cũ để việc bóc tách không kéo theo sửa 24 file checker; nơi ở
# thật của chúng nay là presentation/shell/.
from .presentation.shell.rail_metrics import ( # noqa: E402,F401
_NAV_COLLAPSED_WIDTH, _NAV_EXPANDED_WIDTH, _NAV_MAX_CEILING, _NAV_MAX_SHARE,
_NAV_MIN_WIDTH, _NAV_ROW_GAP, _NAV_ROW_INSET, _NavItemDelegate,
)
from .presentation.shell.toast import Toast as _Toast # noqa: E402,F401
from .presentation.shell.lifecycle_coordinator import LifecycleCoordinator
from .presentation.shell.tray_manager import TrayManager
from .state import AppContext
from .ui.widgets import tidy_popup
from .theme import current_palette, set_active_theme, stylesheet
from .core.task_scheduler import TaskScheduler
from .ui.cowork_tab import CoworkTab
from .ui.dashboard_tab import DashboardTab
from .ui.monitoring_tab import MonitoringTab
from .ui.schedule_task_tab import ScheduleTaskTab
from .ui.settings_dialog import SettingsDialog
from .ui.sidebar import HistorySidebar
from .ui.structure_graph_view import StructureGraphView
from .ui.workspace_tab import WorkspaceTab
def _set_windows_app_id() -> None:
"""Make Windows use our window icon on the taskbar (not python.exe's)."""
if sys.platform != "win32":
return
try:
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("FPT.CoworkLocal.2.0")
except Exception:
pass
def run(argv: List[str] | None = None) -> int:
argv = argv if argv is not None else sys.argv
_set_windows_app_id()
app = QApplication.instance() or QApplication(argv)
app.setApplicationName(APP_NAME)
app.setWindowIcon(app_icon())
# Composition Root: presentation/shell/bootstrap.py quyết định app chạy
# bằng mảnh nào. Từ R02, đó là JsonConfigRepository + kho bí mật của hệ
# điều hành, không còn config.py::AppConfig.
ctx = build_context()
set_language(ctx.config.language)
# Built-in default skills (if any are bundled) are always-on and loaded
# straight from the package; tidy away any copy seeded by older versions so they
# stay hidden from the Skills manager.
try:
from .core.skills import prune_seeded_builtins
prune_seeded_builtins()
except Exception: # noqa: BLE001 - housekeeping must never block startup
pass
# Seed the bundled built-in skill library + the built-in Co4E flow into the
# user's editable stores on first run, so they show up in the Skill Manager
# and the Flow sidebar out-of-the-box (a user-deleted one is not re-seeded).
try:
from .core.skills import seed_library_skills
from .core.co4e_builtins import seed_builtin_flows
changed = False
# Content-versioned: returns the full tag list to persist (delivers updates
# to shipped skills, preserves user edits to unchanged ones, respects deletion).
skill_tags = seed_library_skills(ctx.config.seeded_library_skills)
if set(skill_tags) != set(ctx.config.seeded_library_skills):
ctx.config.seeded_library_skills = skill_tags
changed = True
new_flows = seed_builtin_flows(ctx.config.seeded_builtin_flows)
if new_flows:
ctx.config.seeded_builtin_flows = ctx.config.seeded_builtin_flows + new_flows
changed = True
if changed:
ctx.config.save()
except Exception: # noqa: BLE001 - seeding must never block startup
pass
set_active_theme(ctx.config.theme)
app.setStyleSheet(stylesheet(ctx.config.theme))
# Follow the OS light/dark scheme live when theme is "Auto (System)".
import socket
from .core import audit_log, usage_tracker
machine = socket.gethostname()
usage_tracker.set_identity("local", machine, "")
audit_log.set_identity("local", machine, "admin", "")
win = MainWindow(ctx, user_name="local")
def _reapply_system_theme(*_a):
if ctx.config.theme == "system":
set_active_theme("system")
app.setStyleSheet(stylesheet("system"))
win.cowork.apply_theme()
try:
app.styleHints().colorSchemeChanged.connect(_reapply_system_theme)
except Exception:
pass
win.show()
return app.exec()