Compare commits

...
Author SHA1 Message Date
huongltt35 95b3b27578 feat(R10): implement CI Quality Gates, Contributor Recipes, E2E Smoke Tests, and update docs 2026-08-28 11:08:53 +09:00
huongltt35 b8783526d0 feat(R08): finalize Chat UI Hub components, AudioRecorderWidget, and integration tests (100% PASS) 2026-08-28 10:45:43 +09:00
huongltt35 1de3336970 merge: merge origin/feature/teamhoa/r05-r06 (R07/R08) into feature/delta-team/epic-R04 2026-08-28 10:32:38 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 7e11e9676d refactor: nốt 3 chỗ R08 còn thiếu — ChatPanel và 2 tab admin về đúng chỗ
Soát lại từng dòng plan thì thấy tôi báo R08 xong hơi sớm. Ba chỗ thiếu thật:

  T06  ChatPanel vẫn ở ui/, plan đòi presentation/chat/chat_panel.py
  T08  agents_admin_tab.py (498) và tools_admin_tab.py (245) vẫn ở ui/

    presentation/chat/chat_panel.py                    346
    presentation/monitoring/tabs/agents_admin_tab.py   383
    presentation/monitoring/tabs/agent_edit_dialog.py  143
    presentation/monitoring/tabs/tools_admin_tab.py    245
    ui/chat_panel.py / agents_admin_tab.py / tools_admin_tab.py  ~10 mỗi cái

agents_admin_tab.py 498 dòng nên tách thêm agent_edit_dialog.py: bảng danh
sách và hộp thoại sửa là hai việc, và hộp thoại còn tự đi hỏi provider xem có
model nào — thứ bảng không cần biết.

BA CHỖ CÒN LẠI KHÔNG PHẢI THIẾU, đã kiểm từng cái:
* audio_recorder_widget.py (T04) — repo KHÔNG có chức năng ghi âm nào.
* connector_settings_widget.py (T07) — UI Connector đã dời khỏi Cài đặt.
* sandbox_status_tab.py / mcp_history_tab.py (T08) — Hiệp đặt tên sandbox_tab
  và mcp_tab, nội dung đủ.

R08: 14/14 task, 0 file thiếu thật sự.
756 test xanh. 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 01:24:45 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 fdaedfa1c2 refactor(chat): tách nốt phần nối lại lượt đang chạy — chat_session_store 414 -> 352
chat_live_turns.py (90 dòng) là phần tinh tế nhất của khung chat: người dùng
mở phiên khác rồi quay lại trong khi lượt cũ vẫn đang chạy. Phải nối vào đúng
luồng đó và đúng danh sách tin nhắn đang sống, chứ không đọc bản trên đĩa (đã
cũ) hay khởi động lại. Sai thì hoặc mất phần agent viết lúc mình vắng mặt,
hoặc hai bên cùng ghi vào một file.

Giờ Gamma không còn file production nào vượt 400 dòng.

756 test xanh.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 01:11:22 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 577b81a641 refactor(chat): R08-T01..T06 — chat_panel.py 1821 -> 345, composer 663 -> 11
presentation/chat/
      chat_history_widget.py   348  T01  mạch hội thoại (từ ui/chat_view.py)
      chat_bubble_style.py     202  T01  cách vẽ bong bóng, diff, đường thời gian
      composer_widget.py       364  T02  thanh công cụ quanh ô nhập
      chat_input_box.py        328  T02  ô nhập: Ctrl+Enter, dán ảnh, popup /skill
      attachment_picker.py     215  T03  đọc tệp đính kèm + chặn theo chính sách
      chat_output_panel.py     186  T05  theo dõi thư mục output, hiện tệp mới
      chat_turn_runner.py      281  T06  chạy một lượt
      chat_event_stream.py     228  T06  nhận sự kiện phát về từ luồng nền
      chat_session_store.py    413  T06  lưu/nạp phiên, đếm token, nối lại lượt
      chat_agents.py           246  T06  chọn agent, skill, định tuyến model
      chat_panel_layout.py     148  T06  bố cục hai cột
      chat_helpers.py           53  T06  hàm và bảng tra dùng chung
    ui/chat_panel.py           345  __init__ + trạng thái
    ui/chat_view.py             10  vỏ chuyển tiếp
    ui/composer.py              11  vỏ chuyển tiếp

R08-T04 KHÔNG LÀM ĐƯỢC: plan đòi audio_recorder_widget.py, nhưng trong repo
KHÔNG CÓ chức năng ghi âm nào — grep 'audio|record|voice|micro' toàn ui/ chỉ
ra chữ 'record' trong nghĩa 'ghi lại transcript'. Không có gì để tách, và tôi
không dựng một widget mới nhân danh refactor. Giống hệt trường hợp
connector_settings_widget.py ở T07.

_start_turn (144 dòng) và _on_event (127) để nguyên có chủ ý: cái đầu dựng
trọn ngữ cảnh một lượt rồi giao cho luồng nền, cái sau phân nhánh theo loại sự
kiện. Cắt nhỏ thì phải chuyền hàng chục biến trạng thái qua lại, đọc khó hơn.

Hai lỗi tự gây, cả hai đều do script:
* regex bỏ import cũ chỉ cắt DÒNG ĐẦU của một import nhiều dòng, để lại phần
  đuôi mồ côi -> IndentationError.
* _build_layout dùng biến 'root' vốn cục bộ trong __init__. Bộ test bắt được
  cái này (2 bài integration đỏ), không phải checker — vì nó là lỗi dựng
  widget, không phải lỗi hình học.

756 test xanh. 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 01:08:31 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 f0fd3a41cd refactor(folder): R08-T12 — folder_tab.py 1589 -> 305, tách 8 file
presentation/folder/
      ai_edit_runner.py            325  một lượt AI sửa file, từ gửi tới xem trước
      document_preview_manager.py  317  PDF/Word/Excel/PowerPoint/ảnh/HTML/mã
      ai_file_editor_dialog.py     317  dựng panel AI + chọn model
      code_editor.py               183  ô soạn mã, đánh số dòng, tô cú pháp
      ai_output_writer.py          140  phần DUY NHẤT chạm vào file người dùng
      image_model_picker.py        115  dò model sinh ảnh trên mọi provider
      file_helpers.py              112  nhận dạng loại file + ngưỡng
      workspace_file_tree.py        38  cây thư mục
    ui/folder_tab.py               305  lắp ráp + retranslate

Plan ghi 3 file; khối lượng thật cần 8. Hai file tôi thêm ngoài dự kiến vì
đọc kỹ thì chúng là ranh giới thật:

* ai_output_writer.py — tách ra vì đây là phần duy nhất THẬT SỰ ghi đè file
  của người dùng. Mọi thứ trước nó chỉ dựng bản xem trước. Ranh giới đó đáng
  nhìn thấy trong cấu trúc thư mục.
* image_model_picker.py — chỗ duy nhất trong màn Thư mục biết tới nhiều
  provider cùng lúc (nó gợi ý được model sinh ảnh của provider KHÁC cái đang
  chọn).

Gom mọi hằng nhận dạng loại file (_IMAGE_SUFFIXES, _HAS_PDF, _MAX_EDIT_BYTES…)
về file_helpers.py: cả tám file trong gói đều hỏi tới, để rải ra thì thêm một
đuôi file phải sửa vài chỗ.

LẠI IMPORT LAZY THỤT LỀ: regex đổi mức tương đối của tôi chỉ khớp đầu dòng
nên bỏ sót import nằm trong thân hàm — 3 checker đỏ. Lần này tôi sửa một lượt
cho CẢ cây presentation/ thay vì riêng thư mục vừa tách; nó tìm ra thêm 3 file
ở scheduling cũng đang sai mà chưa nổ.

756 test xanh. 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 23:23:06 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 982fecc8dc refactor(scheduling): R08-T11 — schedule_task_tab.py 794 -> 297, tách 6 file
presentation/scheduling/
      calendar_view_widget.py    231  lịch tháng (chuyển từ ui/calendar_view.py)
      ai_task_creator_dialog.py  208  tạo task bằng AI
      task_actions.py            189  thêm/sửa/chạy/xoá/xem log một task
      kanban_board_widget.py      98  cột Kanban + vùng thả file
      run_history_dialog.py       82  lịch sử các lượt chạy
      ai_task_import_dialog.py    81  nhập task từ file
    ui/schedule_task_tab.py      297  dựng bảng + đổi chế độ xem
    ui/calendar_view.py           10  vỏ chuyển tiếp

Plan ghi 4 file; thực tế cần 6. Hai file thêm là run_history_dialog.py và
task_actions.py — không tách thì schedule_task_tab.py còn 517 dòng, vẫn vượt
ngưỡng 400.

ai_task_import_dialog.py làm mixin chứ không phải hộp thoại rời: plan gọi nó
là dialog, nhưng thực tế nó là TAB THỨ HAI của cùng hộp thoại tạo task, dùng
chung phần xem trước và nút Xác nhận. Tách hẳn thì phải nhân đôi cả hai.

LẠI LỖI DECORATOR: script này tôi quên dùng bản có tính dòng @, nên một
@staticmethod bị bỏ lại mồ côi -> IndentationError. Đây là lần thứ tư cùng
một lỗi. Đã thêm bước dọn decorator mồ côi vào script.

756 test xanh. 16 checker chạy đều qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 22:54:50 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 4fef41481b refactor(graph): R08-T14 — structure_graph_view.py 1034 -> 11, tách 6 file
presentation/graph/
      structure_graph_view.py  325  lớp chính + dựng giao diện
      graph_qa_widget.py       322  hỏi-đáp trên đồ thị (_ask 119 dòng)
      graph_render.py          226  quét, vẽ Qt + D3, xuất ảnh
      graph_scene.py           138  node, cạnh, khung nhìn — thuần đồ hoạ
      graph_project.py         109  chọn project, đổi tab xem
      graph_web.py              38  cờ có dùng được QtWebEngine không
    ui/structure_graph_view.py  11  vỏ chuyển tiếp, giữ đường import cũ

BA LẦN CẮT HỎNG, ĐỀU LÀ TÊN CẤP MODULE BỊ BỎ LẠI
------------------------------------------------
_HAS_WEB, QWebEngineView, QWebChannel, _Bridge, _Edge, _Node — tất cả định
nghĩa ở file gốc, dùng ở file mới, nên NameError ngay lúc chạy. Bộ test đơn
vị KHÔNG bắt được cái nào: 756 bài vẫn xanh suốt ba lần. Chỉ
check_graphrag_rescan bắt, vì nó gọi prewarm() thật rồi chờ đồ thị dựng xong.

Sau lần thứ ba tôi bỏ cách đuổi từng lỗi và viết bộ dò tên chưa định nghĩa có
tính đến phạm vi hàm (tham số, biến cục bộ, except-as, comprehension). Nó
tìm ra nốt _fmt_plan và _qcolor còn thiếu ở hai file Co4E đã tách hôm trước —
hai quả mìn chưa nổ.

_HAS_WEB tách hẳn ra graph_web.py: cả structure_graph_view.py lẫn
graph_render.py đều phải hỏi, để ở một trong hai là vòng import.

756 test xanh. 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 22:45:25 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 062ea4ba21 refactor(dashboard): R08-T13 — dashboard_tab.py 438 -> 215, tách 3 widget
token_usage_card_widget.py    93   5 thẻ số liệu + thẻ Ngân sách
    usage_chart_widget.py        119   biểu đồ tuần/tháng/năm + đường so sánh
    habits_widget.py             171   thói quen dùng token + nhận xét của AI

Ba widget THẬT, không phải mixin — khác với shell và Co4E, ba mảng này tách
bạch trên màn hình và không đọc state của nhau. Giao tiếp bằng signal:
budget_applied, filter_changed, status_message.

Điểm cần biết: các nút lật khoảng và hai ô chọn thuộc về UsageChartWidget
nhưng được Dashboard nhấc lên hàng điều khiển ở trên. Chúng là control của
biểu đồ, chỉ hiển thị ở chỗ khác.

Giữ 18 cầu tương thích cho tên cũ vì check_dashboard, check_design_parity và
check_controls_alive đọc thẳng self.card_total, self._chart_period_lbl...

756 test xanh. check_dashboard, check_design_parity, check_controls_alive qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 22:05:48 +09:00
vudt15andClaude Sonnet 5 a8c6b5c20a docs(refactor): merge Team Hoa R05/R06 and R07/R08 reports into one
Replaces BaoCao_TeamHoa_R05_R06.md and BaoCao_TeamHoa_R07_R08.md with a
single BaoCao_TeamHoa_R05_R08.md covering all 4 EPICs (19/19 tasks) in
Team Hoa's scope, and updates the checklist's report links accordingly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 21:06:18 +09:00
vudt15andClaude Sonnet 5 1efa1d29d1 docs(refactor): add the Team Hoa completion report for R07/R08
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 20:58:08 +09:00
vudt15andClaude Sonnet 5 0e51356a7d feat(R08): split ScheduleTaskTab, FolderTab, DashboardTab, StructureGraphView
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>
2026-08-27 20:55:32 +09:00
vudt15andClaude Sonnet 5 69ab8e125b feat(R07): task repository, schedule calculator, Qt clock adapter, task/AI-planner services
Team Hoa, EPIC R07 (Scheduling & Workflow Runtime) - Team Hoa scope only
(R07-T01 -> T05; R07-T06 Co4EWorkflowService is Team Nam's).

- R07-T01: infrastructure/persistence/json/task_repository_impl.py wraps
  core/tasks.py's CRUD; core/tasks.py::save_task now writes through
  atomic_write.write_json (same durability fix as R06-T02, save_task was
  still doing a plain write_text).
- R07-T02: domain/tasks/schedule_calculator.py::ScheduleCalculator - the
  cron/interval/daily/weekly/monthly due-time math extracted from
  core/tasks.py, pure Python with is_holiday/make_cron injected so domain/
  never imports core (ADR-001 I2). core/tasks.py keeps its old function
  names as thin wrappers so every existing caller is unchanged. This was
  previously untested; now has its own unit suite.
- R07-T03: infrastructure/qt/qt_scheduler_clock.py::QtSchedulerClock wraps
  the QTimer TaskScheduler used to own directly, injected via a new
  `clock=` constructor param (defaults to a real one). Originally planned
  at platform/qt/... ; moved after confirming that name shadows the
  stdlib platform module (used by core/windows_sandbox_vm.py,
  core/appcontainer_sandbox.py) whenever the repo root is on sys.path.
  tests/fakes/fake_clock.py lets scheduler dispatch be tested tick-by-tick
  with no Qt event loop.
- R07-T04: application/scheduling/task_application_service.py centralizes
  run_now/duplicate/pause/delete/bulk_delete and the Kanban drag-drop
  business rules (move_to_status), currently only reachable by driving
  the real ui/schedule_task_tab.py widget.
- R07-T05: application/scheduling/ai_task_planner_service.py wraps
  core/ai_task_planner.py::plan_tasks and core/task_import.py::import_tasks
  as a seam, plus the attachment-stamping step that used to only exist
  inside the AI-create dialog's worker closure.

pytest: 328 pass (same 4 pre-existing failures as the R05/R06 baseline,
unrelated to this work - see docs/refactor/BaoCao_TeamHoa_R05_R06.md).
scripts/check_imports.py: PASS.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-27 17:27:53 +09:00
huongltt35 f8e22f5f5b merge: merge origin/gamma/refactor and origin/feature/teamhoa/r05-r06 into feature/delta-team/epic-R04 2026-08-27 12:23:43 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 af8a3712e2 fix(co4e): 4 chỗ ghi JSON của Gamma đi qua AtomicJsonFile — tiêu chí nghiệm thu A
Soát lại plan.md thì thấy CASAN là NĂM tiêu chí C-A-S-A-N, không phải ba. Tiêu
chí A có hai vế, tôi mới đạt vế đầu:

  vế 1  0 API key plaintext trong JSON          -> đã đạt từ 25/08
  vế 2  MỌI thao tác ghi tệp đi qua AtomicJsonFile  -> CHƯA

Toàn repo còn 15 chỗ ghi JSON thẳng. Bốn trong đó là của Gamma (vùng Co4E):

  core/co4e.py:236   lưu workflow   ghi thẳng, không nguyên tử gì cả
  core/co4e.py:310   lưu agent      ghi thẳng
  core/co4e_run_manager.py:156                  tmp + replace tự viết
  application/workflows/co4e_workflow_service.py:178   tmp + replace tự viết

Hai chỗ đầu nguy hơn: tắt máy giữa lúc lưu là mất luôn workflow hoặc agent.

Hai chỗ sau nhìn thì có vẻ ổn vì đã tmp + replace, nhưng thiếu hai thứ:
* không fsync — dữ liệu có thể còn nằm trong bộ đệm ổ đĩa khi mất điện, nên
  "nguyên tử" chỉ đúng với crash tiến trình, không đúng với mất điện;
* dùng thẳng Path.replace, đúng chỗ dính PermissionError [WinError 5] mà tôi
  vá hôm 25/08 — Defender giữ handle file vừa tạo. Tần suất đo được khoảng
  1/140 lần lưu, nhân với số lần lưu lịch sử chạy flow.

11 chỗ còn lại thuộc team khác (accounts, admin_agents, custom_agents, flows,
groups, history, projects, skills, tasks). Không đụng vào; cần báo lên vì
tiêu chí A là tiêu chí TOÀN DỰ ÁN, Gamma sạch không cứu được cổng.

Đã kiểm application/ vẫn không kéo PySide6 vào sau khi thêm import mới
(tiêu chí C). 714 test xanh, 24/24 checker qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 11:38:44 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 6c68417103 refactor: chia nốt theme.py, i18n.py, usage_tracker.py — Gamma hết file vượt 400 dòng
Ba file dữ liệu cuối cùng của Gamma còn trên ngưỡng CASAN Check 2.

i18n.py  3075 -> 94
    Dict STRINGS 3.000 dòng cắt thành 10 cụm theo đúng mốc phân đoạn có sẵn
    trong file (mỗi mốc là một màn/hộp thoại), cụm nào quá dài thì cắt tiếp ở
    ranh giới khoá. i18n.py giờ chỉ gộp lại và giữ 4 hàm set_language/
    get_language/tr/on_language_changed.

    Kiểm bằng cách so với bản gốc lấy từ git: 1437 mục / 1431 khoá duy nhất
    (bản gốc vốn có 6 khoá lặp), sau khi chia vẫn 1431, KHÔNG thiếu khoá nào,
    KHÔNG thừa khoá nào, KHÔNG giá trị nào lệch. Thứ tự gộp giữ nguyên nên
    quy tắc "khoá trùng thì bản sau thắng" không đổi.

theme.py  907 -> 130
    theme_palettes.py 328  hai bảng màu Tối/Sáng + lớp Palette
    theme_qss.py      198  nửa vỏ (reset + shell)
    theme_qss_controls.py 307  nửa điều khiển (nút, ô nhập, tab, badge)

    Khuôn QSS 470 dòng cắt đôi đúng mốc `/* ---- surfaces */` của chính nó.
    Đã đối chiếu: stylesheet('dark') ra đúng 24762 ký tự y như trước — khớp
    từng byte, không phải "trông có vẻ giống".

core/usage_tracker.py  536 -> 307
    usage_cost.py      101  bảng giá, quy đổi token sang tiền, định dạng
    usage_periods.py   144  gộp theo ngày/tuần/tháng/quý, chuỗi vẽ biểu đồ
    usage_ai_report.py  56  dựng câu nhắc cho AI phân tích

HAI LẦN TỰ CẮT HỎNG, ĐỀU CÙNG MỘT GỐC
--------------------------------------
1. Cắt theo m.lineno mà quên dòng @decorator phía trên -> @dataclass của
   Palette bị bỏ lại mồ côi, "Palette() takes no arguments".
2. Đọc số dòng từ AST GỐC trong khi danh sách dòng đã bị cắt -> lần bóc thứ
   hai dùng toạ độ cũ và cắt vào giữa một chữ ký hàm.

Cả hai lộ ngay vì mỗi script tự parse lại sau khi ghi. Bài học đã áp vào cả
ba lần chia: parse lại sau mỗi lần cắt, và luôn tính cả decorator.

KẾT QUẢ CASAN CHECK 2
---------------------
    Nam       0 file vượt 400   (trước: 4, tổng 5.898 dòng)
    Hiệp      0                 (trước: 1)
    Lâm       0                 (trước: 1)
    file mới  0                 (61 file dưới presentation/ application/
                                 domain/ infrastructure/ — chưa cái nào vượt)

Gamma sạch. 23 file còn vượt đều thuộc team khác (chat_panel.py 1802,
folder_tab.py 1589, structure_graph_view.py 1034...) — cần báo lên sớm chứ
đừng để tới hạn 30/08 mới lộ.

714 test xanh. 24/24 checker qua. CASAN Check 1 sạch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 10:57:01 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 0e00bf3c2f refactor(co4e): co4e_tab.py 1885 -> 389, Co4ETab tách thành 7 mixin
File to nhất còn lại của Gamma. Lâm bàn giao ở 1.885 dòng với 100 method
trong một lớp; chia theo bảy mối quan tâm:

    co4e_runs.py           364   chạy flow, 3 chế độ, bảng lịch sử lượt chạy
    co4e_chat.py           343   khung chat + đếm token + định tuyến riêng
    co4e_layout.py         308   ba khung, bảng cấu hình, bố cục màn hẹp
    co4e_sidebar.py        251   thư viện workflow/agent/skill, 4 mục gập
    co4e_flow_tabs.py      180   dải tab các flow đang mở
    co4e_workflow_crud.py  154   tạo/sửa/xoá/nhân bản workflow
    co4e_agents.py          51   agent và skill dùng trong flow
    ui/co4e_tab.py         389   __init__, set_project, thư mục output

Mọi file dưới 400 dòng.

MỘT LỖI SUÝT LÀM HỎNG FILE: bản đầu tôi cắt method theo m.lineno, mà lineno
trỏ vào dòng `def`, không tính dòng `@...` phía trên. Decorator bị bỏ lại
thành mồ côi ngay trên một hằng số lớp -> file hỏng cú pháp. Bắt được vì
script tự parse lại sau mỗi lần cắt; nếu chỉ cắt rồi ghi thì đã đẩy lên một
file không import nổi.

Ba vòng sửa mức import tương đối: co4e_tab.py nằm ở ui/ (1 cấp), file mới ở
presentation/co4e/ (2 cấp). Còn co4e_canvas / co4e_config_panel /
co4e_agent_dialog thì VẪN ở ui/, nên `.co4e_canvas` phải thành
`...ui.co4e_canvas` chứ không phải `.co4e_canvas` cùng thư mục.

714 test xanh — trong đó có ~4.000 dòng test đặc tả Lâm viết cho đúng vùng
này, nên việc tách được soi khá kỹ. check_co4e, check_controls_alive,
check_layout_geometry, check_probes_bite đều qua.

Cập nhật đích đột biến thứ ba của check_probes_bite: dải tab flow nay ở
presentation/co4e/co4e_layout.py.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 10:43:33 +09:00
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
Nam Pham Dinh ThanhandClaude Opus 5 bc282c71d0 refactor(config): AppConfig thành vỏ mỏng trên repository + vá 3 chỗ gán im lặng hỏng
config.py 623 -> 377 dòng (qua ngưỡng 400 của CASAN Check 2).

Class AppConfig 278 dòng giờ còn 30: mọi lối vào dẫn tới JsonConfigRepository.
Không xoá hẳn vì cái tên còn nằm ở 41 file — 23 checker trong tools/ và 18 file
test, trong đó có test của cả ba người. Sửa 41 chỗ trong một commit là đổi thứ
không cần đổi và làm review không đọc nổi. Giữ tên, đổi ruột.

Thêm JsonConfigRepository.from_data() cho dạng AppConfig(data=..., path=...) mà
13 file test đang dùng: dựng thẳng từ dict, không đọc đĩa, không chạy migration
trên dữ liệu test.

MỘT LỖI TÔI GÂY RA HÔM 25/08, HÔM NAY MỚI LỘ
---------------------------------------------
Lúc tráo R02 tôi có đối chiếu API và kết luận "đủ 34/34 thành viên, thay được".
Đối chiếu đó chỉ so TÊN, không so việc một property có setter hay không.

AppConfig cũ là dataclass nên `config.language = "vi"` chạy bình thường.
Repository để language là property chỉ đọc -> gán vào là AttributeError. Ba chỗ
trong app.py đang gán: đổi ngôn ngữ, đổi giao diện, đổi provider trên thanh bên.

Khó thấy vì cả ba nằm trong slot của Qt, mà Qt NUỐT ngoại lệ trong slot. Không
traceback, không thông báo — bấm đổi ngôn ngữ thì không có gì xảy ra. 709 test
đơn vị vẫn xanh suốt. Chỉ check_nav bắt được vì nó bấm thật vào combo rồi kiểm.

Thêm setter cho theme/language/active_provider, và tests/test_config_gan_duoc.py
đi ngược từ mã nguồn: quét cả repo tìm mọi chỗ `config.X = ...` rồi thử gán
thật. Đã kiểm ngược — bỏ setter đi thì 2 bài đỏ.

BẮC CẦU CHO 55 CONTROL MONITORING
----------------------------------
check_controls_alive so với mốc git 291a611 và đòi 55 control ov_* của Tổng
quan phải còn tới được. Sau khi Hiệp tách 8 tab, chúng về đúng tab/thẻ của mình
và rụng tiền tố -> 3 checker đỏ.

Control còn đủ, chỉ đổi chỗ ở. Bắc cầu bằng __getattr__ định tuyến theo tiền tố
(ov_perm_ -> permissions_card, ov_sbx_ -> sandbox_card, ov_price_/ov_pricing_ ->
pricing_panel, còn lại -> overview_tab), cộng 3 hộp nhóm mà bản thân widget con
chính là hộp đó.

Định tuyến theo tiền tố chứ không dò mờ: overview_tab và permissions_card đều
có network_lbl — một cái là mức dùng mạng, một cái là quyền truy cập mạng. Bản
dò mờ đầu tiên tôi viết vớ nhầm cái đầu tiên tìm thấy.

714 test xanh. 24/24 checker qua (3 cái đã đỏ từ trước khi tôi bắt đầu, do phần
monitoring, nay xanh lại). CASAN Check 1 sạch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 01:03:28 +09:00
Hiep Ha Van 72ed3b4147 Merge remote-tracking branch 'origin/gamma/refactor' 2026-08-25 23:55:46 +09:00
Hiep Ha VanandClaude Sonnet 5 40b12ecb15 refactor(monitoring): N2 - tach monitoring_tab.py, CanonicalAuditLogger, MonitoringQueryService, go circular import, sandbox matrix
- ui/monitoring_tab.py (1546 dong) tach thanh presentation/monitoring/**
  (container + 7 tab/card + shared helper), ui/monitoring_tab.py con lai
  re-export shim de app.py khong doi.
- infrastructure/telemetry/audit_logger.py: CanonicalAuditLogger, core/audit_log.py
  thanh wrapper mong, tuong thich nguoc 100% voi schema .jsonl cu.
- application/monitoring/monitoring_query_service.py: MonitoringQueryService
  read-only, filter/sort/pagination, khong import PySide6.
- Go circular import model_pricing<->usage_tracker va agent_security<->
  agent_security_alert (core/agent_security_types.py moi).
- infrastructure/sandbox/sandbox_capabilities.py: SandboxCapabilityMatrix
  theo OS (Windows/Linux/macOS), chua dau noi vao core/sandbox_manager.py.
- conftest.py: sua loi checkout khong ten cowork_local khien pytest import
  nham thu muc khac.
- 77 test moi, 167/167 pass. QA da xac nhan UI/business logic khong doi
  (xem evidence/report/unified_report.html).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 23:52:36 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 4c3b097977 refactor(ui): xoá 108 dòng MS365 chết trong settings_dialog.py
Sót lại từ lần dời UI Connector sang Monitoring → Tools → Connector. Năm hàm:

    _refresh_ms365_status    13    _show_ms365_device_code   52
    _ms365_sign_in           34    _ms365_sign_out            4
    _close_ms365_code_dialog  5

Chứng minh chết trước khi xoá, không xoá theo cảm tính:

* Dựng đồ thị lời gọi bằng ast: **mọi** lời gọi tới năm hàm này đều xuất phát
  từ bên trong chính năm hàm đó. Không một đường vào nào từ ngoài cụm — cả
  trong file lẫn toàn repo.
* Ba thuộc tính chúng đọc — ms365_status, ms365_signin_btn, ms365_signout_btn
  — **chưa từng được gán ở đâu**. Gọi vào là AttributeError, không phải chạy sai
  mà là sập.
* _ms365_workers chỉ được append bên trong _ms365_sign_in, nên chết theo.

Dọn kèm 6 import chỉ còn dòng import: AgentWorker, icon, EXT_CATEGORIES,
ExtConnectorEditDialog, AppContext, QTreeWidget.

Viết lại docstring đầu file — bản cũ vẫn mô tả file này chứa nhóm Connector
(CAD/CAE/MS365/Other), thứ đã không còn ở đây từ lâu.

settings_dialog.py: 407 -> 303 dòng. Cộng cả R08-T07 thì từ 727 xuống 303.

632 test xanh. check_dialogs, check_no_hscroll, check_design_parity,
check_orphans, check_probes_bite đều qua.

Ghi lại một phát hiện phụ, CHƯA xử lý: i18n.py có 28 khoá settings.ms365_*
mồ côi — 20 khoá đã không ai dùng từ trước lần dời connector, 8 khoá vừa mồ
côi theo commit này. Chỉ 2 khoá còn sống (ms365_local_connected,
ms365_local_none, dùng ở ui/connectors_panel.py). Xoá khoá dịch là đụng vào
dữ liệu ba ngôn ngữ ở file khác nên để anh Nam quyết riêng.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 21:15:15 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 c77ce36191 refactor(shell): R08-T10 — bootstrap + tách TrayManager và LifecycleCoordinator
app.py 1356 -> 1293 dòng. presentation/shell/ có 3 file:

  bootstrap.py               Composition Root (đã vào ở commit trước)
  tray_manager.py            khay hệ thống + thông báo bong bóng
  lifecycle_coordinator.py   canh cửa sổ theo màn hình + tắt cho sạch

Vì sao tách khay: khay là thứ CÓ THỂ KHÔNG TỒN TẠI (một số môi trường Linux,
phiên RDP). Trước đây mỗi chỗ dùng phải tự nhớ kiểm `if self.tray is not None`
— có 6 chỗ như thế, và 3 chỗ còn phải tự bọc try/except quanh showMessage.
Gói lại thì chỗ gọi cứ gọi, không có khay thì không có gì xảy ra.

Vì sao tách vòng đời: hai việc trong đó không phải việc của giao diện. Canh
cửa sổ theo màn hình là số học thuần (anh Nam có hai màn khác độ phân giải và
khác tỉ lệ phóng — kéo qua lại là vùng làm việc đổi). Còn shutdown là thứ tự
dừng có ý nghĩa: bộ lập lịch trước để nó không kịp khởi động việc mới trong
lúc ta đang dừng việc cũ, rồi mới tới worker, rồi ngắt tiến trình MCP.

closeEvent/moveEvent/resizeEvent vẫn ở lớp cửa sổ vì Qt gọi thẳng vào đó,
nhưng phần quyết định đã chuyển đi. closeEvent từ 30 dòng còn 11.

Giữ self.tray thành property trỏ vào self._tray.icon — vài chỗ còn đọc tên cũ.

Đã lấy mốc trước khi bóc rồi so lại sau: 24/24 checker trong tools/ qua cả hai
lần. Đây là bộ đặc tả thật cho MainWindow (check_nav, check_rail_align,
check_layout_geometry, check_controls_alive... dựng cửa sổ thật offscreen trên
BẢN SAO của ~/.cowork_local, scheduler bị vô hiệu hoá). 632 test xanh.

CHƯA làm hết R08-T10: plan ghi tách thành main_window.py + tray_manager.py +
lifecycle_coordinator.py. Hai file sau đã xong, main_window.py thì chưa —
MainWindow vẫn nằm trong app.py và vẫn 1095 dòng. Đo lại thì khối lượng không
nằm ở ba cụm plan nêu mà ở hai cụm khác:

    nav rail    18 method, ~340 dòng
    topbar      8 method,  ~157 dòng
    __init__    279 dòng

Hai cụm đó dính chặt vào state của cửa sổ, chuyển đi cần đổi giao diện giữa
chúng chứ không phải dời chỗ, nên tôi dừng ở đây thay vì làm nửa vời.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:56:37 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 2246d55286 feat(infra): R02 vào thật — app chạy bằng JsonConfigRepository, khoá rời khỏi config.json
Từ 21/08 tôi đã viết xong 7 file R02 với 46 test xanh, và báo là "xong R02".
Báo sai: code mới nằm song song, KHÔNG một dòng nào ngoài infrastructure/ và
tests/ gọi tới nó. App vẫn chạy nguyên trên config.py, 29 file dùng nó, và
khoá API của người dùng vẫn nằm plaintext trong config.json suốt 4 ngày.

Commit này mới là phần refactor thật.

Bù 21 thành viên còn thiếu (85 dòng)
------------------------------------
JsonConfigRepository có 18/34 thành viên công khai của AppConfig nên không
tráo được. Chép nguyên ngữ nghĩa 21 cái còn lại: load, ms365_*, ext_connectors,
connect_external, routing_mode_for, seeded_*, mcp_servers, teams, history,
structure, monitoring_visibility, model_label, ca_bundle... Giờ 40/34, không
thiếu gì. Không phải thiết kế mới — chừng nào 29 file còn gọi qua ctx.config
thì repository phải trả lời được đúng các câu hỏi cũ.

ROUTING_MODES lấy theo bản Delta (4 chế độ, có "fallback" từ R03-T03) chứ
không theo bản main cũ 3 chế độ. Chép bản cũ là routing "fallback" âm thầm rơi
về "off" sau khi Delta merge, không lỗi nào báo.

Composition Root (R08-T10, phần đầu)
-------------------------------------
presentation/shell/bootstrap.py: một chỗ duy nhất quyết định app dựng bằng
mảnh nào. app.py::run giờ gọi build_context() thay cho AppConfig.load().
Đây cũng là chỗ ráp kho bí mật vào; máy không có keyring thì secrets=None và
mọi thứ chạy như cũ.

Kiểm trên dữ liệu thật
----------------------
Chạy lên máy tôi, migration tự chạy đúng như thiết kế:

  openai_compat  39 ký tự  config.json -> Windows Credential Manager
  ollama         giá trị bù nhìn, để nguyên trong file, không đẩy vào kho
  schema_version 1 -> 2
  sao lưu        config.json.v20260825-193206.bak

Sau khi bật lại app và để nó ghi cấu hình, config.json vẫn sạch: api_key rỗng,
không còn chuỗi nào có hình dạng khoá. scripts/audit_security.py sạch.

Tiêu chí nghiệm thu A của plan (dòng 244) — "0 lưu trữ plaintext API Key trong
JSON" — tới commit này mới thật sự đạt.

632 test xanh. check_dialogs, check_nav, check_design_parity đều qua.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:35:44 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 e4ce9b2f5f merge: lấy phần N3 của Lâm (6 widget UI Co4E) về nhánh chung
Không xung đột — Lâm động vào ui/co4e_tab.py và presentation/co4e/,
tôi động vào ui/settings_dialog.py và presentation/settings/. Đúng như
quy tắc phân chia sở hữu đặt ra từ đầu.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:23:20 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 2b90492994 refactor(ui): R08-T07 — bóc settings_dialog.py 727 → 407 dòng thành 4 widget
Bốn mục trong Cài đặt tách thành widget riêng dưới presentation/settings/:

    general_settings_widget.py     ngôn ngữ, giao diện, khay, gợi ý
    provider_settings_widget.py    provider, base URL, key, model + 2 nút nền
    parameter_settings_widget.py   đính kèm, cấu trúc, giới hạn sandbox
    routing_settings_widget.py     Auto Model Routing

Mỗi widget tự dựng control, tự nạp giá trị, tự có apply_to(data). Dialog chỉ
còn lắp ráp và gọi apply_to lúc lưu — _save từ 34 dòng xuống còn phần khung.

Làm lưới an toàn trước khi bóc: tests/ui/test_settings_dialog_dac_ta.py, 7
bài đặc tả hành vi hiện tại (mục nào có mặt, nạp đúng giá trị gì, lưu ghi vào
đúng ô nào, đổi % sang phân lẻ, xoá cache sau lưu). Bóc xong cả 7 vẫn xanh,
và trong lúc bóc chúng đã đỏ đúng hai lần ở chỗ đáng đỏ.

Đây là repo chưa từng có test Qt nào — thêm tests/ui/conftest.py dựng
QApplication offscreen. Offscreen là bắt buộc chứ không phải cho nhanh: máy
dev là máy làm việc thật, test bật cửa sổ lên là nó nhảy ra che màn hình.

Dọn kèm:
* bỏ vòng "dựng vào layout rồi lại gỡ ra" của mục Chung, cùng widget cao 0px
  làm mốc cuộn — không cần nữa khi mục đó tự là một widget
* bỏ _select_combo, _secret, _model_combo, _with_load và 4 hàm provider khác
  đã chuyển vào widget (127 dòng)
* bỏ 5 import chết theo (Dict, QSizePolicy, PROVIDER_LABELS, SegmentedControl,
  LANGUAGES)

Giữ cầu tương thích: self.routing_*, self.prov_*, self.attach_* … thành
property trỏ vào widget con, vì 5 checker trong tools/ đọc thẳng tên cũ. Bỏ
được khi tools/ chuyển sang đọc self._provider_page.

Hai điều KHÔNG làm, ghi lại để khỏi tưởng là quên:
1. Plan ghi 4 widget và có tên `connector`. Thực tế UI connector đã dời khỏi
   Cài đặt từ trước (ghi chú ở settings_dialog.py:180 bản cũ), nên số mục thật
   là 5, không phải 4, và không có mục nào tên connector. Bốn mục bóc ra là 4
   mục có thật; mục Bảo mật sandbox để nguyên trong dialog lần này.
2. Còn ~108 dòng chết của MS365 (_refresh_ms365_status, _ms365_sign_in,
   _show_ms365_device_code, _ms365_sign_out): đọc self.ms365_status,
   self.ms365_signin_btn, self.ms365_signout_btn — ba thuộc tính KHÔNG BAO GIỜ
   được gán, và không hàm nào có người gọi. Gọi vào là AttributeError. Chưa
   xoá vì đó là quyết định của anh Nam, không phải việc kèm theo của T07.

437 test xanh. check_dialogs, check_no_hscroll, check_design_parity đều qua.

Kèm docs/refactor/tin-gui-team-hoa.md — tin báo Hoa về platform/ -> adapters/
và bản vá Windows của AtomicJsonFile.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 19:22:54 +09:00
lamhv7andClaude Sonnet 5 c890a20f45 merge: đồng bộ origin/gamma/refactor (R01/R03/R04 — routing unification,
conversation application service, AtomicJsonFile fix) vào sau khi tách 6
widget UI Co4E (N3)

Đã kiểm trước khi merge: ui/co4e_tab.py và ui/routing_toggle.py đều bị 2
bên cùng đụng, nhưng ở vùng dòng khác nhau hoàn toàn (bên kia sửa
_apply_co4e_routing/RoutingToggle cho R03-T05, N3 chỉ đụng phần dựng
sidebar/canvas/chat) — không có xung đột logic thật.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 18:43:56 +09:00
lamhv7andClaude Sonnet 5 0631abf85f feat(co4e): tách 6 widget UI khỏi ui/co4e_tab.py sang presentation/co4e/*
Lane N3 (Co4E Studio) — dùng bộ workflow refactor-god-file, mỗi bước có
characterization test trước khi tách, hậu kiểm ranh giới tầng sau mỗi bước:

- skills_list_panel.py / agent_list_panel.py — 2 khu vực sidebar
- co4e_canvas_widget.py + canvas_items.py + canvas_interaction_mixin.py —
  Co4ECanvas tách 3 file (vượt 400 dòng nếu đứng một mình)
- node_property_panel.py + node_property_actions_mixin.py +
  step_config_section.py — StepConfigPanel, cùng lý do
- co4e_run_control_widget.py — RunsPagePanel (trang Flow Status)
- co4e_chat_view.py — ChatPanel + _ChatInput + helper autocomplete
- palette_list.py — _PaletteList dời khỏi ui/co4e_tab.py, hết import ngược
  presentation -> ui (agent/skills panel giờ import top-level)

ui/co4e_tab.py giảm 2089 -> 1878 dòng, chỉ còn phần wiring + business logic
(Co4ERunManager/AgentWorker chưa đổi — nằm ngoài phạm vi này, xem docstring
presentation/co4e/co4e_tab.py). ui/co4e_canvas.py và ui/co4e_config_panel.py
còn lại là compat shim re-export, không đổi API cho bên gọi.

Thêm tests/test_co4e_integration.py — dựng thật Co4ETab qua build_co4e_tab(),
lái luồng qua nhiều panel trong cùng instance (thêm node, mở/gập chat, chuyển
trang Flow Status rồi quay lại không mất state canvas) — bắt lỗi wiring
xuyên-panel mà characterization test từng panel riêng không thấy được.

Đã xác minh: pytest 348 passed/1 skipped, tools/check_co4e.py sạch, không
file nào >400 dòng, domain/application không import PySide6, và so pixel
before/after (git worktree tại HEAD cũ) ra 0/1.125.000 pixel khác biệt.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 18:43:42 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 9d6a7be31b fix(infra): AtomicJsonFile — os.replace trên Windows thỉnh thoảng bị từ chối
Bắt được nhờ merge Delta: bộ test của họ chạy lâu hơn nên lộ ra một bài
của tôi chập chờn. Truy ra không phải lỗi test mà là lỗi thật trong code
chạy máy người dùng:

    PermissionError: [WinError 5] Access is denied
      .dem.json.l7x2a8pd.tmp -> dem.json

MoveFileEx trả ERROR_ACCESS_DENIED khi tiến trình khác đang giữ handle
lên nguồn hoặc đích — trên Windows gần như luôn là Defender hoặc Search
Indexer quét file vừa tạo, giữ vài chục mili-giây rồi nhả.

Đo được: hỏng 1 trong 7 lượt chạy 20 lần ghi, tức khoảng 1 trên 140 lần
lưu. Nghĩa là người dùng thỉnh thoảng bấm Lưu là văng lỗi, và không tài
nào tái hiện được để báo.

Thêm vòng thử lại 6 lượt, nghỉ tăng dần 20ms → 640ms. Hết lượt vẫn ném
lỗi, không nuốt lỗi quyền thật, và luôn dọn file tạm.

Hai bài test mới, đã kiểm ngược: bỏ vòng thử lại thì bài thứ nhất đỏ.
Chạy lại 30 lượt sau khi vá: 0 hỏng (trước khi vá: 4).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:21:01 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 dcf2e8f995 merge: kéo Delta epic-R04 (gồm cả R01 và R03) vào gamma/refactor
Nam chốt: không chờ Delta merge vào main, lấy sớm để va chạm nhỏ và sửa
ngay, thay vì dồn một cục lúc cả hai cùng lên main.

R04 chứa trọn R01 và R03 nên một lần merge là đủ cả ba: 96 file, +8260
dòng. Xung đột chỉ 5 file, đều là __init__.py add/add — hai team cùng
dựng khung thư mục nên đụng docstring. Giữ docstring của Gamma (nói rõ
ràng buộc "không import PySide6"), giữ mọi phần code của Delta.

Riêng tests/fakes/__init__.py: bỏ hai dòng import háo hức của Delta
(fake_provider, fake_tool_executor). fake_provider dùng
`from providers.base import ...` — import tuyệt đối, chỉ chạy được khi
cwd là gốc repo — nên nó làm đứt bài test "dùng fake mà không nạp config
thật". Không ai import ở cấp package; test của Delta gọi thẳng module
nên bỏ đi không ảnh hưởng họ. Đã ghi lý do vào docstring của gói.

Delta cũng xoá preview-desktop và "requirements (cloud copy).txt".

430 test xanh sau merge.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:20:36 +09:00
duylh19andClaude Opus 5 3665135c38 feat(R04): run every Cowork turn through ConversationApplicationService
R04-T03 — the turn lifecycle, extracted from `core/chat_agent.py::run_cowork`
into `application/conversations/`. The 260-line body mixed the lifecycle (step
budget, cancel checks, guard -> preview -> gate -> execute ordering, sandbox
tidy-up) with the machinery doing each step, and reaching any of it meant
standing up a Qt widget and a worker thread. It is now a plain object driven
through two Protocols and six callables (`turn_runtime.py`), with the concrete
`core/*` wiring confined to `core_runtime_adapter.py` — the same shape R03 used
for routing. Faithful port, not an improvement pass: where the original had a
quirk (the step-ceiling note only merges into the answer when the last message
is the assistant's) the quirk is preserved and commented.

R04-T04 — `ui/cowork_tab.py::build_job` no longer calls run_cowork. It captures
the widget's state at submit time, builds the request via the new
`cowork_turn_request.py` and executes it. `execute(..., messages=...)` hands the
widget's own list over because `_reattach_running_turn` replays from it WHILE
the worker appends and `_finalize_turn` slices it afterwards — a private list
would break both silently.

R04-T05 — `core/task_executors.py`'s cowork branch shares the same engine. All
five unattended-run behaviours stay put (plan reminder, history_ready, History
autosave per assistant message, timeout notice, plan_incomplete_reason), and
`_unattended_prompt` now expresses the load-bearing prefix order in one
readable call instead of three successive rebindings.

Verification: 74 new tests (364 passed, 1 skipped overall; check_imports PASS).
The two that matter most:
- `test_conversation_service_parity.py` runs the same scripted turn through
  run_cowork AND the service and compares the event stream, the resulting
  conversation and the advertised tool list across 7 scenarios;
- `test_task_executor_turn.py` was written BEFORE the migration and passed 8/8
  against the old code, then unchanged against the new.

Known: `ui/cowork_tab.py` (416 -> 455) and `core/task_executors.py` (476 -> 524)
stay above the 400-LOC limit. Both were already over it before this change;
bringing them under needs the R08 / R07 decompositions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 13:14:15 +09:00
duylh19andClaude Opus 5 19e6b4deb2 feat(R04): add the immutable turn snapshot and typed agent event stream
R04-T01 — `domain/agents/conversation_execution_request.py`: a frozen
snapshot of everything one chat turn needs. Turn inputs previously lived in a
closure plus a 15-key ctx dict inside `ui/chat_panel.py::_start_turn`, and the
worker thread kept reading the widget back while it ran, so every later click
was visible to work already in flight. The request also owns the prompt
composition rules (instruction prefix separator, session notes, model-switch
review note) that were inline in that closure.

R04-T02 — `domain/agents/agent_event.py`: 13 frozen event types replacing the
untyped `{"type": ...}` dicts, whose only specification was the 130-line
if/elif chain in `_on_event`. Each event serialises back to the exact legacy
dict, so the presentation layer is untouched; `agent_event_codec.py` parses the
other way and is a temporary shim, isolated so R08 can delete it in one move.
`assistant_done` is deliberately NOT the end of a turn (it fires once per
provider call), so it maps to AssistantMessageCompletedEvent while the new
TurnCompletedEvent reports the turn itself.

R04-T03 (part) — `domain/agents/agent_result.py`: one named outcome for a
finished turn, replacing the message list / 3-tuple / reconstructed-from-side-
effects trio the three callers each read differently.

Verification: 66 tests. Beyond the unit tests,
`tests/integration/test_agent_event_bridge.py` runs the REAL `run_cowork` loop
offline and asserts every dict it emits is recognised and round-trips
byte-for-byte — a guard against an event type nobody modelled or a key whose
meaning silently drifted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 13:13:56 +09:00
duylh19andClaude Opus 5 176e6aef79 fix(ci): guard the MCP SDK import so pytest can collect the suite
`tests/test_project_context_mcp_template.py` imported `mcp` at module scope,
but the SDK is a runtime dependency (requirements.txt) and is deliberately
absent from requirements-test.txt — the only thing CI installs. Collection
therefore aborted for the ENTIRE suite before a single test ran.

The guard now sits inside the one test that touches the SDK, so the other
cases in the file (pure-Python contract checks) keep running on CI instead
of being skipped along with it.

Unrelated to the R04 refactor; kept as its own commit so it can be cherry-
picked to main on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 13:13:42 +09:00
vudt15andClaude Sonnet 5 8ab29800db docs(refactor): add the Team Hoa completion report for R05/R06
Mirrors docs/refactor/BaoCao_TeamDuy_R01_R03_R04.md's structure: per-EPIC
results, test evidence, the two real bugs found and fixed, secondary
improvements, open items needing another team's sign-off, untested scope,
and what's next.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:30:52 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 ca7ea1479d fix(infra): neo nốt logs/ build/ dist/ out/ — cùng hình dạng lỗi secrets/
Sau khi vá secrets/ thì rà cả file xem còn mẫu không neo nào sắp cắn hai
người kia. Còn hai quả đang sống:

  logs/   -> nuốt infrastructure/logs/   (Hiệp làm CanonicalAuditLogger,
                                          đây là tên rất dễ đặt)
  build/  -> nuốt application/*/build/
  dist/, out/ cùng kiểu

Chưa ai vấp, vá trước. Trong repo không có build//dist//out//logs/ lồng
nhau nào nên neo về gốc không mất gì — đã kiểm hai chiều: đường dẫn mã
nguồn qua được, còn build/x.o, dist/app.exe, logs/run.log ở gốc vẫn bị
chặn như cũ.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 21:15:39 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 d74c052af3 fix(infra): .gitignore nuốt infrastructure/secrets/ — nhánh đỏ với mọi máy trừ máy tôi
Dòng 31 ghi `secrets/`. Mẫu không neo, nên git bỏ qua MỌI thư mục tên
secrets ở mọi độ sâu — kể cả infrastructure/secrets/ vốn là mã nguồn.

Ba file ở đó chưa bao giờ lên repo. Máy tôi vẫn 150 test xanh vì pytest
đọc đĩa chứ không đọc git; ai clone sạch thì đỏ 4 file ngay lúc thu thập:

    ModuleNotFoundError: No module named
    'cowork_local.infrastructure.secrets'

Hiệp phát hiện, không phải tôi. Đã dựng lại bằng clone sạch vào thư mục
đặt đúng tên cowork_local để tái hiện.

Neo mẫu thành /secrets/ và thêm tests/test_no_ignored_source.py — hỏi
thẳng git chứ không hỏi đĩa, nên lần sau lỗi cùng hình dạng sẽ đỏ ngay
trên máy người viết. Đã kiểm ngược: trả lại `secrets/` thì cả ba bài đỏ.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-22 21:11:42 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 8be5ce1bab docs(arch): mô hình chính sách an toàn — R09-T01
Mô tả hệ thống ĐANG CHẠY, không phải hệ thống mong muốn. Mọi khẳng định chỉ
tới file:dòng cụ thể, và mỗi tham chiếu đã được kiểm bằng script: mở đúng file,
đọc đúng dòng, đối chiếu nội dung có khớp điều đang nói không. Lần kiểm đầu bắt
được 3 tham chiếu thiếu tiền tố core/ và 2 số dòng lệch — dòng 249 là "No-op
for any other tool", câu về bộ phân loại luôn bật nằm ở 250.

Bốn điểm đáng chú ý trong tài liệu:

  - Đây KHÔNG phải rào chắn an ninh. Chính agent_security.py nói vậy ở đầu
    file, và hệ quả là mọi tầng AI đều mở khi hỏng. Ai đọc để đánh giá rủi ro
    phải hiểu đúng chỗ này.

  - Phân biệt quy tắc xác định và quy tắc do AI phán. Tắt hết công tắc trong
    màn Cài đặt thì VẪN còn bộ phân loại mẫu và sandbox — đây là điểm dễ hiểu
    nhầm nhất, vì mấy công tắc đó chỉ tắt phần AI.

  - Trạng thái thứ ba: hỏi người dùng. Hệ thống đã có (chat_panel.py:1312) mà
    chưa gọi tên; tool_policy.py gộp thành ALLOW/DENY/ASK.

  - Mục 8 liệt kê 4 chỗ đã biết là yếu, để người sau khỏi tưởng đã kín: mở khi
    hỏng, bí mật vẫn đi trong bộ nhớ (hệ quả của đường A), bộ luật OneDrive
    không ký số, và ASK chưa nối được vào Co4E.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 16:11:01 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 ab0d26761f feat(infra): xong R02 — Settings Facade, versioning, chuyển khoá sang keyring
R02-T03 Typed Settings Facade
  Khắp nơi đang viết ctx.config.routing.get("switch_mode", "off"). Gõ sai một
  chữ thì lặng lẽ nhận mặc định, không ai biết cho tới lúc tính năng "không
  hiểu sao không chạy". ProviderSettings / RoutingSettings / SecuritySettings
  làm sai tên là lỗi ngay, và kiểu ghi rõ nên đọc là biết confirm_timeout_sec
  tính bằng giây.

  Là KHUNG NHÌN lên dict sống, không phải dataclass sao chép — sửa qua đây là
  sửa vào cấu hình, save() là xuống đĩa, khỏi sinh chuyện đồng bộ hai chiều.
  Có raw() để ai thiếu thuộc tính thì dùng tạm, đừng vòng lại config.data.

  Bắt cả trường hợp giá trị là null: file cũ hay để null, đọc ra None rồi đem
  so sánh số là vỡ.

R02-T06 Schema versioning + phục hồi
  config.json hôm nay không có số phiên bản, nên mọi thay đổi hình dạng phải
  đoán — _migrate_connectors() đoán "có khoá office nghĩa là file cũ". Giờ:
  thiếu schema_version thì coi là v1, mỗi bước là một hàm chạy tuần tự, sao
  lưu trước khi nâng, và file mới hơn app thì dùng nguyên trạng chứ không đoán
  ngược.

R02-T05 Chuyển API key sang kho bí mật
  Là bước v1→v2. Người dùng cập nhật app, mở lên, khoá cũ tự vào keyring và
  biến khỏi đĩa — có test cho đúng cảnh đó.

  Hai chỗ cố tình không làm:
    - Máy chưa có keyring: KHÔNG chuyển, giữ nguyên v1. Thà để khoá trong file
      còn hơn xoá đi rồi người dùng mất khoá mà không hiểu vì sao.
    - Giá trị "ollama" là bù nhìn (Ollama đòi có api_key nhưng bỏ qua nội
      dung), đẩy vào keyring chỉ tổ rác.

Hai chuỗi test trông giống khoá thật bị CASAN Check 1 bắt — đánh dấu
"# casan: allow" kèm lý do, đúng lối thoát đã thiết kế cho cả đội.

150 test xanh (129 + 21 mới). CASAN Check 1 sạch. File mới đều dưới 200 dòng.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:50:09 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 a7e369e46c feat(infra): JsonConfigRepository — R02-T02, hiện thực đường A đã chốt
Thay cho config.py::AppConfig. Hai khác biệt về hành vi, cả hai đều là thứ
muốn có; mọi thứ còn lại giữ y nguyên vì đây là refactor.

1. Ghi qua AtomicJsonFile — mất điện giữa lúc lưu không còn làm hỏng cấu hình.
   Có test riêng ở tầng này chứ không chỉ dựa vào test của AtomicJsonFile.

2. Đường A (chốt 21/08): provider_conf() đọc khoá từ SecretStore rồi ghép vào
   dict trả về, còn set_api_key() ghi khoá vào kho và để chuỗi rỗng trên đĩa.
   Kết quả: 5 nơi đang đọc conf["api_key"] không sửa dòng nào — 3 trong đó
   thuộc providers/ của Team Duy — mà file JSON vẫn sạch để qua CASAN Check 1.
   Hai test riêng cho đúng hai vế đó.

provider_conf() trả BẢN SAO. Nếu trả tham chiếu thì khoá vừa ghép vào sẽ lẫn
ngược vào self.data rồi theo save() xuống đĩa — đúng thứ đường A phải tránh.
Có test cho chuyện này.

secrets=None thì lùi về hành vi cũ (khoá nằm trong file). Cần vậy để chuyển
dần ở R02-T05 chứ không phải đổi một phát cả app, và để máy không có keyring
vẫn chạy.

Giữ nguyên có chủ đích: trộn sâu với mặc định, biến môi trường, và
ms365.unlocked không bao giờ chạm đĩa — mỗi thứ một test.

_deep_merge chép lại 6 dòng thay vì import từ config.py: file này phải sống
được sau khi config.py biến mất.

129 test xanh (119 + 10 mới). CASAN Check 1 sạch. File mới: 188/102/86 dòng,
đều dưới ngưỡng 400.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 00:37:43 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 d6dd6a030e feat(infra): AtomicJsonFile + KeyringAdapter, và đổi tên platform/ vì nó che stdlib
Ngày 21/08 của làn N1 (Nam): R02-T01 và R02-T04.

--- Lỗi phải sửa trước khi làm được gì ---

Kế hoạch đặt tên một tầng là platform/. Tôi dựng đúng theo đó sáng nay, có
kiểm "platform stdlib không bị che" và báo là an toàn. Kiểm đó SAI: tôi chỉ
thử từ thư mục cha. Chạy từ gốc repo — đúng cách 26 script trong tools/ và
scripts/ được gọi — thì platform/ che khuất platform của thư viện chuẩn, và
import keyring chết ngay:

    AttributeError: module 'platform' has no attribute 'system'

Nghĩa là R02-T04 không thể làm được chừng nào thư mục đó còn tên cũ. Đổi
platform/ -> adapters/. Đây là lệch khỏi plan.md và ảnh hưởng Team Hoa (họ sở
hữu platform/qt/qt_scheduler_clock.py) — đã ghi vào GammaTeam_decisions.md.

tests/test_no_stdlib_shadow.py chặn lỗi tái diễn, hai lớp: một bài so tên thư
mục gốc repo với sys.stdlib_module_names, một bài chạy tiến trình con với cwd
là gốc repo rồi import keyring thật. Dựng lại platform/ là cả hai đỏ.

--- R02-T01: AtomicJsonFile ---

config.py::save() đang gọi path.write_text(), tức là cắt file về 0 byte rồi
mới ghi. Chết giữa chừng là mất sạch cấu hình. Thay bằng: ghi file tạm cùng
thư mục -> flush + fsync -> os.replace (nguyên tử trên cả Windows và POSIX).

Test tiêm lỗi đúng như cột nghiệm thu của plan.md: cho os.replace ném lỗi
ngay bước cuối rồi khẳng định file cũ còn nguyên. Chỉ test "ghi rồi đọc lại"
thì write_text() cũ cũng qua — mà đó chính là thứ đang thay.

Phần đọc: file hỏng được dời thành .bad-<thời điểm> rồi trả mặc định. Giữ
đúng hành vi "hỏng cấu hình không chặn khởi động" của config.py, thêm phần
cứu được bản hỏng.

--- R02-T04: KeyringAdapter ---

Windows Credential Manager / macOS Keychain / Linux Secret Service. Không bao
giờ ném lỗi: máy không có kho (Linux headless, CI) thì available=False và trả
None, để tầng UI nói "chưa lưu được khoá" thay vì sập app. Test tiêm backend
giả, không đụng keyring thật của máy chạy test.

119 test xanh (102 + 17 mới). CASAN Check 1 sạch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 22:44:34 +09:00
vudt15andClaude Sonnet 5 cf542b7416 feat(R06): workspace session snapshot, atomic persistence, history-dir race fix
EPIC R06 (Team Hoa) - workspace/filesystem isolation, no cross-project
mutable state.

R06-T01 domain/workspaces/workspace_session.py
  WorkspaceSession - project_id/workspace_root/sandbox_dir/allowed_paths
  frozen snapshot + is_allowed(path), same "capture once at submit time"
  shape as R04's ConversationExecutionRequest.

R06-T02 infrastructure/persistence/json/{atomic_write,workspace_repository_impl,conversation_repository_impl}.py
  Real bug fixed: core/projects.py::save_project and core/history.py's
  save_conversation/rename_conversation/set_pinned did a plain
  path.write_text(json.dumps(...)) - two syscalls, no atomicity. A crash
  between them leaves a half-written file that load_project/load_conversation
  then silently treat as "missing". All four now write through
  atomic_write.write_json (temp file + os.replace). WorkspaceRepository/
  ConversationRepository are thin object-shaped facades over the same
  (now-atomic) functions, for future application-layer callers.
  NOTE: atomic_write.py is deliberately NOT named atomic_json_file.py -
  R02-T01 (Team Nam) claims that filename for the same purpose app-wide;
  see the checklist for the consolidation TODO.

R06-T03 infrastructure/filesystem/execution_workspace.py
  ExecutionWorkspace names the output_dir/scratch_dir split that already
  exists (core/chat_agent.py's flat workspace_root/.scratch) - does not
  move anything.

R06-T04 ui/chat_panel.py
  The actual race: ChatPanel._persist_session (saves a BACKGROUND turn's
  conversation) resolved its save directory via a live
  self.ctx.config.history_dir() read at save time. ui/workspace_tab.py::
  _load_current mutates that same config field on every project switch, so
  a turn still running when the user switched projects got saved into the
  NEW project's history folder. Fixed by adding "home_history_dir" to the
  per-turn ctx dict (same "home_*" snapshot convention already used for
  session id/messages/title), captured at submit time. Verified with a real
  offscreen-Qt test, not just a unit double:
  tests/integration/test_history_dir_race.py.

R06-T05 application/workspaces/file_workspace_service.py
  FileWorkspaceService - the File Explorer / AI Editor entry point for the
  same safe read/write/edit operations the agent tool loop has, by calling
  core/tools.py::execute_tool directly (same dispatch, same ToolContext
  containment, same audit log) rather than reimplementing any of it.

New tests: tests/unit/test_workspace_session.py,
test_atomic_write_and_repositories.py, test_execution_workspace.py,
test_file_workspace_service.py, tests/integration/test_history_dir_race.py
(29 new tests, incl. 2 real offscreen-Qt integration tests).

Suite: 283 passed, 4 pre-existing failures unrelated to R05/R06 (see
checklist). check_imports: PASS. All new files < 400 LOC.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 22:34:57 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 2627e691ce docs(refactor): cả ba đẩy chung gamma/refactor; đặt tên Nam, Hiệp, Lâm
Đổi mô hình: không còn nhánh riêng mỗi người, cả ba cùng đẩy vào
gamma/refactor. Ba "nhánh" thành ba "làn" — vẫn chia việc như cũ, nhưng ranh
giới file bây giờ là thứ DUY NHẤT giữ ba người không giẫm chân, vì không còn
nhánh riêng làm vùng đệm.

Thêm quy ước số 4 cho nhánh chung, xếp vào nhóm bắt buộc: pull --rebase trước
mỗi lần đẩy; commit nhỏ, đẩy trong ngày; không bao giờ đẩy thứ làm
pytest tests -q đỏ, vì nhánh hỏng là hai người kia đứng hình.

Phần nghiệm thu đổi theo: trước đây so file giữa ba nhánh, giờ không còn ba
nhánh để so. Thay bằng git log --name-only --pretty=%an trên gamma/refactor —
không file nào được xuất hiện dưới hai tên khác nhau.

Hai quyết định đã chốt, ghi vào GammaTeam_decisions.md:
  1. api_key: đường A — ConfigRepository ghép key từ SecretStore vào dict, 5
     nơi đọc không đổi dòng nào, không cần báo Duy và Hoa.
  2. 24 checker UI: đường A — ai dời file thì sửa checker ngay trong commit
     đó, kèm ràng buộc phải nói rõ sửa gì và chạy check_probes_bite.py sau.
     Không đưa vào CI sprint này vì chúng dựng MainWindow thật.

Baseline trong tài liệu cập nhật 90 -> 102 test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 22:24:03 +09:00
vudt15andClaude Sonnet 5 ae4fe72b2e feat(R05): tool capability registry, unified policy gateway, MCP lifecycle manager
EPIC R05 (Team Hoa) - one security/approval path for every tool call.

R05-T01 domain/tools/{tool_descriptor,tool_registry}.py
  ToolCapability (READ/WRITE/EXECUTE/NETWORK, composable) + ToolDescriptor +
  ToolRegistry, replacing three independently-maintained gating lists
  (core/tools.py::WRITE_TOOLS, code_agent.py's WRITE_TOOLS|MS365_WRITE_TOOLS,
  chat_agent.py's literal ("run_command","install_package") tuple) with one
  capability lookup.

R05-T02 infrastructure/filesystem/{file_tools,command_tools,fetch_tools,tool_context}.py
  core/tools.py's execute_tool if/elif chain split into per-concern modules.
  core/tools.py is now a strangler-fig shim: re-exports ToolContext/ToolError,
  dispatches through a {name: handler} dict built from the split modules.
  core/tools.py: 566 -> 291 lines.

R05-T03 application/conversations/tool_policy_gateway.py
  ToolPolicyGateway.allow(name, gate, payload) - capability-driven ALLOW vs
  ask-the-gate decision. Wired into both chat_agent.py::run_cowork and
  code_agent.py::run_code, replacing their separate hand-rolled checks.
  Verified equivalent to the old hardcoded sets by test.

R05-T04 (behavior change, not just refactor)
  MCP/connector tools (core/mcp_client.py, core/ext_connectors.py) reached
  chat_agent.py via extra_executor(name, args) with NO permission check at
  all. They are now tagged with a conservative default capability
  (WRITE|EXECUTE|NETWORK - no MCP tool self-declares risk) and routed through
  the SAME ToolPolicyGateway as built-ins. When "confirm before running
  commands" is on, MCP/connector calls now prompt like run_command already
  did - a real gap closed, and a user-visible change worth calling out.

R05-T05 infrastructure/mcp/mcp_source_manager.py
  McpToolSourceManager extracts the connection cache/lock/start-or-skip
  lifecycle out of state.py::AppContext (_mcp_connections/_conn_lock) into a
  standalone, directly-testable class. AppContext.build_mcp_tools and
  _ms365_builtin_connection now call ensure()/stop(); _ext_connections
  (unified Connectors) is out of scope for this task and keeps its own lock.

New tests: tests/unit/test_tool_registry_and_policy.py,
test_code_agent_tool_policy.py, test_cowork_extra_tool_policy.py,
test_mcp_source_manager.py (26 new tests).

Suite: 254 passed, 4 pre-existing failures unrelated to R05 (2 EPIC R02
config-security, 2 environment-dependent routing tests - see checklist).
check_imports: PASS. All new files < 400 LOC.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 22:20:57 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 3138856741 feat(domain): DTO ToolPolicyGateway — bản đề xuất, gỡ chốt cho N3
N3 (Co4E) cần gọi tool nhưng Team Hoa chưa bắt đầu. Ba đường: N3 ngồi đợi
(trái nguyên tắc không team nào chặn team nào), N3 tự phỏng đoán (không ai
soi, chắc chắn phải sửa), hoặc viết một bản đề xuất để Hoa duyệt. Chọn cái
thứ ba.

Ranh giới giữ đúng sơ đồ phân hệ trong plan.md: domain/security/ là của
Gamma, application/conversations/tool_policy_gateway.py là của Hoa. Nên Gamma
định nghĩa hình dạng, Hoa cài đặt. Không đụng file nào của họ.

Hình dạng bám vào code đang chạy: SecurityVerdict (allowed/reason/layer) và
hộp thoại xin phép ở chat_panel.py:1312. Khác biệt duy nhất là gộp thành một
câu trả lời ba trạng thái ALLOW/DENY/ASK, thay vì bắt chỗ gọi tự nhớ hỏi hai
nơi.

Hai ràng buộc đưa vào có chủ đích, mỗi cái một test:
  - DENY và ASK bắt buộc có reason, ném lỗi ngay lúc dựng. Người dùng cần
    biết vì sao bị chặn và audit_log cần ghi lại.
  - ASK không phải allowed. Đây là bẫy dễ mắc nhất: coi ASK như ALLOW thì
    tool chạy trước khi có ai đồng ý.

Kèm FakeToolPolicyGateway lập trình được theo tên tool hoặc theo hàm, có ghi
lại đã hỏi những gì — test khẳng định được "có hỏi cổng không", không chỉ
"kết quả đúng không".

docs/refactor/GammaTeam_decisions.md thêm quyết định 3, kèm nguyên văn tin
nhắn cần gửi Hoa và ô đánh dấu đã gửi / đã xác nhận.

102 test xanh (96 + 6 mới). CASAN Check 1 sạch. domain/ và application/ có 0
import PySide6 — kiểm bằng AST, vì grep đếm ra 4 mà cả 4 là chữ "PySide6"
nằm trong chính docstring cảnh báo. Check 3 của Team Duy nên phân tích cú
pháp chứ đừng grep.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 22:07:00 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 a164f32bfb docs(refactor): thêm mục input/output cho từng người
Ba khối, mỗi người một khối: cột trái là thứ phải có trong tay mới làm được kèm
nguồn, cột phải là thứ bắt buộc giao ra kèm người nhận. Nhãn 'có rồi' đánh dấu
những gì mục chung đã giao xong hôm nay (SecretStore, ConfigRepository, fake,
script CASAN).

Kèm bảng output bắt buộc với cả ba mỗi PR, mỗi dòng có lệnh tự kiểm.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 21:25:20 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 8a9ee5f875 chore(refactor): mục chung của Team Gamma — khung, hợp đồng, cổng CASAN
Sáu việc trong "mục chung" của bản phân công, làm trước khi ba nhánh tính năng
tách ra.

1. Khung 5 tầng theo đúng đường dẫn plan.md: domain/ application/
   infrastructure/ presentation/ platform/ + tests/fakes/ — 38 __init__.py.
   Trước đó là 0 file, mà mọi task của cả ba người đều ghi vào đây.
   Đã kiểm platform/ không che khuất module platform của stdlib.

2. Hợp đồng SecretStore và ConfigRepository (Protocol, chưa cài đặt) + fake
   chạy trong bộ nhớ. Danh sách thuộc tính không bịa: đếm 156 lời gọi
   ctx.config.* trong 29 file rồi lấy những cái dùng thật, xếp theo số lần.
   Cố ý bỏ config.data (36 lời gọi, nhiều nhất) — bê dict thô sang kiến trúc
   mới là bê nguyên vấn đề cũ.

3. tests/test_contracts.py — bài nghiệm thu, không phải test cho vui. Bài
   chính chạy tiến trình riêng và khẳng định dùng fake KHÔNG kéo theo
   cowork_local.config lẫn PySide6; đó là điều kiện để N2 và N3 code ngay hôm
   nay thay vì đợi bản thật ngày 23 và 26/08.

4. scripts/audit_security.py — CASAN Check 1, Gamma chủ trì (hạn 30/08). Viết
   sớm để kiểm liên tục trong lúc chuyển API key, không đợi tới ngày cổng.
   Lần chạy đầu ra 3 báo động giả (secret_in_output là tên quy tắc, api_key="x"
   là dữ liệu test) nên đã siết: ngưỡng độ dài, hằng liệt kê, hình dạng khoá
   i18n, và dấu "# casan: allow" làm lối thoát chuẩn.
   --self-test cắm 4 credential thật + 5 mẫu vô hại để chứng minh nó còn cắn
   được — một máy quét không tìm thấy gì chỉ có giá trị nếu chứng minh được nó
   biết tìm.

5. Ba check CASAN vào CI, chạy mọi PR thay vì dồn tới 30/08. Check 2 và 3
   thuộc Team Hoa và Team Duy, chưa có script — bước CI bỏ qua nếu file chưa
   tồn tại, để thêm cổng không làm đỏ CI của hai team kia.

6. docs/refactor/GammaTeam_decisions.md — hai quyết định chờ nhóm trưởng chốt:
   provider_conf() còn trả api_key hay không (ảnh hưởng 5 nơi, 3 nằm ngoài
   team), và số phận 24 checker UI sẽ vỡ khi file bị dời.

96 test xanh (90 cũ + 6 mới). CASAN Check 1: 0 credential lộ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 20:58:35 +09:00
Nam Pham Dinh ThanhandClaude Opus 5 09b1c93624 docs(refactor): phân việc Team Gamma thành 1 mục chung + 3 nhánh song song
Trang HTML tự đứng một mình, mở bằng trình duyệt là xem được, không cần mạng.
Chia toàn bộ phần việc của team trong plan.md (R02, R07-T06, R08-T07…T10, R09,
CASAN Check 1) cho 3 người:

  - Một mục chung nhóm trưởng làm trước, xong mới chia nhánh: dựng khung 5 thư
    mục đích (hiện là 0 file), interface + fake cho Config/Secrets, chốt số phận
    api_key, script CASAN Check 1, đưa 3 check vào CI, quyết số phận 24 checker
    UI sẽ vỡ khi file bị dời.
  - Ba nhánh tính năng ngang nhau, mỗi nhánh ~2.700 dòng: N1 cấu hình và vỏ ứng
    dụng (nhóm trưởng giữ, vì chạm app.py / config.py / theme.py / i18n.py),
    N2 giám sát, N3 Co4E.
  - Bảy quy ước cho N2 và N3, ba trong đó là bắt buộc.

Số dòng code, 156 lời gọi ctx.config, 24 lời gọi audit_log.record và baseline
90 test đều đo trực tiếp trên main ngày 21/08, không lấy từ tài liệu.

Footer ghi rõ phần nào là đề xuất, phần nào lấy từ ba tài liệu gốc — mục chung,
cách chia nhánh, quy ước và nghiệm thu là đề xuất.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 18:53:05 +09:00
anhtnm1andClaude Opus 5 6d3217e0b5 docs(refactor): add the Team Duy completion report for R01/R03/R04
docs/refactor/BaoCao_TeamDuy_R01_R03_R04.md records what was delivered against
each of the 16 tasks, the measured evidence (243 tests, 218 of them in 1.22s;
check_imports PASS; no production file over 400 LOC), the three real defects
found while working - the routing_application() deadlock, the swallowed
"notice" event, and the suite silently testing a different checkout - plus the
six open decisions and, explicitly, what was NOT tested (no manual app launch,
no real provider traffic, tools/check_*.py not run).

Refactoring_Checklist.md now links to it from the progress block.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:58:36 +09:00
anhtnm1andClaude Opus 5 67b8d2edbb docs(refactor): correct the Team Duy scope block in the checklist
The previous commit recorded Team Duy as owning R01/R02/R04/R10. That is wrong.
Feature_Architecture_Proposal.md line 7 and DeltaTeam_prompt.md line 17 both
state R01, R03, R04, R08 (Chat UI) and R10; R02 belongs to Team Nam, which is
also who owns the two failing config-security tests.

The completed work itself (R01, R03, R04) was already correct and is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:52:40 +09:00
anhtnm1andClaude Opus 5 15e1d3eb65 test(R03/R04): cover the three code paths that were changed but never executed
Verification gap closed. The suite proved the new services correct in isolation,
but three paths I had modified had no test actually running them:

tests/integration/test_task_executor_flow.py (7 tests)
  The Schedule Task path after R04-T05. Pins that History is still re-saved from
  the LIVE message list mid-run (the reason begin_turn() exists - the pre-turn
  copy would have frozen progress at the first user message), that update_plan
  tracking still reports an unfinished checklist, and that a failed run still
  raises so execute_task writes error.txt.

tests/integration/test_routing_surfaces.py (11 tests)
  Real offscreen CoworkTab/Co4ETab/FolderTab calling the shared routing service:
  correct surface key per screen, Auto switches, Off does not consult the engine,
  Manual switches only on approval, a pinned Admin agent still wins, and AI-Edit
  still pins TaskType.CODING. Also pins the field contract ui/routing_toggle.py
  reads off RoutingDecision (from_model/to_model as provider/model keys) - a
  rename there would only fail inside a modal dialog.

Also updates docs/refactor/Refactoring_Checklist.md: the 16 completed R01/R03/R04
tasks, the Team Duy daily rows, and a status block recording the measured
numbers, the scope correction (team owns R01/R02/R04/R10), and what is still
outstanding.

Suite: 243 passed, 2 pre-existing failures (EPIC R02). Fast suite (unit +
contracts + characterization + routing): 218 passed in 1.16s.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:45:05 +09:00
anhtnm1andClaude Opus 5 a53163ebaf feat(R04): immutable turn snapshot, typed agent events, conversation service
EPIC R04 (Team Duy) - the turn lifecycle leaves the widget.

R04-T01 domain/agents/conversation_execution_request.py
  Frozen snapshot of one turn, captured on the UI thread at submit time. The
  job closure used to read widget/workspace state from inside the worker
  thread, so a turn could run on a mix of submit-time and later state
  depending on thread timing.
R04-T02 domain/agents/agent_event.py
  13 frozen event types replacing untyped emit() dicts, with a two-way bridge
  so existing widgets keep consuming the legacy shape until EPIC R08. Adds
  TurnCompletedEvent - the end-of-turn signal the engine never had, which is
  why a cancelled turn and a failed turn look identical to the UI today.
R04-T03 application/conversations/conversation_application_service.py
  Runs a turn from a request and reports typed events. Never raises across the
  worker boundary; TurnResult.raise_if_failed() preserves the existing
  exception-based failure path. begin_turn()/execute_turn() expose the live
  message list for callers that autosave history mid-run.
R04-T04 ui/cowork_tab.py::build_job -> snapshot + service.
R04-T05 core/task_executors.py::_run_agent -> same service (was a second,
  slightly different assembly of the same call).

Caught while wiring the bridge: the first event vocabulary had no "notice"
event, so Agent Security warnings and auto-compaction notices would have been
silently swallowed. Added NoticeEvent plus a test that scans the engine sources
for emit() tags and fails when one has no typed counterpart.

New: tests/integration/ - real offscreen CoworkTab running a scripted turn end
to end (7 tests), including a characterisation of the extra provider call Agent
Security spends reviewing each request.

Suite: 225 passed, 2.74s. check_imports: PASS. All new files < 400 LOC.
2 pre-existing failures remain in test_config_security.py (EPIC R02/Team Nam).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:32:14 +09:00
anhtnm1andClaude Opus 5 96bec976e7 feat(R03): unify provider catalogue, routing decisions and usage telemetry
EPIC R03 (Team Duy) - one provider catalogue, one routing flow, one usage seam.

R03-T01 tests/contracts/test_providers.py
  29 contract tests every provider must satisfy: canonical assistant message,
  streamed text == returned content, reasoning never joins the answer, parsed
  tool arguments, ProviderError for every failure. Real adapters exercised
  offline by stubbing Provider._request.
R03-T02 domain/models/provider_descriptor.py
        infrastructure/providers/provider_registry.py
  Provider facts declared once (was split across providers/factory.py,
  DEFAULT_CONFIG and PROVIDER_LABELS). ProviderRegistry.build() also stamps the
  descriptor id onto the instance, so ollama/github_copilot/codex usage is no
  longer all attributed to "openai_compat", and never mutates the caller config.
R03-T03 application/model_routing/routing_application_service.py
  Pure-Python routing policy with four modes: Off, Auto, Manual and the new
  Fallback (switch only AFTER the current model fails). Depends on a RoutingPort
  protocol; production wires the existing core.routing engine underneath.
R03-T04/T05 ui/chat_panel.py, ui/co4e_tab.py, ui/folder_tab.py
  Three near-identical routing copies (~40 lines each) replaced by a call to
  ctx.routing_application() plus a confirm callback. Mode vocabulary now lives
  in one place (normalize_mode/is_valid_mode) instead of four literal tuples.
R03-T06 infrastructure/telemetry/usage_sink.py
  Token usage extracted from both providers into UsageEvent + UsageEventSink.
  Estimation pinned against core.usage_tracker so no recorded number changes.

Also fixes a deadlock introduced while wiring AppContext: routing_application()
held _routing_lock and called routing(), which takes the same non-reentrant lock.

Suite: 186 passed, 1.22s. check_imports: PASS. All new files < 400 LOC.
2 pre-existing failures remain in test_config_security.py (EPIC R02/Team Nam).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:22:28 +09:00
anhtnm1andClaude Opus 5 bbc09f628a feat(R01): architecture foundation, offline fakes and characterization net
EPIC R01 (Team Duy) - safety net before the parallel refactor starts.

R01-T01 docs/architecture/ADR-001-layered-architecture.md
  4-tier boundaries, allowed dependency directions, invariants I1-I6 and
  the strangler-fig migration strategy.
R01-T02 tests/fakes/{fake_provider,fake_tool_executor}.py
  Scripted, offline Provider and extra-tool executor doubles.
R01-T03 scripts/check_imports.py
  AST-based Clean Architecture Guard (CASAN Check 3). Also covers relative
  imports and function-local imports; ASCII-only output for cp932 consoles.
R01-T04 tests/characterization/test_run_cowork.py
  13 snapshot tests pinning run_cowork's current observable contract before
  EPIC R04 moves its orchestration into application/.
R01-T05 docs/architecture/dormant-code.md
  Import-graph scan: 43 unimported modules verified down to 6 genuinely
  dormant items (~1887 LOC); the rest run via subprocess/CLI entry points.

tests/conftest.py binds `cowork_local` to THIS checkout by absolute path -
previously sys.path discovery could import a sibling checkout and the suite
would silently test the wrong code.

Suite: 104 passed, 1.08s (2 pre-existing failures in test_config_security.py
remain - config.py still ships a hardcoded default password, EPIC R02/Team Nam).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:05:50 +09:00
354 changed files with 59178 additions and 19164 deletions
+29
View File
@@ -39,3 +39,32 @@ jobs:
- name: Run tests
run: python -m pytest tests -q
# --- CASAN Verification Gate -------------------------------------
# Ba check này là điều kiện của cổng ngày 30/08. Chạy trên MỌI PR để
# biết vi phạm ngay hôm phát sinh, thay vì dồn tới ngày cổng.
#
# Check 1 do Team Gamma sở hữu và đã có. Check 2 (Team Hoa) và Check 3
# (Team Duy) chưa viết — bước dưới bỏ qua nếu script chưa tồn tại, để
# thêm cổng không làm đỏ CI của hai team kia.
- name: "CASAN Check 1 — không có credential lộ (Team Gamma)"
run: |
python scripts/audit_security.py --self-test
python scripts/audit_security.py
- name: "CASAN Check 2 — file production ≤ 400 dòng (Team Hoa)"
run: |
if [ -f scripts/check_loc.py ]; then
python scripts/check_loc.py
else
echo "scripts/check_loc.py chưa có — Team Hoa viết, hạn 30/08. Bỏ qua."
fi
- name: "CASAN Check 3 — domain/ và application/ không import PySide6 (Team Duy)"
run: |
if [ -f scripts/check_imports.py ]; then
python scripts/check_imports.py
else
echo "scripts/check_imports.py chưa có — Team Duy viết, hạn 30/08. Bỏ qua."
fi
+11 -5
View File
@@ -28,7 +28,10 @@ bower_components/
.env.preview
*.pem
*.key
secrets/
# Neo vào gốc repo: mẫu không neo nuốt MỌI thư mục tên secrets ở mọi độ
# sâu — nó đã âm thầm chặn infrastructure/secrets/ (mã nguồn, không phải
# bí mật) khỏi repo suốt 21-22/08.
/secrets/
credentials.json
.npmrc
.yarnrc
@@ -36,9 +39,11 @@ credentials.json
# =============================================================================
# Build & Distribution
# =============================================================================
dist/
build/
out/
# Neo vao goc — mau khong neo se nuot moi thu muc trung ten o moi do sau,
# ke ca ma nguon. Da mac dung loi do voi secrets/ (xem khoi Credentials).
/dist/
/build/
/out/
.next/
.nuxt/
.output/
@@ -73,7 +78,8 @@ desktop.ini
# Logs & Debug
# =============================================================================
*.log
logs/
# Neo vao goc: infrastructure/logs/ la ma nguon, khong phai log chay may.
/logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+57 -13
View File
@@ -1,30 +1,74 @@
# Cowork Local
Cowork Local is the internal AI cowork desktop platform owned by the Cowork Team. It provides the Cowork runtime, workspace and agent experiences, MCP/connectors, security controls, and model routing foundation.
Cowork Local is the internal AI cowork desktop platform. It provides a local-first desktop runtime, multi-turn conversational agents, workspace isolation, task scheduling, MCP connectors, security guardrails, and model routing.
The Cowork Team owns this product and its stable branch. The FSG AI Core Team contributes selected reusable capabilities through branches and Pull Requests; it is not the owner or final merger of this repository.
---
## Quick start
## 🏛️ 4-Tier Clean Architecture
The imported application is a Python/PySide6 package. Run it from the directory that contains `cowork_local`:
The codebase strictly adheres to **Clean Architecture** with unidirectional inward dependencies:
```text
presentation/ (PySide6 UI, Shell, NavRail, Chat, Scheduling, Settings, Dashboard)
│
▼
application/ (Pure Python Orchestration: Conversations, Scheduling, Workspaces, Monitoring, Routing)
│
▼
domain/ (Pure Python: Entities, Immutable Execution Requests, Agent Events, Descriptors)
▲
│
infrastructure/ (Adapters, LLM Providers, Atomic Persistence, Keyring SecretStore, MCP)
```
- **Domain & Application Layers**: 100% Pure Python (zero Qt/UI imports).
- **Single Responsibility**: Every production module is strictly `<= 400 LOC`.
- **Security & Durability**: API keys stored in OS Keyring; atomic JSON disk persistence.
---
## 🚀 Quick Start
### 1. Run the Desktop Application
From the repository root:
```bash
python -m cowork_local
```
The source snapshot does not include a complete runtime dependency manifest. Use the Cowork Team's supported runtime environment until that packaging contract is documented. The reliable automated test surface currently checked by CI is:
### 2. Run Automated Tests
```bash
python -m pip install -r cowork_local/requirements-test.txt
python -m pytest cowork_local/tests -q
python -m pip install -r requirements-test.txt
pytest -q
```
When already inside this repository, run `python -m pytest tests -q`.
---
Configuration and runtime data live under `~/.cowork_local/`. Provider keys and local unlock codes must be supplied through environment variables or an approved secret manager; see `.env.example`.
## 🛡️ CASAN Quality Gate & Verification
## Contributing
Before submitting any Pull Request, run the unified CASAN Quality Gate:
Start with [START_CONTRIBUTING.md](START_CONTRIBUTING.md), then read [CONTRIBUTING.md](CONTRIBUTING.md). Core AI task execution remains in [fsg-ai-core-assets](http://34.143.229.138/gitea-admin/fsg-ai-core-assets); source changes are reviewed as Pull Requests in this repository.
```bash
# Run all 4 quality gates (Clean Arch, Secrets, LOC, and Pytest Suite)
python scripts/run_quality_gate.py
Security concerns should follow [SECURITY.md](SECURITY.md). Ownership and completion rules are documented under `docs/governance/`.
# Run static and architectural guards only (fast check)
python scripts/run_quality_gate.py --skip-tests
```
Individual guard scripts:
- **Clean Architecture Import Guard**: `python scripts/check_imports.py`
- **Secrets & Plaintext Audit**: `python scripts/audit_security.py`
- **Single Responsibility LOC Guard**: `python scripts/check_loc.py --max-lines 400`
- **Release E2E Smoke Test**: `pytest tests/e2e/test_smoke.py -v`
---
## 🤝 Contributing & Recipes
- **Quick Start Guide**: See [START_CONTRIBUTING.md](START_CONTRIBUTING.md).
- **Contributor Recipes**: See [docs/governance/contributor-recipes.md](docs/governance/contributor-recipes.md) for step-by-step recipes to:
1. Add a new AI Model Provider.
2. Add a new Built-in Tool / MCP Server.
3. Add a new Screen / Tab / Widget.
- **Security Policy**: See [SECURITY.md](SECURITY.md).
+42 -18
View File
@@ -1,40 +1,64 @@
# Start Contributing
## What is this repository?
Welcome to the **Cowork Local** contributor guide!
Cowork Local is the Cowork Team's product/platform repository: desktop runtime, UI/UX, workspaces, agents, MCP/connectors, security, and reusable platform foundations.
---
The Cowork Team owns architecture, product behavior, releases, the stable branch, final review, and merge. The FSG AI Core Team is a contributor for selected generic capabilities such as MCP integration, agent capabilities, orchestration/model-routing tests, evaluation/security integration, and reusable platform improvements.
## 🏛️ Architecture & Ground Rules
## Where are Core AI tasks?
1. **4-Tier Clean Architecture**:
- `domain/`: Business entities and immutable data structures (Pure Python).
- `application/`: Application services and orchestration (Pure Python).
- `infrastructure/`: External integrations, adapters, persistence, and secrets.
- `presentation/`: Desktop UI widgets, PySide6 components, and Qt signals.
- **Rule**: `domain/` and `application/` must NEVER import `PySide6` or any UI framework.
Use [fsg-ai-core-assets Issues/Project](http://34.143.229.138/gitea-admin/fsg-ai-core-assets) as the Core AI task source of truth. Pick and assign a contribution task there, then move it to `In Progress`.
2. **File Size Limit (LOC)**:
- Every file in `domain/`, `application/`, `infrastructure/`, and `presentation/` must be `<= 400 LOC`.
Do not copy the Core AI backlog, golden datasets, CASAN assets, agent catalog, or evaluation repository into Cowork Local. Only source/artifacts required by an agreed Cowork runtime contract belong here.
3. **In-Code Comments**:
- All code logic, error handling, and design rationales must be documented with clear **English comments**.
## Make the change
---
Create a focused branch:
## 🚀 Development Workflow
### 1. Create a Topic Branch
```bash
git switch -c core-ai/TL-xxx-short-name
git switch -c feat/my-new-feature
```
For Cowork-native work use `feat/`, `fix/`, `test/`, `docs/`, `perf/`, or `refactor/`. Keep one logical change in one Pull Request.
### 2. Implement Using Contributor Recipes
Follow the standardized recipes in [`docs/governance/contributor-recipes.md`](docs/governance/contributor-recipes.md):
- **Recipe 1**: Adding a new AI Model Provider.
- **Recipe 2**: Adding a new Tool or MCP Server.
- **Recipe 3**: Adding a new UI Screen or Widget.
Run the application from the parent directory with `python -m cowork_local`. Run the current automated test suite from this repository with:
### 3. Run CASAN Quality Gate Locally
Before committing and pushing your branch, ensure all quality gates pass:
```bash
python -m pip install -r requirements-test.txt
python -m pytest tests -q
python scripts/run_quality_gate.py
```
Use environment variables for credentials; never commit `.env`, `~/.cowork_local/`, logs, customer data, or generated runtime files.
---
## Review and completion
## 🧪 Testing Pyramid
Before opening a Pull Request, obtain Core AI pre-review and move the Core task to `Review`. Open the Pull Request in Cowork Local with the Core repository URL, issue, task ID, scope, validation evidence, and security impact. Then move the Core task to `Upstream Review`.
We maintain a strict multi-tier test pyramid:
- `tests/unit/`: Fast unit tests (no I/O, < 0.05s).
- `tests/contracts/`: Contract tests for Provider and Tool interfaces.
- `tests/integration/`: Component integration tests (Qt offscreen).
- `tests/e2e/`: End-to-End release smoke tests (`pytest tests/e2e/test_smoke.py`).
- `tests/fakes/`: Reusable in-memory test doubles (`FakeProvider`, `FakeToolRuntime`).
The Cowork Team may request changes or approve and merge. A Core AI task is `Done` only after the Cowork Pull Request is merged—not when implementation or Core AI review finishes. Record the Pull Request and merge reference in the Core issue.
---
See [CONTRIBUTING.md](CONTRIBUTING.md) for conventions and `docs/governance/` for ownership, review, and Definition of Done.
## 📋 Definition of Done (DoD)
A Pull Request is ready for merge only when:
- [x] All production files are `<= 400 LOC` (`python scripts/check_loc.py`).
- [x] Clean Architecture boundary check has 0 violations (`python scripts/check_imports.py`).
- [x] Secrets audit finds 0 plaintext credentials (`python scripts/audit_security.py`).
- [x] 100% of test suite passes without regressions (`pytest tests/`).
- [x] E2E release smoke tests pass (`pytest tests/e2e/test_smoke.py`).
+12
View File
@@ -0,0 +1,12 @@
"""adapters/ — Adapter riêng cho Qt (clock, thread, timer).
Kế hoạch gốc đặt tên thư mục này là ``platform/``. Không dùng được: chạy
bất kỳ script nào từ thư mục gốc repo (``python tools/...``,
``python scripts/...``) thì ``platform/`` **che khuất module ``platform``
của thư viện chuẩn**, và ``import keyring`` chết ngay với
``AttributeError: module 'platform' has no attribute 'system'``.
Repo có 26 script chạy đúng kiểu đó.
Đổi tên là cách duy nhất chắc chắn — không thể bắt mọi người nhớ "đừng bao
giờ chạy python từ thư mục gốc".
"""
View File
+22 -1246
View File
File diff suppressed because it is too large Load Diff
+12 -1
View File
@@ -1 +1,12 @@
"""Application Layer: Pure Python use cases and application services."""
"""Application layer - pure Python use-case orchestration.
Sits between ``presentation/`` (Qt widgets) and ``domain/`` (entities). A module
here answers "what has to happen, in what order" for one use case - route a
turn, run a conversation - without knowing whether a human, a scheduler or a
test triggered it.
Hard rule (ADR-001 I1/I3, enforced by ``scripts/check_imports.py``): no
PySide6/PyQt imports and no reach into ``presentation/``/``ui/``. Results travel
back up through plain-Python callbacks; turning those into Qt signals is the
presentation layer's job.
"""
+12 -1
View File
@@ -1 +1,12 @@
"""Application conversations package: turn lifecycle orchestration and agent execution."""
"""Application conversations package: turn lifecycle orchestration, agent execution, and tool approval policy."""
from .conversation_application_service import (
ConversationApplicationService,
)
from .tool_policy_gateway import ConfirmGate, ToolPolicyGateway
__all__ = [
"ConversationApplicationService",
"ToolPolicyGateway",
"ConfirmGate",
]
@@ -0,0 +1,322 @@
"""The turn lifecycle, once, in pure Python (R04-T03).
Extracted from ``core/chat_agent.py::run_cowork``, whose 260-line body mixed the
lifecycle (compose the prompt, call the model, dispatch tools, respect the step
ceiling, tidy the sandbox) with the concrete machinery that does each of those
things. The lifecycle is the part with rules worth testing — and the part that
was untestable, because reaching it meant standing up a Qt widget and a worker
thread.
Here it is a plain object driven through the seams in :mod:`turn_runtime`, so a
test states a rule ("the guard runs before the model", "a rejected command never
executes") in three lines. ``core/chat_agent.py`` keeps its signature and
delegates, and the presentation layer keeps receiving the same events via the
legacy codec, so nothing downstream had to change with it.
Behavioural contract: this is a faithful port, not an improvement pass. Where
the original had a quirk (the step-ceiling note only merges into the answer when
the last message is the assistant's), the quirk is preserved and commented —
changing what a user sees belongs in its own change, not smuggled into a move.
"""
from __future__ import annotations
import logging
from typing import Any, Dict, List, Optional, Tuple
from ...domain.agents.agent_event import (
AssistantMessageCompletedEvent,
ErrorEvent,
OutputsAddedEvent,
OutputsRemovedEvent,
PlanStep,
PlanUpdatedEvent,
ReasoningChunkEvent,
TextChunkEvent,
ToolCallFinishedEvent,
ToolCallStartedEvent,
ToolOutputChunkEvent,
)
from ...domain.agents.agent_result import AgentResult
from ...domain.agents.conversation_execution_request import ConversationExecutionRequest
from .turn_runtime import (
BUDGET_NOTE_TEMPLATE,
GATED_TOOLS,
PLAN_TOOL,
REASONING_ONLY_NOTE,
REJECTED_OUTPUT,
AttachmentReader,
CancelFn,
CommandGuard,
ContextCompactor,
EventSink,
ModelCallPort,
PermissionRequest,
PromptGuard,
PromptPreparer,
ToolRuntimePort,
)
logger = logging.getLogger("cowork_local.application.conversations")
class ConversationApplicationService:
"""Runs one :class:`ConversationExecutionRequest` to completion."""
def __init__(
self,
model: ModelCallPort,
tools: ToolRuntimePort,
*,
prepare_prompt: Optional[PromptPreparer] = None,
prompt_guard: Optional[PromptGuard] = None,
command_guard: Optional[CommandGuard] = None,
compact: Optional[ContextCompactor] = None,
permission_request: Optional[PermissionRequest] = None,
attachment_reader: Optional[AttachmentReader] = None,
) -> None:
self._model = model
self._tools = tools
# Every hook is optional so the service degrades to a plain chat turn.
# That is not only a test convenience: a headless caller legitimately has
# no guards (``security_config=None`` today) and no permission dialog.
self._prepare_prompt = prepare_prompt
self._prompt_guard = prompt_guard
self._command_guard = command_guard
self._compact = compact
self._permission_request = permission_request
self._attachment_reader = attachment_reader
# -- public API ------------------------------------------------------ #
def execute(self, request: ConversationExecutionRequest, sink: EventSink,
cancel: Optional[CancelFn] = None,
messages: Optional[List[Dict[str, Any]]] = None) -> AgentResult:
"""Run the turn, streaming events to ``sink``, and report the outcome.
``messages``, when given, is a working list the caller already built —
it MUST already end with this turn's user message, and the service
appends into that very object instead of composing its own. The Cowork
widget needs this: it hands out the same list to
``_reattach_running_turn``, which replays the steps done so far while the
worker is still appending, and to ``_finalize_turn``, which slices it by
the pre-turn snapshot length. A private list would break both silently.
Passing ``None`` (every headless caller) lets the service compose the
list from the request, which is the mode the rest of this class assumes.
Raises whatever the runtime raises (a blocked prompt, a dead gateway):
the caller already has a failure path for that — ``AgentWorker.failed``
in the UI, the artifact writer in Schedule Task — and swallowing the
exception here would silently turn a failed turn into an empty answer.
An :class:`ErrorEvent` is emitted first so subscribers see the failure
on the same stream as everything else.
"""
cancel = cancel or (lambda: False)
# -- pre-flight. Runs BEFORE the output snapshot, so a turn refused here
# leaves the output folder completely untouched (tidying is not a
# read-only operation — see ToolRuntimePort.finalize).
try:
# The caller's list is used by reference on purpose (see above); only
# the self-composed path may build a fresh one.
working = messages if messages is not None else self._compose_messages(request)
tools = list(self._tools.specs(request.allowed_tools))
if self._prepare_prompt is not None:
self._prepare_prompt(working, tuple(getattr(t, "name", "") for t in tools))
if request.enforce_rules and self._prompt_guard is not None:
self._prompt_guard(working)
except Exception as exc: # noqa: BLE001 — reported, then re-raised as-is
sink(ErrorEvent(message=str(exc)))
raise
before = self._tools.snapshot()
steps_used = 0
plan_steps: Tuple[PlanStep, ...] = ()
completed_naturally = False
try:
for _ in range(request.effective_max_steps):
if cancel():
break
# Auto-compress when nearing the model's context budget; a no-op
# when off or when the conversation is still short.
if self._compact is not None:
self._compact(working, cancel)
assistant = self._model.call(
working, tools,
on_text=lambda piece: sink(TextChunkEvent(delta=piece)),
on_reasoning=lambda piece: sink(ReasoningChunkEvent(delta=piece)),
cancel=cancel,
)
working.append(assistant)
steps_used += 1
tool_calls = assistant.get("tool_calls") or []
if not tool_calls and not (assistant.get("content") or "").strip():
# Written into the message, not just emitted, so the stored
# conversation never ends on a blank assistant turn.
assistant["content"] = REASONING_ONLY_NOTE
sink(TextChunkEvent(delta=REASONING_ONLY_NOTE))
sink(AssistantMessageCompletedEvent(content=assistant.get("content", "")))
if not tool_calls:
completed_naturally = True
break
for call in tool_calls:
if cancel():
break
tool_message, steps = self._dispatch(request, call, sink, cancel)
working.append(tool_message)
if steps is not None:
plan_steps = steps
if not completed_naturally and not cancel():
self._announce_budget_exhausted(request, working, sink)
except Exception as exc: # noqa: BLE001 — reported, then re-raised as-is
sink(ErrorEvent(message=str(exc)))
raise
finally:
# Always tidy: the sandbox and generator scripts must not survive a
# turn that stopped abruptly. Runs on success, cancel and failure.
self._finalize_outputs(before, sink, cancelled=cancel())
result = AgentResult(
messages=working, steps_used=steps_used, cancelled=cancel(),
budget_exhausted=not completed_naturally and not cancel(),
plan_steps=plan_steps,
)
sink(result.to_turn_completed_event())
return result
# -- internals ------------------------------------------------------- #
def _compose_messages(self, request: ConversationExecutionRequest) -> List[Dict[str, Any]]:
"""History snapshot plus this turn's user message.
The attachment text is read HERE rather than when the request was built,
because extraction is slow enough to freeze the UI thread; the request
deliberately carries paths only.
"""
body = request.prompt
if self._attachment_reader is not None:
body = self._attachment_reader(request.prompt, request.attachments)
messages = [dict(m) for m in request.messages]
messages.append({"role": "user", "content": request.user_content(body)})
return messages
def _dispatch(self, request: ConversationExecutionRequest, call: Dict[str, Any],
sink: EventSink, cancel: CancelFn
) -> Tuple[Dict[str, Any], Optional[Tuple[PlanStep, ...]]]:
"""Run one tool call.
Returns ``(tool_message, plan_steps)`` — the message to append to the
conversation, and the new checklist when this call was the plan tool
(``None`` otherwise, so the caller can tell "no change" from "empty
plan").
"""
call_id = str(call.get("id", ""))
name = str(call.get("name", ""))
args = call.get("arguments") or {}
# The plan tool is invisible in the transcript: it updates the Plan panel
# and nothing else, so it skips preview, guard and gate entirely.
if name == PLAN_TOOL:
outcome = self._tools.execute(name, args, on_output=None, cancel=cancel)
steps = tuple(outcome.get("plan_steps") or ())
sink(PlanUpdatedEvent(steps=steps))
return self._tool_message(call_id, name, outcome.get("output", "")), steps
# Announce first: the user sees the code/command about to run before the
# guard or the approval dialog interrupts them, which is the whole point
# of showing the step CLI-style.
preview = self._tools.preview(name, args)
sink(ToolCallStartedEvent(call_id=call_id, name=name, arguments=dict(args),
preview=preview))
if request.enforce_rules and self._command_guard is not None:
self._command_guard(name, args)
if not self._approved(request, name, args, preview, sink, call_id):
return self._tool_message(call_id, name, REJECTED_OUTPUT), None
outcome = self._tools.execute(
name, args,
on_output=lambda piece: sink(ToolOutputChunkEvent(
call_id=call_id, name=name, delta=piece)),
cancel=cancel,
)
sink(ToolCallFinishedEvent(
call_id=call_id, name=name, ok=bool(outcome.get("ok", False)),
output=str(outcome.get("output", "")), path=str(outcome.get("path", "") or ""),
produced=outcome.get("produced") or (),
))
return self._tool_message(call_id, name, outcome.get("output", "")), None
def _approved(self, request: ConversationExecutionRequest, name: str,
args: Dict[str, Any], preview: Any, sink: EventSink,
call_id: str) -> bool:
"""Whether this call may run.
Only command-shaped tools are gated, and only when the workspace asked
to confirm them: file writes stay inside the turn's own sandbox, so
prompting for those would be noise. A rejection is reported as a failed
tool result — the model needs to read back that it was refused, or it
will simply try the same call again.
"""
if not request.requires_permission_gate or name not in GATED_TOOLS:
return True
if self._permission_request is None:
# Confirm mode with nobody to ask: refusing is the safe direction,
# since auto-running is exactly what confirm mode exists to prevent.
logger.warning("turn: confirm mode without a permission callback — refusing %r", name)
approved = False
else:
approved = bool(self._permission_request({
"name": name, "args": args,
"preview": preview.to_dict() if preview is not None else {},
}))
if not approved:
sink(ToolCallFinishedEvent(call_id=call_id, name=name, ok=False,
output=REJECTED_OUTPUT))
return approved
@staticmethod
def _tool_message(call_id: str, name: str, output: Any) -> Dict[str, Any]:
"""The canonical ``role: tool`` message the model reads back."""
return {"role": "tool", "tool_call_id": call_id, "name": name,
"content": str(output or "")}
@staticmethod
def _announce_budget_exhausted(request: ConversationExecutionRequest,
messages: List[Dict[str, Any]], sink: EventSink) -> None:
"""Report being cut off by the step ceiling.
The note always reaches the transcript. It is merged into the stored
answer only when the last message is the assistant's — which, when the
ceiling is hit, it never is (the turn ends on a tool result). The branch
is kept because it is what the current runtime does, and because it is
the correct behaviour the day a caller ends the loop differently.
"""
note = BUDGET_NOTE_TEMPLATE.format(steps=request.effective_max_steps)
sink(TextChunkEvent(delta=note))
if messages and messages[-1].get("role") == "assistant":
messages[-1]["content"] = (messages[-1].get("content") or "") + note
def _finalize_outputs(self, before: Any, sink: EventSink, cancelled: bool) -> None:
"""Tidy the output folder and report what moved.
Failures are logged, never raised: this runs in a ``finally``, so an
exception here would replace the turn's real error (or its success) with
a housekeeping one.
"""
try:
removed, added = self._tools.finalize(before, cancelled=cancelled)
except Exception: # noqa: BLE001
logger.exception("turn: tidying the output folder failed")
return
if removed:
sink(OutputsRemovedEvent(paths=tuple(removed)))
if added:
sink(OutputsAddedEvent(paths=tuple(added)))
__all__ = ["ConversationApplicationService"]
@@ -0,0 +1,325 @@
"""Wires :class:`ConversationApplicationService` to the existing runtime (R04-T03).
The service is written against the narrow seams in :mod:`turn_runtime` so it can
be tested with plain fakes. This module supplies the real implementations — the
provider call with its recovery pass, the tool/sandbox runtime, the security
guards, context compaction — and is therefore the ONLY file in
``application/conversations/`` that knows ``core/*`` exists. Same shape (and
same reason) as ``application/model_routing/core_routing_adapter.py`` in R03.
Every ``core`` import is deferred into a method body: importing the tool runtime
pulls in ``requests``, ``psutil`` and the sandbox stack, and code that merely
*builds* a service must not pay for that.
Faithfulness notes — two places where this reproduces a quirk of the current
runtime rather than the behaviour one would design fresh. Both are marked
inline: the MS365 system-prompt paragraph keys off the CONFIGURED extra tools
(not the advertised subset), and the ``tool_result`` path falls back to the
call's own ``path`` argument resolved against the workdir.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from ...domain.agents.agent_event import PlanStep, ToolPreview
from .conversation_application_service import ConversationApplicationService
from .turn_runtime import PLAN_TOOL, EventSink
# Legacy emit: the dict-based callback every current caller already owns.
LegacyEmit = Callable[[Dict[str, Any]], None]
def legacy_event_sink(emit: LegacyEmit) -> EventSink:
"""Adapt a typed :class:`EventSink` onto the legacy dict ``emit``.
This is what lets R04 land without touching the presentation layer: the
service thinks in typed events, ``ui/chat_panel.py::_on_event`` keeps
receiving exactly the dicts it already dispatches on. Deleted in R08 once
the widget consumes events directly.
"""
return lambda event: emit(event.to_legacy_dict())
class CoreModelCall:
""":class:`ModelCallPort` over ``code_agent._call_provider_with_recovery``.
Not ``provider.chat`` directly: the recovery wrapper adds the one bounded
retry that hides a dropped connection or a momentarily unreachable gateway,
and losing it would be a visible regression on flaky corporate networks.
"""
def __init__(self, provider: Any) -> None:
self._provider = provider
def call(self, messages, tools, on_text=None, on_reasoning=None, cancel=None):
from ...core.code_agent import _call_provider_with_recovery
return _call_provider_with_recovery(self._provider, messages, tools, on_text,
cancel, on_reasoning)
class CoreToolRuntime:
""":class:`ToolRuntimePort` over ``core/tools.py`` + Cowork's file tools."""
def __init__(self, output_dir: Path, *, title: str = "",
extra_tools: Optional[Sequence[Any]] = None, extra_executor=None,
security_config: Any = None, agent_role: str = "") -> None:
self._output_dir = Path(output_dir)
self._title = title
self._extra_tools = list(extra_tools or ())
self._extra_names = {getattr(t, "name", "") for t in self._extra_tools}
# The connector executor MCP/REST tools are routed to; None when the
# turn has no connectors enabled.
self._extra_executor = extra_executor
self._security_config = security_config
self._agent_role = agent_role
self._ctx: Any = None # built on first use (see _tool_context)
# -- the configured extra tools, for the system-prompt hints ---------- #
@property
def extra_names(self) -> frozenset:
return frozenset(self._extra_names)
def _tool_context(self):
"""The sandboxed ``ToolContext`` every built-in tool call runs inside.
Built once per turn and cached: it carries the resource limits and the
network policy, so re-deriving it mid-turn could let a Settings change
take effect halfway through work already in flight.
"""
if self._ctx is None:
from ...core import agent_security
from ...core.tools import ToolContext
limits, block_network = agent_security.sandbox_settings(self._security_config)
self._ctx = ToolContext(
self._output_dir, flatten_writes=True, # keep every file in the Output root
resource_limits=limits, block_network=block_network,
allow_url_fetch=agent_security.url_fetch_allowed(self._security_config),
jira=(self._security_config.data.get("jira") if self._security_config else None),
)
return self._ctx
# -- ToolRuntimePort -------------------------------------------------- #
def specs(self, allowed_tools: Optional[Sequence[str]] = None) -> List[Any]:
"""Advertised tools: Cowork's own two, the enabled built-ins, then MCP.
``allowed_tools`` restricts the list so a read-only step literally cannot
write. ``update_plan`` and the connector tools always survive the filter:
the plan tool has no side effects, and connectors are opted into
explicitly rather than governed by the built-in capability scope.
"""
from ...core.chat_agent import SAVE_FILE_SPEC
from ...core.plan import UPDATE_PLAN_SPEC
from ...core.tools import enabled_tool_specs
specs = ([SAVE_FILE_SPEC, UPDATE_PLAN_SPEC]
+ list(enabled_tool_specs(self._security_config))
+ self._extra_tools)
if allowed_tools is None:
return specs
allow = set(allowed_tools) | {PLAN_TOOL} | self._extra_names
return [t for t in specs if getattr(t, "name", "") in allow]
def preview(self, name: str, args: Dict[str, Any]) -> Optional[ToolPreview]:
"""What the user sees before the call runs."""
# A connector call has no local diff to show, so it renders as the plain
# argument dump the runtime already used.
if name in self._extra_names:
return ToolPreview(kind="info", title=name, text=str(args))
if name == "save_file":
return self._save_file_preview(args)
from ...core.tools import describe_action
raw = describe_action(self._tool_context(), name, args)
return ToolPreview.from_dict(raw)
def _save_file_preview(self, args: Dict[str, Any]) -> ToolPreview:
"""A before/after diff for the file the agent is about to write.
A brand-new file renders all-green (before is empty); an overwrite shows
the real change, so saving a file reads like editing one.
"""
import difflib
from ...core.chat_agent import _structure_summary, _titled_filename
fname = _titled_filename(self._title, args.get("filename", "output.txt"))
content = str(args.get("content", ""))
summary = _structure_summary(fname, content)
old = ""
existing = self._output_dir / fname
if existing.exists():
try:
old = existing.read_text(encoding="utf-8", errors="replace")
except OSError:
pass # unreadable existing file: show it as a fresh write
diff = "".join(difflib.unified_diff(
old.splitlines(keepends=True), content.splitlines(keepends=True),
fromfile=f"a/{fname}", tofile=f"b/{fname}",
)) or content[:4000]
return ToolPreview(kind="diff", title=f"Save {fname}",
text=f"{summary}\n\n{diff[:4000]}")
def execute(self, name: str, args: Dict[str, Any], on_output=None,
cancel=None) -> Dict[str, Any]:
"""Run one tool call and return the runtime's result mapping."""
if name == PLAN_TOOL:
return self._execute_plan(args)
if name in self._extra_names and self._extra_executor is not None:
# Connector results carry no local file, so no path/produced keys —
# matching what the runtime reports for an MCP call today.
result = self._extra_executor(name, args) or {}
return {"ok": bool(result.get("ok", False)), "output": result.get("output", "")}
if name == "save_file":
from ...core.chat_agent import _do_save_file
return dict(_do_save_file(self._output_dir, self._title, args))
from ...core.tools import execute_tool
ctx = self._tool_context()
result = dict(execute_tool(ctx, name, args, cancel=cancel, on_output=on_output,
agent_role=self._agent_role))
# Quirk preserved: a tool that wrote the file named in its OWN arguments
# (write_file/edit_file) does not report a path, so the runtime derives
# one from the argument. Dropping this would empty the Output list.
if not result.get("path") and isinstance(args, dict) and args.get("path"):
result["path"] = str(ctx.workdir / str(args["path"]))
return result
def _execute_plan(self, args: Dict[str, Any]) -> Dict[str, Any]:
"""Apply an ``update_plan`` call: validate the steps and audit them.
Produces no file and no chat bubble; the service turns the returned
steps into a single plan event.
"""
from ...core import agent_roles, audit_log
from ...core.plan import normalize_plan_steps
steps = normalize_plan_steps(args.get("steps"))
audit_log.record("tool_call", PLAN_TOOL, True, f"{len(steps)} step(s)",
agent_role=agent_roles.PLANNER)
return {"ok": True, "output": "Plan updated.",
"plan_steps": [PlanStep(title=s["title"], status=s["status"]) for s in steps]}
def snapshot(self) -> Any:
from ...core.tools import _snapshot
return _snapshot(self._output_dir)
def finalize(self, before: Any, cancelled: bool = False
) -> Tuple[List[str], List[str]]:
"""Drop the scratch sandbox and flatten deliverables into the root.
Returns ``(gone, arrived)``: a file that MOVED counts as both, because
the Output list keys entries by path and must drop the old one.
"""
from ...core.chat_agent import _cleanup_cowork_intermediates
removed, moved = _cleanup_cowork_intermediates(self._output_dir, before,
cancelled=cancelled)
gone = list(removed) + [old for old, _new in moved]
arrived = [new for _old, new in moved]
return gone, arrived
def build_cowork_conversation_service(
provider: Any,
output_dir: Path,
emit: LegacyEmit,
*,
title: str = "",
project_context: str = "",
extra_tools: Optional[Sequence[Any]] = None,
extra_executor=None,
security_config: Any = None,
gate: Any = None,
agent_role: str = "",
) -> ConversationApplicationService:
"""A service wired to the real runtime, ready to execute a Cowork turn.
``emit`` is the legacy dict callback: the guards and the compactor publish
their own notices through it directly (exactly as they do now), while the
service's typed events reach it via :func:`legacy_event_sink`.
``gate`` present means the workspace asked to confirm commands; pass the
request with ``gate_mode="confirm"`` so the two agree. A gate of ``None``
keeps the pre-existing auto-run behaviour.
"""
from ...core import agent_roles
tools = CoreToolRuntime(
output_dir, title=title, extra_tools=extra_tools, extra_executor=extra_executor,
security_config=security_config, agent_role=agent_role or agent_roles.COWORK,
)
def prepare_prompt(messages: List[Dict[str, Any]], advertised: Tuple[str, ...]) -> None:
"""Insert the system prompt, then fold in skills, rules and project text.
``advertised`` is unused on purpose: the runtime decides the MS365
paragraph from the CONFIGURED connector tools, not from the subset a
capability scope left advertised. Changing that changes the prompt the
model sees, so it stays as-is here and belongs to R05's tool-policy work.
"""
from ...core.chat_agent import (
COWORK_TOOL_PROMPT,
OPENDATALOADER_PDF_PROMPT,
_apply_project_context,
_apply_security_rules,
_apply_skills,
)
from ...core.deps import _can_pip
from ...core.java_runtime import find_java
from ...core.security_rules import load_rules
from ...core.skills import active_skills_text
if not messages or messages[0].get("role") != "system":
system = COWORK_TOOL_PROMPT
if any(n.startswith("ms365_") for n in tools.extra_names):
system += ("\nThe user has signed in to Microsoft 365 and enabled some ms365__* "
"tools (Outlook / Teams / OneDrive / SharePoint / meeting transcripts, "
"via the built-in MS365 MCP server). Use them whenever the request "
"involves that data — don't say you can't access it.")
if find_java() is not None and _can_pip():
# Only advertise the Java-backed PDF extractor when BOTH the JVM
# and pip are available, so the agent is never steered into a
# command that cannot work on this machine.
system += "\n\n" + OPENDATALOADER_PDF_PROMPT
messages.insert(0, {"role": "system", "content": system})
_apply_skills(messages, active_skills_text())
_apply_security_rules(messages, load_rules())
_apply_project_context(messages, project_context)
def prompt_guard(messages: List[Dict[str, Any]]) -> None:
from ...core import agent_security
agent_security.enforce_prompt(provider, messages, security_config, emit)
def command_guard(name: str, args: Dict[str, Any]) -> None:
from ...core import agent_security
agent_security.enforce_command(provider, name, args, security_config, emit)
def compact(messages: List[Dict[str, Any]], cancel) -> None:
from ...core import context_budget
context_budget.maybe_compact(provider, messages, security_config,
emit=emit, cancel=cancel)
return ConversationApplicationService(
CoreModelCall(provider), tools,
prepare_prompt=prepare_prompt,
prompt_guard=prompt_guard,
command_guard=command_guard,
compact=compact,
permission_request=(gate.request if gate is not None else None),
)
__all__ = [
"LegacyEmit", "legacy_event_sink", "CoreModelCall", "CoreToolRuntime",
"build_cowork_conversation_service",
]
@@ -0,0 +1,77 @@
"""Turn the Cowork widget's captured state into a request (R04-T04).
``ui/cowork_tab.py::build_job`` reads a dozen values off the widget on the UI
thread and has to translate three of them before a turn can run: which message
is this turn's prompt, which messages are its history, and whether the workspace
wants commands confirmed. Those rules lived inline in the widget, where no test
could reach them — and each fails silently when wrong (a duplicated user message,
or a command that quietly stops asking for approval).
They live here instead, as the mapping step the migration map assigns to the
application layer. The widget keeps only what is genuinely widget-specific:
reading its own state and building the provider.
Layer rules (``docs/architecture/ADR-001-layered-architecture.md``): pure Python.
Everything arrives as a plain value, so this module never sees a widget.
"""
from __future__ import annotations
from typing import Any, Dict, Optional, Sequence
from ...domain.agents.conversation_execution_request import ConversationExecutionRequest
def build_cowork_turn_request(
*,
turn_id: str,
session_id: str,
messages: Sequence[Dict[str, Any]],
surface: str = "cowork",
project_id: str = "",
title: str = "",
provider_id: str = "",
model: str = "",
instructions: str = "",
output_dir: Optional[Any] = None,
home_output_root: Optional[Any] = None,
confirm_commands: bool = False,
agent_role: str = "cowork",
) -> ConversationExecutionRequest:
"""Build one Cowork turn's immutable request.
``messages`` is the widget's working list, which ALREADY ends with this
turn's user message (the chat panel composes it — prefix, attachments,
session notes — before the job starts). So the prompt is that last message
and the history is everything before it. The request records both; the
service is handed the same working list and appends into it.
Keyword-only on purpose: a dozen positional strings in a call site is exactly
how a title ends up in the project-id slot.
"""
history = list(messages or ())
# ``pop`` rather than ``[-1]``/``[:-1]`` so the empty-list case needs no
# special branch: a turn with nothing in it yields an empty prompt instead of
# raising IndexError deep inside a worker thread.
last = history.pop() if history else {}
return ConversationExecutionRequest(
turn_id=turn_id,
session_id=session_id,
surface=surface,
project_id=project_id,
title=title,
prompt=str(last.get("content") or ""),
messages=history,
provider_id=provider_id,
model=model,
project_context=instructions,
output_dir=output_dir,
home_output_root=home_output_root,
# The workspace's Auto-run override (or the global setting) decides
# whether run_command/install_package must be approved first.
gate_mode="confirm" if confirm_commands else "auto",
agent_role=agent_role,
)
__all__ = ["build_cowork_turn_request"]
@@ -0,0 +1,83 @@
"""ToolPolicyGateway - one confirm/deny decision path for every tool call
(R05-T03).
Today "does this tool call need the user's OK first" is answered by a
different hand-written check per engine:
* ``core/chat_agent.py::run_cowork`` — ``name in ("run_command",
"install_package")``, a literal tuple.
* ``core/code_agent.py::run_code`` — ``name in (WRITE_TOOLS | MS365_WRITE_TOOLS)``,
a set built from two other hand-maintained sets.
* MCP/connector tools (``core/mcp_client.py``, ``core/ext_connectors.py``) —
no check at all; ``chat_agent.py`` calls ``extra_executor(name, args)``
directly.
Three answers to the same question, and the third one is a real gap: an MCP
tool that deletes files or calls an external API today runs with zero
confirmation even when the user turned "confirm before running commands" on.
This gateway answers the question from data (:class:`~domain.tools.tool_descriptor.ToolCapability`
via a :class:`~domain.tools.tool_registry.ToolRegistry`) instead of a literal
name list, so registering a tool with the right capability is what gates it -
nothing to remember at each new call site. R05-T04 is what actually registers
MCP/connector tools with a capability; this module only needs the mechanism
to exist.
Pure Python: no Qt, no direct dialog. The actual approval prompt stays exactly
what it is today - a ``gate`` object with a ``.request(payload) -> bool``
method, supplied by the presentation layer (Settings' "confirm before running
commands" wires it up, or None for auto-run) - this module only decides
WHEN to ask it, never how to render the question.
"""
from __future__ import annotations
from typing import Any, Dict, Optional, Protocol
from cowork_local.domain.tools import ToolCapability, ToolRegistry
class ConfirmGate(Protocol):
"""Shape of the existing ``PermissionGate`` both engines already use."""
def request(self, payload: Dict[str, Any]) -> bool: ...
class ToolPolicyGateway:
"""Decides whether a tool call needs approval, for ONE calling surface.
``gated_capabilities`` is what makes this per-surface: Cowork only ever
asked about ``run_command``/``install_package`` (capability ``EXECUTE``),
while the Code tab additionally confirms plain file writes (capability
``WRITE``). Passing the wrong set here would silently change which tools
prompt for approval - see the callers in ``core/chat_agent.py`` and
``core/code_agent.py`` for the exact sets that preserve today's behavior.
"""
def __init__(self, registry: ToolRegistry, gated_capabilities: ToolCapability) -> None:
self._registry = registry
self._gated_capabilities = gated_capabilities
def requires_confirmation(self, name: str) -> bool:
"""True when ``name``'s declared capabilities overlap this surface's
gated set. An unregistered tool never requires confirmation through
this path - callers that must fail safe on unknown tools check
``name in registry`` themselves (see R05-T04's MCP wrapping, which
registers every tool it exposes before any call can reach here)."""
return bool(self._registry.capabilities_for(name) & self._gated_capabilities)
def allow(self, name: str, gate: Optional[ConfirmGate], payload: Dict[str, Any]) -> bool:
"""True when the call may proceed.
``gate is None`` preserves each engine's existing "no gate wired -
auto-run" behavior; a tool outside ``gated_capabilities`` is never
asked about, matching read-only tools "never confirm" today.
``payload`` is whatever ``gate.request(...)`` already expects at that
call site (the two engines use slightly different dict shapes) - this
gateway only decides WHETHER to call it, never reshapes the payload.
"""
if gate is None or not self.requires_confirmation(name):
return True
return bool(gate.request(payload))
__all__ = ["ToolPolicyGateway", "ConfirmGate"]
+177
View File
@@ -0,0 +1,177 @@
"""The seams :mod:`conversation_application_service` runs a turn through (R04-T03).
Two Protocols and six callables — chosen deliberately, not by reflex. The
refactor plan forbids giving every class an interface, so a contract exists here
only where there is both a real ``core/*`` implementation AND a test double:
* :class:`ModelCallPort` — one provider round-trip *including* the app's
existing context-overflow recovery, which is why the raw ``Provider.chat``
signature is not enough.
* :class:`ToolRuntimePort` — the tool + output-folder runtime, kept as one
cohesive object because every method operates on the same sandbox.
Everything else is a single function, so it is expressed as a callable type
rather than a class with one method (the same choice R03 made for
``ConfirmationCallback``). All of them are optional: a service built with none
of them still runs a plain chat turn, which is what keeps the unit tests short.
Layer rules (``docs/architecture/ADR-001-layered-architecture.md``): application
layer — pure Python. Nothing here imports PySide6, ``core.*``, ``providers.*``
or ``ui.*``; the concrete wiring lives in :mod:`core_runtime_adapter`.
"""
from __future__ import annotations
from typing import (
Any,
Callable,
Dict,
List,
Optional,
Protocol,
Sequence,
Tuple,
runtime_checkable,
)
from ...domain.agents.agent_event import AgentEvent, ToolPreview
# The plan tool is special-cased by the loop: it drives the Plan panel and
# produces no chat bubble and no file. Named here so the check is not a bare
# string literal in the middle of the dispatch.
PLAN_TOOL = "update_plan"
# Tools that need approval before they run when the workspace is in confirm
# mode. R05 replaces this tuple with a real ``ToolPolicyGateway`` keyed on
# ToolCapability; until then it mirrors exactly what the runtime gates today.
GATED_TOOLS = ("run_command", "install_package")
# Shown when the user (or the workspace policy) rejects a proposed command. The
# exact string also becomes the tool message the model reads back, so it must
# stay stable.
REJECTED_OUTPUT = "Rejected by user."
# A reasoning model can answer with thinking only. The note is written into the
# assistant message itself, not merely emitted, so an unattended run does not
# read back an empty answer and report "(no output)".
REASONING_ONLY_NOTE = "*(model returned only its reasoning — try rephrasing)*"
# Emitted when the turn is stopped by its own safety ceiling rather than by the
# model finishing. Never silent: being cut off looks exactly like being done.
BUDGET_NOTE_TEMPLATE = (
"\n\n⚠️ Reached the {steps}-step safety limit before the task signalled "
"completion — stopping here. Re-run to continue if more work remains."
)
def combine_instructions(*blocks: Optional[str]) -> str:
"""Join the standing-instruction blocks of a turn, skipping the absent ones.
A turn's instructions arrive as several independent blocks — the project's
shared context, an Admin agent's persona, a skill's rules, the
"this runs unattended" reminder — and each caller was joining them inline
with its own ``f"{a}\\n\\n{b}" if a else b`` expression. Two call sites now
need the same rule (the Cowork widget in R04-T04 and the task runner in
R04-T05), which is the point at which it stops being an expression.
Whitespace-only blocks count as absent: they would otherwise open the system
prompt with a stray blank line.
"""
return "\n\n".join(b.strip() for b in blocks if b and b.strip())
# --------------------------------------------------------------------------- #
# Callables.
# --------------------------------------------------------------------------- #
# Receives every typed event the turn produces. The caller decides what that
# means — render it, forward it as a legacy dict, autosave on it.
EventSink = Callable[[AgentEvent], None]
# True once the user has asked to stop. Polled between steps and between tool
# calls, the same cadence the current runtime uses.
CancelFn = Callable[[], bool]
# ``(prompt, attachment_paths) -> body``. Runs on the worker thread because
# extracting a .docx may pip-install a parser or call LibreOffice.
AttachmentReader = Callable[[str, Tuple[str, ...]], str]
# ``(messages, advertised_tool_names) -> None`` — inserts the system prompt and
# folds in skills, security rules and project instructions, in place. It needs
# the tool names because the system prompt gains an MS365 paragraph only when
# ms365 tools are actually present.
PromptPreparer = Callable[[List[Dict[str, Any]], Tuple[str, ...]], None]
# Reviews the assembled request; raises to refuse the turn outright.
PromptGuard = Callable[[List[Dict[str, Any]]], None]
# Reviews one proposed tool call; raises to refuse it.
CommandGuard = Callable[[str, Dict[str, Any]], None]
# ``(messages, cancel) -> None``. Summarises old turns in place when the
# conversation nears the model's context budget; a no-op when compaction is off
# or the conversation is short. It takes the cancel signal because compacting
# calls the model itself, so Stop has to reach it too.
ContextCompactor = Callable[[List[Dict[str, Any]], "CancelFn"], None]
# ``(action) -> approved``. Blocks the worker thread while a human decides.
PermissionRequest = Callable[[Dict[str, Any]], bool]
# --------------------------------------------------------------------------- #
# Ports.
# --------------------------------------------------------------------------- #
@runtime_checkable
class ModelCallPort(Protocol):
"""One call to the model, with the app's retry/recovery behaviour applied."""
def call(self, messages: List[Dict[str, Any]], tools: Sequence[Any],
on_text: Optional[Callable[[str], None]] = None,
on_reasoning: Optional[Callable[[str], None]] = None,
cancel: Optional[CancelFn] = None) -> Dict[str, Any]:
"""Return the canonical assistant message (content plus tool calls)."""
@runtime_checkable
class ToolRuntimePort(Protocol):
"""The tools a turn may call, and the folder its files land in."""
def specs(self, allowed_tools: Optional[Sequence[str]] = None) -> Sequence[Any]:
"""Tool specs to advertise to the model, already filtered.
Returns opaque objects (the provider layer's ``ToolSpec``); the service
only ever reads ``.name`` off them, which is what keeps this layer free
of a provider import.
"""
def preview(self, name: str, args: Dict[str, Any]) -> Optional[ToolPreview]:
"""Human-readable description of a call that is about to run."""
def execute(self, name: str, args: Dict[str, Any],
on_output: Optional[Callable[[str], None]] = None,
cancel: Optional[CancelFn] = None) -> Dict[str, Any]:
"""Run one tool call.
Returns the runtime's own result mapping: ``ok``, ``output``, optionally
``path``/``produced`` for files it created, and ``plan_steps`` for the
plan tool.
"""
def snapshot(self) -> Any:
"""Opaque record of the output folder before the turn started."""
def finalize(self, before: Any, cancelled: bool = False
) -> Tuple[Sequence[str], Sequence[str]]:
"""Tidy the output folder; return ``(removed_paths, added_paths)``.
Not read-only — it deletes the scratch sandbox and flattens sub-folders —
so the service only calls it for a turn that actually started.
"""
__all__ = [
"PLAN_TOOL", "GATED_TOOLS", "REJECTED_OUTPUT", "REASONING_ONLY_NOTE",
"BUDGET_NOTE_TEMPLATE", "combine_instructions",
"EventSink", "CancelFn", "AttachmentReader", "PromptPreparer", "PromptGuard",
"CommandGuard", "ContextCompactor", "PermissionRequest",
"ModelCallPort", "ToolRuntimePort",
]
+6 -1
View File
@@ -1 +1,6 @@
"""Application monitoring package: Monitoring query service for audit and metrics."""
"""Application monitoring package: Monitoring and dashboard query services."""
from .dashboard_query_service import DashboardQueryService
from .monitoring_query_service import MonitoringQueryService
__all__ = ["DashboardQueryService", "MonitoringQueryService"]
@@ -0,0 +1,112 @@
"""DashboardQueryService - read-only usage/cost queries for the Dashboard
screen (R08-T13, extracted from ``ui/dashboard_tab.py::DashboardTab``, lines
196-199/256-261/284-322 of the original 437-line file: ``_pricing``,
``_period_range``'s date-math, and the ``period_totals``/``period_breakdown``
calls ``_refresh_chart`` made directly).
``ui/dashboard_tab.py`` called ``core/usage_tracker.py``/``core/model_
pricing.py`` directly from FIVE different methods spread across what is now
three widgets (``token_usage_card_widget.py``, ``usage_chart_widget.py``,
``habits_widget.py``) — each recomputing the same merged pricing dict. This
service is the one place that merge happens now; the three widgets share it
instead of each calling ``core.usage_tracker``/``core.model_pricing`` on
their own.
Pure Python: no Qt. Wraps ``core/usage_tracker.py`` (a plain-Python module
already) rather than reimplementing any of its date/cost math.
"""
from __future__ import annotations
from datetime import date, timedelta
from typing import Any, Dict, List, Tuple
class DashboardQueryService:
"""Usage/cost queries scoped to one ``AppContext``.
Args:
ctx: ``AppContext`` — read for ``ctx.config`` (pricing table,
currency, budget) and nothing else; this class does no I/O of
its own beyond what ``core.usage_tracker`` already does.
directory: Optional custom usage directory. If None, uses default USAGE_DIR.
"""
def __init__(self, ctx: Any, directory: Optional[Path] = None) -> None:
self.ctx = ctx
self._directory = directory
def pricing(self) -> Dict[str, Any]:
"""The merged price table (defaults + user overrides), synced from
Monitoring's model-pricing table first so cost figures always agree
between the two screens."""
from cowork_local.core import model_pricing as mp
from cowork_local.core import usage_tracker as ut
mp.sync_to_usage(self.ctx.config)
return {**ut.DEFAULT_PRICING, **(self.ctx.config.data.get("usage") or {})}
def period_range(self, granularity: str, offset: int) -> Tuple[date, date]:
"""The SELECTED period as an inclusive ``(start, end)`` date range —
drives every widget on the screen (cards, chart, habits)."""
from cowork_local.core import usage_tracker as ut
start, end = ut.period_bounds(granularity, offset)
return start, end - timedelta(days=1) # load_events end is inclusive
def summary(self, start: date, end: date) -> Dict[str, Any]:
"""Everything the stat cards + habits panel need for one period:
the raw events, ``usage_tracker.summarize``'s aggregate stats, the
per-bucket costs, and their total — computed once so both widgets
read the same numbers instead of loading events twice."""
from cowork_local.core import usage_tracker as ut
events = ut.load_events(start, end, directory=self._directory)
pricing = self.pricing()
stats = ut.summarize(events)
costs = ut.cost_usd_events(events, pricing)
return {
"events": events,
"pricing": pricing,
"stats": stats,
"costs": costs,
"total_cost": sum(costs.values()),
}
def chart_series(self, granularity: str, offset: int, metric: str
) -> List[Tuple[str, float]]:
"""``(label, value)`` points for the spline chart — WEEK -> 7 days,
MONTH -> weeks, YEAR -> 12 months, in whichever ``metric``
("tokens" | "cost") was selected."""
from cowork_local.core import usage_tracker as ut
events = ut.load_events(directory=self._directory) # all events; breakdown slices by period
pricing = self.pricing()
parts = ut.period_breakdown(events, granularity, pricing, offset=offset)
mi = 0 if metric == "tokens" else 1 # (label, tokens, cost) -> +1 for the value
return [(row[0], float(row[mi + 1])) for row in parts]
def period_totals(self, granularity: str, offset: int) -> Tuple[float, float]:
"""``(tokens, cost)`` totals for one period — used to compute the
vs-previous-period delta the chart's reference line shows."""
from cowork_local.core import usage_tracker as ut
events = ut.load_events(directory=self._directory)
return ut.period_totals(events, granularity, self.pricing(), offset)
def period_range_label(self, granularity: str, offset: int) -> str:
from cowork_local.core import usage_tracker as ut
return ut.period_range_label(granularity, offset)
def budget_status(self):
from cowork_local.core import usage_tracker as ut
return ut.budget_status(self.ctx.config)
def set_budget(self, amount: float, currency: str) -> None:
from cowork_local.core import usage_tracker as ut
ut.set_budget(self.ctx.config, amount, currency)
__all__ = ["DashboardQueryService"]
@@ -0,0 +1,47 @@
"""Application-layer view of an audit event — decoupled from the
infrastructure ``CanonicalAuditEvent`` so ``application/`` doesn't need to
share a concrete class with ``infrastructure/`` (only the shape). Field names
match the canonical audit schema (see
``infrastructure/telemetry/audit_logger.py``) 1:1.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict
@dataclass(frozen=True)
class AuditEventDTO:
ts: str
kind: str
name: str
ok: bool
detail: str
agent_role: str = ""
account: str = ""
role: str = ""
machine: str = ""
@classmethod
def from_raw(cls, raw: Dict[str, Any]) -> "AuditEventDTO":
"""Tolerant of missing keys — accepts both a
``CanonicalAuditEvent.to_dict()`` result and any historical raw
``.jsonl`` row."""
return cls(
ts=str(raw.get("ts", "")),
kind=str(raw.get("kind", "")),
name=str(raw.get("name", "")),
ok=bool(raw.get("ok", False)),
detail=str(raw.get("detail", "")),
agent_role=str(raw.get("agent_role", "")),
account=str(raw.get("account", "")),
role=str(raw.get("role", "")),
machine=str(raw.get("machine", "")),
)
def to_dict(self) -> Dict[str, Any]:
return {
"ts": self.ts, "kind": self.kind, "agent_role": self.agent_role,
"name": self.name, "ok": self.ok, "detail": self.detail,
"account": self.account, "role": self.role, "machine": self.machine,
}
@@ -0,0 +1,54 @@
"""Read-only query service over audit events — filter + sort + pagination.
Pure Python: no PySide6 import, no UI code. Depends only on an injected
``AuditEventRepository`` (see ``repository/audit_event_repository.py``), so it
is fully unit-testable with ``InMemoryAuditEventRepository`` and independent
of file I/O or Qt.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from .dto.audit_event_dto import AuditEventDTO
from .repository.audit_event_repository import AuditEventRepository
@dataclass(frozen=True)
class Page:
items: List[AuditEventDTO]
total: int
page: int
page_size: int
@property
def has_more(self) -> bool:
return self.page * self.page_size < self.total
class MonitoringQueryService:
"""Read-only. Callers ask for a filtered/sorted/paginated slice of the
audit log; this service never writes anything."""
def __init__(self, repository: AuditEventRepository) -> None:
self._repository = repository
def query(self, kind: Optional[str] = None, ok: Optional[bool] = None,
text: Optional[str] = None, sort_by: str = "ts",
descending: bool = True, page: int = 1, page_size: int = 50) -> Page:
events = self._repository.load(kind=kind)
if ok is not None:
events = [e for e in events if e.ok == ok]
if text:
needle = text.lower()
events = [e for e in events
if needle in e.name.lower() or needle in e.detail.lower()]
events = sorted(events, key=lambda e: getattr(e, sort_by, ""), reverse=descending)
total = len(events)
page = max(1, page)
start = (page - 1) * page_size
items = events[start:start + page_size] if page_size > 0 else events
return Page(items=items, total=total, page=page, page_size=page_size)
@@ -0,0 +1,41 @@
"""Audit-event repository — the boundary between ``MonitoringQueryService``
and where events actually live. ``CanonicalAuditEventRepository`` is the real
adapter (wraps an injected ``CanonicalAuditLogger``); ``InMemoryAuditEventRepository``
is a constructor-injected test double, following this repo's existing
``Fake*``/``Recording*`` convention (see ``tests/routing/*``,
``tests/test_project_context_mcp_template.py``) rather than ``unittest.mock``.
"""
from __future__ import annotations
from typing import List, Optional, Protocol
from ..dto.audit_event_dto import AuditEventDTO
class AuditEventRepository(Protocol):
def load(self, kind: Optional[str] = None) -> List[AuditEventDTO]:
...
class CanonicalAuditEventRepository:
"""Adapter over ``infrastructure.telemetry.audit_logger.CanonicalAuditLogger``
— the only place this application service reaches into infrastructure."""
def __init__(self, audit_logger) -> None:
self._audit_logger = audit_logger
def load(self, kind: Optional[str] = None) -> List[AuditEventDTO]:
events = self._audit_logger.load_events(kind=kind)
return [AuditEventDTO.from_raw(e.to_dict()) for e in events]
class InMemoryAuditEventRepository:
"""Test double — holds a fixed list of events, no file I/O."""
def __init__(self, events: List[AuditEventDTO]) -> None:
self._events = list(events)
def load(self, kind: Optional[str] = None) -> List[AuditEventDTO]:
if kind is None:
return list(self._events)
return [e for e in self._events if e.kind == kind]
+6 -1
View File
@@ -1 +1,6 @@
"""Application scheduling package: TaskApplicationService and AI task planning."""
"""Application services for Schedule Task (EPIC R07)."""
from .ai_task_planner_service import AiTaskPlannerService
from .task_application_service import MoveResult, RunNowResult, TaskApplicationService
__all__ = ["TaskApplicationService", "RunNowResult", "MoveResult", "AiTaskPlannerService"]
@@ -0,0 +1,94 @@
"""AiTaskPlannerService - AI-generate / import task lists, outside the widget
(R07-T05).
``ui/schedule_task_tab.py``'s ``_AiCreateDialog`` already delegates the
actual planning to two existing pure functions —
``core/ai_task_planner.py::plan_tasks`` (natural-language description ->
task dicts, via the active provider) and
``core/task_import.py::import_tasks`` (Excel/CSV/JSON -> task dicts) — so
this service does not reimplement either. What it DOES own is one small
piece of business logic that currently only exists inside the dialog's
``AgentWorker`` job closure (``_generate``'s ``job()``): every AI-generated
task must carry the SAME file/link attachments the user attached to the
request, so they're available again at run time, not just visible to the
planner while it drafts the task list. Leaving that step trapped in a Qt
worker closure means it can only be exercised by driving the real dialog;
here it's a plain, independently testable method.
Pure Python: no Qt import. The provider is a constructor-injected factory
(``() -> Provider``, no arguments — matches ``AppContext.build_active_
provider``), the same dependency-inversion shape
``application/conversations/conversation_application_service.py`` (R04-T03)
uses for ITS provider factory.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
ProviderFactory = Callable[[], Any]
CancelFn = Callable[[], bool]
class AiTaskPlannerService:
"""AI task generation + file/Excel/CSV/JSON import, for
``presentation/scheduling/ai_task_creator_dialog.py`` and
``ai_task_import_dialog.py`` (R08-T11) to call instead of importing
``core.ai_task_planner``/``core.task_import`` directly.
Args:
provider_factory: ``() -> Provider``. Production passes
``AppContext.build_active_provider``; tests pass a lambda
returning a :class:`FakeProvider`.
"""
def __init__(self, provider_factory: Optional[ProviderFactory] = None) -> None:
self._provider_factory = provider_factory
def plan(
self,
description: str,
*,
file_paths: Sequence[str] = (),
links: Sequence[str] = (),
provider: Any = None,
cancel: Optional[CancelFn] = None,
) -> List[Dict[str, Any]]:
"""Turn ``description`` into a list of NOT-yet-saved task dicts.
``provider`` overrides the constructor's factory for this one call
(useful for tests, or a caller that already resolved a provider);
omit it to use the injected factory. Raises ``RuntimeError`` when
no provider is available at all, or when the model's reply had no
parseable task list (same error ``core.ai_task_planner.plan_tasks``
already raises).
"""
resolved = provider if provider is not None else self._resolve_provider()
from cowork_local.core.ai_task_planner import plan_tasks
planned = plan_tasks(resolved, description, cancel=cancel)
# Attachments apply to EVERY generated task so they're still there
# when the task actually runs, not just while the planner drafts it
# (see module docstring — this used to only happen inside the
# dialog's worker closure).
for task in planned:
task["input"]["file_paths"] = list(file_paths)
task["input"]["links"] = list(links)
return planned
def import_file(self, path: Union[str, Path]) -> List[Dict[str, Any]]:
"""Excel/CSV/JSON -> NOT-yet-saved task dicts, auto-chained in file
order. Raises ``ValueError`` with a human-readable message on an
unusable/unsupported file (same contract
``core.task_import.import_tasks`` already has)."""
from cowork_local.core.task_import import import_tasks
return import_tasks(path)
def _resolve_provider(self) -> Any:
if self._provider_factory is None:
raise RuntimeError("No provider available to plan tasks.")
return self._provider_factory()
__all__ = ["AiTaskPlannerService"]
@@ -0,0 +1,172 @@
"""TaskApplicationService - task CRUD + dispatch, outside the widget (R07-T04).
``ui/schedule_task_tab.py`` currently does all of this by importing
``core/tasks.py`` module functions directly and calling
``self.scheduler.run_now(...)`` inline inside Qt slot methods
(``_run_now``, ``_context_menu``'s duplicate/pause/delete branches,
``_on_task_dropped``'s per-lane business rules). None of it is Qt — it's
plain CRUD plus a few small rules ("a manual task never auto-runs",
"dropping a card on Done disables its schedule so it won't re-fire",
"dropping on Scheduled with no time set needs the editor, not a silent
no-op") — but it can only be exercised today by driving the real widget.
This service is the seam ``presentation/scheduling/kanban_board_widget.py``
(R08-T11) calls instead: same rules, same
:class:`~infrastructure.persistence.json.task_repository_impl.TaskRepository`
underneath, testable with no Qt at all.
Pure Python: no Qt import. ``run_now`` dispatch is a plain injected callable
(production wires ``TaskScheduler.run_now``; tests inject a stub), the same
constructor-injection shape ``application/conversations/conversation_
application_service.py`` (R04-T03) uses for its provider factory.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional
# "TaskRepository" here is a Protocol-shaped name, not an import: this module
# only calls .get/.save/.delete/.duplicate, so any object with that shape
# (the real infrastructure.persistence.json.task_repository_impl.TaskRepository,
# or a test double) works without this file importing infrastructure/ at
# module scope.
RunNowFn = Callable[[str], bool]
@dataclass
class RunNowResult:
"""Outcome of asking a task to run immediately.
``reason`` is one of ``""`` (ok), ``"not_found"``, ``"manual_task"``
(manual tasks never auto-run — spec: they exist to be run by a human),
``"no_scheduler"`` (no ``run_now`` callable was wired in), or
``"already_running"`` (the scheduler's own dedupe rejected it).
"""
ok: bool
reason: str = ""
@dataclass
class MoveResult:
"""Outcome of dropping a task card onto a Kanban lane
(``move_to_status``). The caller (kanban widget) uses the flags to decide
what to show — a full re-render, a "task is running" toast, or opening
the task editor — without re-deriving the business rule itself."""
task: Optional[Dict[str, Any]]
blocked: bool = False # dropped while already running — ignored
ran_now: bool = False # dropped on the Running lane — dispatched
run_now_result: Optional[RunNowResult] = None
needs_schedule: bool = False # dropped on Scheduled with no run_at set — needs editing
class TaskApplicationService:
"""CRUD + dispatch for Schedule Task, backed by a ``TaskRepository``.
Args:
repository: a ``TaskRepository``-shaped object (``.get``, ``.save``,
``.delete``, ``.duplicate``). Production passes
``infrastructure.persistence.json.task_repository_impl.
TaskRepository()``; tests pass one scoped to a ``tmp_path``.
run_now: ``(task_id) -> bool``. Production passes
``TaskScheduler.run_now``; ``None`` means no scheduler is wired
(matches the widget's own "no scheduler" guard today).
"""
def __init__(self, repository: Any, run_now: Optional[RunNowFn] = None) -> None:
self._repository = repository
self._run_now = run_now
# -- single-task actions ------------------------------------------------ #
def run_now(self, task_id: str) -> RunNowResult:
"""Dispatch ``task_id`` immediately. A "Run now" always counts as
manual approval (spec §13) — this is the ONE path that bypasses
``execution.requires_approval``, same as the scheduler's own
``run_now`` already does."""
task = self._repository.get(task_id)
if task is None:
return RunNowResult(False, "not_found")
if task.get("task_type") == "manual":
return RunNowResult(False, "manual_task")
if self._run_now is None:
return RunNowResult(False, "no_scheduler")
ok = self._run_now(task_id)
return RunNowResult(ok, "" if ok else "already_running")
def duplicate(self, task_id: str) -> Optional[Dict[str, Any]]:
"""A saved copy with a fresh identity — see
``core/tasks.py::duplicate_task`` for what's preserved/reset."""
task = self._repository.get(task_id)
if task is None:
return None
dup = self._repository.duplicate(task)
self._repository.save(dup)
return dup
def toggle_pause(self, task_id: str) -> Optional[Dict[str, Any]]:
"""Pause a task, or resume a paused one back to Backlog (matches
``ui/schedule_task_tab.py``'s context-menu action exactly — resuming
does NOT restore whatever status the task had before pausing, only
Backlog, so the user re-schedules explicitly rather than a stale
schedule silently re-firing)."""
task = self._repository.get(task_id)
if task is None:
return None
task["status"] = "backlog" if task.get("status") == "paused" else "paused"
self._repository.save(task)
return task
def delete(self, task_id: str) -> bool:
if self._repository.get(task_id) is None:
return False
self._repository.delete(task_id)
return True
def bulk_delete(self, task_ids: List[str]) -> int:
"""Delete every id in ``task_ids``; returns how many actually
existed (mirrors ``_confirm_and_delete_selected``'s best-effort
loop — a stale id in the selection doesn't abort the rest)."""
return sum(1 for tid in task_ids if self.delete(tid))
# -- Kanban drag/drop ----------------------------------------------------- #
def move_to_status(self, task_id: str, new_status: str) -> Optional[MoveResult]:
"""Apply the business rule behind dropping a card into a lane
(``ui/schedule_task_tab.py::_on_task_dropped``, moved here so it's
testable without a real ``QListWidget`` drag gesture):
* already running -> the drop is ignored (a running task can't be
re-filed by dragging it).
* dropped on Running -> runs it now (counts as manual approval).
* dropped on Done -> marks it done AND disables its schedule, so a
repeating task marked done by hand doesn't quietly re-fire later.
* dropped on Scheduled with no ``run_at`` set yet -> saved as-is but
flagged ``needs_schedule`` — the caller should open the editor
rather than leave a Scheduled card that will never actually run.
* anything else -> plain status change.
"""
task = self._repository.get(task_id)
if task is None:
return None
if task.get("status") == "running":
return MoveResult(task=task, blocked=True)
if new_status == "running":
result = self.run_now(task_id)
return MoveResult(task=self._repository.get(task_id), ran_now=True, run_now_result=result)
if new_status == "done":
task["status"] = "done"
task["schedule"]["enabled"] = False
self._repository.save(task)
return MoveResult(task=task)
task["status"] = new_status
if new_status == "scheduled" and not task["schedule"].get("enabled"):
if task["schedule"].get("run_at"):
task["schedule"]["enabled"] = True
else:
self._repository.save(task)
return MoveResult(task=task, needs_schedule=True)
self._repository.save(task)
return MoveResult(task=task)
__all__ = ["TaskApplicationService", "RunNowResult", "MoveResult"]
@@ -0,0 +1,379 @@
"""``Co4EWorkflowService`` — nửa "hành vi" tách ra từ ``Co4ERunManager`` cũ.
Bối cảnh: ``core/co4e_run_manager.py::Co4ERunManager`` là một ``QObject`` gộp
chung dữ liệu run (nay là ``domain/workflows/run_record.py::RunRecord``), logic
chạy job trên ``AgentWorker``/``QThread``, và logic đọc/ghi lịch sử ra đĩa. File
này là phần còn lại sau khi tách DTO: quản lý vòng đời nhiều run cùng lúc, các
hook nhận sự kiện từ worker, và lưu/nạp lịch sử — nhưng THUẦN PYTHON, không kế
thừa ``QObject`` và không tự dựng ``QThread`` (``application/`` cấm PySide6).
Hai điều thay ``Signal`` cũ:
* ``changed = Signal()`` -> danh sách callback ``self._changed_callbacks`` +
``on_changed(cb)`` để đăng ký; mọi chỗ code cũ gọi ``self.changed.emit()``
nay gọi ``self._emit_changed()``, gọi callback theo ĐÚNG thứ tự đã đăng ký.
* ``event = Signal(str, dict)`` -> ``self._event_callbacks`` + ``on_event(cb)``,
tương tự, thay ``self.event.emit(rid, ev)`` bằng ``self._emit_event(rid, ev)``.
* ``self.changed.connect(self._save_history)`` (lớp cũ tự nối signal của
chính nó vào slot riêng, trong ``__init__``) -> ở đây gọi thẳng
``self._save_history()`` làm bước ĐẦU TIÊN bên trong ``_emit_changed()``,
trước khi chạy các callback đã đăng ký từ bên ngoài. Chọn cách "gọi thẳng"
(thay vì "đăng ký như callback đầu tiên") vì nó khớp với thứ tự nối cũ
(``_save_history`` luôn được nối sớm nhất trong ``__init__`` nên luôn chạy
trước mọi slot ngoài nối sau) mà không cần một danh sách callback nội bộ
riêng chỉ để chứa đúng một phần tử cố định.
``start()`` KHÔNG tự tạo ``AgentWorker``/``QThread`` — nó nhận một ``runner``
(``WorkflowRunner`` Protocol, mặc định ``None``) tiêm qua constructor. Adapter
Qt thật (bọc ``AgentWorker`` — xem ``core/worker.py``) là việc của widget ở
``presentation/``, không viết ở đây; test dùng fake chạy đồng bộ
(``tests/fakes/fake_co4e_workflow_service.py`` hoặc fake cục bộ trong
``tests/test_co4e_workflow_service.py``).
KHÔNG xoá/sửa ``core/co4e_run_manager.py`` — lớp cũ tiếp tục chạy song song
cho tới khi widget Co4E Studio thật (``ui/co4e_tab.py``) chuyển hẳn sang dùng
service này.
"""
from __future__ import annotations
from ...infrastructure.persistence.json.atomic_json_file import AtomicJsonFile
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Callable, Dict, List, Optional, Protocol, Set
from ...core.co4e import CO4E_DIR, STEP_DONE, STEP_ERROR, STEP_PLANNED, Workflow, slugify, workflow_to_dict
from ...domain.workflows.run_record import RunRecord
_TERMINAL_NODE = {STEP_DONE, STEP_ERROR, STEP_PLANNED}
_HISTORY_CAP = 500 # giữ N run gần nhất trên đĩa
def _now_str() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M")
def _current_user() -> str:
"""Best-effort creator name for a run (signed-in MS365 identity -> OS user)."""
return os.environ.get("USERNAME") or os.environ.get("USER") or "you"
# ---- ports (Protocol) — thay QThread thật bằng thứ tiêm được ---------------
class RunnerJob(Protocol):
"""Bề mặt tối thiểu mà job workflow cần từ 'worker' của nó.
Tương ứng ``AgentWorker.emit_event``/``AgentWorker.is_cancelled`` cũ
(``core/worker.py``) — giữ nguyên chữ ký đó để hàm job bên trong
``co4e_runner.run_workflow`` không phải đổi khi runner đứng sau là
``AgentWorker``/``QThread`` thật (adapter ở presentation/) hay là fake
đồng bộ trong test.
"""
def emit_event(self, ev: dict) -> None: ...
def is_cancelled(self) -> bool: ...
class RunWorkerHandle(Protocol):
"""Điều khiển một job đang chạy nền — tương ứng phần
``AgentWorker.request_stop()`` cũ mà ``Co4ERunManager.stop()`` gọi."""
def request_stop(self) -> None: ...
class WorkflowRunner(Protocol):
"""Cổng chạy một job nền, tiêm qua constructor ``Co4EWorkflowService``.
Thay cho việc service tự ``AgentWorker(job); worker.start()`` (cần
``QThread`` -> cấm ở ``application/``). Bên gọi ``start()`` truyền vào
``job`` với đúng chữ ký cũ (``job(worker) -> Optional[dict]``); runner chịu
trách nhiệm chạy nó (nền thật hay đồng bộ) và gọi lại ba callback tương ứng
ba signal cũ của ``AgentWorker`` (``event``/``finished_ok``/``failed``).
"""
def start(self, run_id: str, job: Callable[[RunnerJob], Optional[dict]],
on_event: Callable[[dict], None],
on_finished: Callable[[Optional[dict]], None],
on_failed: Callable[[str], None]) -> RunWorkerHandle: ...
class Co4EWorkflowService:
"""Tầng application: vòng đời nhiều run Co4E cùng lúc, thuần Python.
Vai trò: đây là nơi ``build_co4e_tab(ctx, workflow_service)``
(``presentation/co4e/co4e_tab.py``) sẽ lấy ``workflow_service`` thật một
khi widget Co4E Studio được lắp lại để dùng nó — hiện widget thật
(``ui/co4e_tab.py``) vẫn dùng ``Co4ERunManager`` cũ song song.
"""
def __init__(self, ctx, *, history_path: Optional[Path] = None,
runner: Optional[WorkflowRunner] = None):
self.ctx = ctx
self._runs: Dict[str, RunRecord] = {}
self._worker_handles: Dict[str, RunWorkerHandle] = {}
self._seq = 0
self._output_root: Optional[Path] = None # thư mục output co4e của workspace đang chọn
self._project_id: str = "" # workspace đang chọn — Flow Status lọc theo no
self._runner = runner
# DTO domain khong duoc cham dia (xem domain/workflows/run_record.py),
# nen viec doc/ghi file lich su nam o day, tang application.
self._history_path_value = (
Path(history_path) if history_path is not None else (CO4E_DIR / "run_history.json")
)
self._changed_callbacks: List[Callable[[], None]] = []
self._event_callbacks: List[Callable[[str, dict], None]] = []
self._load_history() # khoi phuc lich su cu de Flow Status
# giu du lich su qua cac lan restart
# ---- callback thay Signal ---------------------------------------------
def on_changed(self, cb: Callable[[], None]) -> None:
self._changed_callbacks.append(cb)
def on_event(self, cb: Callable[[str, dict], None]) -> None:
self._event_callbacks.append(cb)
def _emit_changed(self) -> None:
self._save_history() # xem docstring dau file: giu dung thu tu ban Qt cu
for cb in self._changed_callbacks:
cb()
def _emit_event(self, run_id: str, ev) -> None:
for cb in self._event_callbacks:
cb(run_id, ev)
# ---- persistence --------------------------------------------------
# Doc/ghi thu cong (json.loads/write_text + tmp.replace), KHONG dung
# AtomicJsonFile — ban dau file nay dung AtomicJsonFile.read(), nhung
# review phat hien no doi hanh vi that so voi Co4ERunManager cu: gap
# JSON hong, AtomicJsonFile.read() ĐOI TEN file hong thanh
# "<ten>.bad-<timestamp>" (quarantine) roi moi tra ve mac dinh, trong
# khi ban cu chi bat loi va ĐE NGUYEN file hong tai cho, khong dong gi
# vao no. Day la mot thay doi quan sat duoc tren dia ma khong test nao
# khoa lai va khong co comment bao truoc — Lam (N3) da quyet 24/08:
# GIU HANH VI CU nguyen van (khong quarantine), vi day la buoc tach
# chi duoc phep doi hanh vi khi da noi ra ro rang va co lưới an toan,
# khong phai luc nay.
def _load_history(self) -> None:
try:
data = json.loads(self._history_path_value.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
max_seq = 0
for rec in data.get("runs", []):
try:
record = RunRecord.from_dict(rec)
except Exception:
continue
if not record.id:
continue
self._runs[record.id] = record
if record.id.startswith("run") and record.id[3:].isdigit():
max_seq = max(max_seq, int(record.id[3:]))
self._seq = max_seq # tranh sinh id trung voi lich su
def _save_history(self) -> None:
runs = list(self._runs.values())[-_HISTORY_CAP:]
payload = {"runs": [r.to_dict() for r in runs]}
try:
self._history_path_value.parent.mkdir(parents=True, exist_ok=True)
# AtomicJsonFile thay cho tmp+replace tự viết: bản cũ thiếu fsync
# (dữ liệu có thể còn trong bộ đệm khi mất điện) và dùng thẳng
# Path.replace, vốn thỉnh thoảng bị Defender từ chối trên Windows.
AtomicJsonFile(self._history_path_value).write(payload)
except OSError:
# Giu dung hanh vi cu (core/co4e_run_manager.py::_save_history):
# mot lan luu that bai (day dia, mat quyen...) KHONG duoc phep
# chan luong goi cua moi hook (_on_event/_on_finished/_on_failed)
# dang di qua _emit_changed(). Bo try/except nay se lam mot loi
# ghi dia lam vo ca luot xu ly su kien dang chay, chi vi lich su
# khong luu duoc lan nay -- nguoi dung van thay Flow Status dung
# trong phien hien tai, chi la ban ghi tren dia lui lai mot buoc.
pass
# ---- lifecycle ----------------------------------------------------
def _next_id(self) -> str:
self._seq += 1
return f"run{self._seq}"
def start(self, wf: Workflow, *, skill_map: Optional[Dict[str, str]] = None,
plan_mode: bool = False, only_nodes: Optional[set] = None,
seed_outputs: Optional[Dict[str, str]] = None,
manual: bool = False, label: Optional[str] = None) -> str:
"""Đăng ký một run mới và giao job cho ``self._runner`` (nếu có).
Không tự thực thi AI thật ở đây: khi ``self._runner`` là ``None``
(mặc định), run được ghi nhận nhưng không job nào được giao đi — dùng
cho test/khi chưa lắp adapter Qt thật.
"""
run_id = self._next_id()
total = len(only_nodes) if only_nodes else len(wf.nodes)
record = RunRecord(run_id, wf.id, label or wf.name, total, plan_mode, manual,
created_by=_current_user(), created_at=_now_str(),
project_id=self._project_id)
# workflow_to_dict() tu dung dataclasses.asdict() de dung ca cay (node,
# step, sub-agent) -> ban than no da la mot "deep copy" sang dict moi,
# khong con giu tham chieu toi wf.nodes/wf.edges song. Vi vay KHONG can
# deepcopy(wf) truoc nhu ban Qt cu (RunHandle.wf giu nguyen doi tuong
# Workflow) -- xem doc string dau file domain/workflows/run_record.py
# ve ly do snapshot o day la dict tho chu khong phai doi tuong.
record.wf = workflow_to_dict(wf)
nodes = list(wf.nodes)
edges = list(wf.edges)
out_dir = self._out_dir(wf)
record.out_dir = str(out_dir)
ctx = self.ctx
sk = dict(skill_map or {})
only: Optional[Set[str]] = set(only_nodes) if only_nodes else None
seed = dict(seed_outputs or {})
run_label = record.name
self._runs[run_id] = record
if self._runner is not None:
def job(worker: RunnerJob):
from ...core import co4e_runner
return co4e_runner.run_workflow(
ctx, nodes, edges, out_dir, worker.emit_event, worker.is_cancelled,
plan_mode=plan_mode, skill_map=sk, only_nodes=only, seed_outputs=seed,
usage_label=run_label)
self._worker_handles[run_id] = self._runner.start(
run_id, job,
on_event=lambda ev, rid=run_id: self._on_event(rid, ev),
on_finished=lambda _r=None, rid=run_id: self._on_finished(rid),
on_failed=lambda e, rid=run_id: self._on_failed(rid, e),
)
self._emit_changed()
return run_id
# ---- worker callbacks (goi tu runner, thay slot Qt cu) -----------------
def _on_event(self, run_id: str, ev) -> None:
record = self._runs.get(run_id)
if record is not None and isinstance(ev, dict):
t = ev.get("type")
if t == "node_status":
record.node_status[ev.get("node_id")] = ev.get("status")
record.done = sum(1 for s in record.node_status.values() if s in _TERMINAL_NODE)
self._emit_changed()
elif t == "run_done":
if record.status == "running":
record.status = "done" if ev.get("ok", True) else "error"
self._emit_changed()
# quirk co y giu nguyen (xem test_on_event_unknown_run_id... trong ca
# test cu lan test moi): re-emit VO DIEU KIEN, ke ca run_id la hoac ev
# khong phai dict/None -- khac _on_finished/_on_failed la no-op hoan
# toan khi run_id la.
#
# Khac biet CO CHU Y so voi ban Qt cu: Signal(str, dict) cua PySide6 ep
# ev=None thanh {} khi giao cho slot (tac dung phu cua kieu Signal khai
# bao cung). O day khong con Signal nen callback nhan DUNG gia tri ev
# goc (None neu goi voi None) -- khong gia lap lai viec ep kieu do vi
# no la tac dung phu cua Qt, khong phai quy tac nghiep vu can giu.
self._emit_event(run_id, ev)
def _on_finished(self, run_id: str) -> None:
record = self._runs.get(run_id)
if record is not None and record.status == "running":
# job returned without a run_done event (shouldn't happen) — settle it
record.status = "done"
self._emit_changed()
def _on_failed(self, run_id: str, err: str) -> None:
record = self._runs.get(run_id)
if record is not None:
record.status = "error"
record.error = str(err)
self._emit_event(run_id, {"type": "run_error", "error": str(err)})
self._emit_changed()
# ---- control --------------------------------------------------------
def stop(self, run_id: str) -> None:
record = self._runs.get(run_id)
worker = self._worker_handles.get(run_id)
if record is not None and worker is not None and record.running:
worker.request_stop()
record.status = "stopped"
self._emit_changed()
def stop_all(self) -> None:
# Only the CURRENT workspace's runs (Flow Status is per-project).
for run_id in [r for r, rec in self._runs.items() if self._belongs(rec)]:
self.stop(run_id)
def rename(self, run_id: str, new_name: str) -> None:
"""Rename a run in the Flow Status history (and its kept workflow snapshot),
then persist + refresh views. No-op on a blank name / unknown run."""
record = self._runs.get(run_id)
new_name = (new_name or "").strip()
if record is None or not new_name or new_name == record.name:
return
record.name = new_name
# DTO doi: RunHandle.wf cu la doi tuong Workflow (gan record.wf.name),
# RunRecord.wf o day la dict tho (xem domain/workflows/run_record.py)
# nen doi truc tiep khoa "name" cua dict thay vi thuoc tinh doi tuong.
if record.wf is not None:
record.wf["name"] = new_name
self._emit_changed()
def remove(self, run_id: str) -> None:
record = self._runs.get(run_id)
if record is not None and record.running:
self.stop(run_id)
self._runs.pop(run_id, None)
self._worker_handles.pop(run_id, None)
self._emit_changed()
def clear_finished(self) -> None:
# Only clear finished runs of the CURRENT workspace.
for run_id in [r for r, rec in self._runs.items() if not rec.running and self._belongs(rec)]:
self._runs.pop(run_id, None)
self._worker_handles.pop(run_id, None)
self._emit_changed()
# ---- queries ----------------------------------------------------------
def _belongs(self, r: RunRecord) -> bool:
"""Whether a run belongs to the currently-selected workspace."""
return getattr(r, "project_id", "") == self._project_id
def runs(self) -> List[RunRecord]:
"""Runs of the CURRENT workspace only — Flow Status is per-project."""
return [r for r in self._runs.values() if self._belongs(r)]
def all_runs(self) -> List[RunRecord]:
"""Every tracked run across all workspaces (background tracking)."""
return list(self._runs.values())
def get(self, run_id: str) -> Optional[RunRecord]:
return self._runs.get(run_id)
def active_count(self) -> int:
return sum(1 for r in self._runs.values() if r.running and self._belongs(r))
def set_current_project(self, project_id: str) -> None:
"""Filter Flow Status (and new runs) to this workspace. Runs started while
this is set are tagged with it; the Runs view shows only matching runs."""
pid = project_id or ""
if pid != self._project_id:
self._project_id = pid
self._emit_changed() # re-render Flow Status for the new workspace
def set_output_root(self, root: Optional[Path]) -> None:
"""Point flow outputs at the SELECTED workspace's co4e folder (set by the
Co4E tab when a project is chosen). ``None`` → fall back to the global
Cowork output dir."""
self._output_root = Path(root) if root else None
def _out_dir(self, wf: Workflow) -> Path:
# Flow deliverables are written into the SELECTED workspace (the active
# project's folder) so they land where the user works with files (Folder
# tab), not in the config/install folder. One subfolder per flow keeps
# runs tidy. Falls back to the global Cowork output dir when no workspace
# is selected.
base = self._output_root
if base is None:
try:
base = self.ctx.config.cowork_output_dir() / "co4e"
except Exception: # noqa: BLE001 - fall back to the config dir if unavailable
base = CO4E_DIR / "runs" / "co4e"
d = Path(base) / slugify(wf.name or "flow")
d.mkdir(parents=True, exist_ok=True)
return d
+17 -1
View File
@@ -1 +1,17 @@
"""Application workspaces package: File workspace and AI file editor services."""
"""Workspace file operations for non-agent-loop callers (EPIC R06, R08)."""
from .ai_edit_output import parse_ai_output, split_code_block
from .file_preview_helpers import is_probably_text, pptx_available, read_text
from .file_workspace_service import FileWorkspaceService
from .graph_index_service import extract_file_contents, pdf_to_markdown
__all__ = [
"FileWorkspaceService",
"read_text",
"is_probably_text",
"pptx_available",
"split_code_block",
"parse_ai_output",
"pdf_to_markdown",
"extract_file_contents",
]
+40
View File
@@ -0,0 +1,40 @@
"""Parse an AI file-edit reply into its parts (R08-T12, moved out of
``ui/folder_tab.py`` — that file's module-level ``_split_code_block``/
``_parse_ai_output``, lines 1536-1562 of the original 1587-line file). Pure
string parsing, no Qt — used by ``presentation/folder/ai_file_editor_dialog.py``
to turn a model's raw reply into a proposed edit.
"""
from __future__ import annotations
import re
from typing import List, Optional, Tuple
def split_code_block(text: str) -> Tuple[Optional[str], str]:
"""Split an AI reply into ``(file_content, summary)``. ``file_content``
is the first fenced code block (the edited file); ``summary`` is any
prose before it. Returns ``(None, text)`` when there's no code block."""
m = re.search(r"```[^\n]*\n(.*?)```", text or "", re.DOTALL)
if not m:
return None, (text or "")
return m.group(1), (text[:m.start()].strip())
def parse_ai_output(text: str) -> Tuple[Optional[str], Optional[str], str, List[Tuple[str, str]]]:
"""Parse an AI edit reply into ``(target, content, summary, image_gens)``.
``FILE: <path>`` names a NEW file to create; ``IMAGE_GEN: <prompt> =>
<path>`` lines request generated illustration images (relative paths)."""
content, summary = split_code_block(text)
target = None
m = re.search(r"(?mi)^\s*FILE:\s*(.+?)\s*$", text or "")
if m:
target = m.group(1).strip().strip("`\"'")
image_gens = []
for gm in re.finditer(r"(?mi)^\s*IMAGE_GEN:\s*(.+?)\s*=>\s*(\S+)\s*$", text or ""):
image_gens.append((gm.group(1).strip(), gm.group(2).strip().strip("`\"'")))
# Strip the directive lines out of the shown summary.
summary = re.sub(r"(?mi)^\s*(FILE|IMAGE_GEN):\s*.+?$", "", summary).strip()
return target, content, summary, image_gens
__all__ = ["split_code_block", "parse_ai_output"]
@@ -0,0 +1,54 @@
"""Pure helpers for previewing a file (R08-T12, moved out of
``ui/folder_tab.py`` — that file's module-level functions
``_read_text``/``_is_probably_text``/``_pptx_available``, lines 1519-1533 and
1565-1587 of the original 1587-line file). No Qt, no widget state — the
"is this file text? is pptx editing available?" questions the preview
manager asks before it decides how to render something.
"""
from __future__ import annotations
from pathlib import Path
_PPTX_READY = None # cached: pptx-editing library available (after auto-install)
def pptx_available() -> bool:
"""True when python-pptx is importable. If it's MISSING, auto-download &
install it (via deps.ensure_module) so pptx editing 'just works' — cached
so the (one-time) install is attempted only once."""
global _PPTX_READY
if _PPTX_READY is None:
try:
from cowork_local.core.deps import ensure_module
_PPTX_READY = ensure_module("pptx", "python-pptx") is not None
except Exception: # noqa: BLE001
_PPTX_READY = False
return _PPTX_READY
def read_text(path: str) -> str:
try:
return Path(path).read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return f"[could not read file: {exc}]"
def is_probably_text(path: str) -> bool:
try:
with open(path, "rb") as f:
chunk = f.read(4096)
except OSError:
return False
if b"\x00" in chunk:
return False
try:
chunk.decode("utf-8")
return True
except UnicodeDecodeError:
# Latin-ish text still edits fine via errors="replace"; only reject on
# a hard binary signal (NUL above), so most source files pass.
return True
__all__ = ["pptx_available", "read_text", "is_probably_text"]
@@ -0,0 +1,81 @@
"""FileWorkspaceService - the safe file operations File Explorer and the AI
File Editor need, outside the agent tool loop (R06-T05).
``ui/folder_tab.py`` (File Explorer) and the AI File Editor dialog need the
exact same guarantees the agent's tools already have — path containment
inside the workspace, precise context-anchored edits, syntax warnings on a
bad Python write — but today that logic only exists wired to a model's tool
call (``core/tools.py::execute_tool``). A UI action that isn't a tool call
(browsing the tree, applying an AI-suggested diff from a review dialog) has
no equivalent entry point of its own.
This service IS that entry point. It reuses ``core/tools.py::execute_tool``
verbatim - same dispatch table, same ``ToolContext`` containment check, same
audit-log entry, same Python-syntax warning on write/edit - rather than
re-implementing any of it, so a fix to one path fixes both. It only adds the
:class:`~domain.workspaces.workspace_session.WorkspaceSession` seam: which
workspace root a call is scoped to is decided by the session, not by
whichever folder a widget happens to have open.
"""
from __future__ import annotations
from typing import Any, Dict
class FileWorkspaceService:
"""File operations scoped to one :class:`WorkspaceSession`.
Read-only by name (``list_tree``/``read_preview``) vs. writing
(``write_file``/``apply_edit``) mirrors the same READ/WRITE split
``domain/tools/tool_registry.py`` uses for the agent's own tools - a
caller that only wants to browse never accidentally has write access.
"""
def __init__(self, session) -> None: # WorkspaceSession - see module docstring
self._session = session
def list_tree(self, rel: str = ".") -> Dict[str, Any]:
"""Entries at ``rel`` (default: the workspace root)."""
return self._execute("list_dir", {"path": rel})
def read_preview(self, rel: str) -> Dict[str, Any]:
"""A text file's content (truncated by
``infrastructure/filesystem/file_tools.py::MAX_READ_BYTES``, same as
the agent's ``read_file`` tool)."""
return self._execute("read_file", {"path": rel})
def write_file(self, rel: str, content: str) -> Dict[str, Any]:
"""Create or fully overwrite ``rel``."""
return self._execute("write_file", {"path": rel, "content": content})
def apply_edit(self, rel: str, old_string: str, new_string: str,
replace_all: bool = False) -> Dict[str, Any]:
"""Replace an exact snippet in an existing file - the same
context-anchored algorithm the agent's ``edit_file`` tool uses, so an
AI-suggested diff applies with the same precision and the same
"old_string not found / ambiguous" failure messages either path
would give the caller."""
return self._execute("edit_file", {
"path": rel, "old_string": old_string, "new_string": new_string,
"replace_all": replace_all,
})
# -- internals --------------------------------------------------------- #
def _tool_context(self):
"""A ``ToolContext`` scoped to this session's workspace root.
``flatten_writes=False`` (unlike Cowork's agent context) - File
Explorer must preserve whatever subfolder structure the user is
actually browsing, not collapse every write into the root."""
from cowork_local.infrastructure.filesystem.tool_context import ToolContext
return ToolContext(self._session.workspace_root, flatten_writes=False)
def _execute(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""Dispatch through ``core/tools.py::execute_tool`` - see the module
docstring for why this delegates instead of reimplementing."""
from cowork_local.core.tools import execute_tool
return execute_tool(self._tool_context(), name, args)
__all__ = ["FileWorkspaceService"]
@@ -0,0 +1,91 @@
"""Temporary file-content extraction for Graph-RAG Q&A (R08-T14, moved out
of ``ui/structure_graph_view.py`` — that file's module-level
``_pdf_to_markdown``/``_extract_file_contents``, lines 964-1034 of the
original 1035-line file). Runs inside the ask worker's job function so the
answer is synthesized from real file content, not just the graph structure.
Pure Python: no Qt. Best-effort throughout (never raises) — a failed
extraction degrades to "no content for this file", not a broken Q&A turn.
"""
from __future__ import annotations
from pathlib import Path
from typing import Dict, List, Optional, Tuple
def pdf_to_markdown(pdf_path: str, out_dir: str) -> Optional[str]:
"""Convert a PDF to Markdown with opendataloader-pdf when available
(richer structure than a plain text dump). Best-effort — returns None
if the package isn't installed or the call fails, so the caller falls
back to ``core/doc_extract.py``."""
try:
import opendataloader_pdf # optional; auto-installed elsewhere if present
except Exception: # noqa: BLE001
try:
from cowork_local.core.deps import ensure_module
if ensure_module("opendataloader_pdf", "opendataloader-pdf") is None:
return None
import opendataloader_pdf # noqa: F811
except Exception: # noqa: BLE001
return None
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
for call in (
lambda: opendataloader_pdf.convert(input_path=[str(pdf_path)], output_dir=str(out),
generate_markdown=True),
lambda: opendataloader_pdf.convert(input_path=str(pdf_path), output_dir=str(out)),
lambda: opendataloader_pdf.convert(str(pdf_path), str(out)),
):
try:
call()
break
except TypeError:
continue
except Exception: # noqa: BLE001
return None
mds = list(out.rglob(Path(pdf_path).stem + "*.md")) or list(out.rglob("*.md"))
for md in mds:
try:
return md.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
return None
def extract_file_contents(paths: List[str], cache: Dict[str, str], tmp_dir: str,
max_files: int = 15, max_total: int = 120_000
) -> Tuple[str, Dict[str, str]]:
"""Read the ACTUAL content of ``paths`` (PDF -> markdown via
opendataloader when available, else ``doc_extract`` for office/pdf/
text). Returns ``(block, cache)`` — ``block`` is the concatenated
content for the prompt (bounded), ``cache`` maps path -> text for
reuse. Never raises."""
from cowork_local.core import doc_extract
cache = dict(cache or {})
parts, total = [], 0
for p in paths[:max_files]:
if total >= max_total:
break
text = cache.get(p)
if text is None:
try:
if Path(p).suffix.lower() == ".pdf":
text = pdf_to_markdown(p, tmp_dir)
if not text:
text, _n = doc_extract.extract_text(p)
else:
text, _n = doc_extract.extract_text(p)
except Exception: # noqa: BLE001
text = ""
cache[p] = text or ""
text = cache.get(p) or ""
if not text:
continue
chunk = text[: max(0, max_total - total)]
total += len(chunk)
parts.append(f'--- {Path(p).name} ({p}) ---\n{chunk}')
return ("\n\n".join(parts), cache)
__all__ = ["pdf_to_markdown", "extract_file_contents"]
+29 -274
View File
@@ -16,6 +16,8 @@ import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from .infrastructure.config.json_config_repository import JsonConfigRepository
from typing import Any, Dict, List
CONFIG_DIR = Path.home() / ".cowork_local"
@@ -343,281 +345,34 @@ def _migrate_connectors(data: Dict[str, Any]) -> None:
data["mcp_servers"] = [] # migrated — the UI no longer manages this
@dataclass
class AppConfig:
"""In-memory view of the configuration with load/save helpers."""
class AppConfig(JsonConfigRepository):
"""Vỏ tương thích — R02 đã thay lớp này bằng :class:`JsonConfigRepository`.
data: Dict[str, Any] = field(default_factory=lambda: copy.deepcopy(DEFAULT_CONFIG))
path: Path = CONFIG_PATH
Ngày 25/08 app chuyển hẳn sang repository (ghi nguyên tử, khoá nằm trong
kho bí mật của hệ điều hành). Nhưng cái tên ``AppConfig`` còn nằm ở 41 file
— 23 checker trong ``tools/`` và 18 file test, trong đó có test của cả ba
người. Sửa hết 41 chỗ trong một commit là đổi thứ không cần đổi và làm
review không đọc nổi.
Nên giữ tên, đổi ruột: mọi lối vào đều dẫn tới repository.
Bỏ hẳn được khi ``tools/`` và ``tests/`` chuyển sang gọi
``presentation.shell.bootstrap.build_context()``.
"""
def __init__(self, data=None, path: Path = CONFIG_PATH, **kw):
if data is None:
super().__init__(Path(path), **kw)
return
# Dạng AppConfig(data=..., path=...) mà 13 file test đang dùng: dựng
# thẳng từ dict, không đụng đĩa.
built = JsonConfigRepository.from_data(data, Path(path))
self.__dict__.update(built.__dict__)
# ---- persistence -------------------------------------------------
@classmethod
def load(cls, path: Path = CONFIG_PATH) -> "AppConfig":
merged = copy.deepcopy(DEFAULT_CONFIG)
if path.exists():
try:
stored = json.loads(path.read_text(encoding="utf-8"))
merged = _deep_merge(merged, stored)
except (json.JSONDecodeError, OSError):
# Corrupt config should never block startup.
merged = copy.deepcopy(DEFAULT_CONFIG)
merged = _apply_env_overrides(merged)
# "unlocked" is a runtime-only Settings-panel state (see the "ms365"
# comment in DEFAULT_CONFIG) — never trust a stored/hand-edited value,
# every launch starts locked.
merged.setdefault("ms365", {})["unlocked"] = False
_migrate_connectors(merged) # office→ms365 + legacy mcp_servers→other
return cls(data=merged, path=path)
def load(cls, path: Path = CONFIG_PATH) -> "JsonConfigRepository":
"""Điểm vào cũ. Giờ đi qua Composition Root nên checker và app dùng
chung một đường dựng — kể cả phần ráp kho bí mật."""
from .presentation.shell.bootstrap import build_config
return build_config(Path(path))
def save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
to_write = self.data
if self.data.get("ms365", {}).get("unlocked"):
# Defense in depth: even if some caller saves without having gone
# through the Settings dialog's own auto-lock-after-save flow, the
# unlock state must never reach disk.
to_write = copy.deepcopy(self.data)
to_write["ms365"]["unlocked"] = False
self.path.write_text(
json.dumps(to_write, indent=2, ensure_ascii=False), encoding="utf-8"
)
# ---- convenience accessors --------------------------------------
@property
def active_provider(self) -> str:
# Migrate configs that still point at a removed provider (e.g. an older
# install saved "ollama") to a supported one, so the app never tries to
# build an unknown provider.
val = self.data.get("active_provider", "openai_compat")
return val if val in PROVIDER_LABELS else "openai_compat"
@active_provider.setter
def active_provider(self, value: str) -> None:
self.data["active_provider"] = value
def provider_conf(self, name: str | None = None) -> Dict[str, Any]:
name = name or self.active_provider
return self.data["providers"].get(name, {})
@property
def ca_bundle(self) -> str:
"""Path to a custom CA/certificate PEM file, or '' for normal validation.
Used as ``requests``' ``verify=`` argument for every outbound HTTPS call
— see the "tls_ca_bundle" comment above for when this is needed."""
return (self.data.get("tls_ca_bundle") or "").strip()
@ca_bundle.setter
def ca_bundle(self, value: str) -> None:
self.data["tls_ca_bundle"] = (value or "").strip()
# ---- Microsoft 365 connections (Settings-panel lock, see DEFAULT_CONFIG) --
@property
def ms365(self) -> Dict[str, Any]:
return self.data.setdefault("ms365", copy.deepcopy(DEFAULT_CONFIG["ms365"]))
# ---- Login / RBAC / shared cross-machine store (see DEFAULT_CONFIG) ------
@property
def auth(self) -> Dict[str, Any]:
return self.data.setdefault("auth", copy.deepcopy(DEFAULT_CONFIG["auth"]))
@property
def shared_dir(self) -> str:
return (self.auth.get("shared_dir") or "").strip()
def ms365_try_unlock(self, code: str) -> bool:
"""Unlock the MS365 Settings group for this session if ``code`` matches.
This is a client-side UI lock (prevents casually toggling a sensitive
section), NOT Microsoft authentication — see the DEFAULT_CONFIG
comment. Never persisted as unlocked; see ``save()``."""
if (code or "") and code == self.ms365.get("unlock_code", ""):
self.data["ms365"]["unlocked"] = True
return True
return False
def ms365_lock(self) -> None:
self.data.setdefault("ms365", {})["unlocked"] = False
@property
def theme(self) -> str:
return self.data.get("theme", "dark")
@theme.setter
def theme(self, value: str) -> None:
self.data["theme"] = value
@property
def language(self) -> str:
from .i18n import DEFAULT_LANGUAGE, LANGUAGES
val = self.data.get("language", DEFAULT_LANGUAGE)
return val if val in LANGUAGES else DEFAULT_LANGUAGE
@language.setter
def language(self, value: str) -> None:
self.data["language"] = value
@property
def code(self) -> Dict[str, Any]:
return self.data["code"]
@property
def tools_disabled(self) -> list:
"""Built-in agent tool names the admin has turned off (Monitoring → Tools)."""
return self.data.setdefault("tools", {}).setdefault("disabled", [])
def set_tool_enabled(self, name: str, enabled: bool) -> None:
"""Enable/disable a built-in agent tool by name and persist it."""
disabled = set(self.tools_disabled)
if enabled:
disabled.discard(name)
else:
disabled.add(name)
self.data.setdefault("tools", {})["disabled"] = sorted(disabled)
self.save()
@property
def connect_external(self) -> bool:
"""Master switch (Monitoring → Tools → Connector): when off, the agent
connects to NO external connectors (CAD/CAE/MS365/Other MCP + REST).
Defaults ON so existing setups keep working."""
return bool(self.data.setdefault("tools", {}).get("connect_external", True))
def set_connect_external(self, enabled: bool) -> None:
self.data.setdefault("tools", {})["connect_external"] = bool(enabled)
self.save()
# ---- one-time seeding bookkeeping (built-in skill library / flows) -------
@property
def seeded_library_skills(self) -> List[str]:
"""Slugs of bundled library skills already seeded into the user's Skill
Manager — so a user-deleted one is never silently re-seeded."""
return list(self.data.setdefault("seeded_library_skills", []))
@seeded_library_skills.setter
def seeded_library_skills(self, slugs) -> None:
self.data["seeded_library_skills"] = list(dict.fromkeys(slugs or []))
@property
def seeded_builtin_flows(self) -> List[str]:
"""Ids of built-in Co4E flows already seeded (same respect-user-deletion
rule as seeded_library_skills)."""
return list(self.data.setdefault("seeded_builtin_flows", []))
@seeded_builtin_flows.setter
def seeded_builtin_flows(self, ids) -> None:
self.data["seeded_builtin_flows"] = list(dict.fromkeys(ids or []))
@property
def teams(self) -> Dict[str, Any]:
return self.data["teams"]
@property
def history(self) -> Dict[str, Any]:
return self.data["history"]
@property
def codebase_memory(self) -> Dict[str, Any]:
return self.data["codebase_memory"]
@property
def agent_security(self) -> Dict[str, Any]:
return self.data["agent_security"]
@property
def mcp_servers(self) -> List[Dict[str, Any]]:
return self.data.setdefault("mcp_servers", [])
@property
def ext_connectors(self) -> Dict[str, List[Dict[str, Any]]]:
"""Unified Connectors (MCP), grouped by category CAD/CAE/MS365/Other —
see core/ext_connectors.py for the per-entry shape and CATEGORIES."""
d = self.data.setdefault("ext_connectors", {"cad": [], "cae": [], "ms365": [], "other": []})
for cat in ("cad", "cae", "ms365", "other"):
d.setdefault(cat, [])
return d
@property
def cowork(self) -> Dict[str, Any]:
return self.data["cowork"]
@property
def routing(self) -> Dict[str, Any]:
"""Auto Model Assessment & Routing behaviour config (see DEFAULT_CONFIG).
Always returns a dict with every expected key present, backfilling any
missing sub-keys from the defaults so older configs upgrade seamlessly."""
d = self.data.setdefault("routing", copy.deepcopy(DEFAULT_CONFIG["routing"]))
for k, v in DEFAULT_CONFIG["routing"].items():
d.setdefault(k, copy.deepcopy(v))
d.setdefault("surface_modes", {})
for surface in ("cowork", "co4e", "ai_edit"):
d["surface_modes"].setdefault(surface, "")
return d
# The routing modes a surface may be in. "fallback" joined the set in
# R03-T03 (keep the selected model; re-route only when it cannot serve the
# turn) — see application/model_routing/routing_models.py::RoutingMode,
# which is the authority on what each mode means.
ROUTING_MODES = ("off", "auto", "manual", "fallback")
def routing_mode_for(self, surface: str) -> str:
"""Effective Off/Auto/Manual/Fallback mode for a chat surface.
A per-surface override wins; an empty override falls back to the global
``switch_mode``. Anything unrecognised degrades to "off" so routing
stays opt-in even with a hand-edited config."""
routing = self.routing
override = (routing.get("surface_modes", {}) or {}).get(surface, "")
mode = override or routing.get("switch_mode", "off")
return mode if mode in self.ROUTING_MODES else "off"
def set_routing_mode_for(self, surface: str, mode: str) -> None:
"""Persist a chat surface's routing toggle selection."""
mode = mode if mode in self.ROUTING_MODES else "off"
self.routing.setdefault("surface_modes", {})[surface] = mode
self.save()
@property
def structure(self) -> Dict[str, Any]:
return self.data.setdefault("structure", {"max_nodes": 400, "max_edges": 400})
@property
def monitoring_visibility(self) -> Dict[str, bool]:
return self.data.setdefault(
"monitoring_visibility", copy.deepcopy(DEFAULT_CONFIG["monitoring_visibility"]))
def cowork_output_dir(self) -> Path:
"""Where Cowork saves generated files (OneDrive folder by default)."""
custom = (self.cowork.get("output_dir") or "").strip()
if custom:
return Path(custom).expanduser()
from . import paths # local import avoids any import cycle
root = paths.primary_onedrive_root()
if root is not None:
return root / "CoworkLocal" / "output"
return CONFIG_DIR / "output" / "cowork"
def history_dir(self) -> Path:
"""Resolve where conversation history is stored.
When a project is open, its history is stored INSIDE the project's
workspace folder (``_project_history_dir``, set by the Workspace screen)
so that sharing/syncing that folder shares the history — another machine
opening the same folder sees the conversations and can continue them.
Otherwise: Local (default) or OneDrive."""
rt = getattr(self, "_project_history_dir", None)
if rt:
return Path(rt)
custom = (self.history.get("custom_dir") or "").strip()
if custom:
return Path(custom).expanduser()
if self.history.get("location") == "onedrive":
from . import paths # local import avoids any import cycle
root = paths.primary_onedrive_root()
if root is not None:
return root / "CoworkLocal" / "history"
return HISTORY_DIR
def model_label(self) -> str:
return str(self.provider_conf().get("model", "?"))
+32
View File
@@ -0,0 +1,32 @@
"""Root pytest conftest — loaded before ``tests/conftest.py``.
This checkout lives on disk as ``Refactor`` (not ``cowork_local``), while
``tests/`` imports everything as ``from cowork_local... import ...`` and
``tests/conftest.py`` makes that resolve by putting this repo's *parent*
directory on ``sys.path`` (expecting the repo root itself to be named
``cowork_local``). A sibling folder literally named ``cowork_local`` (an
unrelated, older checkout) already exists next to this one, so without this
file Python would silently import THAT folder instead of this repository
whenever a test does ``import cowork_local``.
Registering the alias here — before ``tests/conftest.py`` touches
``sys.path`` — caches this repository in ``sys.modules['cowork_local']``
first, so the later ``sys.path`` mutation has nothing left to do (imports
are cached by name; the first successful import of a given name wins for
the rest of the process).
"""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
_ROOT = Path(__file__).resolve().parent
if "cowork_local" not in sys.modules:
spec = importlib.util.spec_from_file_location(
"cowork_local", _ROOT / "__init__.py", submodule_search_locations=[str(_ROOT)],
)
module = importlib.util.module_from_spec(spec)
sys.modules["cowork_local"] = module
spec.loader.exec_module(module)
+2 -19
View File
@@ -27,27 +27,12 @@ from __future__ import annotations
import json
import re
from dataclasses import dataclass
from typing import List, Optional
from ..providers.base import Provider
from . import security_rules
class SecurityBlocked(RuntimeError):
"""A guardrail refused an action. ``verdict`` carries the full detail for
the admin alert; ``str(exc)`` is the short, user-facing reason."""
def __init__(self, verdict: "SecurityVerdict"):
super().__init__(verdict.reason or f"Blocked by agent security ({verdict.layer}).")
self.verdict = verdict
@dataclass
class SecurityVerdict:
allowed: bool
reason: str = ""
layer: str = "" # "prompt" | "attachment" | "command"
from .agent_security_alert import notify_admin
from .agent_security_types import SecurityBlocked, SecurityVerdict
def combined_rules_text(config, max_chars: int = 8000, agent_kind: str = "cowork") -> str:
@@ -236,7 +221,6 @@ def enforce_prompt(provider: Provider, messages: List[dict], config, emit,
emit({"type": "notice", "level": "warning",
"text": f"🛡 Yêu cầu bị chặn bởi Agent Security: {verdict.reason}"})
from . import audit_log
from .agent_security_alert import notify_admin
audit_log.record("security_block", "prompt", False, verdict.reason)
notify_admin(config, verdict, detail=user_text[:1000])
@@ -266,7 +250,6 @@ def enforce_command(provider: Provider, name: str, args: dict, config, emit,
emit({"type": "notice", "level": "warning",
"text": f"🛡 Lệnh bị chặn bởi Agent Security ({verdict.layer}): {verdict.reason}"})
from . import audit_log
from .agent_security_alert import notify_admin
audit_log.record("security_block", name, False, f"{verdict.layer}: {verdict.reason}")
notify_admin(config, verdict, detail=command)
+1 -1
View File
@@ -12,7 +12,7 @@ from __future__ import annotations
from typing import Tuple
from . import ms365_graph
from .agent_security import SecurityVerdict
from .agent_security_types import SecurityVerdict
from .ms365_auth import Ms365AuthError, get_access_token
+33
View File
@@ -0,0 +1,33 @@
"""Shared value types for the Agent Security guardrails.
``SecurityVerdict``/``SecurityBlocked`` used to be defined in
``agent_security.py``, which forced ``agent_security_alert.py`` (which only
needs the *type*, to annotate/read ``notify_admin``'s ``verdict`` argument) to
import from it — while ``agent_security.py`` itself needed to call
``agent_security_alert.notify_admin()``, an architectural cycle only avoided
at runtime by deferring that second import inside a function body.
Hoisting the shared type into this dependency-free leaf module lets both
sides import it directly, so ``agent_security.py`` can import
``agent_security_alert`` at module top level too — no cycle, no deferred
imports needed for this pair.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class SecurityVerdict:
allowed: bool
reason: str = ""
layer: str = "" # "prompt" | "attachment" | "command"
class SecurityBlocked(RuntimeError):
"""A guardrail refused an action. ``verdict`` carries the full detail for
the admin alert; ``str(exc)`` is the short, user-facing reason."""
def __init__(self, verdict: SecurityVerdict):
super().__init__(verdict.reason or f"Blocked by agent security ({verdict.layer}).")
self.verdict = verdict
+15 -72
View File
@@ -6,15 +6,23 @@ storage systems).
One JSON line per event, one file per day under ``~/.cowork_local/audit/`` —
same on-disk shape as ``usage_tracker.py`` (day-sharded ``.jsonl``, append-only,
``record()`` never raises so audit logging can never break a chat turn).
This module is now a thin, backward-compatible wrapper around
:class:`infrastructure.telemetry.audit_logger.CanonicalAuditLogger` — every
existing call site (``agent_security.py``, ``chat_agent.py``, ``tools.py``,
``ext_connectors.py``, ``mcp_client.py``, ``ms365_local.py``,
``permissions.py``, ``ui/structure_graph_view.py``, ``app.py``) keeps calling
``audit_log.set_identity``/``record``/``load_events`` exactly as before; only
the implementation moved.
"""
from __future__ import annotations
import json
from datetime import date, datetime
from datetime import date
from pathlib import Path
from typing import Any, Dict, List, Optional
from ..config import CONFIG_DIR
from ..infrastructure.telemetry.audit_logger import CanonicalAuditLogger
AUDIT_DIR = CONFIG_DIR / "audit"
@@ -23,66 +31,21 @@ AUDIT_DIR = CONFIG_DIR / "audit"
# action), "mcp_call" (a call to an external MCP server's tool).
Kind = str
# Process-global identity — who's logged in, their role, and this machine's
# name — set once right after login (app.py::run()), mirroring
# usage_tracker.py's identical pattern. NOT thread-local: fixed per process.
_identity_account = ""
_identity_role = ""
_identity_machine = ""
_identity_shared_dir = ""
_logger = CanonicalAuditLogger(AUDIT_DIR)
def set_identity(account: str, machine: str, role: str = "", shared_dir: str = "") -> None:
"""Called once after login succeeds. ``shared_dir``, when reachable,
makes every subsequent :func:`record` ALSO best-effort-append to the
shared cross-machine telemetry store (see :mod:`telemetry_shared`)."""
global _identity_account, _identity_role, _identity_machine, _identity_shared_dir
_identity_account = account or ""
_identity_role = role or ""
_identity_machine = machine or ""
_identity_shared_dir = shared_dir or ""
_logger.set_identity(account, machine, role=role, shared_dir=shared_dir)
def record(kind: Kind, name: str, ok: bool, detail: str = "",
agent_role: str = "") -> None:
"""Append one audit event. Never raises — audit logging must never break
a chat turn, a permission decision, or a tool call."""
try:
now = datetime.now()
event = {
"ts": now.isoformat(timespec="seconds"),
"kind": kind,
"agent_role": agent_role or "",
"name": name or "",
"ok": bool(ok),
"detail": (detail or "")[:2000], # bounded — never let a huge blob bloat the log
"account": _identity_account,
"role": _identity_role,
"machine": _identity_machine,
}
AUDIT_DIR.mkdir(parents=True, exist_ok=True)
path = AUDIT_DIR / f"{now.strftime('%Y-%m-%d')}.jsonl"
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
_write_shared(event, now)
except Exception: # noqa: BLE001
pass
def _write_shared(event: Dict[str, Any], now: datetime) -> None:
"""Best-effort mirror of ``event`` into the shared cross-machine store —
one file PER MACHINE per day, so no two machines ever write the same
file. Never raises."""
if not _identity_shared_dir or not _identity_machine:
return
try:
shared = Path(_identity_shared_dir).expanduser() / "telemetry" / "audit"
shared.mkdir(parents=True, exist_ok=True)
path = shared / f"{_identity_machine}-{now.strftime('%Y-%m-%d')}.jsonl"
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
except Exception: # noqa: BLE001
pass
_logger.record(kind, name, ok, detail=detail, agent_role=agent_role)
def load_events(start: Optional[date] = None, end: Optional[date] = None,
@@ -91,25 +54,5 @@ def load_events(start: Optional[date] = None, end: Optional[date] = None,
"""Events between ``start``/``end`` (inclusive; None = unbounded),
optionally filtered to one ``kind`` — this IS how each Monitoring
Dashboard panel gets its own slice of the same underlying log."""
directory = directory or AUDIT_DIR
if not directory.exists():
return []
events: List[Dict[str, Any]] = []
for path in sorted(directory.glob("*.jsonl")):
try:
day = datetime.strptime(path.stem, "%Y-%m-%d").date()
except ValueError:
continue
if (start and day < start) or (end and day > end):
continue
try:
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
event = json.loads(line)
if kind is not None and event.get("kind") != kind:
continue
events.append(event)
except (OSError, json.JSONDecodeError):
continue
return events
events = _logger.load_events(start=start, end=end, kind=kind, directory=directory)
return [e.to_dict() for e in events]
+46 -10
View File
@@ -11,6 +11,8 @@ import re
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from ..application.conversations.tool_policy_gateway import ToolPolicyGateway
from ..domain.tools import ToolCapability, default_registry
from ..providers.base import Provider, ToolSpec
from . import agent_roles
from . import agent_security
@@ -27,6 +29,13 @@ from .tools import TOOL_SPECS, ToolContext, _snapshot, describe_action, execute_
# Generator / helper scripts — never a final deliverable in Cowork's output.
_SCRIPT_EXTS = {".py", ".pyw", ".js", ".mjs", ".cjs", ".ts", ".sh", ".bat", ".ps1", ".rb", ".pl"}
# R05-T03/T04: replaces the literal ``name in ("run_command",
# "install_package")`` check below with a capability lookup — EXECUTE is
# exactly the capability those two (and only those two) built-in tools carry
# (see domain/tools/tool_registry.py::BUILT_IN_CAPABILITIES). Copied per-turn
# into ``turn_tool_policy`` inside run_cowork() once extra_tools are known.
_COWORK_TOOL_REGISTRY = default_registry(TOOL_SPECS)
EmitFn = Callable[[Dict[str, Any]], None]
CancelFn = Callable[[], bool]
@@ -388,6 +397,19 @@ def run_cowork(
jira=(security_config.data.get("jira") if security_config else None))
extra_tools = extra_tools or []
extra_names = {t.name for t in extra_tools}
# R05-T04: MCP servers (core/mcp_client.py) and unified connectors
# (core/ext_connectors.py) — everything that arrives here as extra_tools —
# advertise no standard risk metadata, so each is tagged with the same
# conservative default (WRITE|EXECUTE|NETWORK) domain/tools/tool_registry.py
# uses for any unclassified tool. Copying the built-in registry per turn
# (cheap - under 20 entries) rather than mutating the shared module-level
# one keeps different turns' extra_tools from leaking into each other.
from ..domain.tools import ToolDescriptor, ToolRegistry
from ..domain.tools.tool_registry import UNKNOWN_SOURCE_CAPABILITIES
_turn_registry = ToolRegistry(_COWORK_TOOL_REGISTRY.all())
for _spec in extra_tools:
_turn_registry.register(ToolDescriptor.from_spec(_spec, UNKNOWN_SOURCE_CAPABILITIES))
turn_tool_policy = ToolPolicyGateway(_turn_registry, ToolCapability.EXECUTE)
# update_plan drives the Plan panel (above Output); it produces no file.
# Built-in tools the admin disabled (Monitoring → Tools) are filtered out.
from .tools import enabled_tool_specs
@@ -489,6 +511,18 @@ def run_cowork(
preview = {"kind": "info", "title": name, "text": str(args)}
emit({"type": "tool_proposed", "id": tc_id, "name": name, "args": args,
"preview": preview})
# R05-T04: MCP/connector tools used to run with NO permission
# check at all — this is what closes that gap. Same policy,
# same gate object as the built-in tools below.
if not turn_tool_policy.allow(
name, gate, {"name": name, "args": args, "preview": preview}
):
result = {"ok": False, "output": "Rejected by user."}
emit({"type": "tool_result", "id": tc_id, "name": name,
"ok": False, "output": result["output"]})
messages.append({"role": "tool", "tool_call_id": tc_id, "name": name,
"content": result["output"]})
continue
result = extra_executor(name, args)
emit({"type": "tool_result", "id": tc_id, "name": name,
"ok": result.get("ok", False), "output": result.get("output", "")})
@@ -528,16 +562,18 @@ def run_cowork(
# Permission Management (Sandbox Security Layer) — only when a
# gate was actually supplied (Settings: "confirm before running
# commands"); None preserves the pre-existing auto-run behavior.
if gate is not None and name in ("run_command", "install_package"):
approved = gate.request({"name": name, "args": args, "preview": preview})
if not approved:
result = {"ok": False, "output": "Rejected by user."}
evt = {"type": "tool_result", "id": tc_id, "name": name,
"ok": False, "output": result["output"]}
emit(evt)
messages.append({"role": "tool", "tool_call_id": tc_id,
"name": name, "content": result["output"]})
continue
# R05-T03: gating is now capability-driven (see
# turn_tool_policy above) instead of a literal name tuple.
if not turn_tool_policy.allow(
name, gate, {"name": name, "args": args, "preview": preview}
):
result = {"ok": False, "output": "Rejected by user."}
evt = {"type": "tool_result", "id": tc_id, "name": name,
"ok": False, "output": result["output"]}
emit(evt)
messages.append({"role": "tool", "tool_call_id": tc_id,
"name": name, "content": result["output"]})
continue
if name == "save_file":
result = _do_save_file(output_dir, title, args)
+6 -2
View File
@@ -18,6 +18,8 @@ existing ``core/skills.py`` registry.
"""
from __future__ import annotations
from ..infrastructure.persistence.json.atomic_json_file import AtomicJsonFile
import json
from dataclasses import asdict, dataclass, field
from pathlib import Path
@@ -233,7 +235,9 @@ def save_workflow(wf: Workflow, directory: Optional[Path] = None) -> Path:
directory = directory or WORKFLOWS_DIR
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{wf.id}.json"
path.write_text(json.dumps(workflow_to_dict(wf), ensure_ascii=False, indent=2), encoding="utf-8")
# Tiêu chí nghiệm thu A: mọi thao tác ghi tệp đi qua AtomicJsonFile. Trước
# đây ghi thẳng, nên tắt máy giữa lúc lưu là mất luôn workflow.
AtomicJsonFile(path).write(workflow_to_dict(wf))
return path
@@ -307,7 +311,7 @@ def save_custom_agent(agent: CustomAgent, directory: Optional[Path] = None) -> P
directory = directory or AGENTS_DIR
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{agent.id}.json"
path.write_text(json.dumps(agent_to_dict(agent), ensure_ascii=False, indent=2), encoding="utf-8")
AtomicJsonFile(path).write(agent_to_dict(agent))
return path
+6 -4
View File
@@ -13,6 +13,8 @@ the run that is currently open.
"""
from __future__ import annotations
from ..infrastructure.persistence.json.atomic_json_file import AtomicJsonFile
import json
from pathlib import Path
from typing import Dict, List, Optional
@@ -152,10 +154,10 @@ class Co4ERunManager(QObject):
payload = {"runs": [h.to_record() for h in runs]}
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8")
tmp.replace(path) # atomic — never leaves a half-written file
# AtomicJsonFile thay cho tmp+replace tự viết: bản cũ thiếu fsync
# (dữ liệu có thể còn trong bộ đệm khi mất điện) và dùng thẳng
# Path.replace, vốn thỉnh thoảng bị Defender từ chối trên Windows.
AtomicJsonFile(path).write(payload)
except OSError:
pass
+15 -4
View File
@@ -12,6 +12,8 @@ import re
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from ..application.conversations.tool_policy_gateway import ToolPolicyGateway
from ..domain.tools import ToolCapability, ToolDescriptor, ToolRegistry
from ..providers.base import Provider
from . import agent_roles
from . import agent_security
@@ -225,6 +227,14 @@ def run_code(
# read/list ms365 tools count as "read-only, never confirm". Names are
# the MCP-qualified "ms365__*" form the agent sees (see ms365_tools.py).
gated_tools = WRITE_TOOLS | MS365_WRITE_TOOLS
# R05-T03/T04: ``gated_tools`` stays the authoritative name set (unchanged),
# but the actual confirm decision now goes through the same
# ToolPolicyGateway class run_cowork uses, instead of a separate
# hand-rolled ``if name in gated_tools`` + direct ``gate.request(...)``.
code_tool_policy = ToolPolicyGateway(
ToolRegistry(ToolDescriptor(n, "", {}, ToolCapability.WRITE) for n in gated_tools),
ToolCapability.WRITE,
)
# In PLAN mode, don't advertise write/run tools (analysis only).
advertised = [t for t in all_tools if t.name not in gated_tools] if plan else all_tools
has_memory = any(t.name.startswith("cmem_") for t in extra_tools)
@@ -297,10 +307,11 @@ def run_code(
agent_security.enforce_command(provider, name, args, security_config, emit,
agent_kind="code")
if name in gated_tools:
approved = gate.request({"id": tc_id, "name": name, "args": args, "preview": preview})
else:
approved = True # read-only tools (incl. codebase memory) never confirm
# read-only tools (incl. codebase memory) never consult the gate —
# code_tool_policy.requires_confirmation(name) is False for them.
approved = code_tool_policy.allow(
name, gate, {"id": tc_id, "name": name, "args": args, "preview": preview}
)
if cancel():
return messages
+13 -6
View File
@@ -16,8 +16,6 @@ from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List
from ..config import HISTORY_DIR
def new_session_id() -> str:
return datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3]
@@ -66,7 +64,9 @@ def save_conversation(
"outputs": list(outputs or []),
"messages": messages,
}
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
# R06-T02: atomic write - see infrastructure/persistence/json/atomic_write.py.
from ..infrastructure.persistence.json.atomic_write import write_json
write_json(path, payload)
return path
@@ -78,15 +78,19 @@ def delete_conversation(path) -> None:
def rename_conversation(path, new_title: str) -> None:
from ..infrastructure.persistence.json.atomic_write import write_json
data = load_conversation(path)
data["title"] = new_title
Path(path).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
write_json(Path(path), data)
def set_pinned(path, pinned: bool) -> None:
from ..infrastructure.persistence.json.atomic_write import write_json
data = load_conversation(path)
data["pinned"] = bool(pinned)
Path(path).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
write_json(Path(path), data)
def load_conversation(path: Path) -> Dict[str, Any]:
@@ -111,13 +115,16 @@ def _matches_query(query: str, title: str, messages: List[Dict[str, Any]]) -> bo
return False
def list_conversations(directory: Path = HISTORY_DIR, query: str = "") -> List[Dict[str, Any]]:
def list_conversations(directory: Optional[Path] = None, query: str = "") -> List[Dict[str, Any]]:
"""List saved conversations, most recent first (pinned always on top).
``query`` (from the sidebar's search box), when non-empty, keeps only
conversations whose title OR any message's content contains it
(case-insensitive) — since every file is already parsed to build the
metadata below, this search costs no extra I/O over listing alone."""
if directory is None:
from ..config import HISTORY_DIR
directory = HISTORY_DIR
if not directory or not directory.exists():
return []
q = (query or "").strip().lower()
+7
View File
@@ -106,6 +106,13 @@ class McpServerConnection:
if self._thread is not None:
self._thread.join(timeout=5)
def is_alive(self) -> bool:
"""True while the connection's background thread (and therefore its
event loop and subprocess) is still running — used by
``infrastructure/mcp/mcp_source_manager.py`` (R05-T05) to tell a live
cached connection from one whose subprocess already died."""
return self._thread is not None and self._thread.is_alive()
# ---- tools -----------------------------------------------------------
def list_tool_specs(self) -> List[ToolSpec]:
"""The server's tools, wrapped as :class:`ToolSpec` — the same shape
+13 -3
View File
@@ -32,6 +32,14 @@ _SYMBOL_CCY = {"₫": "VND", "vnd": "VND", "đ": "VND",
_DEFAULT_UNIT = "Million tokens"
# Flat USD/1M-token fallback rates used by turn_cost_usd() when a model isn't
# in the price table. Owned here (not usage_tracker.DEFAULT_PRICING) so this
# module never needs to import usage_tracker — usage_tracker imports this
# module instead, keeping the dependency one-directional. Values match
# usage_tracker.DEFAULT_PRICING's price_per_mtok_in_usd/out_usd exactly.
_FALLBACK_RATE_IN_USD = 0.5
_FALLBACK_RATE_OUT_USD = 1.5
# ---- currency ------------------------------------------------------------
def _rates(config) -> Dict[str, float]:
@@ -138,9 +146,11 @@ def turn_cost_usd(model: str, in_tok: int, out_tok: int, config) -> float:
switches models (a different model → its own row / rates)."""
rates = usd_rates_for(model, config)
if rates is None:
from . import usage_tracker as ut
p = {**ut.DEFAULT_PRICING, **((getattr(config, "data", {}) or {}).get("usage") or {})}
rates = {"in": float(p["price_per_mtok_in_usd"]), "out": float(p["price_per_mtok_out_usd"])}
usage = (getattr(config, "data", {}) or {}).get("usage") or {}
rates = {
"in": float(usage.get("price_per_mtok_in_usd", _FALLBACK_RATE_IN_USD)),
"out": float(usage.get("price_per_mtok_out_usd", _FALLBACK_RATE_OUT_USD)),
}
return (in_tok or 0) / 1e6 * rates["in"] + (out_tok or 0) / 1e6 * rates["out"]
+5 -3
View File
@@ -116,10 +116,12 @@ def new_project(name: str, description: str = "", instructions: str = "",
def save_project(project: Project, directory: Path = None) -> Path:
directory = directory or PROJECTS_DIR
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{project.project_id}.json"
path.write_text(json.dumps(asdict(project), ensure_ascii=False, indent=2),
encoding="utf-8")
# R06-T02: atomic write — a crash/kill between truncate and write used to
# leave a half-written project.json that load_project() then silently
# treats as "missing" (see infrastructure/persistence/json/atomic_write.py).
from ..infrastructure.persistence.json.atomic_write import write_json
write_json(path, asdict(project))
return path
+69 -19
View File
@@ -2,7 +2,9 @@
``execute_task`` dispatches by ``task_type`` to the app's existing engines:
- ``cowork`` → ``chat_agent.run_cowork`` (documents/answers, real files)
- ``cowork`` → ``ConversationApplicationService`` (documents/answers, real
files) — the same turn engine the interactive Cowork chat
runs on since R04-T05
- ``co4e_code`` → ``code_agent.run_code`` (code agent with file/command tools)
- ``script`` → local subprocess with a timeout
- ``flow`` → the task's own simple step list, run sequentially, each
@@ -162,6 +164,30 @@ _TIMEOUT_NOTICE_TMPL = (
)
_UNATTENDED_PREFIX = (
"This runs unattended (Schedule Task) — no one is watching live. Use "
"update_plan to track your steps and keep it accurate: mark a step "
"'error' (not silently skip it) if it genuinely can't be completed."
)
def _unattended_prompt(prompt: str, *, skill_text: str = "",
agent_instructions: str = "") -> str:
"""Assemble the user message an unattended run sends.
The order is load-bearing and used to be encoded as three successive
rebindings of ``prompt``, each prepending its own block: the plan reminder
must lead (it is the instruction that keeps a run without a human watching
honest), then the chosen skill's rules, then the Admin agent's persona, and
the task's own words last. Routing it through ``combine_instructions`` keeps
that order in one readable expression and drops the absent blocks instead of
leaving blank lines behind.
"""
from ..application.conversations.turn_runtime import combine_instructions
return combine_instructions(_UNATTENDED_PREFIX, skill_text, agent_instructions, prompt)
def _cancel_with_timeout(cancel: CancelFn, timeout_sec: Optional[int]) -> Tuple[CancelFn, Callable[[], bool]]:
"""Wrap ``cancel`` so it also fires once ``timeout_sec`` of wall-clock time
elapses. ``timed_out()`` tells the caller whether THAT is why it stopped
@@ -218,36 +244,29 @@ def _run_agent(ctx, task_type: str, prompt: str, out_dir: Path,
# default, see state.build_provider_for). A legacy Admin-agent preset
# (task.admin_agent_id), if still set on an older task, keeps working and
# takes precedence — it pins the provider/model AND prepends instructions.
agent_instructions = ""
if admin_agent is not None:
from .admin_agents import build_agent_provider
provider = build_agent_provider(ctx, admin_agent)
agent_instructions = admin_agent.effective_prompt()
if agent_instructions:
prompt = f"{agent_instructions}\n\n{prompt}"
elif provider_name or model:
# An explicit per-task provider/model override.
provider = ctx.build_provider_for(provider_name or None, model or None)
else:
# Neither overridden → the machine's own Settings default, exactly as before.
provider = ctx.build_active_provider()
# A chosen skill's instructions are prepended so this unattended run follows
# A chosen skill's instructions are applied so this unattended run follows
# them, mirroring how the interactive chat applies /skill.
skill_text = ""
if skill_slug:
from .skills import skill_prefix_for
skill_text = skill_prefix_for(skill_slug)
if skill_text:
prompt = f"{skill_text}\n\n{prompt}"
# This is an UNATTENDED run (no human watching to catch a half-finished
# job) — push the agent to actually use the Plan checklist so completion
# can be verified afterward, instead of just trusting "no exception".
prompt = (
"This runs unattended (Schedule Task) — no one is watching live. Use "
"update_plan to track your steps and keep it accurate: mark a step "
"'error' (not silently skip it) if it genuinely can't be completed.\n\n"
f"{prompt}"
)
# Assemble reminder + skill + persona + the task's own words in one place
# (see _unattended_prompt for why that order matters).
prompt = _unattended_prompt(prompt, skill_text=skill_text,
agent_instructions=agent_instructions)
messages = [{"role": "user", "content": prompt}]
session_id = new_session_id()
project_id = project.project_id if project is not None else ""
@@ -273,10 +292,41 @@ def _run_agent(ctx, task_type: str, prompt: str, out_dir: Path,
watched_cancel, timed_out = _cancel_with_timeout(cancel, timeout_sec)
try:
if task_type == "cowork":
from .chat_agent import run_cowork
run_cowork(provider, messages, out_dir, emit_and_autosave, watched_cancel,
security_config=ctx.config, agent_role=agent_roles.TASK,
project_context=project_context)
# R04-T05: the unattended run shares the interactive turn engine
# instead of calling run_cowork itself, so there is exactly one place
# where a turn's lifecycle is defined. Everything unattended-specific
# stays here (the plan reminder above, the History autosave in
# emit_and_autosave, the timeout notice below).
from ..application.conversations.core_runtime_adapter import (
build_cowork_conversation_service,
legacy_event_sink,
)
from ..domain.agents.conversation_execution_request import (
ConversationExecutionRequest,
)
# No extra_tools/extra_executor and no permission gate: a scheduled
# run gets no MCP connectors and nobody is there to approve a
# command, which is exactly what run_cowork was called with.
service = build_cowork_conversation_service(
provider, out_dir, emit_and_autosave, title=title,
project_context=project_context, security_config=ctx.config,
agent_role=agent_roles.TASK,
)
request = ConversationExecutionRequest(
# The artifact folder is named by the run id, which identifies
# this attempt in the audit log.
turn_id=out_dir.name or session_id, session_id=session_id,
surface="task", title=title, project_id=project_id,
prompt=prompt, output_dir=out_dir,
agent_role=agent_roles.TASK, unattended=True,
timeout_sec=timeout_sec,
)
# ``messages`` is handed over so the History autosave in
# emit_and_autosave (and the final save in the finally block below)
# keep reading the live conversation as it grows.
service.execute(request, legacy_event_sink(emit_and_autosave),
cancel=watched_cancel, messages=messages)
else:
from .code_agent import run_code
limits, block_network = agent_security.sandbox_settings(ctx.config)
+20 -10
View File
@@ -17,7 +17,7 @@ from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
from PySide6.QtCore import QCoreApplication, QObject, QTimer, Signal
from PySide6.QtCore import QObject, Signal
from .tasks import (
advance_after_run, chain_action, dependencies_met, due_tasks, format_run_at,
@@ -39,22 +39,32 @@ class TaskScheduler(QObject):
# which fires before the worker thread has even begun).
history_ready = Signal(str) # task_id
def __init__(self, ctx, tasks_dir: Optional[Path] = None, parent=None):
def __init__(self, ctx, tasks_dir: Optional[Path] = None, parent=None, clock=None):
super().__init__(parent)
self.ctx = ctx
self.tasks_dir = tasks_dir # None → default TASKS_DIR
self._workers: Dict[str, AgentWorker] = {} # task_id → running worker
self._retries: Dict[str, int] = {}
self._session_ids: Dict[str, str] = {} # task_id → its run's History session id
self._timer = QTimer(self)
self._timer.setInterval(TICK_MS)
self._timer.timeout.connect(self.tick)
# R07-T03: the QTimer this class used to own directly is now behind a
# small clock interface (start/stop/pump) — see
# platform/qt/qt_scheduler_clock.py::QtSchedulerClock. Defaulting to a
# real one here keeps every existing production call site (which
# never passes `clock=`) unchanged; tests inject
# tests/fakes/fake_clock.py::FakeClock to control ticks by hand with
# no Qt event loop running. Imported lazily so importing core.tasks/
# core.task_scheduler for the Qt-free logic doesn't require the Qt
# adapter module to even exist in a headless test context.
if clock is None:
from ..infrastructure.qt.qt_scheduler_clock import QtSchedulerClock
clock = QtSchedulerClock(self)
self._clock = clock
# ---- lifecycle ----------------------------------------------------
def start(self) -> None:
self._recover_orphans()
self.tick() # catch up overdue tasks right at app start
self._timer.start()
self._clock.start(TICK_MS, self.tick)
def stop(self) -> None:
"""Request every running worker to stop, then WAIT (bounded) for them
@@ -67,15 +77,15 @@ class TaskScheduler(QObject):
``_on_done`` (the only place that writes the run into the task's
history) never runs. The task's real output can already be sitting on
disk while its history stays stuck on "running" forever. Pumping
``processEvents()`` here lets that queued signal actually get
delivered before the app finishes quitting.
the clock here lets that queued signal actually get delivered before
the app finishes quitting.
"""
self._timer.stop()
self._clock.stop()
deadline = time.monotonic() + STOP_WAIT_SECS
while self._workers and time.monotonic() < deadline:
for w in list(self._workers.values()):
w.request_stop()
QCoreApplication.processEvents()
self._clock.pump()
for w in list(self._workers.values()):
w.wait(50)
# Anything still alive past the deadline is abandoned here;
+29 -71
View File
@@ -151,7 +151,14 @@ def save_task(task: Dict[str, Any], directory: Path = None) -> Path:
directory.mkdir(parents=True, exist_ok=True)
task["updated_at"] = datetime.now().isoformat(timespec="seconds")
path = task_path(task["task_id"], directory)
path.write_text(json.dumps(task, ensure_ascii=False, indent=2), encoding="utf-8")
# R07-T01: atomic write — same class of bug already fixed in
# core/projects.py and core/history.py at R06-T02 (plain write_text has a
# gap between truncate and write; a crash there leaves a half-written
# tasks/<id>.json that load_task() then silently treats as "missing",
# dropping the task). Lazy import to match the existing call sites and
# avoid a core -> infrastructure import at module load time.
from ..infrastructure.persistence.json.atomic_write import write_json
write_json(path, task)
return path
@@ -287,36 +294,32 @@ def chain_error(tasks: List[Dict[str, Any]], task_id: str,
# ---- schedule math --------------------------------------------------------
def _is_excluded_day(dt: datetime, sched: Dict[str, Any]) -> bool:
"""True when ``dt`` falls on a day this schedule must skip: a weekend
(working_days_only) or a public holiday of the configured country."""
if sched.get("working_days_only") and dt.weekday() >= 5: # 5=Sat, 6=Sun
return True
if sched.get("skip_holidays"):
# R07-T02: the actual date/cron math now lives in
# domain/tasks/schedule_calculator.py::ScheduleCalculator (pure Python, unit
# tested on its own — see tests/unit/test_schedule_calculator.py). Everything
# below is a thin wrapper kept for backward compatibility: task_scheduler.py,
# task_executors.py and ui/task_editor_dialog.py all still import these
# module-level names from core.tasks, and core/holiday_calendar.py::is_holiday
# / core/cron.py::Cron are only wired in HERE (lazily, matching the previous
# lazy-import style) — domain/ is not allowed to import core/ (ADR-001 I2).
_calculator: Optional[Any] = None
def _get_calculator():
global _calculator
if _calculator is None:
from .cron import Cron
from .holiday_calendar import is_holiday
from ..domain.tasks.schedule_calculator import ScheduleCalculator
if is_holiday(dt.date(), sched.get("holiday_country", "")):
return True
return False
def _add_month(dt: datetime) -> datetime:
import calendar
year = dt.year + (1 if dt.month == 12 else 0)
month = 1 if dt.month == 12 else dt.month + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
_calculator = ScheduleCalculator(is_holiday=is_holiday, make_cron=Cron)
return _calculator
def shift_off_excluded_days(dt: datetime, sched: Dict[str, Any]) -> datetime:
"""Push ``dt`` forward one day at a time until it lands on an allowed day
(same time of day) — used for one-time schedules set on a weekend/holiday."""
guard = 0
while _is_excluded_day(dt, sched) and guard < 400:
dt += timedelta(days=1)
guard += 1
return dt
return _get_calculator().shift_off_excluded_days(dt, sched)
def compute_next_run(task: Dict[str, Any], after: datetime) -> Optional[datetime]:
@@ -324,57 +327,12 @@ def compute_next_run(task: Dict[str, Any], after: datetime) -> Optional[datetime
(daily / weekly / monthly / cron), or None for one-shot schedules.
Occurrences on excluded days (weekends with working_days_only, public
holidays with skip_holidays+holiday_country) are skipped forward."""
sched = task.get("schedule", {})
repeat = sched.get("repeat_type", "none")
if repeat == "cron":
from .cron import Cron, CronError
try:
cron = Cron(sched.get("cron_expression") or "")
except CronError:
return None
nxt = cron.next_after(after)
guard = 0
while nxt is not None and _is_excluded_day(nxt, sched) and guard < 400:
nxt = cron.next_after(nxt)
guard += 1
return nxt
base = parse_run_at(sched.get("run_at"))
if base is None:
return None
if repeat == "daily":
advance = lambda d: d + timedelta(days=1) # noqa: E731
elif repeat == "weekly":
advance = lambda d: d + timedelta(weeks=1) # noqa: E731
elif repeat == "monthly":
advance = _add_month
else:
return None
nxt = base
while nxt <= after:
nxt = advance(nxt)
guard = 0
while _is_excluded_day(nxt, sched) and guard < 400:
nxt = advance(nxt)
guard += 1
return nxt
return _get_calculator().compute_next_run(task, after)
def due_tasks(tasks: List[Dict[str, Any]], now: datetime) -> List[Dict[str, Any]]:
"""Tasks that should start now: Scheduled + schedule enabled + run_at due."""
due = []
for t in tasks:
if t.get("status") != "scheduled":
continue
sched = t.get("schedule", {})
if not sched.get("enabled"):
continue
run_at = parse_run_at(sched.get("run_at"))
if run_at is not None and run_at <= now:
due.append(t)
return due
return _get_calculator().due_tasks(tasks, now)
# ---- post-run bookkeeping (pure; scheduler applies + saves) ---------------
+38 -312
View File
@@ -3,79 +3,29 @@
Every path is resolved relative to the working directory and must stay inside
it (path-traversal is rejected). ``run_command`` executes inside the workdir
with a timeout and captured output.
R05-T02: the actual handlers (``read_file``/``list_dir``/``write_file``/
``edit_file``/``run_command``/``install_package``/``fetch_url``/
``jira_search``/``jira_get_issue``) now live in
``infrastructure/filesystem/{file_tools,command_tools,fetch_tools}.py``, split
out of what used to be one big if/elif chain here. This module is the
strangler-fig shim (ADR-001 section 4): it re-exports ``ToolContext``/
``ToolError`` (actually defined in
``infrastructure/filesystem/tool_context.py`` now) so every existing
``from .tools import ToolContext`` keeps working, and ``execute_tool``
dispatches through a small ``{name: handler}`` table built from the moved
modules instead of the chain itself.
"""
from __future__ import annotations
import ast
import difflib
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from ..infrastructure.filesystem import command_tools, fetch_tools, file_tools
from ..infrastructure.filesystem.command_tools import _snapshot # noqa: F401 - re-export, core/chat_agent.py imports this name
from ..infrastructure.filesystem.tool_context import CancelFn, ToolContext, ToolError # noqa: F401 - re-export
from ..providers.base import ToolSpec
CancelFn = Callable[[], bool]
MAX_READ_BYTES = 200_000
COMMAND_TIMEOUT = 120 # seconds
class ToolError(Exception):
pass
def _flatten_rel(rel: str) -> str:
"""Collapse a sub-folder path down to a bare filename so the file lands in the
workdir root — EXCEPT the ``.scratch`` sandbox subtree, which is preserved.
Used by the Cowork agent (flatten_writes=True) so it can never create a
per-session / per-chat / per-task output sub-folder: every deliverable stays
directly in the single configured Output folder."""
parts = Path(rel).parts
if parts and parts[0] == ".scratch":
return rel # temporary sandbox is allowed (and cleaned up afterwards)
return Path(rel).name or rel
@dataclass
class ToolContext:
workdir: Path
flatten_writes: bool = False # Cowork: force every write into the workdir root
sandbox: bool = False # Code tab: isolate run_command/install_package into <workdir>/.venv
# Sandbox Security Layer — Settings' "Resource Limits" (cpu_percent/memory_mb/
# disk_mb), applied to every run_command/install_package this context runs.
# None (default) = no limits, matching pre-existing behavior.
resource_limits: Optional[Dict[str, float]] = None
# Sandbox Security Layer — Settings' "Block network for agent commands"
# (policy-level, see deps.py::network_blocked_env). False (default) =
# unrestricted, matching pre-existing behavior.
block_network: bool = False
# Whether the fetch_url tool may read URLs — SEPARATE from block_network
# (reading a web page/share link for info is safe; running networked shell
# commands is the risk). Defaults True; set from agent_security.allow_url_fetch.
allow_url_fetch: bool = True
# Jira read connector config (base_url/email/api_token) — None disables the
# jira_* tools' ability to connect. Populated from config.data["jira"].
jira: Optional[Dict[str, Any]] = None
def resolve(self, rel: str) -> Path:
"""Resolve ``rel`` inside the workdir, rejecting escapes."""
if rel in ("", "."):
return self.workdir
candidate = (self.workdir / rel).expanduser()
try:
resolved = candidate.resolve()
except OSError as exc:
raise ToolError(f"Invalid path: {rel} ({exc})")
root = self.workdir.resolve()
if resolved != root and root not in resolved.parents:
raise ToolError(
f"Refused: '{rel}' is outside the working folder ({root})."
)
return resolved
# --------------------------------------------------------------------------
# Tool specs advertised to the model
# --------------------------------------------------------------------------
@@ -192,6 +142,23 @@ TOOL_SPECS: List[ToolSpec] = [
# Actions gated by the permission gate in confirm mode (auto-approved in Auto-run).
WRITE_TOOLS = {"write_file", "edit_file", "run_command", "install_package"}
# name -> handler(ctx, args[, cancel, on_output]) — built once from the split
# infrastructure modules. Replaces the if/elif chain execute_tool used to be.
_HANDLERS: Dict[str, Callable[..., Dict[str, Any]]] = {
"read_file": file_tools.read_file,
"list_dir": file_tools.list_dir,
"write_file": file_tools.write_file,
"edit_file": file_tools.edit_file,
"run_command": command_tools.run_command,
"install_package": command_tools.install_package,
"fetch_url": fetch_tools.fetch_url,
"jira_search": fetch_tools.jira_search,
"jira_get_issue": fetch_tools.jira_get_issue,
}
# Handlers that accept the long-running (cancel, on_output) signature — every
# other handler takes just (ctx, args).
_CANCELLABLE = {"run_command", "install_package"}
def enabled_tool_specs(security_config=None) -> List[ToolSpec]:
"""The built-in TOOL_SPECS minus any the admin turned OFF in Monitoring →
@@ -301,27 +268,14 @@ def execute_tool(ctx: ToolContext, name: str, args: Dict[str, Any],
labels WHICH agent role made it."""
from . import audit_log
handler = _HANDLERS.get(name)
try:
if name == "read_file":
result = _read_file(ctx, args)
elif name == "list_dir":
result = _list_dir(ctx, args)
elif name == "write_file":
result = _write_file(ctx, args)
elif name == "edit_file":
result = _edit_file(ctx, args)
elif name == "run_command":
result = _run_command(ctx, args, cancel, on_output)
elif name == "install_package":
result = _install_package(ctx, args, cancel, on_output)
elif name == "fetch_url":
result = _fetch_url(ctx, args)
elif name == "jira_search":
result = _jira_search(ctx, args)
elif name == "jira_get_issue":
result = _jira_get_issue(ctx, args)
else:
if handler is None:
result = {"ok": False, "output": f"Tool not found: {name}"}
elif name in _CANCELLABLE:
result = handler(ctx, args, cancel, on_output)
else:
result = handler(ctx, args)
except ToolError as exc:
result = {"ok": False, "output": str(exc)}
except Exception as exc: # defensive: a tool must never crash the agent
@@ -331,234 +285,6 @@ def execute_tool(ctx: ToolContext, name: str, args: Dict[str, Any],
return result
def _fetch_url(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
"""Fetch a URL's text content (web page / online document / SharePoint-
OneDrive share link) via link_fetch — the same parser task-link attachments
use. Honors the Sandbox Security Layer's "Block network" policy."""
url = str(args.get("url", "")).strip()
if not url:
return {"ok": False, "output": "fetch_url: 'url' is required."}
if not url.lower().startswith(("http://", "https://")):
return {"ok": False, "output": f"fetch_url: not an http(s) URL: {url}"}
if not ctx.allow_url_fetch:
return {"ok": False,
"output": ("fetch_url: URL fetching is turned off in Settings → Security "
"(\"Allow the agent to fetch URLs\").")}
# A pasted Jira issue link on the CONNECTED Jira host is read via the
# authenticated API (so private issues resolve, not a login page). Public
# links / any other URL fall through to the normal fetcher below.
from . import jira_tool
if jira_tool.is_jira_issue_url(ctx.jira, url):
return {"ok": True, "output": jira_tool.get_issue_by_url(ctx.jira, url)}
from .link_fetch import fetch_link_preview
return {"ok": True, "output": fetch_link_preview(url)}
def _jira_search(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
from . import jira_tool
out = jira_tool.search(ctx.jira, str(args.get("jql", "")),
int(args.get("max_results", 25) or 25))
return {"ok": not out.lower().startswith(("jira is not configured", "jira search failed")),
"output": out}
def _jira_get_issue(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
from . import jira_tool
out = jira_tool.get_issue(ctx.jira, str(args.get("key", "")))
return {"ok": not out.lower().startswith(("jira is not configured", "could not fetch")),
"output": out}
def _read_file(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
target = ctx.resolve(str(args.get("path", "")))
if not target.exists():
return {"ok": False, "output": f"File not found: {args.get('path')}"}
data = target.read_bytes()[:MAX_READ_BYTES]
text = data.decode("utf-8", errors="replace")
return {"ok": True, "output": text}
def _list_dir(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
rel = str(args.get("path", ".") or ".")
target = ctx.resolve(rel)
# A missing/not-yet-created path is NOT a tool failure — report it as an
# ordinary result so the agent can create it or pick another path and keep
# going. Returning ok=False here surfaced a false "tool failed: list_dir" in
# Co4E flows and could stall a step on a recoverable situation.
if not target.exists():
return {"ok": True, "output": f"(path '{rel}' does not exist yet — create it or use another path)"}
if target.is_file():
return {"ok": True, "output": f"('{rel}' is a file, not a directory)"}
entries = []
for child in sorted(target.iterdir(), key=lambda p: (p.is_file(), p.name.lower())):
marker = "/" if child.is_dir() else ""
entries.append(f"{child.name}{marker}")
return {"ok": True, "output": "\n".join(entries) or "(empty folder)"}
def _check_python_syntax(target: Path, content: str) -> str:
"""Return a short warning if ``content`` is invalid Python, else ''.
Catches syntax errors the instant a .py file is written/edited — before the
agent wastes a whole run_command round-trip just to get the same error back
from a traceback."""
if target.suffix.lower() not in (".py", ".pyw"):
return ""
try:
ast.parse(content, filename=str(target))
return ""
except SyntaxError as exc:
return f"\n⚠ Syntax error at line {exc.lineno}: {exc.msg} — fix this before running the file."
def _write_file(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
rel = str(args.get("path", ""))
if ctx.flatten_writes:
rel = _flatten_rel(rel)
target = ctx.resolve(rel)
content = str(args.get("content", ""))
target.parent.mkdir(parents=True, exist_ok=True)
# A .xlsx is a binary package — build a REAL workbook from the content
# (CSV/TSV/Markdown-table/JSON) rather than writing raw text (which corrupts it).
if target.suffix.lower() in (".xlsx", ".xlsm"):
from . import xlsx_write
if xlsx_write.build_xlsx_from_text(target, content):
return {"ok": True, "path": str(target),
"output": f"Wrote spreadsheet {rel} ({target.name})."}
return {"ok": False, "output": "Could not build the .xlsx (openpyxl unavailable) — "
"write a .csv instead, or use a generator script."}
target.write_text(content, encoding="utf-8")
warning = _check_python_syntax(target, content)
return {"ok": True, "path": str(target),
"output": f"Wrote {len(content)} chars to {rel}.{warning}"}
def _edit_file(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
"""Replace an exact snippet inside an existing file (precise patch edit)."""
rel = str(args.get("path", ""))
if ctx.flatten_writes:
rel = _flatten_rel(rel)
target = ctx.resolve(rel)
if not target.exists():
return {"ok": False,
"output": f"File not found: {rel} — use write_file to create it."}
old = str(args.get("old_string", ""))
new = str(args.get("new_string", ""))
replace_all = bool(args.get("replace_all", False))
if not old:
return {"ok": False, "output": "old_string is empty — provide the exact text to replace."}
try:
text = target.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
return {"ok": False, "output": f"Could not read file: {exc}"}
count = text.count(old)
if count == 0:
return {"ok": False, "output": ("old_string not found. Read the file and copy the exact "
"text to replace, including indentation/whitespace.")}
if count > 1 and not replace_all:
return {"ok": False, "output": (f"old_string appears {count} times — add surrounding "
"context to make it unique, or set replace_all=true.")}
updated = text.replace(old, new) if replace_all else text.replace(old, new, 1)
target.write_text(updated, encoding="utf-8")
n = count if replace_all else 1
warning = _check_python_syntax(target, updated)
return {"ok": True,
"output": f"Edited {args.get('path')} ({n} replacement{'' if n == 1 else 's'}).{warning}"}
def _sandbox_python(ctx: ToolContext, cancel: Optional[CancelFn] = None,
on_output: Optional[Callable[[str], None]] = None) -> Optional[str]:
"""Lazily create/reuse this ctx's project sandbox venv (Code tab only —
``ctx.sandbox``); returns its python path, or None to use the app's own."""
if not ctx.sandbox:
return None
from .deps import ensure_project_venv
py = ensure_project_venv(ctx.workdir, cancel=cancel, on_output=on_output)
return str(py) if py else None
def _install_package(ctx: ToolContext, args: Dict[str, Any], cancel: Optional[CancelFn] = None,
on_output: Optional[Callable[[str], None]] = None) -> Dict[str, Any]:
from .deps import pip_install
package = str(args.get("package", "")).strip()
if not package:
return {"ok": False, "output": "No package specified."}
python = _sandbox_python(ctx, cancel, on_output)
ok, detail = pip_install(package, cancel=cancel, on_output=on_output, python=python)
head = f"Installed {package}." if ok else f"Could not install {package}."
return {"ok": ok, "output": f"{head}\n{detail}"}
_SNAPSHOT_SKIP = {".git", "__pycache__", "node_modules", ".scratch", ".venv",
".idea", ".mypy_cache", ".pytest_cache"}
def _snapshot(workdir: Path) -> Dict[str, Any]:
"""Map of file path -> (mtime, size) under the workdir (noise dirs skipped)."""
snap: Dict[str, Any] = {}
try:
for dirpath, dirnames, filenames in os.walk(str(workdir)):
dirnames[:] = [d for d in dirnames if d not in _SNAPSHOT_SKIP]
for fn in filenames:
full = os.path.join(dirpath, fn)
try:
st = os.stat(full)
snap[full] = (st.st_mtime_ns, st.st_size)
except OSError:
pass
if len(snap) > 5000:
return snap
except OSError:
pass
return snap
def _run_command(ctx: ToolContext, args: Dict[str, Any],
cancel: Optional[CancelFn] = None,
on_output: Optional[Callable[[str], None]] = None) -> Dict[str, Any]:
from .deps import network_blocked_env, run_cancellable, sandbox_env
from .sandbox_manager import SandboxManager, ExecutionConfig
from ..security.command_risk_classifier import classify_command
command = str(args.get("command", "")).strip()
if not command:
return {"ok": False, "output": "Empty command."}
# --- Security validation pipeline ---
risk = classify_command(command, is_cowork_mode=ctx.flatten_writes)
if risk.blocked:
denial = "Command blocked by security policy: " + "; ".join(risk.reasons)
return {"ok": False, "output": denial}
# Route through SandboxManager for risk-based isolation
mgr = SandboxManager(ExecutionConfig(
enabled=True,
block_network_by_default=ctx.block_network,
is_cowork_mode=ctx.flatten_writes,
))
sandbox_result = mgr.run(
command=command,
workdir=str(ctx.workdir),
block_network=ctx.block_network,
timeout_sec=COMMAND_TIMEOUT,
cancel=cancel,
)
# Sandbox ALWAYS executes (never double-run). Return its result directly.
if sandbox_result.get("sandbox") == "blocked":
return {"ok": False, "output": sandbox_result.get("stderr", "Command blocked")}
out = sandbox_result.get("stdout", "").strip() or "(no output)"
err = sandbox_result.get("stderr", "")
rc = sandbox_result.get("returncode", -1)
if err:
out = f"{out}\n{err}" if out else err
return {"ok": sandbox_result.get("ok", False), "output": f"[exit {rc}]\n{out}"}
def _short_json(obj: Any, limit: int = 500) -> str:
import json
text = json.dumps(obj, ensure_ascii=False, indent=2)
+56
View File
@@ -0,0 +1,56 @@
"""Dựng câu nhắc cho AI phân tích mức dùng — R09-T02.
Chỉ sinh văn bản. Tách riêng vì đây là phần dễ đổi nhất (câu chữ, cột hiển
thị) và không liên quan tới việc ghi nhận hay tính tiền.
"""
from __future__ import annotations
import json
import threading
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from ..config import CONFIG_DIR
from . import model_pricing as mp
from .usage_periods import period_breakdown, period_range_label
_AI_ANALYSIS_HEADERS = {
"vi": ("Nhận xét thói quen", "Cách viết prompt tiết kiệm hơn", "Hành động giảm token"),
"en": ("Usage habits", "Writing more efficient prompts", "Actions to cut token usage"),
"ja": ("利用傾向", "より効率的なプロンプトの書き方", "トークン削減のためのアクション"),
}
def build_ai_analysis_prompt(summary: Dict[str, Any], language: str = "vi") -> str:
"""The prompt sent to the model for '✨ AI analyze my usage': aggregated
numbers only — never raw prompt contents — asking for concrete habits
feedback and token-saving recommendations, in the CURRENTLY SELECTED
display language (headers included — not just the model's free-text reply,
which would otherwise leave the section titles in Vietnamese regardless of
the app's language setting)."""
lang_names = {"vi": "Vietnamese", "ja": "Japanese", "en": "English"}
h1, h2, h3 = _AI_ANALYSIS_HEADERS.get(language, _AI_ANALYSIS_HEADERS["vi"])
top = "\n".join(f"- {label}: {tok:,} tokens"
for label, tok in summary.get("top_labels", []))
by_source = ", ".join(f"{k}={v:,}" for k, v in summary.get("by_source", []))
return (
"You are a token-efficiency coach for an AI desktop app (chat tabs + "
"scheduled agent tasks). Analyze this usage summary and give the user "
"practical advice, replying in "
f"{lang_names.get(language, 'Vietnamese')}.\n\n"
f"Period stats: {summary.get('turns', 0)} turns, "
f"input={summary.get('in', 0):,} tokens, output={summary.get('out', 0):,}, "
f"cache={summary.get('cache', 0):,}, "
f"avg per prompt={summary.get('avg_per_turn', 0):,}.\n"
f"Top consumers:\n{top or '- (none)'}\n"
f"By area: {by_source or '(none)'}\n"
f"Busiest day: {summary.get('busiest_day')} · busiest hour: {summary.get('busiest_hour')}\n\n"
"Reply with EXACTLY these 3 short sections, in markdown, using THESE "
f"section headers verbatim (already in {lang_names.get(language, 'Vietnamese')}):\n"
f"1. **{h1}** — 2-3 bullet points about the usage pattern.\n"
f"2. **{h2}** — 3 concrete prompt-writing tips "
"tailored to the numbers above (e.g. long inputs → attach less / summarize "
"first; many small turns → batch questions).\n"
f"3. **{h3}** — 2-3 app-level actions (compact history, "
"smaller model for simple tasks, reuse task outputs instead of re-asking).\n"
"Keep the whole reply under 250 words."
)
+101
View File
@@ -0,0 +1,101 @@
"""Bảng giá và quy đổi token thành tiền — R09-T02.
Tách khỏi ``usage_tracker.py``: ghi nhận mức dùng và tính tiền là hai việc
khác nhau. Bảng giá đổi theo nhà cung cấp, cách ghi nhận thì không.
"""
from __future__ import annotations
import json
import threading
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from ..config import CONFIG_DIR
from . import model_pricing as mp
DEFAULT_PRICING = {
"price_per_mtok_in_usd": 0.5, # USD per 1M input tokens (flat fallback rate)
"price_per_mtok_out_usd": 1.5, # USD per 1M output tokens
"price_per_mtok_cache_usd": 0.1, # USD per 1M cached tokens
"currency": "USD", # display currency: USD | VND | JPY
"usd_to_vnd": 25000.0,
"usd_to_jpy": 150.0,
# Per-model price table (USD / 1M tokens): {model: {"in","out","cache"}}.
# Events whose model has an entry are costed with ITS rates; everything
# else falls back to the flat price_per_mtok_* rates above. Edited in the
# Monitoring Overview's pricing table.
"model_prices": {},
# Reference URL of the price list the table was filled from (set in
# Settings; shown as a link beside the table — informational only, the
# app never scrapes it).
"pricing_url": "",
}
_CURRENCY_FMT = {"USD": ("$", 4), "VND": ("₫", 0), "JPY": ("¥", 1)}
SUPPORTED_CURRENCIES = tuple(_CURRENCY_FMT)
def cost_usd(summary: Dict[str, Any], pricing: Dict[str, Any]) -> Dict[str, float]:
p = {**DEFAULT_PRICING, **(pricing or {})}
return {
"in": summary.get("in", 0) / 1e6 * float(p["price_per_mtok_in_usd"]),
"out": summary.get("out", 0) / 1e6 * float(p["price_per_mtok_out_usd"]),
"cache": summary.get("cache", 0) / 1e6 * float(p["price_per_mtok_cache_usd"]),
}
def cost_usd_events(events: List[Dict[str, Any]], pricing: Dict[str, Any]) -> Dict[str, float]:
"""Per-bucket USD cost computed EVENT BY EVENT so the per-model price
table applies: an event whose ``model`` has an entry in
``pricing["model_prices"]`` is costed with that model's own rates; any
other event uses the flat ``price_per_mtok_*`` rates. With an empty
table this equals ``cost_usd(summarize(events), pricing)`` exactly."""
p = {**DEFAULT_PRICING, **(pricing or {})}
table = p.get("model_prices") or {}
flat = {"in": float(p["price_per_mtok_in_usd"]),
"out": float(p["price_per_mtok_out_usd"]),
"cache": float(p["price_per_mtok_cache_usd"])}
out = {"in": 0.0, "out": 0.0, "cache": 0.0}
for e in events:
rates = table.get(e.get("model", "")) or {}
for bucket in ("in", "out", "cache"):
try:
rate = float(rates.get(bucket, flat[bucket]))
except (TypeError, ValueError):
rate = flat[bucket]
out[bucket] += e.get(bucket, 0) / 1e6 * rate
return out
def format_cost(usd: float, pricing: Dict[str, Any], digits: Optional[int] = None) -> str:
"""Format a USD amount in the display currency. ``digits`` caps the number
of decimal places (e.g. ``digits=2`` for the Total cost / Budget cards, so
USD shows $1.23 not the default up-to-4 $1.2345) — never ADDS decimals to a
currency that uses fewer (VND stays whole, JPY one place)."""
p = {**DEFAULT_PRICING, **(pricing or {})}
cur = p.get("currency", "USD")
rate = {"USD": 1.0, "VND": float(p["usd_to_vnd"]), "JPY": float(p["usd_to_jpy"])}.get(cur, 1.0)
symbol, cur_digits = _CURRENCY_FMT.get(cur, ("$", 2))
if digits is not None:
cur_digits = min(cur_digits, digits)
value = usd * rate
return f"{symbol}{value:,.{cur_digits}f}"
def format_cost_compact(usd: float, pricing: Dict[str, Any]) -> str:
"""Compact cost format for the Dashboard chart's y-axis/endpoint labels —
always 2 decimals (not format_cost's up-to-4 for USD) and abbreviated with
K/M above 1,000/1,000,000, same convention as ``fmt_tokens``. The chart's
y-axis label box is narrow; the longer full-precision string used to
overflow it, visually clipping/obscuring the leading currency symbol."""
p = {**DEFAULT_PRICING, **(pricing or {})}
cur = p.get("currency", "USD")
rate = {"USD": 1.0, "VND": float(p["usd_to_vnd"]), "JPY": float(p["usd_to_jpy"])}.get(cur, 1.0)
symbol, _digits = _CURRENCY_FMT.get(cur, ("$", 2))
value = usd * rate
sign = "-" if value < 0 else ""
value = abs(value)
if value >= 1_000_000:
body = f"{value / 1_000_000:,.2f}M"
elif value >= 1_000:
body = f"{value / 1_000:,.2f}K"
else:
body = f"{value:,.2f}"
return f"{sign}{symbol}{body}"
+144
View File
@@ -0,0 +1,144 @@
"""Gộp mức dùng theo khoảng thời gian — R09-T02.
Ngày / tuần / tháng / quý: ranh giới khoảng, nhãn hiển thị, chuỗi số vẽ biểu
đồ. Thuần tính toán trên danh sách sự kiện, không đụng đĩa.
"""
from __future__ import annotations
import json
import threading
from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
from ..config import CONFIG_DIR
from . import model_pricing as mp
from .usage_cost import cost_usd_events
def bucketed_series(events: List[Dict[str, Any]], granularity: str = "day",
pricing: Dict[str, Any] = None, last: int = None) -> List[tuple]:
"""Group usage events into time buckets → ordered ``[(label, tokens, cost_usd)]``.
``granularity``: ``day`` (YYYY-MM-DD) · ``month`` (YYYY-MM) · ``year`` (YYYY).
``last`` keeps only the most recent N buckets (for the dashboard chart)."""
from collections import OrderedDict
pricing = pricing or {}
def _key(ts: Any) -> str:
s = str(ts or "")[:10]
if granularity == "year":
return s[:4]
if granularity == "month":
return s[:7]
return s
buckets: "OrderedDict[str, List[Dict[str, Any]]]" = OrderedDict()
for e in sorted(events, key=lambda ev: str(ev.get("ts", ""))):
k = _key(e.get("ts"))
if k:
buckets.setdefault(k, []).append(e)
out = []
for k, evs in buckets.items():
tokens = sum(int(e.get("in", 0) or 0) + int(e.get("out", 0) or 0)
+ int(e.get("cache", 0) or 0) for e in evs)
cost = sum(cost_usd_events(evs, pricing).values())
out.append((k, tokens, cost))
if last and len(out) > last:
out = out[-last:]
return out
def period_bounds(gran: str, offset: int, today: Optional[date] = None) -> tuple:
"""[start, end) dates of the period ``offset`` periods from the current one
(0 = current, -1 = the previous week/month/year). Weeks run Mon→Sun."""
from datetime import timedelta
today = today or date.today()
if gran == "week":
monday = today - timedelta(days=today.weekday()) # Monday of this week
start = monday + timedelta(weeks=offset)
return start, start + timedelta(days=7)
if gran == "year":
y = today.year + offset
return date(y, 1, 1), date(y + 1, 1, 1)
# month (default)
base = today.year * 12 + (today.month - 1) + offset
y, m = divmod(base, 12)
y2, m2 = divmod(base + 1, 12)
return date(y, m + 1, 1), date(y2, m2 + 1, 1)
def _period_label(gran: str, start: date) -> str:
if gran == "week":
return start.isoformat() # the week's Monday (YYYY-MM-DD)
if gran == "year":
return str(start.year)
return start.strftime("%Y-%m")
def _sum_between(events: List[Dict[str, Any]], start: date, end: date,
pricing: Dict[str, Any]) -> tuple:
lo, hi = start.isoformat(), end.isoformat()
evs = [e for e in events if lo <= str(e.get("ts", ""))[:10] < hi]
tokens = sum(int(e.get("in", 0) or 0) + int(e.get("out", 0) or 0)
+ int(e.get("cache", 0) or 0) for e in evs)
cost = sum(cost_usd_events(evs, pricing).values()) if evs else 0.0
return tokens, cost
def period_totals(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
offset: int = 0, today: Optional[date] = None) -> tuple:
"""(tokens, cost_usd) for the single period ``offset`` periods from now."""
start, end = period_bounds(gran, offset, today)
return _sum_between(events, start, end, pricing)
def period_window(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
count: int, offset: int = 0, today: Optional[date] = None) -> List[tuple]:
"""``count`` consecutive, ZERO-FILLED periods ending at (current + offset),
ordered oldest→newest → ``[(label, tokens, cost_usd)]``. ``offset`` (≤ 0)
pages the window into the past for the Dashboard's prev/next navigation."""
out = []
for i in range(count - 1, -1, -1):
start, end = period_bounds(gran, offset - i, today)
tok, cost = _sum_between(events, start, end, pricing)
out.append((_period_label(gran, start), tok, cost))
return out
def period_breakdown(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
offset: int = 0, today: Optional[date] = None) -> List[tuple]:
"""Break the SELECTED period (``offset`` periods from now) into its sub-parts
→ ``[(label, tokens, cost_usd)]``:
· week → 7 days Mon→Sun (label ``MM/DD``)
· month → weeks W1…Wn (7-day chunks from the 1st)
· year → 12 months (label ``01``…``12``)."""
from datetime import timedelta
start, end = period_bounds(gran, offset, today)
out = []
if gran == "week":
for i in range(7):
d = start + timedelta(days=i)
tok, cost = _sum_between(events, d, d + timedelta(days=1), pricing)
out.append((d.strftime("%m/%d"), tok, cost))
elif gran == "year":
for m in range(1, 13):
ms = date(start.year, m, 1)
me = date(start.year + 1, 1, 1) if m == 12 else date(start.year, m + 1, 1)
tok, cost = _sum_between(events, ms, me, pricing)
out.append((f"{m:02d}", tok, cost))
else: # month → weeks W1..Wn
ndays = (end - start).days
wk, day = 1, 1
while day <= ndays:
ws = date(start.year, start.month, day)
we = date(start.year, start.month, day + 7) if day + 7 <= ndays else end
tok, cost = _sum_between(events, ws, we, pricing)
out.append((f"W{wk}", tok, cost))
wk += 1
day += 7
return out
def period_range_label(gran: str, offset: int, today: Optional[date] = None) -> str:
"""Human label for the selected period (shown in the Dashboard header) —
week → MM/DD – MM/DD, month → YYYY/MM, year → YYYY."""
from datetime import timedelta
start, end = period_bounds(gran, offset, today)
if gran == "week":
last_day = end - timedelta(days=1)
return f"{start.strftime('%m/%d')} – {last_day.strftime('%m/%d')}"
if gran == "year":
return str(start.year)
return start.strftime("%Y/%m")
+12 -241
View File
@@ -12,6 +12,17 @@ The turn's source/label is set by the caller ON THE WORKER THREAD via
"""
from __future__ import annotations
# Giữ đường vào cũ: nhiều nơi import mấy tên này thẳng từ usage_tracker.
from .usage_ai_report import build_ai_analysis_prompt # noqa: F401
from .usage_cost import ( # noqa: F401
DEFAULT_PRICING, SUPPORTED_CURRENCIES, cost_usd, cost_usd_events,
format_cost, format_cost_compact,
)
from .usage_periods import ( # noqa: F401
bucketed_series, period_bounds, period_breakdown, period_range_label,
period_totals, period_window,
)
import json
import threading
from datetime import date, datetime
@@ -19,6 +30,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional
from ..config import CONFIG_DIR
from . import model_pricing as mp
USAGE_DIR = CONFIG_DIR / "usage"
@@ -203,198 +215,30 @@ def summarize(events: List[Dict[str, Any]]) -> Dict[str, Any]:
# ---- cost ------------------------------------------------------------------
DEFAULT_PRICING = {
"price_per_mtok_in_usd": 0.5, # USD per 1M input tokens (flat fallback rate)
"price_per_mtok_out_usd": 1.5, # USD per 1M output tokens
"price_per_mtok_cache_usd": 0.1, # USD per 1M cached tokens
"currency": "USD", # display currency: USD | VND | JPY
"usd_to_vnd": 25000.0,
"usd_to_jpy": 150.0,
# Per-model price table (USD / 1M tokens): {model: {"in","out","cache"}}.
# Events whose model has an entry are costed with ITS rates; everything
# else falls back to the flat price_per_mtok_* rates above. Edited in the
# Monitoring Overview's pricing table.
"model_prices": {},
# Reference URL of the price list the table was filled from (set in
# Settings; shown as a link beside the table — informational only, the
# app never scrapes it).
"pricing_url": "",
}
_CURRENCY_FMT = {"USD": ("$", 4), "VND": ("₫", 0), "JPY": ("¥", 1)}
# Currencies the display picker offers — exactly the ones format_cost() can
# actually convert to (symbol/precision above + a usd_to_* rate below).
SUPPORTED_CURRENCIES = tuple(_CURRENCY_FMT)
def cost_usd(summary: Dict[str, Any], pricing: Dict[str, Any]) -> Dict[str, float]:
p = {**DEFAULT_PRICING, **(pricing or {})}
return {
"in": summary.get("in", 0) / 1e6 * float(p["price_per_mtok_in_usd"]),
"out": summary.get("out", 0) / 1e6 * float(p["price_per_mtok_out_usd"]),
"cache": summary.get("cache", 0) / 1e6 * float(p["price_per_mtok_cache_usd"]),
}
def cost_usd_events(events: List[Dict[str, Any]], pricing: Dict[str, Any]) -> Dict[str, float]:
"""Per-bucket USD cost computed EVENT BY EVENT so the per-model price
table applies: an event whose ``model`` has an entry in
``pricing["model_prices"]`` is costed with that model's own rates; any
other event uses the flat ``price_per_mtok_*`` rates. With an empty
table this equals ``cost_usd(summarize(events), pricing)`` exactly."""
p = {**DEFAULT_PRICING, **(pricing or {})}
table = p.get("model_prices") or {}
flat = {"in": float(p["price_per_mtok_in_usd"]),
"out": float(p["price_per_mtok_out_usd"]),
"cache": float(p["price_per_mtok_cache_usd"])}
out = {"in": 0.0, "out": 0.0, "cache": 0.0}
for e in events:
rates = table.get(e.get("model", "")) or {}
for bucket in ("in", "out", "cache"):
try:
rate = float(rates.get(bucket, flat[bucket]))
except (TypeError, ValueError):
rate = flat[bucket]
out[bucket] += e.get(bucket, 0) / 1e6 * rate
return out
def bucketed_series(events: List[Dict[str, Any]], granularity: str = "day",
pricing: Dict[str, Any] = None, last: int = None) -> List[tuple]:
"""Group usage events into time buckets → ordered ``[(label, tokens, cost_usd)]``.
``granularity``: ``day`` (YYYY-MM-DD) · ``month`` (YYYY-MM) · ``year`` (YYYY).
``last`` keeps only the most recent N buckets (for the dashboard chart)."""
from collections import OrderedDict
pricing = pricing or {}
def _key(ts: Any) -> str:
s = str(ts or "")[:10]
if granularity == "year":
return s[:4]
if granularity == "month":
return s[:7]
return s
buckets: "OrderedDict[str, List[Dict[str, Any]]]" = OrderedDict()
for e in sorted(events, key=lambda ev: str(ev.get("ts", ""))):
k = _key(e.get("ts"))
if k:
buckets.setdefault(k, []).append(e)
out = []
for k, evs in buckets.items():
tokens = sum(int(e.get("in", 0) or 0) + int(e.get("out", 0) or 0)
+ int(e.get("cache", 0) or 0) for e in evs)
cost = sum(cost_usd_events(evs, pricing).values())
out.append((k, tokens, cost))
if last and len(out) > last:
out = out[-last:]
return out
def period_bounds(gran: str, offset: int, today: Optional[date] = None) -> tuple:
"""[start, end) dates of the period ``offset`` periods from the current one
(0 = current, -1 = the previous week/month/year). Weeks run Mon→Sun."""
from datetime import timedelta
today = today or date.today()
if gran == "week":
monday = today - timedelta(days=today.weekday()) # Monday of this week
start = monday + timedelta(weeks=offset)
return start, start + timedelta(days=7)
if gran == "year":
y = today.year + offset
return date(y, 1, 1), date(y + 1, 1, 1)
# month (default)
base = today.year * 12 + (today.month - 1) + offset
y, m = divmod(base, 12)
y2, m2 = divmod(base + 1, 12)
return date(y, m + 1, 1), date(y2, m2 + 1, 1)
def _period_label(gran: str, start: date) -> str:
if gran == "week":
return start.isoformat() # the week's Monday (YYYY-MM-DD)
if gran == "year":
return str(start.year)
return start.strftime("%Y-%m")
def _sum_between(events: List[Dict[str, Any]], start: date, end: date,
pricing: Dict[str, Any]) -> tuple:
lo, hi = start.isoformat(), end.isoformat()
evs = [e for e in events if lo <= str(e.get("ts", ""))[:10] < hi]
tokens = sum(int(e.get("in", 0) or 0) + int(e.get("out", 0) or 0)
+ int(e.get("cache", 0) or 0) for e in evs)
cost = sum(cost_usd_events(evs, pricing).values()) if evs else 0.0
return tokens, cost
def period_totals(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
offset: int = 0, today: Optional[date] = None) -> tuple:
"""(tokens, cost_usd) for the single period ``offset`` periods from now."""
start, end = period_bounds(gran, offset, today)
return _sum_between(events, start, end, pricing)
def period_window(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
count: int, offset: int = 0, today: Optional[date] = None) -> List[tuple]:
"""``count`` consecutive, ZERO-FILLED periods ending at (current + offset),
ordered oldest→newest → ``[(label, tokens, cost_usd)]``. ``offset`` (≤ 0)
pages the window into the past for the Dashboard's prev/next navigation."""
out = []
for i in range(count - 1, -1, -1):
start, end = period_bounds(gran, offset - i, today)
tok, cost = _sum_between(events, start, end, pricing)
out.append((_period_label(gran, start), tok, cost))
return out
def period_breakdown(events: List[Dict[str, Any]], gran: str, pricing: Dict[str, Any],
offset: int = 0, today: Optional[date] = None) -> List[tuple]:
"""Break the SELECTED period (``offset`` periods from now) into its sub-parts
→ ``[(label, tokens, cost_usd)]``:
· week → 7 days Mon→Sun (label ``MM/DD``)
· month → weeks W1…Wn (7-day chunks from the 1st)
· year → 12 months (label ``01``…``12``)."""
from datetime import timedelta
start, end = period_bounds(gran, offset, today)
out = []
if gran == "week":
for i in range(7):
d = start + timedelta(days=i)
tok, cost = _sum_between(events, d, d + timedelta(days=1), pricing)
out.append((d.strftime("%m/%d"), tok, cost))
elif gran == "year":
for m in range(1, 13):
ms = date(start.year, m, 1)
me = date(start.year + 1, 1, 1) if m == 12 else date(start.year, m + 1, 1)
tok, cost = _sum_between(events, ms, me, pricing)
out.append((f"{m:02d}", tok, cost))
else: # month → weeks W1..Wn
ndays = (end - start).days
wk, day = 1, 1
while day <= ndays:
ws = date(start.year, start.month, day)
we = date(start.year, start.month, day + 7) if day + 7 <= ndays else end
tok, cost = _sum_between(events, ws, we, pricing)
out.append((f"W{wk}", tok, cost))
wk += 1
day += 7
return out
def period_range_label(gran: str, offset: int, today: Optional[date] = None) -> str:
"""Human label for the selected period (shown in the Dashboard header) —
week → MM/DD – MM/DD, month → YYYY/MM, year → YYYY."""
from datetime import timedelta
start, end = period_bounds(gran, offset, today)
if gran == "week":
last_day = end - timedelta(days=1)
return f"{start.strftime('%m/%d')} – {last_day.strftime('%m/%d')}"
if gran == "year":
return str(start.year)
return start.strftime("%Y/%m")
def set_budget(config, amount: float, currency: Optional[str] = None) -> None:
@@ -409,7 +253,6 @@ def set_budget(config, amount: float, currency: Optional[str] = None) -> None:
order and ``budget_set_at`` only has 1-second resolution, so a timestamp
cutoff could mis-include/exclude an event recorded in that same second —
the count baseline is exact regardless of timing."""
from . import model_pricing as mp
usage = config.data.setdefault("usage", {})
ccy = (currency or usage.get("currency") or "USD").upper()
usage["budget_amount_usd"] = mp.convert(float(amount or 0), ccy, "USD", config)
@@ -454,83 +297,11 @@ def budget_status(config) -> Optional[Dict[str, Any]]:
}
def format_cost(usd: float, pricing: Dict[str, Any], digits: Optional[int] = None) -> str:
"""Format a USD amount in the display currency. ``digits`` caps the number
of decimal places (e.g. ``digits=2`` for the Total cost / Budget cards, so
USD shows $1.23 not the default up-to-4 $1.2345) — never ADDS decimals to a
currency that uses fewer (VND stays whole, JPY one place)."""
p = {**DEFAULT_PRICING, **(pricing or {})}
cur = p.get("currency", "USD")
rate = {"USD": 1.0, "VND": float(p["usd_to_vnd"]), "JPY": float(p["usd_to_jpy"])}.get(cur, 1.0)
symbol, cur_digits = _CURRENCY_FMT.get(cur, ("$", 2))
if digits is not None:
cur_digits = min(cur_digits, digits)
value = usd * rate
return f"{symbol}{value:,.{cur_digits}f}"
def format_cost_compact(usd: float, pricing: Dict[str, Any]) -> str:
"""Compact cost format for the Dashboard chart's y-axis/endpoint labels —
always 2 decimals (not format_cost's up-to-4 for USD) and abbreviated with
K/M above 1,000/1,000,000, same convention as ``fmt_tokens``. The chart's
y-axis label box is narrow; the longer full-precision string used to
overflow it, visually clipping/obscuring the leading currency symbol."""
p = {**DEFAULT_PRICING, **(pricing or {})}
cur = p.get("currency", "USD")
rate = {"USD": 1.0, "VND": float(p["usd_to_vnd"]), "JPY": float(p["usd_to_jpy"])}.get(cur, 1.0)
symbol, _digits = _CURRENCY_FMT.get(cur, ("$", 2))
value = usd * rate
sign = "-" if value < 0 else ""
value = abs(value)
if value >= 1_000_000:
body = f"{value / 1_000_000:,.2f}M"
elif value >= 1_000:
body = f"{value / 1_000:,.2f}K"
else:
body = f"{value:,.2f}"
return f"{sign}{symbol}{body}"
_AI_ANALYSIS_HEADERS = {
"vi": ("Nhận xét thói quen", "Cách viết prompt tiết kiệm hơn", "Hành động giảm token"),
"en": ("Usage habits", "Writing more efficient prompts", "Actions to cut token usage"),
"ja": ("利用傾向", "より効率的なプロンプトの書き方", "トークン削減のためのアクション"),
}
def build_ai_analysis_prompt(summary: Dict[str, Any], language: str = "vi") -> str:
"""The prompt sent to the model for '✨ AI analyze my usage': aggregated
numbers only — never raw prompt contents — asking for concrete habits
feedback and token-saving recommendations, in the CURRENTLY SELECTED
display language (headers included — not just the model's free-text reply,
which would otherwise leave the section titles in Vietnamese regardless of
the app's language setting)."""
lang_names = {"vi": "Vietnamese", "ja": "Japanese", "en": "English"}
h1, h2, h3 = _AI_ANALYSIS_HEADERS.get(language, _AI_ANALYSIS_HEADERS["vi"])
top = "\n".join(f"- {label}: {tok:,} tokens"
for label, tok in summary.get("top_labels", []))
by_source = ", ".join(f"{k}={v:,}" for k, v in summary.get("by_source", []))
return (
"You are a token-efficiency coach for an AI desktop app (chat tabs + "
"scheduled agent tasks). Analyze this usage summary and give the user "
"practical advice, replying in "
f"{lang_names.get(language, 'Vietnamese')}.\n\n"
f"Period stats: {summary.get('turns', 0)} turns, "
f"input={summary.get('in', 0):,} tokens, output={summary.get('out', 0):,}, "
f"cache={summary.get('cache', 0):,}, "
f"avg per prompt={summary.get('avg_per_turn', 0):,}.\n"
f"Top consumers:\n{top or '- (none)'}\n"
f"By area: {by_source or '(none)'}\n"
f"Busiest day: {summary.get('busiest_day')} · busiest hour: {summary.get('busiest_hour')}\n\n"
"Reply with EXACTLY these 3 short sections, in markdown, using THESE "
f"section headers verbatim (already in {lang_names.get(language, 'Vietnamese')}):\n"
f"1. **{h1}** — 2-3 bullet points about the usage pattern.\n"
f"2. **{h2}** — 3 concrete prompt-writing tips "
"tailored to the numbers above (e.g. long inputs → attach less / summarize "
"first; many small turns → batch questions).\n"
f"3. **{h3}** — 2-3 app-level actions (compact history, "
"smaller model for simple tasks, reuse task outputs instead of re-asking).\n"
"Keep the whole reply under 250 words."
)
@@ -0,0 +1,101 @@
# Báo cáo hoàn tất — extract:co4e_canvas_widget (lane N3 — Co4E Studio)
- **Ngày:** 2026-08-25
- **Người:** hiephv3@fpt.com (N3)
- **Nhánh:** `gamma/refactor`
- **Lệnh đo dùng xuyên suốt:** `.venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors`
---
## 1. Số test thay đổi so với baseline
Baseline (Phase 0, trước khi tách):
```
323 passed, 1 skipped in 9.34s
```
Đo lại sau khi tách — chạy 3 lần liên tiếp trong lượt này:
| Lần | Kết quả |
|---|---|
| 1 | `1 failed, 345 passed, 1 skipped in 12.25s` — `FAILED tests/test_no_ignored_source.py::test_khong_file_py_nao_bi_bo_quen_chua_theo_doi` |
| 2 | `346 passed, 1 skipped in 13.31s` |
| 3 | `346 passed, 1 skipped in 12.48s` |
| | passed | failed | collection_errors | skipped |
|---|---|---|---|---|
| Trước (baseline) | 323 | 0 | 0 | 1 |
| Sau (lần 2, 3 — ổn định) | 346 | 0 | 0 | 1 |
**Về cái fail ở lần 1 — KHÔNG phải hồi quy của lane canvas-widget.** Tại đúng thời điểm chạy lần 1, `git status --porcelain` cho thấy `tests/characterization/test_co4e_runs_page.py` và `presentation/co4e/co4e_run_control_widget.py` đang ở trạng thái untracked (`??`) — đây là sản phẩm của một phiên Claude khác (lane run-control) đang làm việc song song trên cùng thư mục và chưa kịp `git add`. `test_no_ignored_source` kiểm tra "mọi file `.py` phải đã được git add trong clone sạch", nên nó bắt trúng khoảnh khắc file kia chưa staged — đây chính là kiểu hiện tượng "nhiều phiên Claude song song" mà tài liệu hướng dẫn có cảnh báo. Kiểm tra lại `git status` ngay sau đó xác nhận hai file này đã chuyển sang trạng thái `A` (đã add), và lần đo 2, 3 chạy lại đều xanh ổn định (346 passed, 0 failed cả hai lần) — không phải flaky do code của lane này, không phải do `test_atomic_json` (test flaky đã biết) xuất hiện lần nào trong 3 lần chạy.
Kết luận: `passed` tăng 323 → 346 (+23, đến từ bộ test đặc tả mới `test_co4e_canvas_widget.py` của lane này cộng với các lane khác đang chạy song song trên cùng nhánh). Không có test fail mới thuộc phạm vi lane canvas-widget. `collection_errors` = 0 ở cả hai mốc. `skipped` giữ nguyên 1 (mốc cũ có giải thích trong docstring, không phải nợ phát sinh từ lane này).
---
## 2. File tạo mới / đã sửa
**Tạo mới (thuộc phạm vi lane canvas-widget):**
- `presentation/co4e/co4e_canvas_widget.py`
- `presentation/co4e/canvas_items.py`
- `presentation/co4e/canvas_interaction_mixin.py`
- `tests/characterization/test_co4e_canvas_widget.py`
- `docs/architecture/co4e-split-map-canvas-widget.md`
- `docs/architecture/co4e-split-map-canvas-widget.json`
- `docs/architecture/co4e-refactor-run-report-canvas-widget.md` (chính file này)
**Đã sửa:**
- `ui/co4e_canvas.py` — giữ lại làm shim tương thích ngược, xem mục 5.
**Không thuộc lane này** (xuất hiện trong `git status --porcelain` chung của repo, do các lane khác — node-property, run-control, v.v. — đang chạy song song, liệt kê để tránh nhận vơ): `application/workflows/co4e_workflow_service.py`, `domain/workflows/run_record.py`, `presentation/co4e/agent_list_panel.py`, `presentation/co4e/canvas_geometry.py`, `presentation/co4e/co4e_tab.py`, `presentation/co4e/node_property_panel.py`, `presentation/co4e/node_property_actions_mixin.py`, `presentation/co4e/skills_list_panel.py`, `presentation/co4e/step_config_section.py`, `presentation/co4e/co4e_run_control_widget.py`, `ui/co4e_tab.py`, `ui/co4e_config_panel.py`, `tests/characterization/test_co4e_agent_panel.py`, `tests/characterization/test_co4e_run_manager_behavior.py`, `tests/characterization/test_co4e_skills_panel.py`, `tests/characterization/test_node_property_panel.py`, `tests/characterization/test_co4e_runs_page.py`, `tests/fakes/fake_co4e_workflow_service.py`, `tests/test_build_co4e_tab.py`, `tests/test_co4e_workflow_service.py`, `docs/architecture/co4e-split-map.md`, `docs/architecture/co4e-split-map.json`, `docs/architecture/co4e-split-map-node-property.md`, `docs/architecture/co4e-split-map-node-property.json`, `docs/architecture/co4e-split-map-run-control.md`, `docs/architecture/co4e-split-map-run-control.json`, `docs/architecture/co4e-refactor-run-report.md`, `docs/architecture/co4e-refactor-run-report-node-property.md`.
---
## 3. Kết quả cổng ranh giới
**ĐỎ (FAIL)** — theo kết quả Phase 5 đã chạy (`clean: false`). Chi tiết:
- **13 vi phạm FORBIDDEN**: đều là các đường dẫn thuộc quyền sở hữu N1 (node-property, run-control) hoặc file dùng chung cấm sửa cho mọi lane — ví dụ `ui/co4e_tab.py`, `ui/co4e_config_panel.py`, `presentation/co4e/node_property_panel.py`, `node_property_actions_mixin.py`, `step_config_section.py`, `docs/architecture/co4e-split-map-node-property.*`, `co4e-refactor-run-report-node-property.md`, `co4e-split-map.md/json`, `co4e-refactor-run-report.md`, `co4e-split-map-run-control.*`. **Không cái nào trong số này do lane canvas-widget đụng tới trong lượt làm việc này.**
- **14 vi phạm OUT-OF-WHITELIST**: `application/workflows/co4e_workflow_service.py`, `domain/workflows/run_record.py`, `presentation/co4e/agent_list_panel.py`, `presentation/co4e/canvas_geometry.py`, `presentation/co4e/co4e_tab.py`, `presentation/co4e/skills_list_panel.py`, `tests/characterization/test_co4e_agent_panel.py`, `tests/characterization/test_co4e_canvas_geometry.py`, `tests/characterization/test_co4e_run_manager_behavior.py`, `tests/characterization/test_co4e_skills_panel.py`, `tests/characterization/test_node_property_panel.py`, `tests/fakes/fake_co4e_workflow_service.py`, `tests/test_build_co4e_tab.py`, `tests/test_co4e_workflow_service.py`, và mới phát sinh `tests/characterization/test_co4e_runs_page.py`. **Cũng không phải sản phẩm của lane canvas-widget** — đây là artefact của các lane khác đang chạy song song, cùng nằm trong `git status` chung của repo vì cổng chặn quét trạng thái toàn repo chứ không tách theo phiên.
Đối chiếu với whitelist được cấp cho chính lane này (`tests/characterization/test_co4e_canvas_widget.py`, `presentation/co4e/co4e_canvas_widget.py`, `presentation/co4e/canvas_items.py`, `presentation/co4e/canvas_interaction_mixin.py`, `ui/co4e_canvas.py`, `docs/architecture/co4e-split-map-canvas-widget.md/json`): **không có mục nào trong 7 file này xuất hiện trong danh sách vi phạm** — cổng đỏ hoàn toàn do trạng thái git dùng chung của các lane khác chưa dọn/commit, không phải do vi phạm ranh giới của lane canvas-widget.
---
## 4. Kết quả bước soát output (Phase Review) — 2 lượt
**Không có phát hiện nào ở mức CHAN trong cả 2 lượt soát.** Cả hai đều verdict `DAT` (đạt), `repaired: false` (không cần sửa lại trong lúc soát).
### Lượt 1 — subject: `tests/characterization/test_co4e_canvas_widget.py` (verdict: DAT)
- Mức CHAN: không có.
- Mức SUA: không có.
- Mức GHI_NHAN (4):
1. `test_relayout_on_empty_canvas_is_a_safe_noop` (dòng 723-724): assert dựa trên giá trị hardcode `True` ngay sau khi gọi `relayout()` — chỉ là phép thử "không ném exception", không khoá được giá trị/hành vi cụ thể nào của `relayout()` trên canvas rỗng. Không phải lỗi, nhưng không phải lưới an toàn thật cho trường hợp này.
2. Comment tại `test_zoom_in_clamps_at_max_after_7_steps_from_1_0` (dòng 686-696) lệch một đơn vị so với tính toán độc lập (chạm 3.0 ở lần áp dụng thứ 8, không phải thứ 7 như comment nói) — nhưng giá trị assert (mảng 20 phần tử) vẫn đúng 100% với hành vi thật, chỉ comment giải thích bị lệch.
3. `ui/co4e_canvas.py` có 2 "equivalent mutant" phát hiện qua mutation-test: xoá điều kiện `src != target_id` trong `_finish_connect` và xoá guard `if source == target: return` trong `_make_edge` đều không làm test đỏ, vì các điểm gọi `_make_edge` đã tự lọc `source != target` từ trước — hai lớp bảo vệ trùng nhau. Không phải lỗi hành vi hiện tại, nhưng là điểm cần lưu ý cho người tách sau: nếu một lớp bảo vệ mất đi trong tương lai mà không có lớp kia, quirk "tự nối vào mình" sẽ mất hiệu lực mà test này không bắt được tại đúng điểm đó.
4. Ghi nhận về git status: 2 file `docs/architecture/co4e-split-map-run-control.md/json` xuất hiện thêm giữa lúc soát — xác nhận là sản phẩm của một agent khác chạy song song (cùng mtime), không phải do lượt soát này gây ra; `ui/co4e_canvas.py` không đổi trạng thái và pytest 43/43 vẫn xanh sau khi khôi phục mutation.
### Lượt 2 — subject: `presentation/co4e/co4e_canvas_widget.py` (verdict: DAT)
- Mức CHAN: không có.
- Mức SUA (1): `co4e_canvas_widget.py` dòng 75-89 (`Co4ECanvas.load`) — điểm chuyển từ domain (list Node/Edge) sang item hiển thị thiếu comment giải thích quirk "edge có source/target không nằm trong `self._nodes` bị âm thầm bỏ qua". Quirk có thật, kế thừa nguyên văn từ `ui/co4e_canvas.py` gốc (không phải lỗi mới do lần tách này gây ra — đã đối chứng bằng `git show HEAD`), nhưng theo yêu cầu B4 (bắt buộc có comment tại các điểm chuyển tầng DTO), cần bổ sung comment trong lượt sửa tiếp theo.
- Mức GHI_NHAN (4):
1. Hai khối comment mâu thuẫn nhau trong `canvas_items.py` dòng 128-133 (`_NodeItem.paint`) về vị trí cổng (một khối nói "top-center/bottom-center", khối liền sau nói "left-center/right-center" — code thực tế vẽ left-center/right-center). Lỗi tồn tại sẵn trong bản gốc, được dời nguyên văn đúng kỷ luật B1 "không đổi", không phải lỗi mới. Cần dọn ở lượt sau.
2. Docstring của 3 file (`co4e_canvas_widget.py`, `canvas_items.py`, `canvas_interaction_mixin.py`) dẫn số dòng cụ thể của `ui/co4e_canvas.py` (ví dụ "289-317", "701 dòng tổng") không khớp với `ui/co4e_canvas.py` tại git HEAD hiện tại (791 dòng, class `Co4ECanvas` bắt đầu ở dòng 379, không phải 289). Nội dung code đã được xác minh khớp 100% bằng AST diff độc lập — đây là vấn đề chất lượng tài liệu (số dòng tham chiếu một trạng thái trung gian chưa commit), không phải lỗi hành vi.
3. Suite tổng đỏ 1 test (`test_no_ignored_source`) tại thời điểm soát, do file `tests/characterization/test_co4e_runs_page.py` (thuộc nhánh tách khác) chưa được `git add` — không liên quan 3 file thuộc phạm vi soát này, đã tự hết khi lane kia add file (khớp với mục 1 của báo cáo này).
4. `docs/architecture/co4e-refactor-run-report-canvas-widget.md` chưa được tạo tại thời điểm soát — ghi nhận thiếu deliverable, không chặn. (Báo cáo này chính là file được yêu cầu tạo, viết trong lượt hiện tại.)
---
## 5. Việc để lại cho lần sau
- **`ui/co4e_canvas.py` vẫn còn chạy song song** với `presentation/co4e/co4e_canvas_widget.py` — hiện đóng vai trò shim/re-export để các chỗ import cũ (`from .co4e_canvas import Co4ECanvas, CO4E_MIME`) không vỡ. Cần dọn các nơi còn import theo đường cũ, chuyển sang import trực tiếp từ `presentation/co4e/co4e_canvas_widget.py`, rồi mới an toàn để rút gọn/xoá shim.
- **1 điểm SUA từ lượt soát 2 chưa được sửa**: bổ sung comment giải thích quirk bỏ-qua-edge-mồ-côi tại `presentation/co4e/co4e_canvas_widget.py` (hàm `load`, dòng 75-89) theo đúng yêu cầu B4.
- **2 GHI_NHAN không chặn nhưng nên dọn cùng đợt sau**: (a) comment mâu thuẫn vị trí cổng trong `canvas_items.py` dòng 128-133 (kế thừa từ bản gốc); (b) số dòng tham chiếu trong docstring của 3 file mới không khớp trạng thái HEAD hiện tại — cần cập nhật lại số dòng khi file được commit để người đọc sau đối chiếu lại được.
- `docs/architecture/co4e-split-map-canvas-widget.md/json` là input cho bước dọn shim `ui/co4e_canvas.py` ở lượt tiếp theo.
- Cổng ranh giới hiện đang đỏ do trạng thái git dùng chung của nhiều lane chưa commit/dọn — cần các lane liên quan (node-property, run-control, v.v.) tự commit hoặc dọn phần của mình để cổng có thể xanh trở lại cho toàn repo; lane canvas-widget không có vi phạm nào trong whitelist của chính nó (xem mục 3).
## 6. Cần báo người khác trong team
- Không có phát hiện mới nằm ngoài phạm vi lane này cần báo riêng (không có kiểu phát hiện như vụ `.gitignore` nuốt `infrastructure/secrets/` trước đây).
- Đáng lưu ý (không cần hành động thêm, chỉ để các lane khác biết): trong lúc đo baseline lần 1 của lượt này, `test_no_ignored_source` đỏ thoáng qua vì lane run-control (`tests/characterization/test_co4e_runs_page.py`, `presentation/co4e/co4e_run_control_widget.py`) chưa kịp `git add` hai file mới của họ. Tự hết ở lần đo thứ 2 sau khi họ add xong. Gợi ý: các lane nên `git add` sớm sau khi tạo file mới để tránh gate/test đỏ giả khi nhiều phiên Claude chạy song song trên cùng thư mục.
@@ -0,0 +1,156 @@
# Báo cáo refactor — Chat view / Composer (widget cuối) — làn N3 Co4E Studio
- **Ngày:** 2026-08-25
- **Người:** Lâm (hiephv3@fpt.com)
- **Nhánh:** `gamma/refactor`
- **Phạm vi:** trích xuất `_ChatInput`, `_skill_names`, `_agent_names`, `_directive_token`
và phần dựng UI của `ChatPanel` (từ `_build_chat` cũ) trong `ui/co4e_tab.py` sang
`presentation/co4e/co4e_chat_view.py`.
---
## 1. Số test thay đổi thế nào so với baseline
Lệnh đo (chạy lại đúng lệnh baseline ngay trước khi viết báo cáo này):
```
.venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors
```
Kết quả vừa đo:
```
347 passed, 1 skipped in 8.10s
```
So với baseline được giao (Phase 0): `346 passed, 0 failed, 0 collection_errors, 1 skipped`.
| | Trước (Phase 0) | Sau (vừa đo lại) |
|---|---|---|
| passed | 346 | 347 |
| failed | 0 | 0 |
| collection_errors | 0 | 0 |
| skipped | 1 (giữ nguyên, lý do đã biết — thứ tự import `CONFIG_DIR` giữa các file test, không liên quan chat view) | 1 (cùng lý do) |
**+1 passed** đúng bằng đúng 1 test mới `tests/characterization/test_co4e_chat_view.py`
được thêm trong đợt này. Không có test fail mới, không có collection error mới →
**không hồi quy**.
- Lỗi MỐC CŨ có từ trước (nợ của làn khác): **không có** — 0 collection error, 0 failed
ở cả trước và sau.
- Flaky đã biết (`tests/test_atomic_json.py::test_ghi_de_nhieu_lan_van_dung`,
`PermissionError [WinError 5]` khi Windows giữ khoá file tạm): **không xuất hiện**
trong lần đo cuối cùng này (347 passed, 0 failed). Trong lượt soát trước đó nó có
xuất hiện đúng 1 lần trên 2 lần chạy (`1 failed, 346 passed, 1 skipped`), rồi lần
chạy kế tiếp lại xanh (`347 passed, 1 skipped`) — đúng đặc điểm flaky đã biết, không
quy cho đợt trích xuất này.
## 2. File đã tạo, file đã sửa
Theo `git status --porcelain` (đối chiếu với whitelist được cấp cho lượt chat-view):
**Tạo mới (thuộc lượt này):**
- `presentation/co4e/co4e_chat_view.py` — file production mới (258 dòng, ≤ 400 dòng,
chỉ import PySide6.QtCore/QtWidgets, không đụng domain/application).
- `tests/characterization/test_co4e_chat_view.py` — test đặc trưng hoá hành vi cũ.
- `docs/architecture/co4e-split-map-chat-view.md`
- `docs/architecture/co4e-split-map-chat-view.json`
- `docs/architecture/co4e-refactor-run-report-chat-view.md` — chính file báo cáo này
(trước lượt này file chưa tồn tại — đây là khoảng thiếu mà bước soát đã ghi nhận,
nay bù lại).
**Sửa (thuộc lượt này):**
- `ui/co4e_tab.py` — dây lại để dùng `ChatPanel`/`_ChatInput` từ module mới thay vì
định nghĩa tại chỗ.
**Các mục khác trong `git status` (canvas widget, node property, run control, agent
panel, run manager, v.v.) không thuộc lượt chat-view** — đó là dấu vết của các làn/
phiên khác đang chạy song song trên cùng thư mục làm việc (repo này có nhiều phiên
Claude chạy đồng thời). Không đụng, không sửa trong lượt này.
## 3. Cổng chặn (Phase 5)
**Kết quả: ĐỎ** (`"clean": false`).
Tuy nhiên toàn bộ vi phạm liệt kê **không thuộc phần lượt chat-view đã viết ra** — kiểm
tra riêng 5 đường dẫn thuộc whitelist của lượt này
(`presentation/co4e/co4e_chat_view.py`, `tests/characterization/test_co4e_chat_view.py`,
`docs/architecture/co4e-split-map-chat-view.md`, `.json`, `ui/co4e_tab.py`): **không có
đường dẫn nào trong 5 file này xuất hiện trong danh sách `violations`.**
Danh sách vi phạm thật (đỏ) đến từ file của các làn khác đang tồn tại chung trong working
tree (không do lượt chat-view tạo ra):
- `FORBIDDEN` (khớp `forbidden_paths` của N1): `presentation/co4e/canvas_interaction_mixin.py`,
`canvas_items.py`, `co4e_canvas_widget.py`, `co4e_run_control_widget.py`,
`node_property_actions_mixin.py`, `node_property_panel.py`, `step_config_section.py`,
`ui/co4e_canvas.py`, `ui/co4e_config_panel.py`, cùng các `docs/architecture/co4e-split-map*.md/json`
và `co4e-refactor-run-report*.md` khác của N1.
- `OUTSIDE_WHITELIST` (file mới không khớp `allowed_write_globs` của *lượt này*):
`application/workflows/co4e_workflow_service.py`, `domain/workflows/run_record.py`,
`presentation/co4e/agent_list_panel.py`, `canvas_geometry.py`,
`presentation/co4e/co4e_tab.py` (khác `ui/co4e_tab.py` được phép), `skills_list_panel.py`,
và các test/fakes tương ứng (`test_co4e_agent_panel.py`, `test_co4e_canvas_geometry.py`,
`test_co4e_canvas_widget.py`, `test_co4e_run_manager_behavior.py`, `test_co4e_runs_page.py`,
`test_co4e_skills_panel.py`, `test_node_property_panel.py`, `fake_co4e_workflow_service.py`,
`test_build_co4e_tab.py`, `test_co4e_workflow_service.py`).
Kết luận: cổng chặn báo đỏ ở mức **toàn working tree**, không phải đỏ do lượt
chat-view — vì cổng chặn quét nguyên `git status` chung, còn nhiều làn/phiên khác đang
ghi đè cùng thư mục. Phần việc riêng của lượt chat-view (5 đường dẫn whitelist) **sạch**.
## 4. Bước soát output — 2 lượt
Không có phát hiện ở mức **CHAN** (chặn) trong bất kỳ lượt soát nào — cả hai lượt đều
có `verdict: "DAT"` (đạt).
**Lượt 1 — soát `tests/characterization/test_co4e_chat_view.py`:** verdict **DAT**.
Một phát hiện mức `SUA`:
- Dòng 193: `assert ci._popup.width() == max(280, ci.width())` — assertion rỗng nghĩa
cho riêng claim "280" vì `ci.width()` mặc định (chưa show/setFixedWidth) là 640 trong
môi trường test, luôn thắng trong `max()` bất kể 280 đổi thành gì < 640. Xác nhận bằng
mutation thật (280→300 trong `ui/co4e_tab.py`): test vẫn xanh (`1 passed in 2.01s`).
23 case còn lại trong file đều bắt được mutation tương ứng (11/12 hành vi bị làm hỏng
→ test đỏ đúng như kỳ vọng).
**Lượt 2 — soát `presentation/co4e/co4e_chat_view.py`:** verdict **DAT**. Hai phát hiện
mức `SUA`, một mức `GHI_NHAN`:
- `SUA`: `docs/architecture/co4e-refactor-run-report-chat-view.md` (đúng file này) chưa
tồn tại tại thời điểm soát — thiếu deliverable bắt buộc của quy trình. **Đã bù lại
bằng chính báo cáo này.**
- `SUA`: docstring module (dòng 6-7, 15-18) trích sai số dòng gốc trong `ui/co4e_tab.py`
(lệch 3-35 dòng, ví dụ `_build_chat` ghi "1030-1093" nhưng thật là "1065-1128" theo
`git show HEAD`). Không ảnh hưởng hành vi — thân hàm đã được đối chiếu bằng
`ast.get_source_segment` + `difflib` và **IDENTICAL** 100% với bản gốc. Đây là lỗi
trích dẫn tài liệu, chưa sửa trong lượt viết báo cáo này (ngoài phạm vi được giao cho
lượt này — chỉ viết báo cáo, không sửa code sản xuất).
- `GHI_NHAN`: hai file `docs/architecture/co4e-refactor-run-report-node-property.md` và
`co4e-refactor-run-report-run-control.md` (thuộc `forbidden_paths` của lượt chat-view)
có thay đổi/tồn tại — nhưng nội dung xác nhận thuộc lane khác (node-property, run-control),
không phải do lượt chat-view đụng vào. Không quy lỗi cho lượt này.
Ngoài ra, bước soát đã tự chạy lại bộ test 2 lần độc lập để loại trừ flaky trước khi kết
luận: lần 1 gặp `1 failed` (đúng flaky `test_atomic_json` đã biết), lần 2 `347 passed,
1 skipped, 0 failed` — nhất quán với con số ở mục 1.
## 5. Việc để lại cho lần chạy sau / cần báo người khác
**Để lại cho lần sau (trong phạm vi lượt chat-view, chưa làm ở lượt viết báo cáo này):**
- Sửa docstring module trong `presentation/co4e/co4e_chat_view.py` (dòng 6-7, 15-18) để
khớp đúng số dòng thật trong `ui/co4e_tab.py` (HEAD): `_skill_names` 60-64,
`_agent_names` 67-70, `_directive_token` 121-133, `_ChatInput` 136-225, `_build_chat`
1065-1128 — hiện ghi sai (63-73, 124-228, 1030-1093).
- Làm chặt lại assertion popup-width-floor tại `tests/characterization/test_co4e_chat_view.py:193`
(claim "280" hiện không được khoá thật vì `ci.width()` mặc định 640 luôn thắng trong
`max()`) — cần set `ci` về chiều rộng nhỏ hơn 280 trước khi assert, hoặc mock riêng, để
test thực sự khoá hằng số 280.
- `ui/co4e_tab.py` vẫn còn nhiều phần khác chưa tách (không thuộc phạm vi widget
chat/composer) — các widget khác đã có báo cáo riêng của N1
(`canvas-widget`, `node-property`, `run-control`).
**Cần báo người khác trong team:** không có phát hiện mới nào ngoài phạm vi làn này cần
escalate ở lượt này. Ghi nhận (không phải lỗi mới, chỉ là quan sát): repo đang có nhiều
phiên Claude/nhiều làn chạy song song trên cùng một working tree, khiến cổng chặn của
lượt chat-view báo đỏ ở mức toàn cục do file của các làn khác — điều này không phải do
lượt chat-view gây ra và không cần hành động thêm từ N3, nhưng đội điều phối nên biết để
không hiểu nhầm là lượt này làm vỡ ranh giới của N1.
@@ -0,0 +1,226 @@
# Báo cáo chạy — tách `StepConfigPanel` khỏi `ui/co4e_config_panel.py`
- **Ngày:** 2026-08-24
- **Người:** hiephv3@fpt.com
- **Nhánh:** gamma/refactor
- **Làn:** N3 — Co4E Studio, phạm vi `node_property_panel`
Ghi chú: repo này có nhiều phiên Claude chạy song song trên cùng một thư mục
làm việc. Báo cáo dưới đây chỉ trả lời 5 câu bắt buộc, không lan sang phần đã
viết ở các lượt trước (chi tiết cắt-dán từng dòng xem
`docs/architecture/co4e-split-map-node-property.md`/`.json`).
## 1. Số test thay đổi thế nào so với baseline
Lệnh đo (baseline Phase 0, chạy trước khi làn này bắt đầu):
```
.venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors
279 passed, 1 skipped
```
Lệnh đo lại (chạy ngay bây giờ, sau khi làn này đã xong):
```
$ .venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors
330 passed, 1 skipped in 10.15s
```
| | passed | failed | collection_errors | skipped |
|---|---|---|---|---|
| Trước (Phase 0) | 279 | 0 | 0 | 1 |
| Sau (bây giờ) | 330 | 0 | 0 | 1 |
- **Không có test fail nào**, mới hay cũ. `passed` sau ≥ passed trước
(330 ≥ 279) → không hồi quy theo tiêu chí so lệch.
- Chênh lệch +51 **không** đến từ riêng làn này. Làn này chỉ thêm đúng 1 test
mới (`tests/characterization/test_node_property_panel.py`). +50 còn lại đến
từ các làn song song khác đã nhập vào cùng thư mục làm việc trong lúc làn
này chạy (`test_co4e_agent_panel.py`, `test_co4e_canvas_geometry.py`,
`test_co4e_canvas_widget.py`, `test_co4e_skills_panel.py`,
`test_build_co4e_tab.py`, `test_co4e_workflow_service.py`, ...) — thấy rõ
trong `git status --porcelain` ở câu 2, không phải việc của làn N3.
- **1 skip** là mốc cũ có từ trước, không phải do lượt này gây ra:
`tests/characterization/test_co4e_run_manager_behavior.py:140` — tự skip
vì `cowork_local.config` bị file test khác import với `HOME` thật trước nó
trong cùng phiên pytest (giới hạn đã biết, ghi rõ trong docstring đầu file
đó, không liên quan `StepConfigPanel`).
- Test flaky đã biết của repo
(`tests/test_atomic_json.py::test_ghi_de_nhieu_lan_van_dung`, do
`os.replace()` gặp khoá file tạm trên Windows) **không xuất hiện** trong
lần chạy này — không có gì để báo thêm về nó.
- Chưa cần chạy lại lần hai để xác nhận vì không có test nào đỏ ở cả hai lần
đo (Phase 0 và bây giờ) — không có ca nghi flaky cần phân xử.
## 2. File đã tạo, file đã sửa
`git status --porcelain` (nguyên văn, chạy ngay lúc viết báo cáo):
```
AM application/workflows/co4e_workflow_service.py
A docs/architecture/co4e-refactor-run-report-node-property.md
A docs/architecture/co4e-split-map-node-property.json
A docs/architecture/co4e-split-map-node-property.md
A domain/workflows/run_record.py
A presentation/co4e/agent_list_panel.py
A presentation/co4e/canvas_geometry.py
A presentation/co4e/co4e_tab.py
A presentation/co4e/node_property_actions_mixin.py
A presentation/co4e/node_property_panel.py
A presentation/co4e/skills_list_panel.py
A presentation/co4e/step_config_section.py
A tests/characterization/test_co4e_agent_panel.py
AM tests/characterization/test_co4e_canvas_geometry.py
A tests/characterization/test_co4e_canvas_widget.py
AM tests/characterization/test_co4e_run_manager_behavior.py
AM tests/characterization/test_co4e_skills_panel.py
A tests/characterization/test_node_property_panel.py
A tests/fakes/fake_co4e_workflow_service.py
A tests/test_build_co4e_tab.py
AM tests/test_co4e_workflow_service.py
M ui/co4e_canvas.py
M ui/co4e_config_panel.py
M ui/co4e_tab.py
?? .codegraph/
?? cowork_local
?? docs/architecture/co4e-refactor-run-report.md
?? docs/architecture/co4e-split-map.json
?? docs/architecture/co4e-split-map.md
?? run_app.bat
?? stop_running.ps1
```
**Của đúng làn N3 (`node_property_panel`) — khớp danh sách đường dẫn được
cấp quyền:**
- Mới: `presentation/co4e/node_property_panel.py` (293 dòng),
`presentation/co4e/node_property_actions_mixin.py` (202 dòng),
`presentation/co4e/step_config_section.py` (134 dòng),
`tests/characterization/test_node_property_panel.py`,
`docs/architecture/co4e-split-map-node-property.md`,
`docs/architecture/co4e-split-map-node-property.json`,
`docs/architecture/co4e-refactor-run-report-node-property.md` (chính file
này).
- Sửa: `ui/co4e_config_panel.py` (528 dòng → 14 dòng, chỉ còn re-export
`StepConfigPanel`).
- Cả 3 file production mới đều ≤ 400 dòng (293/202/134).
**Không thuộc làn N3 — xuất hiện trong `git status` vì có phiên khác đang
chạy song song trên cùng thư mục, làn này không đụng tới:**
`application/workflows/co4e_workflow_service.py`,
`domain/workflows/run_record.py`, `presentation/co4e/agent_list_panel.py`,
`presentation/co4e/canvas_geometry.py`, `presentation/co4e/co4e_tab.py`,
`presentation/co4e/skills_list_panel.py`,
`tests/characterization/test_co4e_agent_panel.py`,
`tests/characterization/test_co4e_canvas_geometry.py`,
`tests/characterization/test_co4e_canvas_widget.py`,
`tests/characterization/test_co4e_run_manager_behavior.py`,
`tests/characterization/test_co4e_skills_panel.py`,
`tests/fakes/fake_co4e_workflow_service.py`, `tests/test_build_co4e_tab.py`,
`tests/test_co4e_workflow_service.py`, `ui/co4e_canvas.py`,
`ui/co4e_tab.py`, cùng các file untracked
`docs/architecture/co4e-split-map.md`/`.json`,
`docs/architecture/co4e-refactor-run-report.md`, `.codegraph/`,
`cowork_local`, `run_app.bat`, `stop_running.ps1`.
## 3. Cổng ranh giới: xanh hay đỏ
**Đỏ** (`clean: false`), nhưng **không phải vì làn N3 tự ý sửa các file cấm**
— tất cả vi phạm đều là file thuộc phạm vi làn khác (N1) hoặc làn song song
khác đang có mặt trong cùng thư mục làm việc tại thời điểm chạy cổng chặn:
- **FORBIDDEN** (đúng danh sách cấm tuyệt đối của N3, thuộc làn N1):
`ui/co4e_tab.py` (M), `ui/co4e_canvas.py` (M),
`docs/architecture/co4e-split-map.md` (mới), `docs/architecture/co4e-split-map.json` (mới),
`docs/architecture/co4e-refactor-run-report.md` (mới).
- **OUTSIDE-WHITELIST** (không khớp `allowed_write_globs` của N3):
`application/workflows/co4e_workflow_service.py`,
`domain/workflows/run_record.py`,
`presentation/co4e/agent_list_panel.py`,
`presentation/co4e/canvas_geometry.py`, `presentation/co4e/co4e_tab.py`,
`presentation/co4e/skills_list_panel.py`,
`tests/characterization/test_co4e_agent_panel.py`,
`tests/characterization/test_co4e_canvas_geometry.py`,
`tests/characterization/test_co4e_canvas_widget.py`,
`tests/characterization/test_co4e_run_manager_behavior.py`,
`tests/characterization/test_co4e_skills_panel.py`,
`tests/fakes/fake_co4e_workflow_service.py`, `tests/test_build_co4e_tab.py`,
`tests/test_co4e_workflow_service.py`.
- `loc_over_cap`: rỗng — không file nào của làn N3 vượt 400 dòng.
- `pyside_leaks`: rỗng — không có import PySide6/PyQt trong
`domain/`/`application/` (kiểm bằng AST parse, không phải grep).
Kết luận: 8 file đúng phạm vi được cấp cho làn N3 (danh sách 400-file ở đầu
prompt) đều nằm gọn trong whitelist, không file nào của làn N3 chạm vào danh
sách cấm. Cổng đỏ là do **trạng thái chung của working tree** (nhiều làn ghi
song song), không phải hồi quy do thay đổi của làn này gây ra. Người quyết
định commit cần biết: nếu commit y nguyên `git status` hiện tại, sẽ commit
luôn cả các thay đổi của những làn khác (N1 và các làn Co4E khác) — cần
tách bằng `git add` đúng danh sách 8 file của N3 trước khi commit, không
`git add -A`.
## 4. Bước soát output — 2 lượt, tách riêng theo mức `CHAN`
**Không lượt soát nào phát hiện mức `CHAN`.** (Mức `CHAN` = test không bắt
được lỗi, hoặc code bị viết lại thay vì dời — không có trường hợp nào như
vậy trong cả 2 lượt.)
- **Lượt 1 — chủ thể `tests/characterization/test_node_property_panel.py`,
verdict: ĐẠT.**
1 phát hiện mức **SUA** (không phải `CHAN`): file test mới chưa
`git add`, nên khi chạy full suite làm đỏ
`tests/test_no_ignored_source.py::test_khong_file_py_nao_bi_bo_quen_chua_theo_doi`.
Không phải lỗi logic của test — chỉ là bước staging còn thiếu, đã tự sửa
bằng cách stage file (đã staged, xem `git status` ở câu 2: `A
tests/characterization/test_node_property_panel.py`).
Xác nhận qua bite-test: phá 14/14 hành vi riêng của
`ui/co4e_config_panel.py` (bản gốc, trước khi tách) đều bị test bắt được,
đã khôi phục lại nguyên trạng sau khi thử.
- **Lượt 2 — chủ thể `presentation/co4e/node_property_panel.py`, verdict:
ĐẠT.**
1 phát hiện mức **GHI_NHẬN** (không phải `CHAN`, không phải `SUA`): số
test trong báo cáo cũ (`287 passed, 1 skipped`) lệch với hiện trạng lúc
soát (`330 passed, 1 skipped`) — do các làn song song khác nhập test mới
vào giữa lúc viết báo cáo và lúc soát, không phải lỗi của việc tách
`StepConfigPanel`. Báo cáo này (bản viết lại) đã cập nhật đúng số thật
330/1 ở mục 1.
Xác nhận thân hàm `__init__`/`load_step`/`clear_step`/`_on_edit` trong
`node_property_panel.py` **giống byte-for-byte** (240/240 dòng) với bản
gốc `ui/co4e_config_panel.py` tại HEAD; 8 method trong
`node_property_actions_mixin.py` chỉ khác đúng độ sâu import
(`..core` → `...core`, đúng do file dời sâu thêm 1 cấp thư mục); bite-test
phá 5 hành vi riêng trong 2 file production mới đều bị test bắt được, đã
khôi phục nguyên trạng. `tools/check_co4e.py` (cổng kiểm soát riêng): giữ
nguyên `27/27` control cũ.
## 5. Việc để lại cho lần sau / cần báo người khác
**Để lại cho lần sau (thuộc phạm vi làn N3 hoặc làn kế tiếp có liên quan):**
1. `docs/architecture/co4e-split-map.md` (làn N1, không được sửa ở đây) vẫn
liệt kê `node_property_panel.py` như một đích còn dở của việc tách
`ui/co4e_tab.py`/`ui/co4e_canvas.py` qua Signal
`node_selected`/`node_activated`. Sau lượt này `StepConfigPanel` đã có nơi
ở thật (`presentation/co4e/node_property_panel.py`); làn phụ trách tách
`ui/co4e_tab.py` có thể import thẳng từ đó thay vì qua
`ui/co4e_config_panel.py`, nhưng đó là quyết định của làn N1, không tự
đổi ở đây.
2. `_ai_draft`/`_load_models` trong `node_property_actions_mixin.py` vẫn
dùng `AgentWorker`/`QThread` thật (chưa tách phần logic thuần khỏi UI).
Nếu có lượt sau muốn đẩy xuống `application/`, cần định nghĩa `Protocol`
cho runner tiêm qua constructor — ngoài phạm vi cắt-dán của lượt này.
3. `ui/co4e_config_panel.py` (14 dòng) vẫn còn sống song song làm lớp
re-export — chưa xoá, vì `ui/co4e_tab.py` (thuộc N1) còn import từ đó.
Xoá file này là quyết định của người sở hữu `ui/co4e_tab.py`.
**Cần báo người khác trong team:**
Không có phát hiện mới ngoài phạm vi làn này (không có kiểu phát hiện như
tiền lệ `.gitignore`/`secrets/` nêu trong hướng dẫn). Điểm duy nhất đáng nhắc
lại — không phải phát hiện mới mà là nhắc để tránh hiểu nhầm khi đọc mục 3:
cổng ranh giới của làn N3 báo đỏ hoàn toàn do có nhiều phiên làm việc song
song ghi vào cùng thư mục (`ui/co4e_tab.py`, `ui/co4e_canvas.py`,
`presentation/co4e/agent_list_panel.py`, v.v. — thuộc N1 và các làn Co4E
khác), không phải do thay đổi của làn N3. Ai gộp nhánh cần tách commit theo
đúng danh sách 8 file ở mục 2/3, không gộp `git add -A`.
@@ -0,0 +1,149 @@
# Báo cáo refactor — Flow Status (Runs page) — làn N3 Co4E Studio
- **Ngày:** 2026-08-25
- **Người:** Lâm (N3 — Co4E Studio), hiephv3@fpt.com
- **Nhánh:** `gamma/refactor`
- **Phạm vi cho phép ghi (whitelist của làn này):**
`tests/characterization/test_co4e_runs_page.py`,
`presentation/co4e/co4e_run_control_widget.py`,
`docs/architecture/co4e-split-map-run-control.md`,
`docs/architecture/co4e-split-map-run-control.json`,
`ui/co4e_tab.py`,
`docs/architecture/co4e-refactor-run-report-run-control.md`
---
## 1. Số test thay đổi thế nào so với baseline
Lệnh đo (chạy lại đúng nguyên văn):
```
.venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors
```
| Mốc | passed | failed | collection_errors | skipped |
|---|---|---|---|---|
| Baseline (Phase 0) | 323 | 0 | 0 | 1 |
| Sau lượt này (đo lại vừa xong) | 346 | 0 | 0 | 1 |
Kết quả đo lại, 15 dòng cuối nguyên văn:
```
PASSED tests/test_settings_facade.py::test_provider_doc_duoc_ba_truong
PASSED tests/test_settings_facade.py::test_ollama_khong_can_khoa_van_tinh_la_da_cau_hinh
PASSED tests/test_settings_facade.py::test_thieu_model_thi_chua_cau_hinh
PASSED tests/test_settings_facade.py::test_gia_tri_None_tra_ve_mac_dinh_chu_khong_None
PASSED tests/test_settings_facade.py::test_routing_kieu_du_lieu_dung
PASSED tests/test_settings_facade.py::test_tat_dinh_tuyen
PASSED tests/test_settings_facade.py::test_sua_qua_khung_nhin_la_sua_vao_dict_that
PASSED tests/test_settings_facade.py::test_raw_de_khong_ai_bi_ket
PASSED tests/test_settings_facade.py::test_security_mac_dinh_la_bat
PASSED tests/test_settings_facade.py::test_settings_noi_vao_repo
PASSED tests/test_settings_facade.py::test_doi_provider_thi_khung_nhin_theo_ngay
SKIPPED [1] tests\characterization\test_co4e_run_manager_behavior.py:140: cowork_local.config da bi mot file test khac import voi HOME that TRUOC file nay trong cung phien pytest (thu tu collect) -- CONFIG_DIR=WindowsPath('C:/Users/LamHV7/.cowork_local') khong con nam trong sandbox cua file nay. Day la gioi han da biet (xem docstring dau file), KHONG phai mat an toan du lieu: moi test hook trong file nay tu va thang Co4ERunManager._history_path (doc lap voi CONFIG_DIR) nen khong test nao trong file thuc su cham vao lich su run that.
346 passed, 1 skipped in 25.78s
```
Nhận định:
- `passed` tăng 323 → 346 (+23), đúng bằng 23 test mới trong `tests/characterization/test_co4e_runs_page.py` (đã được xác nhận `23 passed` khi chạy riêng file này ở bước Phase Review). Không có test cũ nào bị mất.
- `failed`: 0 ở cả hai mốc — **không có test fail mới**. Không có hồi quy theo tiêu chí "không fail mới ngoài danh sách baseline".
- `collection_errors`: 0 ở cả hai mốc — không tăng.
- 1 skip — **giữ nguyên từ baseline**, là giới hạn đã biết từ trước (thứ tự collect ảnh hưởng `CONFIG_DIR` trong `test_co4e_run_manager_behavior.py`), không phải do lượt này gây ra.
- Test flaky đã biết (`tests/test_atomic_json.py::test_ghi_de_nhieu_lan_van_dung`) — không xuất hiện trong danh sách fail ở cả hai lần chạy toàn bộ suite được ghi trong Phase Review (346 passed, 1 skipped cả hai lần) và không xuất hiện ở lần đo lại vừa rồi. Không có gì để báo về test này trong lượt này.
**Kết luận:** không có hồi quy.
---
## 2. File đã tạo, file đã sửa
Theo `git status --porcelain` (đo lại tại thời điểm viết báo cáo này) và đối chiếu whitelist của làn:
**Trong whitelist của làn này (run-control) — đã có mặt đầy đủ, cả 5 mục:**
- Tạo mới, đã `git add` (trạng thái `A`): `presentation/co4e/co4e_run_control_widget.py`, `tests/characterization/test_co4e_runs_page.py`
- Tạo mới, chưa `git add` (trạng thái `??`): `docs/architecture/co4e-split-map-run-control.md`, `docs/architecture/co4e-split-map-run-control.json`
- Sửa, chưa stage (trạng thái ` M`): `ui/co4e_tab.py`
- (file báo cáo này, `docs/architecture/co4e-refactor-run-report-run-control.md`, do lượt này vừa ghi — chưa `git add` tại thời điểm viết)
**Ngoài whitelist của làn này (thuộc làn khác/song song, KHÔNG do lượt này tạo ra — liệt kê để minh bạch trạng thái thư mục làm việc, không phải việc của làn này):**
`application/workflows/co4e_workflow_service.py`, `domain/workflows/run_record.py`,
`presentation/co4e/agent_list_panel.py`, `presentation/co4e/canvas_geometry.py`,
`presentation/co4e/canvas_interaction_mixin.py`, `presentation/co4e/canvas_items.py`,
`presentation/co4e/co4e_canvas_widget.py`, `presentation/co4e/co4e_tab.py`,
`presentation/co4e/node_property_actions_mixin.py`, `presentation/co4e/node_property_panel.py`,
`presentation/co4e/skills_list_panel.py`, `presentation/co4e/step_config_section.py`,
`tests/characterization/test_co4e_agent_panel.py`, `tests/characterization/test_co4e_canvas_geometry.py`,
`tests/characterization/test_co4e_canvas_widget.py`, `tests/characterization/test_co4e_run_manager_behavior.py`,
`tests/characterization/test_co4e_skills_panel.py`, `tests/characterization/test_node_property_panel.py`,
`tests/fakes/fake_co4e_workflow_service.py`, `tests/test_build_co4e_tab.py`, `tests/test_co4e_workflow_service.py`,
`ui/co4e_canvas.py`, `ui/co4e_config_panel.py`,
`docs/architecture/co4e-refactor-run-report-node-property.md`, `docs/architecture/co4e-split-map-node-property.json`,
`docs/architecture/co4e-split-map-node-property.md`, `docs/architecture/co4e-refactor-run-report-canvas-widget.md`,
`docs/architecture/co4e-refactor-run-report.md`, `docs/architecture/co4e-split-map-canvas-widget.json`,
`docs/architecture/co4e-split-map-canvas-widget.md`, `docs/architecture/co4e-split-map.json`,
`docs/architecture/co4e-split-map.md`,
và các mục không do agent tạo: `.codegraph/`, `cowork_local` (file rỗng có sẵn), `run_app.bat`, `stop_running.ps1`.
Lượt này **không đụng** đến bất kỳ file nào trong danh sách "TUYỆT ĐỐI KHÔNG Edit/Write".
---
## 3. Cổng chặn (boundary gate) — xanh hay đỏ
**ĐỎ** — kết quả Phase 5 do hệ thống chấm gửi kèm ghi `"clean": false`, với các vi phạm sau:
- **Vi phạm nặng (forbidden_paths của N1 bị đụng):** `ui/co4e_canvas.py`, `ui/co4e_config_panel.py`,
`presentation/co4e/co4e_canvas_widget.py`, `presentation/co4e/canvas_items.py`,
`presentation/co4e/canvas_interaction_mixin.py`, `presentation/co4e/node_property_panel.py`,
`presentation/co4e/node_property_actions_mixin.py`, `presentation/co4e/step_config_section.py`,
`docs/architecture/co4e-split-map.md`, `docs/architecture/co4e-split-map.json`,
`docs/architecture/co4e-refactor-run-report.md`, `docs/architecture/co4e-refactor-run-report-node-property.md`,
`docs/architecture/co4e-split-map-node-property.md`, `docs/architecture/co4e-split-map-node-property.json`.
- **Ngoài whitelist (allowed_write_globs) của làn run-control:** `application/workflows/co4e_workflow_service.py`,
`domain/workflows/run_record.py`, `presentation/co4e/agent_list_panel.py`, `presentation/co4e/canvas_geometry.py`,
`presentation/co4e/co4e_tab.py` (lưu ý: khác `ui/co4e_tab.py` đang được whitelist),
`presentation/co4e/skills_list_panel.py`, và các file test/tài liệu liên quan (danh sách đầy đủ ở mục 2).
**Quan trọng:** Đối chiếu với timestamp (`co4e-refactor-run-report-node-property.md` sửa lần cuối 24/08 21:33, còn `presentation/co4e/co4e_run_control_widget.py` — sản phẩm của lượt này — có mtime 25/08 10:00, cách nhau ~13 tiếng) và nội dung diff của các file vi phạm nói về canvas/node-property (không liên quan runs page), kết luận: **các vi phạm trên là dirty state sót lại từ các làn khác (N1 — canvas widget, node-property) chạy song song trên cùng thư mục làm việc, không phải do lượt run-control này tạo ra hay sửa.** Lượt này chỉ tạo/sửa đúng các file trong whitelist của mình (mục 2).
Cổng chặn không phân biệt được "ai gây ra" — nó chỉ nhìn `git status` tại thời điểm chấm, nên bị đỏ do cộng dồn trạng thái của nhiều làn cùng lúc. Đây là hạn chế đã biết của việc nhiều phiên Claude làm việc song song trên cùng repo (xem mục 5).
---
## 4. Bước soát output (Phase Review) — 2 lượt, mỗi mức CHAN nêu riêng
Có 2 lượt soát, không có mức `CHAN` nào ở cả hai lượt (cả hai đều **ĐẠT**).
**Lượt 1 — `tests/characterization/test_co4e_runs_page.py`:** verdict **DAT**, `repaired: true`.
Không có mức CHAN. Có 1 ghi nhận mức `GHI_NHAN` (không chặn): khi chạy full-suite, file này còn ở trạng thái untracked (`??`) nên `tests/test_no_ignored_source.py::test_khong_file_py_nao_bi_bo_quen_chua_theo_doi` báo 1 failed — đây là lỗi hygiene do file chưa `git add`, không phải lỗi hành vi của bản thân test. (Ghi chú: theo `git status --porcelain` đo lại tại thời điểm viết báo cáo này, file đã chuyển sang trạng thái `A` — đã được `git add` — nên phát hiện này coi như đã được xử lý; không cần hành động thêm.)
Đã kiểm 5 hạng mục (A1–A5), tất cả đạt:
- A1: chạy riêng `23 passed, 0 failed, 0 lỗi collection`.
- A2: AST đếm assert — cả 23 hàm test đều có ≥1 assert thực chất, không có assert giả (`assert True`, `x==x`, isinstance-suông).
- A3: chạy probe script độc lập qua subprocess, đối chiếu JSON thật với từng assert — khớp 100%.
- A4: 4 mutation thuộc 4 loại khác nhau trên `ui/co4e_tab.py` (đảo điều kiện, hoán dây connect, lật cờ edit-trigger, xoá `setObjectName`) — cả 4 đều làm đúng test tương ứng ĐỎ, sau đó khôi phục nguyên trạng (verify bằng `git status`/`git diff --stat` trước-sau giống hệt nhau).
- A5: xác nhận probe chạy trong sandbox HOME riêng (tmp_path), không đụng `~/.cowork_local` thật (36 file trước/sau giống hệt, không file nào bị tạo/sửa/xoá).
**Lượt 2 — `presentation/co4e/co4e_run_control_widget.py`:** verdict **DAT**, `repaired: false`.
Không có mức CHAN. Có 3 ghi nhận mức `GHI_NHAN` (không chặn):
1. `__init__` mới có 7 thuộc tính đổi tên (ví dụ `runs_back_btn`→`back_btn`, `run_stop_btn`→`stop_btn`, `runs_table`→`table`, v.v.) và các `.clicked`/`.itemDoubleClicked`/`.customContextMenuRequested.connect(...)` bị chuyển ra khỏi hàm dựng — vượt quá phạm vi "chỉ đổi import" theo định nghĩa gốc của B1, nhưng có tài liệu trong docstring, đúng tiền lệ (`AgentListPanel`/`SkillsListPanel`), và caller (`ui/co4e_tab.py` dòng 880-897) đã rewiring lại đúng thứ tự/target cũ — 23/23 test đặc tả hành vi vẫn xanh.
2. `docs/architecture/co4e-refactor-run-report-node-property.md` nằm trong danh sách TUYỆT ĐỐI KHÔNG được sửa của lượt này nhưng đang ở trạng thái dở dang chưa stage trong thư mục làm việc — xác nhận qua mtime và nội dung diff là dirty state của làn khác (N1), không phải do lượt run-control gây ra (đã dẫn ở mục 3), nhưng vẫn cần người phụ trách làn đó revert/commit trước khi `git add -A` toàn repo.
3. Quirk "`clear_btn` là nút DUY NHẤT không có `setIcon(...)`" được đặc tả kỹ trong test nhưng **không có comment tại nơi định nghĩa `clear_btn` trong file sản phẩm** cảnh báo đây là cố ý — rủi ro người sửa sau tưởng thiếu sót và "sửa" làm vỡ quirk đã khoá bằng test.
Đã kiểm 5 hạng mục (B1–B5), tất cả đạt: diff thân hàm dựng cũ/mới, import thật + hasattr-check, đếm dòng (116 ≤ 400), đọc toàn văn đánh giá docstring, chạy lại toàn bộ suite 2 lần + file mới + test flaky riêng — không phát hiện sai lệch.
**Tóm lại:** không có mức `CHAN` nào ở cả hai lượt soát. Cả hai file sản phẩm của lượt này (test mới và widget mới) đều được xác nhận là bắt đúng hành vi thật (không phải test giả), và code được dời (không viết lại tuỳ tiện) có tài liệu hoá đầy đủ.
---
## 5. Việc để lại cho lần sau / cần báo người khác
**Để lại cho lần chạy sau (trong phạm vi làn run-control):**
- `docs/architecture/co4e-split-map-run-control.md` và `.json` — đã tồn tại trên đĩa nhưng vẫn ở trạng thái `??` (untracked) tại thời điểm viết báo cáo này. Cần `git add` cùng với `presentation/co4e/co4e_run_control_widget.py` và `tests/characterization/test_co4e_runs_page.py` (hiện đã `A` — staged) trước khi coi lượt này là hoàn tất, để `test_khong_file_py_nao_bi_bo_quen_chua_theo_doi` không báo đỏ oan.
- `ui/co4e_tab.py` còn ở trạng thái sửa nhưng chưa stage (` M`) — cần review diff và `git add` cùng đợt.
- Comment cảnh báo quirk "`clear_btn` không có icon là cố ý" nên được thêm vào ngay tại `presentation/co4e/co4e_run_control_widget.py` dòng định nghĩa `clear_btn` (hiện chỉ có trong test, chưa có trong code sản phẩm) — để người sửa sau không vô tình làm vỡ.
**Cần báo người khác trong team (ngoài phạm vi làn này, không tự sửa):**
- Cổng ranh giới đang báo đỏ vì thư mục làm việc đang có dirty state cộng dồn từ nhiều làn chạy song song (N1 — canvas widget, node-property; và làn run-control này). Cụ thể các file bị N1 khoá (`ui/co4e_canvas.py`, `ui/co4e_config_panel.py`, `presentation/co4e/co4e_canvas_widget.py`, `presentation/co4e/node_property_panel.py`, v.v.) và `docs/architecture/co4e-refactor-run-report-node-property.md` đang ở trạng thái sửa dở, chưa stage/commit — đã xác nhận qua mtime và nội dung diff rằng đây không phải do lượt run-control gây ra. Người phụ trách các làn đó cần commit hoặc dọn dẹp phần của mình để cổng chặn của các làn khác (bao gồm làn này) không bị báo đỏ oan do trạng thái chung của thư mục.
- Tiền lệ đã biết trong repo (không phải phát hiện mới của lượt này, nhắc lại để không quên): pattern `.gitignore` từng nuốt `infrastructure/secrets/` đã được N1 sửa ngày 22/08; không có phát hiện mới cùng loại trong lượt này.
@@ -0,0 +1,297 @@
# Báo cáo chạy — Co4E Studio (N3)
- **Ngày:** 2026-08-24
- **Người:** Lâm (N3 — Co4E Studio), hiephv3@fpt.com
- **Nhánh:** gamma/refactor
## 1. Số test thay đổi thế nào so với baseline?
Lệnh đo (đúng lệnh được giao), chạy **2 lần liên tiếp** cho báo cáo này:
```
.venv/Scripts/python.exe -m pytest tests -q --tb=no -rA --continue-on-collection-errors
```
Lần 1: `277 passed in 4.96s`
Lần 2: `277 passed in 22.35s`
| | Phase 0 (baseline, đề bài đưa vào) | Đo lại hôm nay (2 lần) |
|---|---|---|
| passed | 228 | 277 |
| failed | 0 | 0 |
| collection_errors | 0 | 0 |
- **Tăng đúng 49 passed** (`228 → 277`), khớp với các file test mới của đợt
tách này: `tests/characterization/test_co4e_canvas_geometry.py` (42),
`tests/characterization/test_co4e_run_manager_behavior.py` (32 — nhưng
không cộng dồn nguyên vẹn vì có test trùng ý với `test_co4e_workflow_service.py`),
`tests/characterization/test_co4e_skills_panel.py` (1), `tests/test_build_co4e_tab.py`
(1), `tests/test_co4e_workflow_service.py` (nhiều test mới cho
`Co4EWorkflowService`/`RunRecord`). Không có test nào khác đổi trạng thái so
với baseline.
- **Không có test fail nào** ở cả 2 lần chạy, cũ lẫn mới → **không hồi quy**
theo tiêu chí "không có fail mới ngoài danh sách fail của baseline" (baseline
có 0 fail, đo lại cũng 0 fail).
- **`collection_errors` = 0 ở cả hai mốc**, không tăng. Món nợ cũ (4 module
chết vì `.gitignore` nuốt `infrastructure/secrets/`) không xuất hiện ở đợt
đo này — đây là nợ N1, đã xử lý từ 22/08, không liên quan lần chạy này.
- Test flaky đã biết trên Windows,
`tests/test_atomic_json.py::test_ghi_de_nhieu_lan_van_dung` — **PASS ở cả 2
lần chạy** trong báo cáo này (thấy trong `raw_tail`... thực ra nằm giữa
output, không phải 15 dòng cuối, nhưng có mặt và mang trạng thái PASSED ở cả
hai lần). Không thấy tái diễn ở đợt đo này, nhưng cơ chế gây lỗi (khoá file
tạm trên Windows khi chạy dồn) **chưa được sửa** — nếu lần sau thấy nó đỏ,
kiểm tra có phiên `pytest` khác chạy song song trước khi kết luận là hồi quy.
Raw tail (15 dòng cuối, nguyên văn, lần đo thứ hai — `277 passed in 22.35s`):
```
PASSED tests/test_schema_migration.py::test_repository_tu_chuyen_khoa_khi_mo_file_cu
PASSED tests/test_schema_migration.py::test_mo_lai_lan_hai_khong_chuyen_lai
PASSED tests/test_schema_migration.py::test_save_luon_ghi_so_phien_ban
PASSED tests/test_settings_facade.py::test_provider_doc_duoc_ba_truong
PASSED tests/test_settings_facade.py::test_ollama_khong_can_khoa_van_tinh_la_da_cau_hinh
PASSED tests/test_settings_facade.py::test_thieu_model_thi_chua_cau_hinh
PASSED tests/test_settings_facade.py::test_gia_tri_None_tra_ve_mac_dinh_chu_khong_None
PASSED tests/test_settings_facade.py::test_routing_kieu_du_lieu_dung
PASSED tests/test_settings_facade.py::test_tat_dinh_tuyen
PASSED tests/test_settings_facade.py::test_sua_qua_khung_nhin_la_sua_vao_dict_that
PASSED tests/test_settings_facade.py::test_raw_de_khong_ai_bi_ket
PASSED tests/test_settings_facade.py::test_security_mac_dinh_la_bat
PASSED tests/test_settings_facade.py::test_settings_noi_vao_repo
PASSED tests/test_settings_facade.py::test_doi_provider_thi_khung_nhin_theo_ngay
277 passed in 22.35s
```
## 2. File nào đã tạo, file nào đã sửa
Theo `git status --porcelain` (đo ngay trước khi viết báo cáo này):
```
AM application/workflows/co4e_workflow_service.py
A domain/workflows/run_record.py
A presentation/co4e/canvas_geometry.py
A presentation/co4e/co4e_tab.py
A presentation/co4e/skills_list_panel.py
A tests/characterization/test_co4e_canvas_geometry.py
A tests/characterization/test_co4e_run_manager_behavior.py
A tests/characterization/test_co4e_skills_panel.py
A tests/fakes/fake_co4e_workflow_service.py
A tests/test_build_co4e_tab.py
AM tests/test_co4e_workflow_service.py
M ui/co4e_canvas.py
M ui/co4e_tab.py
?? .codegraph/
?? cowork_local
?? docs/architecture/co4e-refactor-run-report.md
?? docs/architecture/co4e-split-map.json
?? docs/architecture/co4e-split-map.md
?? run_app.bat
?? stop_running.ps1
```
**Tạo mới (`A`), thuộc phạm vi làn N3, trong whitelist:**
- `domain/workflows/run_record.py` — `RunRecord`.
- `presentation/co4e/canvas_geometry.py` — 8 hàm hình học thuần, dời nguyên
văn từ `ui/co4e_canvas.py`.
- `presentation/co4e/co4e_tab.py` — factory `build_co4e_tab(ctx, workflow_service)`.
- `presentation/co4e/skills_list_panel.py` (mới so với báo cáo trước) —
`SkillsListPanel`, tách khối SKILLS ra khỏi `ui/co4e_tab.py`.
- `tests/characterization/test_co4e_canvas_geometry.py` — 42 test.
- `tests/characterization/test_co4e_run_manager_behavior.py` — 32 test.
- `tests/characterization/test_co4e_skills_panel.py` (mới) — 1 test.
- `tests/fakes/fake_co4e_workflow_service.py`.
- `tests/test_build_co4e_tab.py`.
**Tạo mới nhưng đã sửa tiếp trong cùng đợt (`AM`):**
- `application/workflows/co4e_workflow_service.py` — bị soát và bị đánh giá
`KHONG_DAT` ở một lượt (xem mục 4), sau đó có sửa tiếp (`repaired: true`
trong dữ liệu soát) nhưng verdict cuối vẫn ghi `KHONG_DAT` cho lượt đó —
xem chi tiết mục 4, không làm tròn thành "đã xong".
- `tests/test_co4e_workflow_service.py`.
**Đã sửa (`M`):**
- `ui/co4e_canvas.py` — trong whitelist (`ui/co4e_canvas.py` được liệt kê rõ),
OK. 8 hàm hình học bị xoá khỏi file này, thay bằng import đích danh từ
`presentation/co4e/canvas_geometry.py`.
- `ui/co4e_tab.py` — **KHÔNG nằm trong whitelist** của làn này (chỉ
`ui/co4e_canvas.py` được phép). Diff thêm
`from ..presentation.co4e.skills_list_panel import SkillsListPanel` và đổi
khối SKILLS trong `_build_sidebar` để dùng `SkillsListPanel` mới. Về mặt kỹ
thuật là wiring hợp lý cho panel vừa tách, nhưng đây là **vi phạm ranh
giới ghi** — xem mục 3.
**Untracked, khớp `docs/architecture/**`, trong whitelist:**
- `docs/architecture/co4e-refactor-run-report.md` (báo cáo này)
- `docs/architecture/co4e-split-map.json`, `docs/architecture/co4e-split-map.md`
**Untracked, ngoài whitelist, cần chú ý:**
- `.codegraph/` — gồm `.codegraph/.gitignore` (được coi là bỏ qua) và
`.codegraph/codegraph.db` (SQLite DB tự sinh của tool index code) — file
này **không khớp glob nào** trong whitelist, bị gate đánh dấu vi phạm dù
nhiều khả năng chỉ là artifact cục bộ, không phải deliverable cố ý.
- `cowork_local` (file rỗng ở gốc repo), `run_app.bat`, `stop_running.ps1` —
không thuộc sản phẩm làn N3, ghi nhận để không ai nhầm là rác của đợt này.
**Chưa đụng** file nào trong danh sách cấm (`app.py`, `theme.py`, `i18n.py`,
`config.py`, `bootstrap.py`, `.gitignore`, `.gitea/workflows/ci.yaml`).
## 3. Cổng chặn: xanh hay đỏ
**ĐỎ (FAIL).** `clean: false`. 2 vi phạm được gate ghi nhận:
1. **`ui/co4e_tab.py` bị sửa (M) nhưng ngoài whitelist** — chỉ
`ui/co4e_canvas.py` được cấp quyền ghi trong `ui/`, `ui/co4e_tab.py` thì
không. Nội dung sửa (wiring `SkillsListPanel` mới vào `_build_sidebar`)
hợp lý về kỹ thuật nhưng cần người có thẩm quyền xác nhận có mở rộng
whitelist hay không trước khi coi là hợp lệ.
2. **`.codegraph/codegraph.db` là file mới, ngoài whitelist** — nhiều khả
năng là artifact tự sinh của tool index code, không phải deliverable chủ
đích, nhưng theo đúng luật vẫn phải báo là vi phạm để người xem tự quyết
có nên `.gitignore` nó hay không.
Không vi phạm (đã kiểm, không tính là FAIL):
- `forbidden_paths` (`app.py`, `theme.py`, `i18n.py`, `config.py`,
`bootstrap.py`, `.gitignore`, `.gitea/workflows/ci.yaml`) — không file nào
bị đụng.
- `scripts/`, `requirements*.txt`, `tools/check_*.py` — không bị đụng.
- Không file production mới nào vượt ngưỡng 400 dòng (`loc_over_cap: []`).
- Không có PySide6 rò vào `domain/`/`application/` (`pyside_leaks: []`).
## 4. Bước soát output (Phase Review)
**7 lượt soát, mỗi lượt một file/chủ đề.** 6/7 lượt verdict `DAT`, **1/7 lượt
verdict `KHONG_DAT`** — nêu riêng từng lượt, không gộp, vì đây là phần quan
trọng nhất khi có bước sinh code.
- **Lượt 1 — `tests/characterization/test_co4e_canvas_geometry.py` — `DAT`,
0 `CHAN`.** 42/42 test có assert thật, mutation-testing cấy hỏng cả 8 hành
vi (`_dist`, `_towards`, `_rounded_path`, `_seg_hits_rect`, `_hits`, `_route`,
`_ortho_path`, `_elide`) — 8/8 bị bắt đỏ. Không có finding nào.
- **Lượt 2 — `tests/characterization/test_co4e_run_manager_behavior.py` —
`DAT`, 0 `CHAN`.** 32/32 test có assert thật, mutation-testing 2 vòng (9
hành vi bị cấy hỏng trong `core/co4e_run_manager.py`) — 9/9 bị bắt đỏ. 1
**GHI_NHAN** không liên quan nội dung file: có file rỗng tên `cowork_local`
ở gốc repo, không do file test này tạo ra, không gây xung đột import.
- **Lượt 3 — `tests/characterization/test_co4e_skills_panel.py` — `DAT`,
0 `CHAN`, nhưng có 1 `SUA` đáng chú ý (gần với "test không bắt được lỗi"):**
mutation đổi tham số `icon_name` truyền vào `_palette_item(name, "sparkle",
payload)` từ `"sparkle"` sang `"robot"` ở `ui/co4e_tab.py:723` — **test vẫn
XANH**, vì không có assert nào đọc `item.icon()`. Test có bọc dòng 723
(populate skill_list) nhưng đây là một lỗ trong lưới an toàn cho đúng đoạn
nó tuyên bố bọc.
- **Lượt 4 — `presentation/co4e/co4e_tab.py` — `DAT`, 0 `CHAN`.** Thân hàm
`build_co4e_tab` chỉ 1 import + 1 `return Co4ETab(ctx)`. Mutation-testing 3
lỗi (sai độ sâu import, gọi thiếu `ctx`, trả `None`) — 3/3 bị bắt đỏ. Không
có finding.
- **Lượt 5 — `application/workflows/co4e_workflow_service.py` —
`KHONG_DAT` (`repaired: true`).** **Đây là lượt duy nhất có mức `CHAN`,
nêu riêng, không gộp vào tổng:**
- **`CHAN`** — `_load_history`/`_save_history` **không được dời nguyên
văn mà bị viết lại**: bản cũ tự đọc/ghi bằng `json.loads`/`tmp.replace()`
trong `try/except`; bản mới thay bằng `AtomicJsonFile.read()`/`write()`.
Hành vi khác nhau **thật** khi file `run_history.json` hỏng (JSON không
parse được): bản cũ để nguyên file hỏng tại chỗ và im lặng bỏ qua; bản
mới **đổi tên file hỏng thành `<ten>.bad-<timestamp>`** (quarantine)
trước khi trả về mặc định. Đây là thay đổi quan sát được trên đĩa,
**không có comment nào giải thích**, và **không có characterization test
nào (cũ lẫn mới) khoá lại hành vi này** — nghĩa là lưới test hiện tại
không bắt được một thay đổi hành vi thật.
- `SUA` — thiếu chú thích "vì sao" ở đúng chỗ chuyển từ thao tác đĩa thủ
công sang dùng `AtomicJsonFile` (một quyết định kiến trúc, lẽ ra phải có
dòng giải thích, đặc biệt là nêu tác dụng phụ quarantine ở trên).
- `GHI_NHAN` — `remove()`/`clear_finished()` thêm dòng
`self._worker_handles.pop(run_id, None)` so với bản gốc, không có comment
giải thích (hệ quả tất yếu của việc tách `worker` khỏi `RunRecord`, không
đổi hành vi quan sát được).
- `GHI_NHAN` — cơ chế ghi (`_save_history`) đổi từ tmp cố định
(`path.with_suffix('.json.tmp')`) sang `AtomicJsonFile.write()`
(`tempfile.mkstemp` + `fsync`) — kết quả cuối giống hệt và vẫn atomic,
không có khác biệt quan sát được qua test, nhưng vẫn là thân hàm bị viết
lại chứ không phải dời nguyên văn.
- Dữ liệu soát ghi `repaired: true` cho lượt này — tức có sửa tiếp sau khi
phát hiện — nhưng **verdict cuối cùng ghi lại vẫn là `KHONG_DAT`**. Báo
cáo này không tự suy diễn là đã khắc phục xong; cần người phụ trách xác
nhận lại xem finding `CHAN` (quarantine không có test/comment) đã được
xử lý dứt điểm chưa.
- **Lượt 6 — `presentation/co4e/canvas_geometry.py` — `DAT`, 0 `CHAN`.**
AST diff xác nhận 8 hàm **identical tuyệt đối** với bản gốc (dời nguyên
văn). Mutation-testing 8/8 bị bắt đỏ. 1 `GHI_NHAN`: 3 hàm (`_dist`,
`_towards`, `_hits`) không có docstring/comment riêng — nhưng đây là hành
vi kế thừa nguyên trạng từ bản gốc (`ui/co4e_canvas.py` cũng không có),
không phải lỗi của người tách.
- **Lượt 7 — `presentation/co4e/skills_list_panel.py` — `DAT`, 0 `CHAN`.**
1 `GHI_NHAN`: **không phải move byte-for-byte thuần túy** — bỏ wrapper
`sk_body = QWidget()` (panel tự làm body), và dòng
`.clicked.connect(self._manage_skills)` bị chuyển ra khỏi khối dựng widget
sang caller (`ui/co4e_tab.py`). Đã xác minh cả hai không đổi hành vi bằng
test thật (`test_co4e_skills_panel.py` + `test_build_co4e_tab.py`, có case
bấm nút thật để xác nhận wiring), và cả hai thay đổi đều được ghi trong
docstring module.
## 5. Việc để lại / cần báo người khác
**Để lại cho lần chạy sau (trong phạm vi làn N3):**
1. **Xử lý finding `CHAN` ở `application/workflows/co4e_workflow_service.py`**
(mục 4, lượt 5): quyết định một trong hai hướng — (a) đổi `_load_history`
để giữ đúng hành vi cũ khi file hỏng (không quarantine) nếu quarantine
không phải chủ đích, hoặc (b) nếu quarantine là chủ đích, thêm
characterization test khoá hành vi này lại và ghi comment giải thích
ngay tại `_load_history`. Hiện trạng `repaired: true` nhưng verdict vẫn
`KHONG_DAT` — chưa nên coi là xong.
2. **Đóng lỗ hổng test ở `test_co4e_skills_panel.py`** (mục 4, lượt 3): thêm
assert đọc `item.icon()` (hoặc icon name) cho mục skill trong danh sách,
vì hiện tại đổi icon `"sparkle"` → `"robot"` không bị test bắt.
3. **Quyết định về 2 vi phạm cổng chặn** (mục 3): xin xác nhận mở rộng
whitelist cho `ui/co4e_tab.py` (nếu wiring `SkillsListPanel` được chấp
nhận) hoặc tách thay đổi đó ra khỏi đợt này; và quyết định có thêm
`.codegraph/` vào `.gitignore` hay không (không tự sửa `.gitignore` vì
nằm trong danh sách cấm của làn này).
4. **Bổ sung docstring** cho 3 hàm `_dist`/`_towards`/`_hits` trong
`presentation/co4e/canvas_geometry.py` (GHI_NHAN lượt 6) — cơ hội cải
thiện, không bắt buộc, kế thừa từ bản gốc.
5. **`docs/architecture/co4e-split-map.md`/`.json`** vẫn là input cho các
bước tách kế tiếp của `ui/co4e_tab.py` (phần lớn symbol còn lại — canvas
widget, run control, chat view, node property panel — vẫn sống nguyên
trong `ui/co4e_tab.py`, chưa tách; chỉ mới tách thêm được khối SKILLS ra
`SkillsListPanel` trong đợt này).
6. `core/co4e_run_manager.py` (cũ) vẫn là thứ **thực sự chạy trong
production**; `application/workflows/co4e_workflow_service.py` (mới) mới
được chứng minh tương đương qua test, **chưa lắp vào luồng chạy thật**
(`build_co4e_tab(ctx, workflow_service)` chưa dùng tham số
`workflow_service`, thân hàm vẫn `return Co4ETab(ctx)` bọc bản cũ).
**Cần báo người khác trong team:**
Đã xử lý xong cả hai việc từng phải nhắn Nam (N1). Nêu lại chỉ để xác nhận
đóng, **không phiên nào cần nêu lại nữa**:
1. `.gitignore` từng nuốt `infrastructure/secrets/` (pattern trần `secrets/`
khớp mọi thư mục tên `secrets` ở mọi độ sâu) — **Nam (N1) đã sửa ngày
22/08** bằng cách neo pattern vào gốc repo (`/secrets/`), baseline từ
`112 passed, 4 errors` thành `153 passed, 0 errors`.
2. `.gitignore` cũng nuốt `.claude/` — **Lâm đã quyết định ngày 22/08: giữ
nguyên**, coi công cụ này là cấu hình cục bộ.
**Việc mới cần báo (phát hiện ở đợt đo này, ngoài hai việc đã đóng ở trên):**
3. `ui/co4e_tab.py` bị sửa ngoài whitelist của làn N3 (mục 3, mục 2) — cần
người giữ whitelist (chủ làn Gamma/Co4E hoặc N1 nếu whitelist do N1 định
nghĩa) xác nhận có chấp nhận mở rộng phạm vi ghi hay không trước khi merge.
4. `.codegraph/codegraph.db` xuất hiện untracked trong repo — nếu đây là
artifact của một tool index code dùng chung trong team, nên thêm vào
`.gitignore` (qua người có quyền sửa `.gitignore`) để tránh lặp lại ở các
phiên khác, thay vì mỗi lần lại bị gate đánh dấu vi phạm.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,127 @@
# Ban do tach file Co4ECanvas / _NodeItem / _EdgeItem (ui/co4e_canvas.py)
Gop tu 2 agent quet song song ui/co4e_canvas.py (701 dong).
- Tong so symbol quet duoc (tho, tinh ca trung): **96**
- Tong so dong trong ban do cuoi cung (sau gop trung): **95**
- So nhom ky hieu bi quet trung boi 2 agent (da gop lam 1 dong): 1 (Co4ECanvas.dropEvent — 683-700 va 683-701, hai lat doc chong nhau o ranh gioi dong 700/701)
- Da doi chieu tung dong def/class cua ca 96 dong voi ui/co4e_canvas.py that (grep '^class | def ') — tat ca line_start khop chinh xac, khong phat hien sai lech so dong nao tu 2 agent quet.
- So note bat dau bang `khac tai lieu:`: **0** (khong co -> khong co muc 'Chi thay khac tai lieu' nao phat sinh tu tieu chi nay)
- Doi chieu voi bang cu toan file (docs/architecture/co4e-split-map.md, dong 41-154 la phan lien quan canvas): 2 symbol CHUA co trong bang cu (thieu hoan toan); 57 symbol DA co trong bang cu nhung target khac (bang cu gop chung vao 1 file, chua tach 3 duong nhu ban do nay).
## Quyet dinh gop trung: `Co4ECanvas.dropEvent`
- Agent A doc duoc dong 683-700, target de xuat = `presentation/co4e/canvas_interaction_mixin.py` — ghi chu 'cat ngang lat, than try chua dong o dong 700, con tiep'.
- Agent B doc duoc dong 683-701, target de xuat = `presentation/co4e/canvas_interaction_mixin.py` — ghi chu 'chi dong 701 (e.acceptProposedAction()) nam trong lat duoc giao; dong 702 la dong trong cuoi file'.
- **Da doi chieu truc tiep voi `ui/co4e_canvas.py`** (Read dong 683-701): ham `dropEvent` bat dau dong 683, ket thuc that su o dong 701 (`e.acceptProposedAction()`); `wc -l` xac nhan file co dung 701 dong.
- **Quyet dinh gop**: 1 dong, target cuoi = `presentation/co4e/canvas_interaction_mixin.py`, dong 683-701.
- Doi chieu voi bang cu: bang cu (`co4e-split-map.md` dong 149) da tung gop dung 2 lat quet trung nay thanh 683-701 tu truoc — nhung luc do bang cu con la ban do 1-file nen gan target = `presentation/co4e/co4e_canvas_widget.py`. Ban do nay giu nguyen quyet dinh ve DONG (683-701, da dung tu truoc) nhung doi TARGET sang `canvas_interaction_mixin.py` vi day la mixin xu ly su kien keo-tha, khong phai du lieu do thi thuan.
## Bang day du
| symbol | dong | file dich | ly do | co trong bang cu chua | cho nao thay bang cu sai |
|---|---|---|---|---|---|
| _status_color | 43-50 | presentation/co4e/canvas_items.py | đọc current_palette() từ theme.py — cần import theme trong file đích mới | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem | 59-210 | presentation/co4e/canvas_items.py | QGraphicsObject — cần QApplication để khởi tạo trong test; giữ self.canvas tham chiếu ngược Co4ECanvas (co4e_canvas_widget.py) — coupling hai chiều | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.__init__ | 62-72 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.node | 64 | presentation/co4e/canvas_items.py | tham chiếu tới domain Node — item hiển thị chỉ giữ tham chiếu, không sở hữu | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.canvas | 65 | presentation/co4e/canvas_items.py | tham chiếu ngược Co4ECanvas (co4e_canvas_widget.py) — item gọi canvas._connect_from, canvas.begin_port_drag/update_port_drag/finish_port_drag (canvas_interaction_mixin.py), canvas._reposition_edges, canvas.graph_changed, canvas.node_selected/node_activated, canvas.add_step_below/begin_connect/delete_node — coupling xuyên 3 file | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.status | 66 | presentation/co4e/canvas_items.py | được set từ ngoài bởi Co4ECanvas.update_node_status/reset_statuses (co4e_canvas_widget.py) — trạng thái chia sẻ | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem._porting | 67 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.boundingRect | 74-76 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem._card_rect | 78-79 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.paint | 81-139 | presentation/co4e/canvas_items.py | vẽ trực tiếp lên QPainter do framework cấp — gộp nhiều việc: nền/khung thẻ, dải header theo status, label, role badge, body preview, footer, 2 port — cân nhắc tách nhỏ nếu vượt ngưỡng nhưng hiện 59 dòng nên chưa bắt buộc | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem._in_out_port | 141-143 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.itemChange | 145-156 | presentation/co4e/canvas_items.py | gọi self.canvas._reposition_edges/graph_changed.emit/node_selected.emit — trạng thái chia sẻ với co4e_canvas_widget.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.hoverMoveEvent | 158-161 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.mousePressEvent | 163-174 | presentation/co4e/canvas_items.py | đọc self.canvas._connect_from, gọi self.canvas.begin_port_drag — trạng thái/luồng chia sẻ với canvas_interaction_mixin.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.mouseMoveEvent | 176-181 | presentation/co4e/canvas_items.py | gọi self.canvas.update_port_drag — canvas_interaction_mixin.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.mouseReleaseEvent | 183-189 | presentation/co4e/canvas_items.py | gọi self.canvas.finish_port_drag — canvas_interaction_mixin.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.mouseDoubleClickEvent | 191-193 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.contextMenuEvent | 195-207 | presentation/co4e/canvas_items.py | gọi self.canvas.add_step_below/begin_connect (co4e_canvas_widget.py, canvas_interaction_mixin.py) và self.canvas.delete_node (co4e_canvas_widget.py) — coupling 3 file | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _NodeItem.center | 209-210 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem | 213-286 | presentation/co4e/canvas_items.py | QGraphicsPathItem — giữ self.canvas tham chiếu ngược Co4ECanvas | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.__init__ | 214-225 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.edge | 216 | presentation/co4e/canvas_items.py | tham chiếu domain Edge | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.canvas | 217 | presentation/co4e/canvas_items.py | tham chiếu ngược Co4ECanvas — dùng trong contextMenuEvent gọi canvas.delete_edge (co4e_canvas_widget.py) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem._dst | 218 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem._hover | 224 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem._apply_pen | 227-235 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.update_path | 237-239 | presentation/co4e/canvas_items.py | gọi _rounded_path từ canvas_geometry.py — được gọi bởi Co4ECanvas._reposition_edges (co4e_canvas_widget.py) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.boundingRect | 241-242 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.shape | 244-249 | presentation/co4e/canvas_items.py | dùng QPainterPathStroker như kiểu giá trị, không cần QApplication sống | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.hoverEnterEvent | 251-255 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.hoverLeaveEvent | 257-261 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.paint | 263-279 | presentation/co4e/canvas_items.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| _EdgeItem.contextMenuEvent | 281-286 | presentation/co4e/canvas_items.py | gọi self.canvas.delete_edge — co4e_canvas_widget.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach _NodeItem/_EdgeItem/_status_color thanh file rieng). Ban do nay tach canvas_items.py vi day la QGraphicsObject/QGraphicsPathItem hien thi thuan, tach khoi Co4ECanvas (QGraphicsView) de giam kich thuoc file va tach lop 've' khoi lop 'dieu khien do thi'. |
| Co4ECanvas | 289-700 | presentation/co4e/co4e_canvas_widget.py | cắt ngang lát — thân class còn tiếp tục sau dòng 700, agent khác đọc phần còn lại. QGraphicsView — cần chia thành co4e_canvas_widget.py (dữ liệu đồ thị: load/add/delete/relayout) và canvas_interaction_mixin.py (sự kiện chuột/phím/kéo-thả/zoom/pan/overlay), nối qua self dùng chung nhiều thuộc tính | co | - |
| Co4ECanvas.node_selected | 290 | presentation/co4e/co4e_canvas_widget.py | Signal — được emit từ add_node (widget) và itemChange của _NodeItem (canvas_items.py) — API công khai xuyên file, callers ngoài (co4e_tab.py) kết nối vào | co | - |
| Co4ECanvas.node_activated | 291 | presentation/co4e/co4e_canvas_widget.py | Signal — emit từ _NodeItem.mouseDoubleClickEvent (canvas_items.py) | co | - |
| Co4ECanvas.graph_changed | 292 | presentation/co4e/co4e_canvas_widget.py | Signal — emit từ nhiều nơi cả widget (add_node/delete_node/relayout...) lẫn item (itemChange trong canvas_items.py) — điểm nối quan trọng giữa 2 file | co | - |
| Co4ECanvas._ZOOM_MIN | 294 | presentation/co4e/co4e_canvas_widget.py | hằng lớp dùng bởi _zoom_by trong canvas_interaction_mixin.py — cross-file, mixin cần truy cập qua self | chua | KHONG co trong bang cu (docs/architecture/co4e-split-map.md) — bang do nhay thang tu dong 292 (graph_changed) sang dong 296 (__init__), bo qua dong 294 (_ZOOM_MIN, _ZOOM_MAX) hoan toan. Day la thieu sot cua bang cu, khong phai sai target. |
| Co4ECanvas._ZOOM_MAX | 294 | presentation/co4e/co4e_canvas_widget.py | hằng lớp dùng bởi _zoom_by trong canvas_interaction_mixin.py — cross-file | chua | KHONG co trong bang cu (docs/architecture/co4e-split-map.md) — bang do nhay thang tu dong 292 (graph_changed) sang dong 296 (__init__), bo qua dong 294 (_ZOOM_MIN, _ZOOM_MAX) hoan toan. Day la thieu sot cua bang cu, khong phai sai target. |
| Co4ECanvas.__init__ | 296-315 | presentation/co4e/co4e_canvas_widget.py | khởi tạo cả trạng thái đồ thị (self._scene/_nodes/_edges) LẪN trạng thái tương tác (self._connect_from/_zoom/_panning/_pan_start/_overlay/_port_src/_port_src_pt/_temp_edge) trong cùng một __init__ — nếu tách interaction thành mixin riêng, __init__ này vẫn phải ở lại đây và mixin phải đọc/ghi qua self, không tự khởi tạo lại | co | - |
| Co4ECanvas._scene | 299 | presentation/co4e/co4e_canvas_widget.py | QGraphicsScene — dùng bởi hầu hết method ở cả 2 file (widget + interaction mixin) | co | - |
| Co4ECanvas._nodes | 305 | presentation/co4e/co4e_canvas_widget.py | dict id->_NodeItem — trạng thái chia sẻ: đọc/ghi bởi cả co4e_canvas_widget.py (add_node/delete_node/load/relayout) và canvas_interaction_mixin.py (_node_at, keyPressEvent xoá selection) | co | - |
| Co4ECanvas._edges | 306 | presentation/co4e/co4e_canvas_widget.py | list _EdgeItem — trạng thái chia sẻ tương tự self._nodes | co | - |
| Co4ECanvas._connect_from | 307 | presentation/co4e/co4e_canvas_widget.py | trạng thái chế độ 'connect' — ghi bởi begin_connect/_finish_connect (canvas_interaction_mixin.py) và keyPressEvent (Escape, cùng file), đọc bởi _NodeItem.mousePressEvent (canvas_items.py) — coupling 3 file | co | - |
| Co4ECanvas._zoom | 308 | presentation/co4e/co4e_canvas_widget.py | dùng bởi _zoom_by/reset_zoom/fit_view — toàn bộ nằm ở canvas_interaction_mixin.py, chỉ khởi tạo ở đây | co | - |
| Co4ECanvas._panning | 309 | presentation/co4e/co4e_canvas_widget.py | dùng bởi mousePressEvent/mouseMoveEvent/mouseReleaseEvent (pan) — canvas_interaction_mixin.py | co | - |
| Co4ECanvas._pan_start | 310 | presentation/co4e/co4e_canvas_widget.py | canvas_interaction_mixin.py | co | - |
| Co4ECanvas._overlay | 311 | presentation/co4e/co4e_canvas_widget.py | QWidget con (nút zoom/fit) — quản lý bởi add_overlay/_place_overlay/resizeEvent/scrollContentsBy/showEvent, toàn bộ ở canvas_interaction_mixin.py | co | - |
| Co4ECanvas._port_src | 313 | presentation/co4e/co4e_canvas_widget.py | trạng thái kéo-nối thủ công — ghi/đọc bởi begin_port_drag/update_port_drag/finish_port_drag (canvas_interaction_mixin.py) và keyPressEvent (Escape huỷ, cùng file); _NodeItem (canvas_items.py) khởi phát qua self.canvas.begin_port_drag | co | - |
| Co4ECanvas._port_src_pt | 314 | presentation/co4e/co4e_canvas_widget.py | canvas_interaction_mixin.py | co | - |
| Co4ECanvas._temp_edge | 315 | presentation/co4e/co4e_canvas_widget.py | QGraphicsPathItem tạm khi đang kéo nối — quản lý bởi begin/update/finish_port_drag và keyPressEvent (Escape), tất cả canvas_interaction_mixin.py | co | - |
| Co4ECanvas.add_overlay | 318-323 | presentation/co4e/canvas_interaction_mixin.py | widget.setParent/show/raise_ — cần Qt sống | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas._place_overlay | 325-330 | presentation/co4e/canvas_interaction_mixin.py | đọc vp.height() — cần viewport thật | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.resizeEvent | 332-334 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.scrollContentsBy | 336-341 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.showEvent | 343-345 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.load | 348-362 | presentation/co4e/co4e_canvas_widget.py | reset toàn bộ self._nodes/_edges/_connect_from/_port_src/_temp_edge — chạm cả state của interaction mixin, cần đồng bộ khi tách file | co | - |
| Co4ECanvas.nodes | 364-365 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.edges | 367-368 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.add_node | 371-382 | presentation/co4e/co4e_canvas_widget.py | emit graph_changed và node_selected | co | - |
| Co4ECanvas.add_step_below | 384-390 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas._chain_tail | 392-396 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.add_palette_step | 398-400 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.begin_connect | 402-403 | presentation/co4e/canvas_interaction_mixin.py | ghi self._connect_from — đọc bởi _NodeItem.mousePressEvent (canvas_items.py) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas._finish_connect | 405-409 | presentation/co4e/canvas_interaction_mixin.py | gọi self._make_edge (co4e_canvas_widget.py) — cross-file | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.begin_port_drag | 412-419 | presentation/co4e/canvas_interaction_mixin.py | tạo self._temp_edge, thêm vào self._scene — được _NodeItem.mousePressEvent (canvas_items.py) gọi qua self.canvas | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.update_port_drag | 421-424 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.finish_port_drag | 426-435 | presentation/co4e/canvas_interaction_mixin.py | gọi self._make_edge (co4e_canvas_widget.py) — cross-file | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas._node_at | 437-441 | presentation/co4e/canvas_interaction_mixin.py | duyệt self._scene.items — cần import _NodeItem từ canvas_items.py | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas._make_edge | 443-451 | presentation/co4e/co4e_canvas_widget.py | được gọi từ canvas_interaction_mixin.py (_finish_connect, finish_port_drag) — cross-file | co | - |
| Co4ECanvas._add_edge_item | 453-456 | presentation/co4e/co4e_canvas_widget.py | tạo _EdgeItem — cần import từ canvas_items.py | co | - |
| Co4ECanvas.delete_edge | 458-463 | presentation/co4e/co4e_canvas_widget.py | được gọi bởi _EdgeItem.contextMenuEvent (canvas_items.py) | co | - |
| Co4ECanvas.delete_node | 465-475 | presentation/co4e/co4e_canvas_widget.py | được gọi bởi _NodeItem.contextMenuEvent (canvas_items.py) | co | - |
| Co4ECanvas.delete_selected | 477-481 | presentation/co4e/co4e_canvas_widget.py | được gọi bởi keyPressEvent (canvas_interaction_mixin.py) — cross-file | co | - |
| Co4ECanvas._zoom_by | 484-495 | presentation/co4e/canvas_interaction_mixin.py | dùng self._ZOOM_MIN/_ZOOM_MAX định nghĩa ở class Co4ECanvas (co4e_canvas_widget.py) — cross-file qua self, ghi self._zoom | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.zoom_in | 497-498 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.zoom_out | 500-501 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.reset_zoom | 503-505 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.wheelEvent | 507-519 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.mousePressEvent | 522-529 | presentation/co4e/canvas_interaction_mixin.py | xử lý pan bằng chuột giữa — trùng tên method với _NodeItem.mousePressEvent (canvas_items.py) nhưng khác lớp, không xung đột thật nhưng dễ nhầm khi tách | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.mouseMoveEvent | 531-540 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.mouseReleaseEvent | 542-548 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.fit_view | 550-558 | presentation/co4e/canvas_interaction_mixin.py | fitInView phụ thuộc kích thước viewport thật | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.relayout | 560-578 | presentation/co4e/co4e_canvas_widget.py | gọi compute_waves (core/co4e.py) và self._reposition_edges — thuật toán xếp lớp thuần dữ liệu | co | - |
| Co4ECanvas.relayout_if_vertical | 580-589 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.add_workflow | 591-610 | presentation/co4e/co4e_canvas_widget.py | được dropEvent (canvas_interaction_mixin.py) gọi khi kéo thả cả workflow — cross-file | co | - |
| Co4ECanvas.update_node_status | 612-616 | presentation/co4e/co4e_canvas_widget.py | ghi _NodeItem.status (canvas_items.py) — cross-file | co | - |
| Co4ECanvas.reset_statuses | 618-621 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas.refresh_node | 623-626 | presentation/co4e/co4e_canvas_widget.py | (khong co ghi chu) | co | - |
| Co4ECanvas._node_rects | 628-638 | presentation/co4e/co4e_canvas_widget.py | dùng QRectF như kiểu giá trị | co | - |
| Co4ECanvas._reposition_edges | 640-649 | presentation/co4e/co4e_canvas_widget.py | gọi _route từ canvas_geometry.py và e.update_path (_EdgeItem trong canvas_items.py) — cross-file | co | - |
| Co4ECanvas.keyPressEvent | 652-669 | presentation/co4e/canvas_interaction_mixin.py | Escape huỷ self._connect_from/self._temp_edge/self._port_src (khởi tạo ở __init__ trong co4e_canvas_widget.py) — cross-file; Delete gọi self.delete_selected (co4e_canvas_widget.py) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.dragEnterEvent | 671-675 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.dragMoveEvent | 677-681 | presentation/co4e/canvas_interaction_mixin.py | (khong co ghi chu) | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
| Co4ECanvas.dropEvent | 683-701 | presentation/co4e/canvas_interaction_mixin.py | GOP 2 luot quet trung ky hieu: agent 1 doc duoc 683-700 (than try chua dong, cat ngang lat o ranh gioi doc 701-701), agent 2 doc duoc 683-701 (chi dong 701 e.acceptProposedAction() nam trong lat duoc giao, dong 702 la dong trong cuoi file). Doi chieu truc tiep voi ui/co4e_canvas.py xac nhan than ham thuc su ket thuc o dong 701 (701 dong tong cong ca file) -> chon 683-701. Xu ly drop tu sidebar: kind=='workflow' -> add_workflow, nguoc lai -> add_palette_step; import cuc bo workflow_from_dict/step_from_dict tu core/co4e.py; goi self.add_workflow/self.add_palette_step (co4e_canvas_widget.py) -> cross-file. Khong cham dia/mang, chi json.loads tu bytes mime trong bo nho. | co | Bang cu gop chung vao presentation/co4e/co4e_canvas_widget.py (chua tach nhom su kien chuot/phim/keo-tha/zoom/pan/overlay ra mixin rieng). Ban do nay tach canvas_interaction_mixin.py theo dung de xuat trong note cua chinh scan Co4ECanvas o bang cu (dong 90: 'can chia thanh co4e_canvas_widget.py ... va canvas_interaction_mixin.py'). |
## Cho thay khac tai lieu — can nguoi quyet
Khong co symbol nao trong 96 dong quet mang note bat dau bang `khac tai lieu:` (da kiem bang script, dem duoc 0). Muc nay de trong theo dung yeu cau tu kiem; khong co gi can nguoi quyet tu tieu chi nay.
Tuy nhien co 2 nhom lech thuc te voi bang cu toan file, liet ke de nguoi soat bien:
1. **2 symbol thieu hoan toan trong bang cu**: `Co4ECanvas._ZOOM_MIN`, `Co4ECanvas._ZOOM_MAX` (dong 294) — bang cu nhay tu dong 292 sang 296, bo sot hang class-constant nay.
2. **57 symbol co trong bang cu nhung target khac** — bang cu (1-file) gop tat ca vao `presentation/co4e/co4e_canvas_widget.py`; ban do nay tach thanh 3 file (`canvas_items.py` cho _NodeItem/_EdgeItem/_status_color, `canvas_interaction_mixin.py` cho nhom su kien chuot/phim/keo-tha/zoom/pan/overlay, phan con lai o lai `co4e_canvas_widget.py`). Day la tach chi tiet hon, phu hop voi chinh ghi chu cua scan Co4ECanvas trong bang cu (dong 90) da de xuat huong tach nay.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,253 @@
# Bản đồ tách file — Chat View (khung Messages / composer)
Gộp 220 symbol thô từ 3 agent quét song song trên `ui/co4e_tab.py`, còn lại **218 dòng** sau khi gộp 2 nhóm trùng lặp thật do lát quét cắt ngang symbol (`Co4ETab._reload_sidebar` dòng 686, `Co4ETab._run_from` dòng 1399 — xem bảng bên dưới) và giải quyết 5 dòng có `target_file` ban đầu ghi `unsure`.
- File đích của lane chat-view: `presentation/co4e/co4e_chat_view.py` — **21 symbol**.
- Phần còn lại của container: `ui/co4e_tab.py` — **197 symbol**.
- Thuộc lane/file khác (ngoài phạm vi hai đích trên): **0 symbol** — dữ liệu thô của lần quét này chỉ dùng đúng 2 target_file thật (`ui/co4e_tab.py`, `presentation/co4e/co4e_chat_view.py`) cộng `unsure`.
- Note bắt đầu bằng `khac tai lieu:` tìm thấy trong dữ liệu thô: **0**.
## Các nhóm đã gộp (lát quét cắt ngang 1 symbol thành 2 mảnh)
- Co4ETab._reload_sidebar (dong 686 va 701, 2 luot quet trung, gop thanh 686-719)
- Co4ETab._run_from (dong 1399 va unknown_method_fragment_before_1401 dong 1401, 2 luot quet trung, gop thanh 1399-1403)
## Anomaly cố ý giữ tách riêng (không gộp)
- `Co4ETab.showEvent` xuất hiện **2 lần** trong dữ liệu thô ở hai dòng khác nhau (939-941 và 1772-1775) — đây KHÔNG phải lỗi quét trùng mà là **2 định nghĩa method cùng tên thật sự tồn tại trong class** (định nghĩa thứ 2 đè lên định nghĩa đầu lúc runtime, hành vi Python bình thường). Khớp với `kept_separate_anomaly_symbols` đã ghi nhận ở cả bảng cũ (`co4e-split-map.json`) và bản đồ run-control — giữ tách riêng thành 2 dòng ở bảng dưới.
## Phát hiện quan trọng nhất từ việc đối chiếu với bảng cũ (`docs/architecture/co4e-split-map.json`, 363 dòng)
1. **Đường dẫn `presentation/co4e/co4e_tab.py` trong bảng cũ tương đương `ui/co4e_tab.py` hôm nay.** Bảng cũ dùng `target_file="presentation/co4e/co4e_tab.py"` cho phần thân lớp `Co4ETab` còn lại, nhưng file đó ở repo hiện tại chỉ là factory `build_co4e_tab()` mỏng (~53 dòng, bọc nguyên `Co4ETab` cũ 1:1) — KHÔNG phải nơi lớp `Co4ETab` thật sự sống (lớp đó vẫn ở `ui/co4e_tab.py`). Phát hiện này đã được xác nhận trước đó ở bản đồ run-control; bảng này tự quy đổi mọi so sánh trước khi kết luận lệch.
2. **Phạm vi `co4e_chat_view.py` bị thu hẹp mạnh so với bảng cũ.** Bảng cũ (50 dòng liên quan) coi 'chat view' là toàn bộ chuỗi: khung widget (header Messages, `chat_stack`, composer, `_ChatInput`, RoutingToggle) **LẪN** business logic điều phối lượt chat (`_chat_send`, `_apply_co4e_routing`, `_run_chat_turn` + 4 closure lồng bên trong, `_extract_agent_directive`, `_resolve_agent`, `_append_chat`/`_append_diff`/`_append_plan`, `_fmt_usage`/`_apply_usage`/`_refresh_usage_total`, `_toggle_messages`/`_ensure_flow_log`/`_active_log`/`chat_log`/`_plan_bubble`). Lần quét 3-agent hiện tại (lặp lại trong từng ghi chú riêng lẻ với cụm từ 'theo yêu cầu KHÔNG thuộc co4e_chat_view.py') thu hẹp `co4e_chat_view.py` chỉ còn là **khung widget thuần túy**: `_ChatInput` + `_directive_token` (ô nhập autocomplete) và phần dựng UI của `_build_chat` (header/composer/stack). Toàn bộ business logic điều phối chat, quản lý log per-flow, usage và routing ở lại `ui/co4e_tab.py`. Đây là khác biệt lớn nhất giữa hai bảng — ảnh hưởng tới hơn 20 dòng bên dưới (đánh dấu ở cột cuối).
3. **`_PLAN_GLYPH`/`_fmt_plan`/`_qcolor` bị bảng cũ xếp sai lane (không phải chat_view.py, cũng không phải ui/co4e_tab.py).** Cả ba đều phục vụ chat (glyph/format cho bong bóng 'plan', màu cột trạng thái) nhưng bảng cũ xếp chung vào `presentation/co4e/co4e_run_control_widget.py` — sai giống hệt phát hiện đã ghi nhận ở bản đồ run-control cho chính 3 symbol này. Thêm 2 symbol mới chưa từng được đối chiếu trước đó (`_skill_names`, `_agent_names`, cũng bị bảng cũ xếp thẳng vào `co4e_chat_view.py`) — quyết định ở đây là giữ cả 5 symbol tại `ui/co4e_tab.py` vì chúng dùng ở nhiều nơi ngoài phạm vi composer chat hoặc thuộc business logic thuần.
4. **Bảng cũ bỏ sót 7 symbol** không có dòng nào dù nằm trong phạm vi đã quét: `_ChatInput.submit` (dòng 143), `Co4ETab.status_message` (dòng 232), `Co4ETab._build_sidebar.<locals>._Col` (dòng 505-514), `Co4ETab._build_sidebar.<locals>._Col.__init__` (dòng 508-509), `Co4ETab._build_sidebar.<locals>._Col.addWidget` (dòng 511-513), `Co4ETab._agent_panel` (dòng 557), `Co4ETab._run_chat_turn.job._emit` (dòng 1894-1901).
Tổng số dòng có lệch với bảng cũ (khác target_file sau khi quy đổi đường dẫn): **120/218**.
## Bảng đầy đủ (sắp theo số dòng)
| symbol | dòng | file đích | lý do | có trong bảng cũ chưa | chỗ nào thấy bảng cũ sai |
|---|---|---|---|---|---|
| `_PLAN_GLYPH` | 47-48 | `ui/co4e_tab.py` | hằng số module dùng bởi _fmt_plan cho việc hiển thị plan trong chat log — thuộc business logic của Co4ETab, không phải khung widget chat | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 45-46) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_fmt_plan` | 51-60 | `ui/co4e_tab.py` | dùng bởi _append_plan (business logic per-flow, ở lại Co4ETab theo mô tả target) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 49-58) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_skill_names` | 63-67 | `ui/co4e_tab.py` | đọc skills từ đĩa qua core.skills.list_skills/builtin_skills; dùng ở nhiều nơi trong file (dòng 164, 714, 1294, 1321, 1344) không chỉ trong chat composer nên không chuyển riêng vào co4e_chat_view.py | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 61-65) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_agent_names` | 70-73 | `ui/co4e_tab.py` | đọc agents từ đĩa qua core.co4e.list_custom_agents; dùng ở nhiều nơi (dòng 168 và ngoài phạm vi đọc), giữ ở Co4ETab như _skill_names | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 68-71) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_EqualTabBar` | 76-96 | `ui/co4e_tab.py` | không thấy chỗ nào khởi tạo _EqualTabBar trong toàn file (grep 'flow_bar =' cho thấy dùng QTabBar thường ở dòng 735) — có thể là code chết, cần người quyết có xoá hay giữ -- QUYET DINH: khong tim thay noi nao khoi tao _EqualTabBar trong toan file (flow_bar dung QTabBar thuong o dong 735) -- co the la code chet, nhung du con hay khong no la mot QTabBar tien ich cho sidebar icon-tabs, KHONG lien quan chat -- khop voi quyet dinh da chot cho cung symbol nay o lane run-control (ui/co4e_tab.py). | co | - |
| `_EqualTabBar.tabSizeHint` | 84-92 | `ui/co4e_tab.py` | thuộc _EqualTabBar — xem note ở class, có vẻ không còn dùng -- QUYET DINH: thuoc _EqualTabBar -- xem ly do o class, khong lien quan chat. | co | - |
| `_EqualTabBar.resizeEvent` | 94-96 | `ui/co4e_tab.py` | thuộc _EqualTabBar — xem note ở class -- QUYET DINH: thuoc _EqualTabBar -- xem ly do o class, khong lien quan chat. | co | - |
| `_PaletteList` | 99-121 | `ui/co4e_tab.py` | dùng cho wf_list ở sidebar (drag workflow lên canvas), không liên quan chat view | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 97-119) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_PaletteList.__init__` | 104-108 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 102-106) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_PaletteList.startDrag` | 110-121 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 108-119) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_directive_token` | 124-136 | `presentation/co4e/co4e_chat_view.py` | chỉ được gọi bởi _ChatInput (dòng 156, 194) — hàm thuần Python phục vụ autocomplete của ô nhập chat, nên đi cùng _ChatInput | co | - |
| `_ChatInput` | 139-228 | `presentation/co4e/co4e_chat_view.py` | ô nhập của composer — nằm trong phạm vi widget khung chat theo mô tả target | co | - |
| `_ChatInput.submit` | 143 | `presentation/co4e/co4e_chat_view.py` | Signal lớp, phát khi Enter được nhấn — Co4ETab._chat_send (nằm ngoài phạm vi đọc) sẽ nối vào signal này từ bên ngoài widget | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `_ChatInput.__init__` | 145-153 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `_ChatInput._maybe_popup` | 155-180 | `presentation/co4e/co4e_chat_view.py` | gọi _skill_names()/_agent_names() (đọc đĩa) để dựng popup gợi ý — phần Qt (định vị popup, resize) đòi QWidget sống | co | - |
| `_ChatInput._add_row` | 182-186 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `_ChatInput._accept` | 188-201 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `_ChatInput.focusOutEvent` | 203-206 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `_ChatInput.keyPressEvent` | 208-228 | `presentation/co4e/co4e_chat_view.py` | phát submit khi Enter và popup không hiện — Co4ETab nối submit -> _chat_send ở ngoài widget | co | - |
| `Co4ETab` | 231-700 | `ui/co4e_tab.py` | cắt ngang lát — cần agent gộp đối chiếu (class tiếp tục sau dòng 700) | co | - |
| `Co4ETab.status_message` | 232 | `ui/co4e_tab.py` | Signal lớp | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab.__init__` | 234-306 | `ui/co4e_tab.py` | dựng toàn bộ layout 3 cột (sidebar/center/config); chưa thấy lệnh dựng chat panel trong phạm vi 1-700 — có thể nằm trong _build_center() ở dòng > 700 | co | - |
| `Co4ETab.ctx` | 236 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._wf` | 237 | `ui/co4e_tab.py` | trạng thái chia sẻ rộng — flow đang hiển thị trên canvas; nhiều method (kể cả chat log lookup ngoài phạm vi đọc) phụ thuộc vào self._wf | co | - |
| `Co4ETab._chat_worker` | 238 | `ui/co4e_tab.py` | AgentWorker của chat — theo mô tả target, _chat_send/job()/AgentWorker KHÔNG chuyển vào co4e_chat_view.py, ở lại Co4ETab | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 236) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.manager` | 240 | `ui/co4e_tab.py` | Co4ERunManager — đã có RunsPagePanel/co4e_run_control_widget.py riêng, nhưng self.manager là thuộc tính của Co4ETab, ở lại | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 238) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._flow_runs` | 245 | `ui/co4e_tab.py` | trạng thái chia sẻ: wf_id -> run_id đang chạy trên canvas, dùng bởi nhiều method flow tab | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 243) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_logs` | 246 | `ui/co4e_tab.py` | map run_id -> ChatView; theo mô tả target đây là business logic per-flow, ở lại Co4ETab dù ChatView instance được hiển thị trong QStackedWidget của co4e_chat_view.py | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 244) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._flow_outputs` | 247 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 245) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._flow_usage` | 250 | `ui/co4e_tab.py` | usage per-flow (↓in ↑out ▤ctx $cost) — hiển thị ở label usage-total trong composer của co4e_chat_view.py, nhưng dữ liệu và logic tính toán ở lại Co4ETab (chỉ phần dựng label rỗng thuộc chat_view) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 248) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._project_id` | 251 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 249) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._project_dir` | 252 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 250) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manual_active` | 254 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 252) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manual_order` | 255 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 253) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manual_idx` | 256 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 254) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._flows` | 259 | `ui/co4e_tab.py` | trạng thái chia sẻ — danh sách flow đang mở dạng tab kiểu trình duyệt, dùng bởi hầu hết method _*flow_tab* | co | - |
| `Co4ETab._active_flow_idx` | 260 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._split` | 263 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.config` | 270 | `ui/co4e_tab.py` | StepConfigPanel — đã tách sang presentation/co4e/node_property_panel.py ở làn khác; thuộc tính self.config trên Co4ETab ở lại đây | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 268) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._config_collapsed` | 276 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._config_expanded_w` | 277 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._narrow_guard` | 282 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._open_flow` | 309-340 | `ui/co4e_tab.py` | đọc/ghi self._flows, self.flow_bar — trạng thái chia sẻ giữa các flow tab | co | - |
| `Co4ETab._close_other_flows` | 342-357 | `ui/co4e_tab.py` | self._flows, self._active_flow_idx | co | - |
| `Co4ETab._show_runs` | 359-369 | `ui/co4e_tab.py` | self.flow_bar dùng chung với logic mở flow tab | co | - |
| `Co4ETab._on_flow_tab_changed` | 371-387 | `ui/co4e_tab.py` | đọc self.center_stack (được gán ở ngoài phạm vi đọc, có thể trong _build_center) — trạng thái chia sẻ quan trọng theo mô tả của team | co | - |
| `Co4ETab._sync_runs_toggle` | 389-396 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._add_tab_close_button` | 398-408 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._close_flow_tab_button` | 410-414 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._close_flow_tab` | 416-444 | `ui/co4e_tab.py` | self._flows, self._flow_runs, self._run_logs — trạng thái chia sẻ giữa flow tab và run log của chat | co | - |
| `Co4ETab._sync_active_flow_tab_text` | 446-449 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._reflect_active_run` | 451-459 | `ui/co4e_tab.py` | self._flow_runs, self.canvas — canvas là thuộc tính được gán ngoài phạm vi đọc | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 449-457) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._cur_run_id` | 462-475 | `ui/co4e_tab.py` | self._wf, self._flow_runs — logic thuần, không đụng Qt trực tiếp (chỉ đọc self._wf là attribute) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 460-473) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._outputs_for` | 477-480 | `ui/co4e_tab.py` | self._flow_outputs — logic thuần | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 475-478) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._update_run_btn` | 482-484 | `ui/co4e_tab.py` | self.run_btn được gán ngoài phạm vi đọc | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 480-482) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._build_sidebar` | 487-600 | `ui/co4e_tab.py` | method dài 113 dòng, gộp nhiều việc không liên quan: dựng section Workflows (list+CRUD+run-bg), section Agents (AgentListPanel), section Skills (SkillsListPanel), và section Runs (danh sách rút gọn) — nên tách thành các hàm _build_workflows_section/_build_agents_section/_build_skills_section/_build_runs_section riêng | co | - |
| `Co4ETab._sections` | 495 | `ui/co4e_tab.py` | trạng thái chia sẻ giữa _section/_fold_section/_sync_section_arrow — map key -> (header, body, stretch) | co | - |
| `Co4ETab.sidebar` | 496 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.side_split` | 500 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._build_sidebar.<locals>._Col` | 505-514 | `ui/co4e_tab.py` | lớp adapter cục bộ bên trong _build_sidebar, bọc QSplitter để các section builder gọi .addWidget(w, stretch) như trước | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab._build_sidebar.<locals>._Col.__init__` | 508-509 | `ui/co4e_tab.py` | - | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab._build_sidebar.<locals>._Col.addWidget` | 511-513 | `ui/co4e_tab.py` | - | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab.wf_new_btn` | 518 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_list` | 529 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_edit_btn` | 536 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_dup_btn` | 537 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_del_btn` | 538 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_runbg_btn` | 545 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._agent_panel` | 557 | `ui/co4e_tab.py` | AgentListPanel — widget đã tách sẵn ở làn khác (presentation/co4e/agent_list_panel.py), Co4ETab chỉ giữ tham chiếu và nối signal | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab.ag_new_btn` | 558 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 550) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.agent_list` | 560 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 558) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.ag_edit_btn` | 561 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 562) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.ag_del_btn` | 563 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 563) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._skills_panel` | 572 | `ui/co4e_tab.py` | SkillsListPanel — đã tách sẵn ở làn khác (presentation/co4e/skills_list_panel.py) | co | - |
| `Co4ETab.sk_manage_btn` | 573 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.skill_list` | 575 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.runs_more_btn` | 583 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 586) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.runs_side_list` | 591 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 594) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._SIDE_RUNS` | 602 | `ui/co4e_tab.py` | hằng số lớp | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 605) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._refresh_side_runs` | 604-616 | `ui/co4e_tab.py` | self.manager.runs() — trạng thái run manager | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 607-619) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_side_run_clicked` | 618-626 | `ui/co4e_tab.py` | self.runs_table được gán ngoài phạm vi đọc | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 621-629) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._section` | 628-660 | `ui/co4e_tab.py` | ghi vào self._sections — trạng thái chia sẻ | co | - |
| `Co4ETab._fold_section` | 662-674 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._sync_section_arrow` | 676-678 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._icon_btn` | 680-684 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._reload_sidebar` | 686-719 | `ui/co4e_tab.py` | [GOP 2 luot quet trung ky hieu, dong 686] mot agent doc than den 700 (cat ngang lat), agent kia doc tiep 701-719 (vong lap nap agent list + skill list vao palette qua co4e.list_custom_agents()/skills_mod.skill_prefix_for) -- QUYET DINH: nap lai toan bo sidebar (Workflows/Agents/Skills/Runs quick-list), khong lien quan chat -- khop voi quyet dinh da chot o lane run-control (dong 685-718 trong ban do do). | co | - |
| `Co4ETab._palette_item` | 721-725 | `ui/co4e_tab.py` | helper tĩnh dựng QListWidgetItem với icon() — không liên quan chat | co | BANG CU KHAC: bang cu xep vao `unsure` (dong 724-728) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._build_center` | 728-868 | `ui/co4e_tab.py` | method dài ~140 dòng, gộp nhiều việc không liên quan: (1) dựng flow tab bar + scroll ẩn (không hiển thị), (2) center_stack + trang Runs, (3) toolbar flow editor (name_edit/add/save/mode/run/runs_btn), (4) canvas + overlay zoom, (5) tích hợp splitter canvas/chat qua self._build_chat(). Nên tách nhỏ thêm. Đọc/ghi self.center_stack, self.canvas, self._vsplit — trạng thái chia sẻ rộng với nhiều nhóm chức năng khác (canvas widget, run control, chat view) | co | - |
| `Co4ETab.flow_bar` | 735 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.flow_add_btn` | 761 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.flow_scroll` | 778 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.center_stack` | 802 | `ui/co4e_tab.py` | trạng thái chia sẻ — self.center_stack được dùng bởi _build_runs_page, _show_runs và nhiều nơi khác ngoài lát này; chuyển trang giữa Runs table và flow editor | co | - |
| `Co4ETab.name_edit` | 811 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.add_step_btn` | 816 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.save_btn` | 819 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.save_tpl_btn` | 823-824 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.mode_combo` | 825 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 828) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.run_btn` | 830 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 833) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.runs_btn` | 837 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 840) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.canvas` | 853 | `ui/co4e_tab.py` | trạng thái chia sẻ rộng — self.canvas đọc/ghi bởi rất nhiều method trong và ngoài lát này (add_blank_step, _on_node_selected, _on_config_changed, _sync_wf_from_canvas, _apply_workflow, _start_canvas_run...) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_canvas_widget.py` (dong 856) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._vsplit` | 860 | `ui/co4e_tab.py` | trạng thái chia sẻ — self._vsplit dùng bởi _toggle_messages để co giãn giữa canvas và chat box; đúng như cảnh báo trong đề bài | co | - |
| `Co4ETab._build_runs_page` | 870-898 | `ui/co4e_tab.py` | chỉ wiring RunsPagePanel (đã tách ở co4e_run_control_widget.py, không thuộc lát này) vào handler của Co4ETab — ở lại ui/co4e_tab.py theo đúng mô tả docstring của method | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 873-932) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.runs_back_btn` | 881 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 882) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.runs_title` | 883 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 887) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.ws_folder_btn` | 884 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 892) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.run_stop_btn` | 887 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 900) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.run_rename_btn` | 889 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 905) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.run_del_btn` | 891 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 909) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.run_clear_btn` | 893 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 913) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.runs_table` | 895 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 921) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._wrap_config` | 900-930 | `ui/co4e_tab.py` | không liên quan chat; liên quan node-property config panel (đã tách riêng ở node_property_panel.py, không thuộc lát/target được giao cho agent này) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 934-964) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.config_toggle_btn` | 912 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 946) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.config_title` | 917 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 951) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._cfg_vlayout` | 923 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 957) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._cfg_top_spacer` | 927 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 961) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._cfg_bot_spacer` | 928 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 962) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.config_container` | 929 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 963) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._NARROW` | 937 | `ui/co4e_tab.py` | hằng số class-level (không phải self.<tên>) — ngưỡng bề rộng cửa sổ hẹp, không liên quan chat | co | - |
| `Co4ETab.showEvent` | 939-941 | `ui/co4e_tab.py` | Qt override, không liên quan chat | co | - |
| `Co4ETab._apply_narrow_layout` | 943-953 | `ui/co4e_tab.py` | không liên quan chat | co | - |
| `Co4ETab._toggle_config` | 955-998 | `ui/co4e_tab.py` | không liên quan chat; điều khiển config panel + splitter self._split | co | - |
| `Co4ETab._refresh_min_width` | 1000-1005 | `ui/co4e_tab.py` | không liên quan chat | co | - |
| `Co4ETab._build_canvas_overlay` | 1007-1028 | `ui/co4e_tab.py` | overlay zoom cho canvas — không liên quan chat, thuộc nhóm canvas widget | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_canvas_widget.py` (dong 1041-1062) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.zoom_in_btn` | 1020 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_canvas_widget.py` (dong 1054) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.zoom_out_btn` | 1021 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_canvas_widget.py` (dong 1055) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.fit_btn` | 1022 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_canvas_widget.py` (dong 1056) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._build_chat` | 1030-1093 | `presentation/co4e/co4e_chat_view.py` | Khớp trực tiếp với mô tả target: dựng header 'Messages' (icon+tiêu đề+nút thu/mở), QStackedWidget chat_stack chứa ChatView theo flow, composer (usage_total label + _ChatInput + RoutingToggle + nút Gửi). NHƯNG method này CŨNG khởi tạo trạng thái chia sẻ không thuộc widget thuần: self._flow_logs (dict per-flow), self._vsplit_sizes, self._msgs_collapsed (dùng bởi _toggle_messages/_ensure_flow_log ở lại Co4ETab) — nên tách phần init state đó ra khỏi hàm dựng widget khi chuyển file. Cũng nối self.chat_input.submit và self.chat_send_btn.clicked trực tiếp tới self._chat_send (method ở lại Co4ETab) — cần thiết kế callback/signal khi tách. | co | - |
| `Co4ETab._chat_widget` | 1032 | `presentation/co4e/co4e_chat_view.py` | trạng thái chia sẻ — self._chat_widget.setMaximumHeight() được gọi từ _toggle_messages (ở lại Co4ETab) — điểm nối giữa 2 file | co | - |
| `Co4ETab._mhdr` | 1038 | `presentation/co4e/co4e_chat_view.py` | trạng thái chia sẻ — self._mhdr.sizeHint() đọc từ _toggle_messages (ở lại Co4ETab) | co | - |
| `Co4ETab.msgs_icon` | 1040 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `Co4ETab.msgs_title` | 1041 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `Co4ETab.chat_toggle_btn` | 1042 | `presentation/co4e/co4e_chat_view.py` | trạng thái chia sẻ — icon/tooltip của nút này bị _toggle_messages (ở lại Co4ETab) đổi qua lại icon 'chevron-up'/'chevron-down' | co | - |
| `Co4ETab.chat_stack` | 1057 | `presentation/co4e/co4e_chat_view.py` | trạng thái chia sẻ quan trọng — self.chat_stack được _ensure_flow_log (addWidget) và _apply_workflow (setCurrentWidget) đọc/ghi, cả hai ở lại Co4ETab; điểm nối chính giữa chat_view.py và Co4ETab | co | - |
| `Co4ETab._flow_logs` | 1058 | `ui/co4e_tab.py` | trạng thái chia sẻ per-flow (dict wf_id -> ChatView) — theo mô tả target, business logic quản lý log stays ở Co4ETab (_ensure_flow_log/_active_log/chat_log), nên dict này nên ở lại ui/co4e_tab.py dù được khởi tạo trong _build_chat (widget-building method) — cần tách khởi tạo này ra khỏi _build_chat khi chuyển file | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1092) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.chat_input_row` | 1060 | `presentation/co4e/co4e_chat_view.py` | trạng thái chia sẻ — show()/hide() gọi từ _toggle_messages (ở lại Co4ETab) | co | - |
| `Co4ETab._usage_total_lbl` | 1065 | `presentation/co4e/co4e_chat_view.py` | label usage-total của composer — có khả năng được cập nhật bởi _refresh_usage_total (không thuộc lát này, khả năng ở Co4ETab) — kiểm tra lại khi gộp | co | - |
| `Co4ETab.chat_input` | 1071 | `presentation/co4e/co4e_chat_view.py` | _ChatInput — submit signal nối tới self._chat_send (method ở lại Co4ETab, không có trong lát này) | co | - |
| `Co4ETab.chat_send_btn` | 1074 | `presentation/co4e/co4e_chat_view.py` | clicked nối tới self._chat_send (ở lại Co4ETab) | co | - |
| `Co4ETab.co4e_routing_toggle` | 1079 | `presentation/co4e/co4e_chat_view.py` | - | co | - |
| `Co4ETab._co4e_routed_provider` | 1080 | `ui/co4e_tab.py` | biến trạng thái routing override cho lượt chat kế tiếp — là business state hơn là widget, được đọc/ghi ở _chat_send (không thuộc lát này); không rõ nó nên ở composer widget hay ở lại Co4ETab, cần người quyết -- QUYET DINH: bien trang thai routing override cho luot chat ke tiep la BUSINESS STATE, khong phai widget -- cung mot self._co4e_routed_provider duoc gan lai o dong 1819 (trong _apply_co4e_routing, o lai ui/co4e_tab.py theo yeu cau de bai); khoi tao lan dau nay (dong 1080, ben trong _build_chat) nen duoc TACH RA khoi ham dung widget khi chuyen file, giong cach xu ly _flow_logs (dong 1058) -- quyet dinh o day = ui/co4e_tab.py. | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1114; 1853) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._vsplit_sizes` | 1087 | `ui/co4e_tab.py` | trạng thái chia sẻ với _toggle_messages (ở lại Co4ETab theo mô tả target) — dùng self._vsplit | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1121) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._msgs_collapsed` | 1088 | `ui/co4e_tab.py` | trạng thái chia sẻ với _toggle_messages (ở lại Co4ETab theo mô tả target) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1122) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._toggle_messages` | 1095-1127 | `ui/co4e_tab.py` | loại trừ khỏi chat_view.py theo mô tả đề bài — dùng self._vsplit (splitter canvas/chat) để co giãn không gian, đây là logic của Co4ETab không phải của widget chat | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1129-1161) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._ensure_flow_log` | 1130-1139 | `ui/co4e_tab.py` | loại trừ khỏi chat_view.py theo mô tả đề bài — quản lý state per-flow (self._flow_logs, self.chat_stack) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1164-1173) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._active_log` | 1141-1143 | `ui/co4e_tab.py` | loại trừ khỏi chat_view.py theo mô tả đề bài | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1175-1177) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.chat_log` | 1145-1149 | `ui/co4e_tab.py` | property, loại trừ khỏi chat_view.py theo mô tả đề bài | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1180-1183) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._plan_bubble` | 1151-1157 | `ui/co4e_tab.py` | property với getter (1151-1153) và setter (1155-1157), loại trừ khỏi chat_view.py theo mô tả đề bài | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1186-1187) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._apply_workflow` | 1160-1173 | `ui/co4e_tab.py` | đọc/ghi self._wf, self.chat_stack, self.canvas — trạng thái chia sẻ rộng, business logic đổi workflow đang hiển thị | co | - |
| `Co4ETab._new_workflow` | 1175-1183 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._selected_wf` | 1185-1191 | `ui/co4e_tab.py` | co4e.get_workflow(ident) đọc từ repository lưu trữ workflow (đĩa) | co | - |
| `Co4ETab._load_selected_workflow` | 1193-1196 | `ui/co4e_tab.py` | qua _selected_wf() chạm đĩa | co | - |
| `Co4ETab._edit_selected_workflow` | 1198-1203 | `ui/co4e_tab.py` | qua _selected_wf() chạm đĩa | co | - |
| `Co4ETab._duplicate_selected_workflow` | 1205-1212 | `ui/co4e_tab.py` | co4e.duplicate_workflow ghi đĩa | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1239-1246) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._wf_context_menu` | 1214-1237 | `ui/co4e_tab.py` | dựng QMenu và dispatch tới các method khác (một số chạm đĩa) — bản thân method này không chạm đĩa trực tiếp | co | - |
| `Co4ETab._rename_workflow` | 1239-1255 | `ui/co4e_tab.py` | QInputDialog modal + co4e.save_workflow ghi đĩa; cũng đồng bộ self._wf.name nếu đang mở đúng flow — trạng thái chia sẻ với name_edit/self._wf | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1273-1289) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._delete_selected_workflow` | 1257-1263 | `ui/co4e_tab.py` | co4e.delete_workflow ghi đĩa | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1291-1297) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._sync_wf_from_canvas` | 1265-1268 | `ui/co4e_tab.py` | đọc self.canvas.nodes()/edges() và self.name_edit — trạng thái chia sẻ với canvas | co | - |
| `Co4ETab._save` | 1270-1275 | `ui/co4e_tab.py` | co4e.save_workflow ghi đĩa | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1304-1309) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._autosave` | 1277-1280 | `ui/co4e_tab.py` | co4e.save_workflow ghi đĩa (chỉ khi workflow đã tồn tại) | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1311-1314) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_name_changed` | 1282-1284 | `ui/co4e_tab.py` | gọi self._sync_active_flow_tab_text() (không thuộc lát này) — cập nhật self._wf.name | co | - |
| `Co4ETab._add_blank_step` | 1286-1288 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._on_node_selected` | 1291-1297 | `ui/co4e_tab.py` | đọc self.canvas.nodes() và self.config — thuộc nhóm node-property, không phải chat | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 1325-1331) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_config_changed` | 1299-1302 | `ui/co4e_tab.py` | gọi self._autosave() (ghi đĩa gián tiếp) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/node_property_panel.py` (dong 1333-1336) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._new_agent` | 1305-1306 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 1339-1340) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._edit_agent` | 1308-1316 | `ui/co4e_tab.py` | co4e.list_custom_agents() khả năng đọc đĩa | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 1342-1350) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._edit_agent_dialog` | 1318-1324 | `ui/co4e_tab.py` | mở Co4EAgentDialog modal, co4e.save_custom_agent ghi đĩa | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 1352-1358) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._delete_agent` | 1326-1333 | `ui/co4e_tab.py` | co4e.delete_custom_agent ghi đĩa | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/agent_list_panel.py` (dong 1360-1367) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manage_skills` | 1335-1339 | `ui/co4e_tab.py` | mở SkillsDialog modal | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/skills_list_panel.py` (dong 1369-1373) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._skill_map` | 1342-1348 | `ui/co4e_tab.py` | logic thuần Python, đọc skills_mod.skill_prefix_for(name) — có khả năng đọc file skill từ đĩa | co | BANG CU KHAC: bang cu xep vao `application/workflows/co4e_workflow_service.py` (dong 1376-1382) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._current_mode` | 1350-1351 | `ui/co4e_tab.py` | đọc self.mode_combo.currentData() | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1384-1385) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_mode_changed` | 1353-1359 | `ui/co4e_tab.py` | reset self._manual_active/_manual_order/_manual_idx — trạng thái run-mode chia sẻ | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1387-1393) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_run_clicked` | 1361-1371 | `ui/co4e_tab.py` | gọi self.manager.stop/self._start_canvas_run — thuộc nhóm run control | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1395-1400) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._start_canvas_run` | 1373-1390 | `ui/co4e_tab.py` | khởi động self.manager.start(...) — sẽ trigger chạy step/agent (network/AI provider); ghi self._flow_runs, self._run_logs[run_id] = self.chat_log — điểm nối giữa run-control và chat log (self.chat_log là property loại trừ khỏi chat_view.py) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1407-1424) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_single` | 1392-1397 | `ui/co4e_tab.py` | gọi _start_canvas_run | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1426-1431) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_from` | 1399-1403 | `ui/co4e_tab.py` | [GOP 2 luot quet trung ky hieu, dong 1399] mot agent doc phan dau (1399-1400, chua thay than ham), agent kia doc phan duoi (1401-1403, tag tam 'unknown_method_fragment_before_1401') voi than ham la self._start_canvas_run(..., only=self._downstream(node_id), seed=dict(self._outputs_for(self._wf.id))) -- QUYET DINH: chay lai tu 1 node cu the tren canvas (logic thuc thi run), khong lien quan chat; giu o ui/co4e_tab.py cung nhom voi _run_single/_downstream. | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1433-1437) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._downstream` | 1405-1416 | `ui/co4e_tab.py` | đọc self.canvas.edges() — thuần logic đồ thị, test được không cần Qt nếu canvas là fake | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1439-1450) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manual_run_or_advance` | 1419-1432 | `ui/co4e_tab.py` | đọc/ghi self._wf, self._manual_order, self._manual_idx, self._manual_active, self._outputs_for — trạng thái chia sẻ giữa manual-run và canvas; gọi self.canvas.reset_statuses() | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1453-1466) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._manual_step` | 1434-1450 | `ui/co4e_tab.py` | ghi self._flow_runs, self._run_logs (định tuyến log theo từng flow — trạng thái chia sẻ then chốt); self.manager.start có thể chạm đĩa/spawn agent; self.run_btn.setText cần widget sống | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1468-1484) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._topo_order` | 1452-1457 | `ui/co4e_tab.py` | - | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1486-1491) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._on_manager_event` | 1460-1516 | `ui/co4e_tab.py` | method dài (~57 dòng) gộp nhiều việc: định tuyến sự kiện theo run_id/flow, cập nhật canvas status, ghi self._outputs_for/self._run_logs/self._flow_runs (trạng thái chia sẻ nhiều flow song song), gọi self._append_chat/_append_diff/_append_plan, hiện popup thông báo — nên cân nhắc tách theo loại event | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1494-1550) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._notify_run_finished` | 1518-1539 | `ui/co4e_tab.py` | dựng QMessageBox không chặn — cần QApplication sống | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1552-1573) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_popups` | 1526-1527 | `ui/co4e_tab.py` | khởi tạo lười (hasattr guard) bên trong _notify_run_finished — không thấy gán trong __init__ ở lát này, agent đọc __init__ nên đối chiếu | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1560-1561) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._refresh_runs` | 1541-1582 | `ui/co4e_tab.py` | cập nhật self.runs_table, self.flow_bar, self._sections — chạm nhiều widget cùng lúc | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1575-1616) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._stop_selected_run` | 1584-1590 | `ui/co4e_tab.py` | đọc self.runs_table.currentRow() | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1618-1624) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._delete_selected_run` | 1592-1605 | `ui/co4e_tab.py` | ghi self._flow_runs, self._run_logs — trạng thái chia sẻ per-flow | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1626-1639) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._runs_context_menu` | 1607-1621 | `ui/co4e_tab.py` | dựng QMenu tại vị trí chuột — cần widget sống | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1641-1655) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.set_project` | 1624-1640 | `ui/co4e_tab.py` | ghi self._project_id, self._project_dir (trạng thái workspace chia sẻ, ảnh hưởng _flow_output_root/_out_dir); load_project đọc dữ liệu project (đĩa); gọi self._refresh_ws_folder_btn nếu widget tồn tại | co | - |
| `Co4ETab._flow_output_root` | 1642-1652 | `ui/co4e_tab.py` | đọc self._project_dir, self.ctx.config — logic thuần tính đường dẫn, không tự chạm đĩa (không mkdir/open) | co | - |
| `Co4ETab._refresh_ws_folder_btn` | 1654-1659 | `ui/co4e_tab.py` | self.ws_folder_btn.setText/setToolTip | co | - |
| `Co4ETab._open_workspace_folder` | 1661-1668 | `ui/co4e_tab.py` | mkdir + open_location (mở file explorer hệ điều hành, spawn process) | co | - |
| `Co4ETab._open_run_output_folder` | 1670-1681 | `ui/co4e_tab.py` | kiểm tra path.exists()/mkdir + open_location | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1704-1715) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._rename_selected_run` | 1683-1714 | `ui/co4e_tab.py` | dựng QInputDialog; ghi self._flows, self.flow_bar (tab text), self._wf, self.name_edit — trạng thái chia sẻ giữa danh sách flow và tab đang mở; co4e.save_workflow ghi đĩa | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1717-1748) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_selected_in_background` | 1716-1726 | `ui/co4e_tab.py` | self.manager.start khởi chạy agent nền (ghi output ra đĩa) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1750-1760) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._wf_by_id` | 1728-1736 | `ui/co4e_tab.py` | co4e.get_workflow đọc workflow đã lưu từ đĩa; đọc self._wf | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1762-1770) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._rerun_run_item` | 1738-1749 | `ui/co4e_tab.py` | item là QTableWidgetItem; manager.start khởi chạy agent nền | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1772-1783) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._open_run_from_table` | 1751-1770 | `ui/co4e_tab.py` | gọi self._open_flow(wf), self.canvas.update_node_status — chạm canvas widget và self._wf | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 1785-1804) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab.showEvent` | 1772-1775 | `ui/co4e_tab.py` | override Qt event | co | - |
| `Co4ETab._out_dir` | 1777-1783 | `ui/co4e_tab.py` | mkdir(parents=True); đọc self._wf.name | co | - |
| `Co4ETab._chat_send` | 1786-1812 | `ui/co4e_tab.py` | theo yêu cầu, _chat_send KHÔNG thuộc co4e_chat_view.py dù đọc self.chat_input — ở lại Co4ETab; đọc/ghi self._chat_worker | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1820-1846) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._apply_co4e_routing` | 1814-1849 | `ui/co4e_tab.py` | ghi self._co4e_routed_provider (trạng thái đọc lại trong _run_chat_turn/job); nhánh manual gọi confirm_switch — mở dialog Qt (routing_toggle) nên cần widget sống ở nhánh đó | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1848-1883) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._co4e_routed_provider` | 1819 | `ui/co4e_tab.py` | gán lại mỗi lần gọi _apply_co4e_routing; được đọc bằng getattr(...,'None') ở _run_chat_turn/job — không chắc có init trong __init__ (nằm ngoài lát này) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1114; 1853) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._extract_agent_directive` | 1851-1857 | `ui/co4e_tab.py` | logic regex thuần, dễ test độc lập | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1885-1891) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._resolve_agent` | 1859-1867 | `ui/co4e_tab.py` | duyệt BUILTIN_AGENTS + co4e.list_custom_agents() (custom agents có thể đọc đĩa nhưng bản thân hàm chỉ gọi list) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1893-1901) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_chat_turn` | 1869-1940 | `ui/co4e_tab.py` | method dài (~72 dòng) gộp: build prompt, định nghĩa 4 closure lồng nhau (job/on_event/done/failed), khởi AgentWorker — nên tách; theo yêu cầu KHÔNG đưa job()/AgentWorker sang co4e_chat_view.py; đọc/ghi self.chat_log, self._wf, self._chat_worker (trạng thái chia sẻ) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1903-1974) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_chat_turn.job` | 1883-1912 | `ui/co4e_tab.py` | closure lồng trong _run_chat_turn, chạy trong AgentWorker thread; gọi run_cowork → gọi provider AI qua mạng; theo yêu cầu ở lại Co4ETab cùng _chat_send | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1917-1946) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_chat_turn.job._emit` | 1894-1901 | `ui/co4e_tab.py` | helper lồng bên trong job(), chuyển tiếp event streaming sang worker.emit_event | chua | BANG CU BO SOT: khong co dong nao cho symbol nay trong bang cu (363 dong) du no ro rang ton tai trong pham vi da quet -- co the do agent quet truoc bo lot, hoac day la ten sinh ra tu buoc gop lat cua ban do nay (vd ten method suy doan/tam). |
| `Co4ETab._run_chat_turn.on_event` | 1914-1920 | `ui/co4e_tab.py` | closure cập nhật assistant.set_markdown/log.scroll_to_bottom — cần widget sống; gọi self._append_plan | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1948-1954) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_chat_turn.done` | 1922-1928 | `ui/co4e_tab.py` | ghi self._chat_worker=None, gọi self._apply_usage — chạm self._flow_usage | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1956-1962) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._run_chat_turn.failed` | 1930-1933 | `ui/co4e_tab.py` | ghi self._chat_worker=None, gọi self._append_chat | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1964-1967) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._append_chat` | 1942-1957 | `ui/co4e_tab.py` | theo yêu cầu, _append_chat KHÔNG thuộc co4e_chat_view.py — dùng self.chat_log mặc định, business logic per-flow ở lại Co4ETab | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1976-1991) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._fmt_usage` | 1960-1967 | `ui/co4e_tab.py` | logic thuần định dạng chuỗi + tra bảng giá từ self.ctx.config.data — test được không cần Qt | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 1994-2001) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._apply_usage` | 1969-1986 | `ui/co4e_tab.py` | ghi self._flow_usage (tổng usage theo từng flow — trạng thái chia sẻ với composer label usage-total ở co4e_chat_view.py); gọi bub.add_usage cần widget bubble sống | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 2003-2020) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._refresh_usage_total` | 1988-2003 | `ui/co4e_tab.py` | đọc self._flow_usage, self._wf; ghi self._usage_total_lbl.setText — label này được dựng trong co4e_chat_view.py (composer) nên đây là điểm nối trạng thái chia sẻ giữa 2 file | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 2022-2037) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._append_diff` | 2005-2009 | `ui/co4e_tab.py` | theo yêu cầu KHÔNG thuộc co4e_chat_view.py — ở lại Co4ETab | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 2039-2043) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._append_plan` | 2011-2022 | `ui/co4e_tab.py` | theo yêu cầu KHÔNG thuộc co4e_chat_view.py — dùng log._co4e_plan_bubble (state gắn trên đối tượng ChatView, không phải self) | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 2045-2056) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `Co4ETab._retranslate` | 2025-2045 | `ui/co4e_tab.py` | duyệt self._sections (trạng thái chia sẻ toàn tab) và setText hàng loạt widget nhiều khu vực khác nhau (runs, sidebar, header) — cắt ngang nhiều nhóm chức năng khác nhau nên khó tách gọn | co | - |
| `_html_escape` | 2048-2049 | `ui/co4e_tab.py` | hàm module-level, tiện ích thuần chuỗi, không thuộc riêng chat_view | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_chat_view.py` (dong 2082-2083) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
| `_qcolor` | 2052-2054 | `ui/co4e_tab.py` | QColor dùng như kiểu giá trị, không cần QApplication sống | co | BANG CU KHAC: bang cu xep vao `presentation/co4e/co4e_run_control_widget.py` (dong 2086-2088) nhung theo mo ta dich cua lan quet nay -> quyet dinh o day = `ui/co4e_tab.py`. |
## Chỗ thấy khác tài liệu — cần người quyết
Không có symbol nào trong 220 symbol thô có note bắt đầu bằng `khac tai lieu:` — mục này để trống theo đúng yêu cầu tự kiểm (không có gì cần liệt kê).
@@ -0,0 +1,123 @@
{
"scope": "StepConfigPanel (ui/co4e_config_panel.py, dong 1-528)",
"source_file": "ui/co4e_config_panel.py",
"symbols": [
{
"symbol": "_SECTION_ANIM_MS",
"source_lines": "27",
"target_file": "presentation/co4e/step_config_section.py",
"note": "hang so animation cho _add_section"
},
{
"symbol": "_SectionHeader",
"source_lines": "30-52",
"target_file": "presentation/co4e/step_config_section.py",
"note": "QLabel clickable, khung UI dung chung, khong co hanh vi nghiep vu rieng"
},
{
"symbol": "_add_section",
"source_lines": "55-130",
"target_file": "presentation/co4e/step_config_section.py",
"note": "khung section gap/mo dung chung cho 4 nhom truong cua StepConfigPanel"
},
{
"symbol": "StepConfigPanel (Signal + __init__)",
"source_lines": "133-313",
"target_file": "presentation/co4e/node_property_panel.py",
"note": "4 Signal (changed/run_node/run_from/delete_node) + dung toan bo form"
},
{
"symbol": "StepConfigPanel.load_step",
"source_lines": "316-354",
"target_file": "presentation/co4e/node_property_panel.py",
"note": "nap Step vao form"
},
{
"symbol": "StepConfigPanel.clear_step",
"source_lines": "356-359",
"target_file": "presentation/co4e/node_property_panel.py",
"note": "xoa state, tat panel"
},
{
"symbol": "StepConfigPanel._on_edit",
"source_lines": "362-378",
"target_file": "presentation/co4e/node_property_panel.py",
"note": "ghi field UI nguoc vao Step"
},
{
"symbol": "StepConfigPanel._available_agent_names",
"source_lines": "380-390",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "staticmethod, chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._add_subagent",
"source_lines": "392-408",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._edit_subagent",
"source_lines": "410-428",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._del_subagent",
"source_lines": "430-437",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._add_attachment",
"source_lines": "439-453",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._del_attachment",
"source_lines": "455-462",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin"
},
{
"symbol": "StepConfigPanel._ai_draft",
"source_lines": "464-498",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin; dung AgentWorker that"
},
{
"symbol": "StepConfigPanel._load_models",
"source_lines": "500-528",
"target_file": "presentation/co4e/node_property_actions_mixin.py",
"note": "chuyen vao mixin _StepConfigActionsMixin; dung AgentWorker that"
}
],
"old_file_after_split": {
"file": "ui/co4e_config_panel.py",
"content": "module docstring (sua, van tieng Anh) + import lai StepConfigPanel tu presentation/co4e/node_property_panel.py + __all__",
"lines": 14
},
"new_files": [
{"file": "presentation/co4e/step_config_section.py", "lines": 134},
{"file": "presentation/co4e/node_property_actions_mixin.py", "lines": 202},
{"file": "presentation/co4e/node_property_panel.py", "lines": 293}
],
"inheritance": {
"class": "StepConfigPanel",
"bases": ["_StepConfigActionsMixin", "QScrollArea"],
"mandatory_order": false,
"reason": "khong co method nao cua _StepConfigActionsMixin trung ten voi QScrollArea (khac Co4ECanvas voi paintEvent/mousePressEvent), nen thu tu ke thua khong anh huong hanh vi; giu mixin-truoc chi de nhat quan quy uoc"
},
"deliberate_unused_import_kept": {
"name": "PROVIDER_LABELS",
"source_line": 21,
"target_file": "presentation/co4e/node_property_panel.py",
"reason": "khong dung o dau trong ban goc (da xac minh bang grep); giu nguyen de dung pham vi chi doi cho, khong don dep import thua"
},
"test_patch_adaptation": {
"file": "tests/characterization/test_node_property_panel.py",
"what_changed": "case CASE_ADD_SUBAGENT_EMPTY_NAMES_USES_GETTEXT_QUIRK_OK doi tu StepConfigPanel.__dict__[\"_available_agent_names\"] (luu roi gan lai) sang del StepConfigPanel._available_agent_names (xoa override de roi ve lai method ke thua tu mixin)",
"why": "sau khi _available_agent_names chuyen vao _StepConfigActionsMixin, no khong con nam truc tiep trong StepConfigPanel.__dict__ nen loi KeyError; day la thay doi CACH patch/restore trong test, KHONG doi assert/hanh vi nao duoc kiem tra"
}
}
@@ -0,0 +1,102 @@
# Bản đồ tách `StepConfigPanel` (`ui/co4e_config_panel.py` → `presentation/co4e/`)
- **Phạm vi lượt này:** chỉ `StepConfigPanel` (nguyên bản dòng 1-528 của
`ui/co4e_config_panel.py`). Không đụng file nào khác thuộc làn N1
(`ui/co4e_tab.py`, `ui/co4e_canvas.py`, `docs/architecture/co4e-split-map.md`/`.json`).
- **Lý do phải tách thêm, dù chỉ 1 class:** `StepConfigPanel` một mình đã 396
dòng (133-528); cộng thêm module docstring + khối import của một file riêng
sẽ vượt trần 400 dòng (CASAN Check 2). Giải pháp: cắt-dán (không viết lại
logic) thành 3 file theo trách nhiệm.
## File đích
| symbol | dòng gốc | file đích | ghi chú |
|---|---|---|---|
| `_SECTION_ANIM_MS` | 27 | `presentation/co4e/step_config_section.py` | hằng số dùng bởi `_add_section` |
| `_SectionHeader` | 30-52 | `presentation/co4e/step_config_section.py` | `QLabel` clickable, không có hành vi nghiệp vụ riêng |
| `_add_section` | 55-130 | `presentation/co4e/step_config_section.py` | khung ▶/▼ dùng chung cho 4 nhóm trường của `StepConfigPanel`; không đọc/ghi state của panel |
| `StepConfigPanel` (Signal + `__init__`) | 133-313 | `presentation/co4e/node_property_panel.py` | 4 Signal (`changed`/`run_node`/`run_from`/`delete_node`) + dựng toàn bộ form |
| `StepConfigPanel.load_step` | 316-354 | `presentation/co4e/node_property_panel.py` | nạp `Step` vào form |
| `StepConfigPanel.clear_step` | 356-359 | `presentation/co4e/node_property_panel.py` | xoá state, tắt panel |
| `StepConfigPanel._on_edit` | 362-378 | `presentation/co4e/node_property_panel.py` | ghi field UI ngược vào `Step` |
| `StepConfigPanel._available_agent_names` | 380-390 | `presentation/co4e/node_property_actions_mixin.py` (`_StepConfigActionsMixin`) | staticmethod, dùng bởi `_add_subagent`/`_edit_subagent` |
| `StepConfigPanel._add_subagent` | 392-408 | `presentation/co4e/node_property_actions_mixin.py` | |
| `StepConfigPanel._edit_subagent` | 410-428 | `presentation/co4e/node_property_actions_mixin.py` | |
| `StepConfigPanel._del_subagent` | 430-437 | `presentation/co4e/node_property_actions_mixin.py` | |
| `StepConfigPanel._add_attachment` | 439-453 | `presentation/co4e/node_property_actions_mixin.py` | |
| `StepConfigPanel._del_attachment` | 455-462 | `presentation/co4e/node_property_actions_mixin.py` | |
| `StepConfigPanel._ai_draft` | 464-498 | `presentation/co4e/node_property_actions_mixin.py` | dùng `AgentWorker` thật (không mock trong `__init__`) |
| `StepConfigPanel._load_models` | 500-528 | `presentation/co4e/node_property_actions_mixin.py` | dùng `AgentWorker` thật |
## Cách ghép lại: mixin + đa kế thừa
`node_property_panel.py`:
```python
class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
...
```
`_StepConfigActionsMixin` là mixin THUẦN — không `__init__` riêng, chỉ đọc/ghi
state có sẵn trên `self` do `StepConfigPanel.__init__` định nghĩa
(`self._step`, `self._node_id`, `self.ctx`, `self.sub_list`, `self.attach_list`,
`self.instructions_edit`, `self.gen_btn`, `self.model_combo`,
`self.load_models_btn`).
Khác với bước `co4e_canvas_widget.py` (Co4ECanvas override nhiều method Qt như
`paintEvent`/`mousePressEvent`, nên thứ tự mixin-trước-base là **bắt buộc** để
MRO ưu tiên override của mixin): ở đây **không có method nào của
`_StepConfigActionsMixin` trùng tên với `QScrollArea`**, nên thứ tự kế thừa
không ảnh hưởng hành vi. Giữ thứ tự mixin-trước chỉ để nhất quán quy ước, không
phải yêu cầu kỹ thuật bắt buộc.
## Import thừa cố ý giữ nguyên
`PROVIDER_LABELS` (nguyên bản dòng 21, `from ..config import PROVIDER_LABELS`)
không được dùng ở đâu trong toàn bộ `ui/co4e_config_panel.py` gốc (đã xác minh
bằng grep). Vẫn giữ nguyên import này trong `node_property_panel.py` (chỉ đổi
số cấp `..` → `...`), không xoá, để đúng phạm vi "chỉ dời chỗ" của lượt tách
này — xoá một import "thừa" là một quyết định dọn dẹp ngoài phạm vi được giao.
## Thay đổi comment/test ngoài phạm vi "chỉ dời chỗ" (ghi riêng, không lẫn vào phần move)
1. **Docstring module của 3 file mới** (`step_config_section.py`,
`node_property_actions_mixin.py`, `node_property_panel.py`) — viết MỚI hoàn
toàn bằng tiếng Việt theo quy ước CASAN cho file mới trong `presentation/`
(mẫu `infrastructure/persistence/json/atomic_json_file.py`). Đây không phải
sửa một comment cũ bị sai do dời chỗ — module docstring nguyên bản (dòng
1-9 của `ui/co4e_config_panel.py`) mô tả cả file cũ (đã bị chia làm 3), nên
mỗi file mới cần một docstring kiến trúc riêng thay vì copy y hệt bản gốc.
2. **`ui/co4e_config_panel.py`** (file cũ) — docstring được viết lại (vẫn
tiếng Anh, khớp quy ước "sửa file cũ tiếng Anh thì giữ tiếng Anh") để nói rõ
`StepConfigPanel` đã dời đi đâu, thay vì mô tả hành vi như thể class còn
định nghĩa tại chỗ — comment cũ sẽ SAI (nói rằng lớp "ở đây" trong khi
không còn) nếu giữ nguyên.
3. **`tests/characterization/test_node_property_panel.py`** (dòng ~296-307
nguyên bản) — SỬA kỹ thuật patch/restore của case
`CASE_ADD_SUBAGENT_EMPTY_NAMES_USES_GETTEXT_QUIRK_OK`, không đổi bất kỳ
assert/hành vi nào. Bản gốc dùng
`StepConfigPanel.__dict__["_available_agent_names"]` để lưu lại method gốc
trước khi monkey-patch, rồi gán lại y hệt lúc restore. Sau khi
`_available_agent_names` chuyển vào `_StepConfigActionsMixin` (mixin riêng),
nó không còn nằm trong `StepConfigPanel.__dict__` (chỉ được kế thừa qua
MRO) → `KeyError`. Thay bằng: gán đè trực tiếp lên `StepConfigPanel` (vẫn
shadow đúng như cũ), và khi xong dùng `del StepConfigPanel._available_agent_names`
để nó rơi trở lại đúng method kế thừa từ mixin — hành vi quan sát được của
test (các assert `sub_agents`) giữ nguyên 100%, chỉ đổi CÁCH lưu/khôi phục
attribute bị monkey-patch. Đây là hệ quả tất yếu của yêu cầu tách mixin
trong lượt này (test được viết khi class còn nguyên khối), không phải sửa
test để che một thay đổi hành vi.
## Xác minh
- `.venv/Scripts/python.exe tools/check_co4e.py` — chạy TRƯỚC và SAU khi sửa,
output giống hệt nhau cả 2 lần (`KET QUA: Co4E sap xep lai, khong mat control nao`).
- `.venv/Scripts/python.exe -m pytest tests/characterization/test_node_property_panel.py -q`
— `1 passed` cả trước (đo trên code gốc, class còn ở `ui/co4e_config_panel.py`)
lẫn sau khi tách.
- `.venv/Scripts/python.exe -m pytest tests -q --tb=short -rf --continue-on-collection-errors`
— `287 passed, 1 skipped` sau khi tách (không có test nào khác vỡ vì import
`StepConfigPanel` từ `ui/co4e_config_panel.py`).
- AST-scan `domain/`+`application/` cho import PySide6/PyQt: `KHONG CO`.
- Số dòng file mới: `node_property_panel.py` 293, `node_property_actions_mixin.py`
202, `step_config_section.py` 134 — cả 3 đều ≤ 400.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,238 @@
# Bản đồ tách file — Run Control (trang Runs / Flow Status)
Gộp 215 symbol thô từ 3 agent quét song song trên `ui/co4e_tab.py`, còn lại **214 dòng** sau khi gộp 1 trùng lặp thật (`Co4ETab._reload_sidebar` dòng 685, xem bên dưới).
- File đích của lane run-control: `presentation/co4e/co4e_run_control_widget.py` — **18 symbol**.
- Phần còn lại của container: `ui/co4e_tab.py` — **173 symbol**.
- Thuộc lane/file khác (ngoài phạm vi run-control, chỉ ghi lại để tham khảo): **23 symbol** (application/workflows/co4e_workflow_service.py, presentation/co4e/agent_list_panel.py, presentation/co4e/skills_list_panel.py, presentation/co4e/co4e_canvas_widget.py).
- Note bắt đầu bằng `khac tai lieu:` tìm thấy trong dữ liệu thô: **0**.
## Phát hiện quan trọng nhất từ việc đối chiếu với bảng cũ
1. **Đường dẫn `co4e_tab.py` trong bảng cũ sai.** Bảng cũ (`docs/architecture/co4e-split-map.json`) dùng `target_file="presentation/co4e/co4e_tab.py"` cho phần thân lớp `Co4ETab` còn lại, nhưng file đó ở repo hiện tại chỉ là factory `build_co4e_tab()` dài 53 dòng (bọc nguyên `Co4ETab` cũ 1:1, xem docstring của nó) — KHÔNG phải nơi lớp `Co4ETab` thật sự sống. Lớp đó vẫn đang ở `ui/co4e_tab.py`. Bảng này đã tự quy đổi mọi so sánh trước khi kết luận lệch.
2. **Phạm vi `co4e_run_control_widget.py` đã bị thu hẹp so với bảng cũ.** Bảng cũ coi 'run control' là toàn bộ chuỗi: bảng Runs + logic thực thi run (start/stop/manual-mode/mode toolbar/event routing/popup) + sidebar quick-list các run gần đây. Lần quét 3-agent hiện tại (theo mô tả đích lặp lại trong nhiều ghi chú riêng lẻ) chỉ còn coi `co4e_run_control_widget.py` là **trang Runs/Flow Status**: bảng `runs_table` + các nút hành động trên từng dòng (stop/rename/delete/clear/mở thư mục) + nút quay lại + tiêu đề. Logic thực thi run, toolbar mode/run, và sidebar quick-list quay lại ở lại `ui/co4e_tab.py`. Đây là khác biệt lớn nhất — ảnh hưởng tới 34 dòng bên dưới (đánh dấu ở cột cuối).
3. **Bảng cũ không nhất quán giữa alias của Agent panel và Skills panel.** `ag_new_btn`/`agent_list`/`ag_edit_btn`/`ag_del_btn` (alias trỏ vào `AgentListPanel` đã tách) được bảng cũ xếp vào `presentation/co4e/agent_list_panel.py`, nhưng `sk_manage_btn`/`skill_list` (alias trỏ vào `SkillsListPanel`, cùng bản chất) lại bị xếp vào `co4e_tab.py`. Bảng này chọn xử lý đồng nhất — coi cả hai cặp alias đều thuộc file panel tương ứng.
4. **Bảng cũ bỏ sót 2 symbol:** `Co4ETab.status_message` (Signal cấp lớp) và `Co4ETab._agent_panel` (instance `AgentListPanel` do container giữ) không có dòng nào trong bảng cũ dù nằm trong phạm vi đã quét.
## Bảng đầy đủ (sắp theo số dòng)
| symbol | dòng | file đích | lý do | có trong bảng cũ chưa | chỗ nào thấy bảng cũ sai |
|---|---|---|---|---|---|
| `_PLAN_GLYPH` | 46-47 | `ui/co4e_tab.py` | module-level dict constant, không phải self.<attr> -- QUYET DINH: glyph dùng bởi _fmt_plan cho bong bóng 'plan' trong CHAT, không phải bảng Runs; bảng cũ xếp nhầm vào co4e_run_control_widget.py | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 45-46) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `_fmt_plan` | 50-59 | `ui/co4e_tab.py` | helper format cho _append_plan (chat), không đụng runs_table; bảng cũ xếp nhầm vào co4e_run_control_widget.py | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 49-58) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `_skill_names` | 62-66 | `ui/co4e_tab.py` | gọi skills_mod.list_skills()/builtin_skills() — có thể chạm đĩa qua core.skills -- QUYET DINH: helper autocomplete cho _ChatInput — thuộc lane co4e_chat_view.py (chưa tồn tại), ngoài phạm vi lane run-control nên giữ nguyên vị trí hiện tại | co | - |
| `_agent_names` | 69-72 | `ui/co4e_tab.py` | gọi co4e.list_custom_agents() — chạm đĩa qua core.co4e -- QUYET DINH: cùng lý do với _skill_names — autocomplete /agent trong chat | co | - |
| `_EqualTabBar` | 75-95 | `ui/co4e_tab.py` | helper QTabBar cho sidebar icon-tabs — không liên quan Flow Status -- QUYET DINH: QTabBar tiện ích cho sidebar icon-tabs, không liên quan Runs | co | - |
| `_EqualTabBar._GAP` | 81 | `ui/co4e_tab.py` | hằng số nội bộ của _EqualTabBar | co | - |
| `_EqualTabBar.tabSizeHint` | 83-91 | `ui/co4e_tab.py` | - | co | - |
| `_EqualTabBar.resizeEvent` | 93-95 | `ui/co4e_tab.py` | - | co | - |
| `_PaletteList` | 98-120 | `ui/co4e_tab.py` | list kéo-thả vào canvas cho Workflows/Agents/Skills palette — không phải Runs -- QUYET DINH: list kéo-thả cho palette Workflows/Agents/Skills, không phải Runs | co | - |
| `_PaletteList.__init__` | 103-107 | `ui/co4e_tab.py` | - | co | - |
| `_PaletteList._payload_role` | 105 | `ui/co4e_tab.py` | - | co | - |
| `_PaletteList.startDrag` | 109-120 | `ui/co4e_tab.py` | - | co | - |
| `_directive_token` | 123-135 | `ui/co4e_tab.py` | logic thuần regex cho autocomplete /skill /agent trong chat — test được không cần Qt -- QUYET DINH: regex thuần cho autocomplete /skill /agent — lane co4e_chat_view.py (chưa tồn tại), giữ nguyên | co | - |
| `_ChatInput` | 138-227 | `ui/co4e_tab.py` | ô chat với popup autocomplete — không liên quan Flow Status -- QUYET DINH: ô nhập chat với popup autocomplete — lane co4e_chat_view.py (chưa tồn tại), giữ nguyên | co | - |
| `_ChatInput.submit` | 142 | `ui/co4e_tab.py` | Signal khai báo ở cấp lớp -- QUYET DINH: Signal của _ChatInput — đi cùng class | chua | - |
| `_ChatInput.__init__` | 144-152 | `ui/co4e_tab.py` | - | co | - |
| `_ChatInput._popup` | 146 | `ui/co4e_tab.py` | - | co | - |
| `_ChatInput._maybe_popup` | 154-179 | `ui/co4e_tab.py` | gọi _skill_names/_agent_names (chạm đĩa gián tiếp) và định vị popup bằng tọa độ màn hình | co | - |
| `_ChatInput._add_row` | 181-185 | `ui/co4e_tab.py` | - | co | - |
| `_ChatInput._accept` | 187-200 | `ui/co4e_tab.py` | - | co | - |
| `_ChatInput.focusOutEvent` | 202-205 | `ui/co4e_tab.py` | - | co | - |
| `_ChatInput.keyPressEvent` | 207-227 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab` | 230-700 | `ui/co4e_tab.py` | cắt ngang lát — cần agent gộp đối chiếu (thân lớp trải dài quá dòng 700, đây chỉ là phần đầu) -- QUYET DINH: lớp container chính — phần còn lại sau khi các widget con (canvas/node-property/agent/skills/run-control/chat) đã tách | co | - |
| `Co4ETab.status_message` | 231 | `ui/co4e_tab.py` | Signal khai báo ở cấp lớp -- QUYET DINH: Signal cấp lớp của chính Co4ETab; KHÔNG có trong bảng cũ (thiếu sót ở đó) | chua | BANG CU BO SOT: khong co dong nao cho symbol nay du no ro rang ton tai trong pham vi da quet (367 symbol tho cua bang cu) -- co the do agent quet truoc bo lot. |
| `Co4ETab.__init__` | 233-305 | `ui/co4e_tab.py` | gộp nhiều việc: khởi state run-per-flow, dựng splitter 3 cột, wiring StepConfigPanel, narrow-guard, rồi mở flow đầu tiên — biên độ rủi ro cao khi tách vì đụng gần hết thuộc tính self chia sẻ toàn tab -- QUYET DINH: constructor container — sẽ đổi để dựng Co4ERunControlWidget thay vì tự vẽ bảng Runs | co | - |
| `Co4ETab.ctx` | 235 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._wf` | 236 | `ui/co4e_tab.py` | trạng thái chia sẻ toàn tab — workflow đang hiển thị trên canvas, đọc/ghi bởi rất nhiều method (flow tabs, run, sidebar, config) -- QUYET DINH: trạng thái trung tâm toàn tab, container giữ | co | - |
| `Co4ETab._chat_worker` | 237 | `ui/co4e_tab.py` | AgentWorker của chat — lane co4e_chat_view.py chưa tồn tại, giữ nguyên | co | - |
| `Co4ETab.manager` | 239 | `ui/co4e_tab.py` | Co4ERunManager dùng chung giữa canvas (mirror trạng thái node) và trang Runs (self.runs_table — định nghĩa ngoài dòng 700, có thể ở co4e_run_control_widget) — điểm nối quan trọng giữa hai lát -- QUYET DINH: Co4ERunManager dùng chung giữa canvas, chat VÀ bảng Runs — quyết định: container SỞ HỮU, co4e_run_control_widget.py nhận qua constructor/callback (dependency injection) thay vì tự tạo. Bảng cũ xếp thẳng vào co4e_run_control_widget.py dù chính ghi chú của nó gọi đây là 'điểm nối' — coi là quá vội | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 238) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._flow_runs` | 244 | `ui/co4e_tab.py` | trạng thái chia sẻ wf_id -> active run id, đọc/ghi bởi _open_flow, _close_flow_tab, _cur_run_id, _reflect_active_run -- QUYET DINH: dict wf_id->run id, ghi bởi _open_flow/_close_flow_tab/_start_canvas_run (đều ở co4e_tab.py) — container giữ, run-control đọc/ghi qua callback. Bảng cũ xếp vào co4e_run_control_widget.py — không khớp nơi ghi chính | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 243) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._run_logs` | 245 | `ui/co4e_tab.py` | map run_id->ChatView (thuộc lane chat), ghi bởi _manual_step/_start_canvas_run ở co4e_tab.py — container giữ | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 244) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._flow_outputs` | 246 | `application/workflows/co4e_workflow_service.py` | đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi lane run-control. Hiện tại vật lý vẫn còn ở ui/co4e_tab.py dòng 246 chờ lane đó dọn | co | - |
| `Co4ETab._flow_usage` | 249 | `ui/co4e_tab.py` | usage token/cost hiển thị ở header CHAT (Messages), không phải bảng Runs — bảng cũ xếp nhầm vào co4e_run_control_widget.py | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 248) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._project_id` | 250 | `ui/co4e_tab.py` | workspace hiện chọn — dùng chung bởi chat (_out_dir) và nút mở-thư-mục của Runs; container giữ, expose qua callback | co | - |
| `Co4ETab._project_dir` | 251 | `ui/co4e_tab.py` | cùng lý do với _project_id | co | - |
| `Co4ETab._manual_active` | 253 | `ui/co4e_tab.py` | trạng thái MODE THỦ CÔNG — thuộc nhóm run-execution, mô tả đích lane này loại trừ mode/run toolbar khỏi co4e_run_control_widget.py. Bảng cũ xếp vào co4e_run_control_widget.py — mâu thuẫn trực tiếp với phạm vi hiện tại | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 252) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_order` | 254 | `ui/co4e_tab.py` | cùng nhóm với _manual_active — xem lý do ở đó | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 253) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_idx` | 255 | `ui/co4e_tab.py` | cùng nhóm với _manual_active — xem lý do ở đó | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 254) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._flows` | 258 | `ui/co4e_tab.py` | trạng thái chia sẻ danh sách flow đang mở (browser-style tabs) — đọc/ghi bởi toàn bộ nhóm _open_flow/_close_flow_tab/_on_flow_tab_changed -- QUYET DINH: danh sách flow-tab kiểu browser, không phải Runs | co | - |
| `Co4ETab._active_flow_idx` | 259 | `ui/co4e_tab.py` | cùng nhóm trạng thái chia sẻ với _flows -- QUYET DINH: cùng nhóm với _flows | co | - |
| `Co4ETab._split` | 262 | `ui/co4e_tab.py` | splitter 3 cột của cả tab | co | - |
| `Co4ETab.config` | 269 | `ui/co4e_tab.py` | container giữ tham chiếu StepConfigPanel (đã tách ở node_property_panel.py, file cấm sửa của lane khác) — cùng khuôn mẫu với _agent_panel/_skills_panel: instance do container tạo/giữ, nội dung panel ở file riêng. Bảng cũ xếp thẳng dòng này vào node_property_panel.py — không nhất quán với cách nó xử lý _agent_panel | co | - |
| `Co4ETab._config_collapsed` | 275 | `ui/co4e_tab.py` | trạng thái thu/phóng của KHUNG bọc quanh panel (co4e_tab.py), không phải nội dung panel | co | - |
| `Co4ETab._config_expanded_w` | 276 | `ui/co4e_tab.py` | cùng lý do với _config_collapsed | co | - |
| `Co4ETab._narrow_guard` | 281 | `ui/co4e_tab.py` | guard bố cục hẹp của cả tab | co | - |
| `Co4ETab._open_flow` | 308-339 | `ui/co4e_tab.py` | đọc/ghi self._flows, self._active_flow_idx, self.flow_bar — quản lý flow tab kiểu browser, không phải trang Runs -- QUYET DINH: quản lý flow-tab kiểu browser | co | - |
| `Co4ETab._close_other_flows` | 341-356 | `ui/co4e_tab.py` | đọc/ghi self._flows, self._active_flow_idx, self.flow_bar | co | - |
| `Co4ETab._show_runs` | 358-368 | `ui/co4e_tab.py` | chuyển center_stack giữa flow editor và trang Runs; gọi bởi self.runs_btn (định nghĩa ngoài dòng 700, thuộc toolbar) và runs_more_btn (sidebar) — không thao tác trực tiếp runs_table nên không chắc thuộc co4e_run_control_widget hay ở lại co4e_tab.py làm điều phối trang -- QUYET DINH: điều phối chuyển trang center_stack giữa flow editor và trang Runs — container sở hữu center_stack; sẽ gọi API show()/hide() hoặc setCurrentWidget trên Co4ERunControlWidget thay vì tự vẽ | co | - |
| `Co4ETab._on_flow_tab_changed` | 370-386 | `ui/co4e_tab.py` | đọc/ghi self._active_flow_idx, self.center_stack (self.center_stack định nghĩa ngoài dòng 700) | co | - |
| `Co4ETab._sync_runs_toggle` | 388-395 | `ui/co4e_tab.py` | dùng getattr(self, 'runs_btn', None) vì runs_btn (toolbar, ngoài dòng 700) có thể chưa tồn tại — đồng bộ trạng thái toggle của trang Runs -- QUYET DINH: đồng bộ nút toggle runs_btn ở toolbar (thuộc co4e_tab.py, KHÔNG phải trang Runs) | co | - |
| `Co4ETab._add_tab_close_button` | 397-407 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._close_flow_tab_button` | 409-413 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._close_flow_tab` | 415-443 | `ui/co4e_tab.py` | đọc/ghi self._flow_runs, self._run_logs, self._flows, self._active_flow_idx, self.run_btn (định nghĩa ngoài dòng 700) — nhiều trạng thái chia sẻ chạm cùng lúc | co | - |
| `Co4ETab._sync_active_flow_tab_text` | 445-448 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._reflect_active_run` | 450-458 | `ui/co4e_tab.py` | đọc self.manager.all_runs(), ghi self._flow_runs, gọi self.canvas.update_node_status — cầu nối giữa run manager (chia sẻ với trang Runs) và canvas -- QUYET DINH: cầu nối manager -> canvas (update_node_status trên canvas thuộc co4e_tab.py) — đi cùng nhóm thực thi run, không phải bảng Runs | co | - |
| `Co4ETab._cur_run_id` | 461-474 | `ui/co4e_tab.py` | logic thuần: đọc self._wf, self._flow_runs, self.manager.get() — test được không cần Qt -- QUYET DINH: tra cứu run đang chạy CỦA FLOW HIỆN TẠI, dùng bởi _reflect_active_run (canvas mirror, co4e_tab.py) — không đụng runs_table. Bảng cũ xếp vào co4e_run_control_widget.py — không khớp nơi dùng chính | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 460-473) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._outputs_for` | 476-479 | `application/workflows/co4e_workflow_service.py` | logic thuần dict, test được không cần Qt -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ) cho cặp _flow_outputs/_outputs_for; ngoài phạm vi lane run-control | co | - |
| `Co4ETab._update_run_btn` | 481-483 | `ui/co4e_tab.py` | thuộc nhóm run toolbar (self.run_btn) — theo mô tả target, co4e_run_control_widget KHÔNG bao gồm mode/run toolbar nên method này không nên vào đó -- QUYET DINH: nút Run của toolbar mode/run — mô tả đích loại trừ nhóm này khỏi co4e_run_control_widget.py; bảng cũ xếp vào đó — mâu thuẫn với phạm vi hiện tại | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 480-482) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._build_sidebar` | 486-599 | `ui/co4e_tab.py` | method dài >80 dòng, gộp nhiều việc không liên quan nhau: dựng section Workflows (list + edit/dup/del/run-bg), section Agents (AgentListPanel wiring), section Skills (SkillsListPanel wiring), section Runs sidebar quick-list, và lắp splitter dọc side_split — nên tách nhỏ thêm theo từng section -- QUYET DINH: dựng toàn bộ sidebar (Workflows/Agents/Skills/Runs quick-list) | co | - |
| `Co4ETab._sections` | 494 | `ui/co4e_tab.py` | dict trạng thái chia sẻ cho các section sidebar (fold/unfold) — đọc/ghi bởi _section, _fold_section, _sync_section_arrow | co | - |
| `Co4ETab.sidebar` | 495 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.side_split` | 499 | `ui/co4e_tab.py` | - | co | - |
| `_build_sidebar._Col` | 504-512 | `ui/co4e_tab.py` | class cục bộ (locals) bên trong _build_sidebar — adapter cho side_split, không phải class module-level -- QUYET DINH: class cục bộ, adapter cho side_split | co | - |
| `_Col.__init__` | 507-508 | `ui/co4e_tab.py` | - | co | - |
| `_Col.addWidget` | 510-512 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_new_btn` | 517 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_list` | 528 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_edit_btn` | 535 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_dup_btn` | 536 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_del_btn` | 537 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.wf_runbg_btn` | 544 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._agent_panel` | 556 | `ui/co4e_tab.py` | AgentListPanel — panel đã tách sẵn ở presentation/co4e/agent_list_panel.py (ngoài phạm vi lát này) -- QUYET DINH: container giữ instance AgentListPanel (đã tách sẵn) — KHÔNG có trong bảng cũ (thiếu sót ở đó, ag_new_btn/agent_list/ag_edit_btn/ag_del_btn có dòng nhưng _agent_panel thì không) | chua | BANG CU BO SOT: khong co dong nao cho symbol nay du no ro rang ton tai trong pham vi da quet (367 symbol tho cua bang cu) -- co the do agent quet truoc bo lot. |
| `Co4ETab.ag_new_btn` | 557 | `presentation/co4e/agent_list_panel.py` | alias trỏ tới self._agent_panel.new_btn — widget thật nằm ở agent_list_panel.py | co | - |
| `Co4ETab.agent_list` | 559 | `presentation/co4e/agent_list_panel.py` | alias trỏ tới self._agent_panel.list_widget | co | - |
| `Co4ETab.ag_edit_btn` | 560 | `presentation/co4e/agent_list_panel.py` | alias trỏ tới self._agent_panel.edit_btn | co | - |
| `Co4ETab.ag_del_btn` | 562 | `presentation/co4e/agent_list_panel.py` | alias trỏ tới self._agent_panel.del_btn | co | - |
| `Co4ETab._skills_panel` | 571 | `ui/co4e_tab.py` | SkillsListPanel — panel đã tách sẵn ở presentation/co4e/skills_list_panel.py (ngoài phạm vi lát này) -- QUYET DINH: container giữ instance SkillsListPanel (đã tách sẵn) — khớp bảng cũ | co | - |
| `Co4ETab.sk_manage_btn` | 572 | `presentation/co4e/skills_list_panel.py` | alias trỏ tới self._skills_panel.manage_btn — cùng bản chất với ag_new_btn ở trên. Bảng cũ xếp dòng này (và skill_list) vào co4e_tab.py trong khi ag_* tương ứng lại xếp vào agent_list_panel.py — KHÔNG NHẤT QUÁN giữa 2 cặp alias giống hệt nhau trong cùng bảng cũ; ở đây chọn xử lý đồng nhất với ag_* | co | BANG CU KHONG NHAT QUAN: xep Co4ETab.sk_manage_btn vao ui/co4e_tab.py trong khi alias tuong duong ben Agent (ag_new_btn/agent_list/...) lai xep vao agent_list_panel.py; o day chon dong nhat -> presentation/co4e/skills_list_panel.py. |
| `Co4ETab.skill_list` | 574 | `presentation/co4e/skills_list_panel.py` | alias trỏ tới self._skills_panel.list_widget — xem ghi chú ở sk_manage_btn | co | BANG CU KHONG NHAT QUAN: xep Co4ETab.skill_list vao ui/co4e_tab.py trong khi alias tuong duong ben Agent (ag_new_btn/agent_list/...) lai xep vao agent_list_panel.py; o day chon dong nhat -> presentation/co4e/skills_list_panel.py. |
| `Co4ETab.runs_more_btn` | 582 | `ui/co4e_tab.py` | nút icon trong sidebar mở trang Runs (gọi self._show_runs(True)) — điểm vào trang Flow Status nhưng không phải một phần của bảng runs_table -- QUYET DINH: nút icon nằm trong sidebar (dựng bởi _build_sidebar, ở co4e_tab.py) mở trang Runs — không phải một phần của runs_table. Bảng cũ xếp vào co4e_run_control_widget.py vì cùng 'chủ đề Runs', nhưng nơi nó được XÂY lại là sidebar | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 586) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab.runs_side_list` | 590 | `ui/co4e_tab.py` | danh sách rút gọn các run trong sidebar — KHÁC với self.runs_table của trang Flow Status (định nghĩa ngoài dòng 700, có thể ở co4e_run_control_widget); dễ nhầm là cùng một bảng nên tách agent gộp cần đối chiếu -- QUYET DINH: danh sách rút gọn run trong sidebar, KHÁC self.runs_table của trang Flow Status — dựng trong _build_sidebar (co4e_tab.py). Mô tả đích của _build_runs_page nói rõ co4e_run_control_widget.py = bảng runs_table + nút hành động, không bao gồm sidebar quick-list | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 594) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._SIDE_RUNS` | 601 | `ui/co4e_tab.py` | hằng số class — số run hiển thị trong sidebar quick-list, không phải trang runs_table chính -- QUYET DINH: hằng số cho sidebar quick-list — cùng nhóm runs_side_list | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 605) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._refresh_side_runs` | 603-615 | `ui/co4e_tab.py` | đọc self.manager.runs(), ghi self.runs_side_list — sidebar quick-list, khác trang Flow Status runs_table -- QUYET DINH: cùng nhóm runs_side_list | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 607-619) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._on_side_run_clicked` | 617-625 | `ui/co4e_tab.py` | gọi self._show_runs(True) rồi đọc self.runs_table (định nghĩa ngoài dòng 1-700, khả năng ở co4e_run_control_widget) để chọn dòng tương ứng — điểm nối giữa sidebar quick-list và trang Runs, cần agent gộp đối chiếu với file định nghĩa runs_table -- QUYET DINH: handler click của sidebar quick-list; có đọc self.runs_table nên cần API cầu nối sang co4e_run_control_widget.py khi tách, nhưng bản thân handler thuộc sidebar nên ở co4e_tab.py | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 621-629) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._section` | 627-659 | `ui/co4e_tab.py` | helper dựng UI section chung cho sidebar, ghi vào self._sections[key] | co | - |
| `Co4ETab._fold_section` | 661-673 | `ui/co4e_tab.py` | đọc self._sections | co | - |
| `Co4ETab._sync_section_arrow` | 675-678 | `ui/co4e_tab.py` | đọc self._sections | co | - |
| `Co4ETab._icon_btn` | 679-683 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._reload_sidebar` | 685-718 | `ui/co4e_tab.py` | [GOP 2 luot quet trung ky hieu dong 685] cắt ngang lát — cần agent gộp đối chiếu (thân method tiếp tục ngoài dòng 700); gọi co4e.list_workflows() nên chạm đĩa // cắt ngang lát — cần agent gộp đối chiếu (bắt đầu ở dòng 685, trước khoảng được giao 701-1400; phần thấy được chỉ là vòng lặp nạp custom agents + skills vào agent_list/skill_list) -- QUYET DINH: [GỘP 2 lượt quét trùng ký hiệu ở dòng 685] một agent đọc thân đến 700 (cắt ngang lát), agent kia đọc tới 718 (vòng lặp nạp agent/skill) — gộp thành 1 dòng 685-718; nạp lại toàn bộ sidebar, không phải trang Runs | co | - |
| `Co4ETab._palette_item` | 720-724 | `ui/co4e_tab.py` | staticmethod tạo QListWidgetItem cho palette — không liên quan trang Runs -- QUYET DINH: factory QListWidgetItem cho palette — sidebar, không phải Runs | co | - |
| `Co4ETab._build_center` | 727-867 | `ui/co4e_tab.py` | method dài >80 dòng, gộp nhiều việc không liên quan: dựng flow tab bar (QTabBar ẩn), gọi _build_runs_page() để nhét vào center_stack, dựng toolbar flow (name/add/save/mode/run/runs toggle), dựng canvas + overlay + splitter dọc với chat. Nên tách nhỏ. Gán self.center_stack — trạng thái chia sẻ dùng ở nhiều nơi (switch giữa trang Runs và flow editor, cả _show_runs ngoài lát này). -- QUYET DINH: dựng flow tab bar + toolbar + canvas/chat splitter; GỌI self._build_runs_page() để nhét vào center_stack — khi tách, chỗ gọi này đổi thành khởi tạo Co4ERunControlWidget(...) rồi add vào center_stack | co | - |
| `Co4ETab.flow_bar` | 734 | `ui/co4e_tab.py` | QTabBar ẩn dùng làm index ánh xạ flow<->canvas, không phải trang Runs | co | - |
| `Co4ETab.flow_add_btn` | 760 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.flow_scroll` | 777 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab.center_stack` | 801 | `ui/co4e_tab.py` | trạng thái chia sẻ giữa trang Runs (stack 0) và flow editor (stack 1) — dùng bởi _show_runs (ngoài lát này) để chuyển trang -- QUYET DINH: container sở hữu QStackedWidget chứa [trang Runs, flow editor]; trang Runs (index 0) sẽ LÀ instance Co4ERunControlWidget được add vào đây | co | - |
| `Co4ETab._build_runs_page` | 869-928 | `presentation/co4e/co4e_run_control_widget.py` | khớp đúng mô tả đích: dựng bảng runs_table + nút back/stop/rename/delete/clear/mở-thư-mục-workspace | co | - |
| `Co4ETab.runs_back_btn` | 878 | `presentation/co4e/co4e_run_control_widget.py` | - | co | - |
| `Co4ETab.runs_title` | 883 | `presentation/co4e/co4e_run_control_widget.py` | - | co | - |
| `Co4ETab.ws_folder_btn` | 888 | `presentation/co4e/co4e_run_control_widget.py` | nút mở thư mục workspace — click gọi self._open_workspace_folder (định nghĩa ngoài lát này, có khả năng touches_disk_or_network=true) | co | - |
| `Co4ETab.run_stop_btn` | 896 | `presentation/co4e/co4e_run_control_widget.py` | - | co | - |
| `Co4ETab.run_rename_btn` | 901 | `presentation/co4e/co4e_run_control_widget.py` | - | co | - |
| `Co4ETab.run_del_btn` | 905 | `presentation/co4e/co4e_run_control_widget.py` | - | co | - |
| `Co4ETab.run_clear_btn` | 909 | `presentation/co4e/co4e_run_control_widget.py` | click gọi self.manager.clear_finished() — self.manager là trạng thái chia sẻ (run manager) không định nghĩa trong lát này | co | - |
| `Co4ETab.runs_table` | 917 | `presentation/co4e/co4e_run_control_widget.py` | bảng chính của trang Runs; double-click gọi self._open_run_from_table, context menu gọi self._runs_context_menu (cả hai định nghĩa ngoài lát này) | co | - |
| `Co4ETab._wrap_config` | 930-960 | `ui/co4e_tab.py` | wrap panel cấu hình step, không thuộc trang Runs -- QUYET DINH: khung bọc/thu-phóng quanh StepConfigPanel — thuộc bố cục của co4e_tab.py, không phải nội dung panel. Bảng cũ xếp cả cụm này vào node_property_panel.py (file cấm sửa của lane khác) — không đúng vai trò 'khung bọc' vs 'nội dung panel' | co | - |
| `Co4ETab.config_toggle_btn` | 942 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab.config_title` | 947 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab._cfg_vlayout` | 953 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab._cfg_top_spacer` | 957 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab._cfg_bot_spacer` | 958 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab.config_container` | 959 | `ui/co4e_tab.py` | thuộc khung bọc _wrap_config | co | - |
| `Co4ETab._NARROW` | 967 | `ui/co4e_tab.py` | hằng số class-level, không liên quan trang Runs -- QUYET DINH: hằng số bố cục hẹp của cả tab | co | - |
| `Co4ETab.showEvent` | 969-971 | `ui/co4e_tab.py` | Qt override, gắn narrow_guard -- QUYET DINH: [ANOMALY — 2 định nghĩa showEvent cùng tên trong 1 class, bảng cũ đã ghi nhận 'kept_separate_anomaly_symbols'] bản đầu (969-971) chỉ gắn narrow_guard, bị bản thứ 2 (1802) ghi đè lúc runtime; giữ TÁCH RIÊNG như bảng cũ | co | - |
| `Co4ETab._apply_narrow_layout` | 973-983 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._toggle_config` | 985-1028 | `ui/co4e_tab.py` | không thuộc trang Runs; đọc/ghi self._split (splitter 3 cột chia sẻ với _build_center/_wrap_config) | co | - |
| `Co4ETab._refresh_min_width` | 1030-1035 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._build_canvas_overlay` | 1037-1058 | `presentation/co4e/co4e_canvas_widget.py` | overlay zoom cho canvas — không thuộc trang Runs -- QUYET DINH: overlay zoom/fit gắn LÊN canvas qua self.canvas.add_overlay(); chấp nhận quyết định của bảng cũ — thuộc lane canvas, ngoài phạm vi run-control. Hiện tại canvas vẫn ở ui/co4e_canvas.py (chưa đổi tên), việc dời file này KHÔNG thuộc lane này | co | - |
| `Co4ETab.zoom_in_btn` | 1050 | `presentation/co4e/co4e_canvas_widget.py` | nút overlay canvas — ngoài phạm vi run-control | co | - |
| `Co4ETab.zoom_out_btn` | 1051 | `presentation/co4e/co4e_canvas_widget.py` | nút overlay canvas — ngoài phạm vi run-control | co | - |
| `Co4ETab.fit_btn` | 1052 | `presentation/co4e/co4e_canvas_widget.py` | nút overlay canvas — ngoài phạm vi run-control | co | - |
| `Co4ETab._build_chat` | 1060-1123 | `ui/co4e_tab.py` | method dài >60 dòng, dựng toàn bộ khung chat (header, stack theo flow, composer, routing toggle, usage total) — không thuộc trang Runs -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._chat_widget` | 1062 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._mhdr` | 1068 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.msgs_icon` | 1070 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.msgs_title` | 1071 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_toggle_btn` | 1072 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_stack` | 1087 | `ui/co4e_tab.py` | một ChatView mỗi flow — trạng thái chia sẻ đọc bởi _apply_workflow, _ensure_flow_log, _active_log -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._flow_logs` | 1088 | `ui/co4e_tab.py` | Dict[str, ChatView] theo wf.id — trạng thái chia sẻ giữa các tab flow -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_input_row` | 1090 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._usage_total_lbl` | 1095 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_input` | 1101 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_send_btn` | 1104 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.co4e_routing_toggle` | 1109 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._co4e_routed_provider` | 1110 | `ui/co4e_tab.py` | override provider định tuyến cho lượt kế tiếp — trạng thái đọc/ghi ở nhiều nơi ngoài lát này (dòng 1849, 1871, 1878) -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._vsplit_sizes` | 1117 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._msgs_collapsed` | 1118 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._toggle_messages` | 1125-1157 | `ui/co4e_tab.py` | expand/collapse khung chat, đọc/ghi self._vsplit — không thuộc trang Runs -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._ensure_flow_log` | 1160-1169 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._active_log` | 1171-1173 | `ui/co4e_tab.py` | khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab.chat_log` | 1175-1179 | `ui/co4e_tab.py` | property, không phải attribute gán trực tiếp — liệt kê vì là symbol công khai -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._plan_bubble` | 1181-1187 | `ui/co4e_tab.py` | property getter/setter, ủy quyền sang self._active_log()._co4e_plan_bubble -- QUYET DINH: khung CHAT — thuộc lane co4e_chat_view.py (chưa tồn tại); giữ nguyên ui/co4e_tab.py cho tới khi lane đó tách, ngoài phạm vi lane run-control. Bảng cũ đã xếp sẵn vào presentation/co4e/co4e_chat_view.py | co | - |
| `Co4ETab._apply_workflow` | 1190-1204 | `ui/co4e_tab.py` | gán self._wf — trạng thái chia sẻ trung tâm của cả tab (đọc/ghi khắp nơi); gọi self.canvas.load/relayout/fit_view và self._update_run_btn/_refresh_usage_total (ngoài lát này) -- QUYET DINH: gán self._wf trung tâm — container | co | - |
| `Co4ETab._new_workflow` | 1205-1213 | `ui/co4e_tab.py` | gọi self._open_flow (ngoài lát này) | co | - |
| `Co4ETab._selected_wf` | 1215-1221 | `ui/co4e_tab.py` | co4e.get_workflow đọc storage — thuần logic sidebar, không thuộc trang Runs | co | - |
| `Co4ETab._load_selected_workflow` | 1223-1226 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._edit_selected_workflow` | 1228-1233 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._duplicate_selected_workflow` | 1235-1242 | `application/workflows/co4e_workflow_service.py` | co4e.duplicate_workflow ghi storage -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._wf_context_menu` | 1244-1267 | `ui/co4e_tab.py` | menu chuột phải cho danh sách flow đã lưu, không phải trang Runs -- QUYET DINH: menu chuột phải cho danh sách flow đã lưu (sidebar) | co | - |
| `Co4ETab._rename_workflow` | 1269-1285 | `application/workflows/co4e_workflow_service.py` | co4e.save_workflow ghi storage; đọc/ghi self._wf.name và self.name_edit -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._delete_selected_workflow` | 1287-1293 | `application/workflows/co4e_workflow_service.py` | co4e.delete_workflow ghi storage -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._sync_wf_from_canvas` | 1295-1298 | `ui/co4e_tab.py` | đọc self.canvas.nodes()/edges() và self.name_edit, ghi vào self._wf — trạng thái chia sẻ -- QUYET DINH: khớp bảng cũ | co | - |
| `Co4ETab._save` | 1300-1305 | `application/workflows/co4e_workflow_service.py` | co4e.save_workflow ghi storage -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._autosave` | 1307-1310 | `application/workflows/co4e_workflow_service.py` | co4e.save_workflow ghi storage -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._on_name_changed` | 1312-1314 | `ui/co4e_tab.py` | gọi self._sync_active_flow_tab_text (ngoài lát này) | co | - |
| `Co4ETab._add_blank_step` | 1316-1318 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._on_node_selected` | 1321-1327 | `ui/co4e_tab.py` | đọc self.canvas.nodes(), self.config, self._config_collapsed -- QUYET DINH: đọc canvas selection rồi TOGGLE khung bọc _wrap_config (self._config_collapsed) — thuộc container, không phải nội dung StepConfigPanel. Bảng cũ xếp vào node_property_panel.py — không đúng vai trò khung bọc vs nội dung panel | co | - |
| `Co4ETab._on_config_changed` | 1329-1332 | `ui/co4e_tab.py` | cùng lý do với _on_node_selected | co | - |
| `Co4ETab._new_agent` | 1335-1336 | `presentation/co4e/agent_list_panel.py` | khớp bảng cũ, ngoài phạm vi run-control | co | - |
| `Co4ETab._edit_agent` | 1338-1346 | `presentation/co4e/agent_list_panel.py` | khớp bảng cũ, ngoài phạm vi run-control | co | - |
| `Co4ETab._edit_agent_dialog` | 1348-1354 | `presentation/co4e/agent_list_panel.py` | co4e.save_custom_agent ghi storage; mở dialog Qt -- QUYET DINH: khớp bảng cũ, ngoài phạm vi run-control | co | - |
| `Co4ETab._delete_agent` | 1356-1363 | `presentation/co4e/agent_list_panel.py` | co4e.delete_custom_agent ghi storage -- QUYET DINH: khớp bảng cũ, ngoài phạm vi run-control | co | - |
| `Co4ETab._manage_skills` | 1365-1369 | `presentation/co4e/skills_list_panel.py` | mở SkillsDialog (Qt) -- QUYET DINH: khớp bảng cũ, ngoài phạm vi run-control | co | - |
| `Co4ETab._skill_map` | 1372-1378 | `application/workflows/co4e_workflow_service.py` | logic thuần, không phải trang Runs — thuộc nhóm run/mode bị loại trừ khỏi run_control_widget theo mô tả đích -- QUYET DINH: đã có quyết định của lane workflow-service (bảng cũ); ngoài phạm vi run-control | co | - |
| `Co4ETab._current_mode` | 1380-1381 | `ui/co4e_tab.py` | thuộc mode/run toolbar — loại trừ khỏi run_control_widget theo mô tả đích -- QUYET DINH: đọc mode_combo của toolbar mode/run — mô tả đích loại trừ nhóm mode/run khỏi co4e_run_control_widget.py; bảng cũ xếp vào đó — mâu thuẫn với phạm vi hiện tại | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1384-1385) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._on_mode_changed` | 1383-1389 | `ui/co4e_tab.py` | reset self._manual_active/_manual_order/_manual_idx — thuộc mode/run toolbar, loại trừ khỏi run_control_widget theo mô tả đích -- QUYET DINH: cùng nhóm mode/run toolbar — xem lý do ở _current_mode | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1387-1393) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._on_run_clicked` | 1391-1400 | `ui/co4e_tab.py` | cắt ngang lát — cần agent gộp đối chiếu (thân method tiếp tục sau dòng 1400). Đây là logic thực thi run — loại trừ khỏi run_control_widget theo mô tả đích; gọi self.manager.stop (trạng thái chia sẻ run manager) -- QUYET DINH: logic bấm nút Run (thực thi) — cùng nhóm bị loại trừ, xem lý do ở _current_mode | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1395-1400) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._start_canvas_run` | 1403-1420 | `ui/co4e_tab.py` | logic khởi chạy run trên canvas (không phải bảng Flow Status); đọc/ghi self._wf, self._flows tiles, self._flow_runs, self._run_logs — trạng thái chia sẻ với _on_manager_event và _manual_step | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1407-1424) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._plan_bubble` | 1413 | `ui/co4e_tab.py` | gán lại None khi bắt đầu run mới; cũng gán ở _manual_run_or_advance (1457) và đọc/ghi trong _append_plan qua log._co4e_plan_bubble — có thể đã khởi tạo lần đầu ở __init__ ngoài phạm vi đọc | co (nhung o dong khac: 1186-1187) | - |
| `Co4ETab._run_single` | 1422-1427 | `ui/co4e_tab.py` | - | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1426-1431) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._run_from` | 1429-1433 | `ui/co4e_tab.py` | - | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1433-1437) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._downstream` | 1435-1446 | `ui/co4e_tab.py` | đọc self.canvas.edges() — chỉ cần canvas object tồn tại, không cần app hiển thị; logic đồ thị thuần | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1439-1450) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_run_or_advance` | 1449-1462 | `ui/co4e_tab.py` | khởi tạo self._manual_order/_manual_idx/_manual_active — trạng thái mode thủ công, không liên quan bảng Flow Status | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1453-1466) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_order` | 1458 | `ui/co4e_tab.py` | trạng thái mode thủ công, dùng bởi _manual_step; có thể đã khởi tạo ở __init__ ngoài phạm vi đọc | co (nhung o dong khac: 253) | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 253) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_idx` | 1459 | `ui/co4e_tab.py` | trạng thái mode thủ công, dùng bởi _manual_step/_on_manager_event | co (nhung o dong khac: 254) | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 254) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_active` | 1460 | `ui/co4e_tab.py` | trạng thái mode thủ công, đọc bởi _on_manager_event | co (nhung o dong khac: 252) | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 252) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._manual_step` | 1464-1480 | `ui/co4e_tab.py` | ghi self._flow_runs[wf.id] và self._run_logs[run_id] — dict chia sẻ với _start_canvas_run/_on_manager_event | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1468-1484) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._topo_order` | 1482-1487 | `ui/co4e_tab.py` | đọc self.canvas.nodes()/edges() — thuần logic sắp xếp topo | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1486-1491) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._on_manager_event` | 1490-1546 | `ui/co4e_tab.py` | method gộp nhiều việc không liên quan: routing event theo loại (node_status/node_output/node_diff/node_plan/node_tool/run_done/error), cập nhật canvas, ghi self._outputs_for, dọn self._flow_runs/self._run_logs, gọi popup thông báo — nên tách nhỏ thêm dù chưa vượt 80 dòng. KHÔNG thuộc bảng Flow Status (không đụng runs_table trực tiếp), là logic thực thi run nên ở lại co4e_tab.py theo _doc | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1494-1550) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._notify_run_finished` | 1548-1569 | `ui/co4e_tab.py` | tạo QMessageBox không chặn, ghi self._run_popups — popup thông báo chung, không phải phần bảng Flow Status | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1552-1573) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._run_popups` | 1557 | `ui/co4e_tab.py` | danh sách giữ tham chiếu QMessageBox không-chặn để tránh bị GC — khởi tạo có điều kiện (hasattr) ngay trong _notify_run_finished thay vì __init__ | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1560-1561) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._refresh_runs` | 1571-1612 | `presentation/co4e/co4e_run_control_widget.py` | dựng lại bảng self.runs_table từ manager — đúng lõi 'Flow Status'; cũng đụng self._sections và self.flow_bar (tab text 'RUNS N') và gọi self._refresh_side_runs() — trạng thái chia sẻ với sidebar/tab strip ngoài phạm vi widget này, cần API cầu nối khi tách | co | - |
| `Co4ETab._stop_selected_run` | 1614-1620 | `presentation/co4e/co4e_run_control_widget.py` | nút Stop của bảng Flow Status | co | - |
| `Co4ETab._delete_selected_run` | 1622-1635 | `presentation/co4e/co4e_run_control_widget.py` | nút Delete; ghi self._flow_runs.pop/self._run_logs.pop — dict chia sẻ với logic thực thi run ở co4e_tab.py | co | - |
| `Co4ETab._runs_context_menu` | 1637-1651 | `presentation/co4e/co4e_run_control_widget.py` | context menu của runs_table (open run/output/rename/delete); action 'open_run' gọi self._open_run_from_table vốn cần self._open_flow + self.canvas (ở co4e_tab.py) — cần callback cầu nối khi tách | co | - |
| `Co4ETab.set_project` | 1654-1670 | `ui/co4e_tab.py` | đọc/ghi self._project_id, self._project_dir; gọi load_project (đọc đĩa) và manager.set_output_root/set_current_project; gọi self._refresh_ws_folder_btn() thuộc widget Flow Status — cần API cầu nối khi tách ra co4e_run_control_widget.py | co | - |
| `Co4ETab._project_id` | 1659 | `ui/co4e_tab.py` | trạng thái workspace hiện tại, dùng bởi manager.set_current_project và các hàm mở thư mục — chia sẻ giữa co4e_tab.py và co4e_run_control_widget.py | co (nhung o dong khac: 249) | - |
| `Co4ETab._project_dir` | 1660 | `ui/co4e_tab.py` | dùng bởi _flow_output_root — ảnh hưởng trực tiếp tới nút 'mở thư mục workspace' của Flow Status | co (nhung o dong khac: 250) | - |
| `Co4ETab._flow_output_root` | 1672-1682 | `ui/co4e_tab.py` | helper Path dùng chung bởi cả chat (_out_dir) và nút 'mở thư mục workspace' của Flow Status (_open_workspace_folder/_refresh_ws_folder_btn) — widget Flow Status cần được truyền hàm này qua callback/property thay vì tự tính | co | - |
| `Co4ETab._refresh_ws_folder_btn` | 1684-1689 | `presentation/co4e/co4e_run_control_widget.py` | cập nhật self.ws_folder_btn (nút mở thư mục workspace) — phụ thuộc self._flow_output_root() ở co4e_tab.py | co | - |
| `Co4ETab._open_workspace_folder` | 1691-1698 | `presentation/co4e/co4e_run_control_widget.py` | hành động của nút 'mở thư mục workspace'; mkdir + open_location (spawn process) | co | - |
| `Co4ETab._open_run_output_folder` | 1700-1711 | `presentation/co4e/co4e_run_control_widget.py` | mở thư mục output của 1 run cụ thể — dùng trong context menu bảng Flow Status; mkdir + open_location | co | - |
| `Co4ETab._rename_selected_run` | 1713-1744 | `presentation/co4e/co4e_run_control_widget.py` | nút Rename của bảng Flow Status; nhưng đồng bộ qua self._flows, self.flow_bar.setTabText, self.name_edit — trạng thái tab/canvas chia sẻ với co4e_tab.py, cần callback cầu nối; co4e.save_workflow ghi đĩa | co | - |
| `Co4ETab._run_selected_in_background` | 1746-1756 | `ui/co4e_tab.py` | chạy 1 flow được chọn (self._selected_wf(), không rõ nguồn — có thể là danh sách sidebar chứ không phải runs_table); gọi self._refresh_side_runs() — không khớp mô tả 'CHỈ bảng Flow Status' nên giữ ở co4e_tab.py | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1750-1760) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._wf_by_id` | 1758-1766 | `ui/co4e_tab.py` | co4e.get_workflow đọc file workflow đã lưu trên đĩa; helper dùng chung nhiều nơi (rerun, open-from-table) | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1762-1770) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._rerun_run_item` | 1768-1779 | `ui/co4e_tab.py` | docstring nói 'double-click a run in the history' nhưng item.data(Qt.UserRole) trực tiếp gợi ý đây là list sidebar 'side runs', KHÔNG phải bảng Flow Status (khác cách _open_run_from_table truy cập runs_table qua item.row()) — cần người quyết đây thuộc trang nào -- QUYET DINH: gọi self.manager.start(...) tức THỰC THI run (network/AI) — cùng nhóm run-execution bị loại trừ khỏi co4e_run_control_widget.py; bảng cũ xếp vào đó. Nghi vấn về nguồn item (sidebar hay bảng) không đổi kết luận vì lý do loại trừ là do HÀNH VI thực thi chứ không phải nơi click | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1772-1783) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab._open_run_from_table` | 1781-1800 | `ui/co4e_tab.py` | double-click bảng Flow Status nhưng gọi self._open_flow (chuyển tab) và self.canvas.update_node_status trực tiếp — vượt ra ngoài phạm vi 'chỉ bảng runs_table' nên giữ ở co4e_tab.py, cần callback nếu tách runs_table riêng | co | BANG CU SAI/QUA RONG: xep vao presentation/co4e/co4e_run_control_widget.py (dong 1785-1804) nhung pham vi run-control hien tai (mo ta dich cua 3 agent quet) loai tru nhom nay -> quyet dinh o day = ui/co4e_tab.py. |
| `Co4ETab.showEvent` | 1802-1805 | `ui/co4e_tab.py` | override Qt lifecycle của chính Co4ETab, gọi self._refresh_runs() — phải ở lại widget chính | co | - |
| `Co4ETab._out_dir` | 1807-1813 | `ui/co4e_tab.py` | mkdir; dùng cho chat/flow deliverables, không liên quan bảng Flow Status | co | - |
| `Co4ETab._chat_send` | 1816-1842 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._apply_co4e_routing` | 1844-1879 | `ui/co4e_tab.py` | ghi self._co4e_routed_provider; nhánh 'manual' dựng dialog confirm_switch(self,...) nên cần widget sống | co | - |
| `Co4ETab._co4e_routed_provider` | 1849 | `ui/co4e_tab.py` | dùng bởi _run_chat_turn để chọn provider — reset mỗi lần _apply_co4e_routing chạy | co | - |
| `Co4ETab._extract_agent_directive` | 1881-1887 | `ui/co4e_tab.py` | thuần regex, test được không cần Qt | co | - |
| `Co4ETab._resolve_agent` | 1889-1897 | `ui/co4e_tab.py` | co4e.list_custom_agents() đọc dữ liệu agent tuỳ biến đã lưu | co | - |
| `Co4ETab._run_chat_turn` | 1899-1970 | `ui/co4e_tab.py` | method dài, gộp: dựng prompt, chạy AgentWorker nền gọi provider AI (network), stream sự kiện vào bubble Qt, cập nhật usage — nên tách nhỏ thêm dù chỉ 72 dòng vì nhiều trách nhiệm khác nhau (build prompt / worker job / event routing / usage). Không liên quan bảng Flow Status | co | - |
| `Co4ETab._chat_worker` | 1953 | `ui/co4e_tab.py` | vị trí xuất hiện đầu tiên theo văn bản là trong hàm lồng 'done'; gán thật sự lúc chạy là dòng 1969 (w = AgentWorker...); có thể đã khởi tạo None ở __init__ ngoài phạm vi đọc | co (nhung o dong khac: 236) | - |
| `Co4ETab._append_chat` | 1972-1987 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._fmt_usage` | 1990-1997 | `ui/co4e_tab.py` | thuần formatting, không cần Qt | co | - |
| `Co4ETab._apply_usage` | 1999-2016 | `ui/co4e_tab.py` | ghi self._flow_usage[wf_id] — tổng usage theo flow, chia sẻ với _refresh_usage_total | co | - |
| `Co4ETab._refresh_usage_total` | 2018-2033 | `ui/co4e_tab.py` | đọc self._flow_usage và self._wf — trạng thái chia sẻ với _apply_usage | co | - |
| `Co4ETab._append_diff` | 2035-2039 | `ui/co4e_tab.py` | - | co | - |
| `Co4ETab._append_plan` | 2041-2052 | `ui/co4e_tab.py` | ghi log._co4e_plan_bubble — thuộc tính gắn động lên ChatView, chia sẻ với _run_chat_turn | co | - |
| `Co4ETab._retranslate` | 2055-2075 | `ui/co4e_tab.py` | gộp retranslate cho CẢ widget chung (wf_new_btn, self._sections) LẪN các nút riêng của Flow Status (runs_back_btn, run_stop_btn, run_rename_btn, run_del_btn, run_clear_btn, runs_table headers, ws_folder_btn) — khi tách co4e_run_control_widget.py cần chia method này làm hai, phần Flow Status nên có retranslate riêng gọi từ đây | co | - |
| `_html_escape` | 2078-2079 | `ui/co4e_tab.py` | hàm module-level thuần string escape; không thấy nơi gọi trong phạm vi 1401-2084 nên chưa rõ nó phục vụ phần nào — có thể dùng ở phần chat render ngoài phạm vi đọc -- QUYET DINH: escape string thuần cho phần render CHAT — lane co4e_chat_view.py (chưa tồn tại); bảng cũ đã xếp sẵn vào đó, ngoài phạm vi run-control nên giữ nguyên vị trí vật lý hiện tại | co | - |
| `_qcolor` | 2082-2084 | `presentation/co4e/co4e_run_control_widget.py` | QColor là kiểu giá trị (như QPointF/QRectF), không cần QApplication sống; chỉ thấy dùng trong _refresh_runs (tô màu cột status của bảng Flow Status) trong phạm vi đọc | co | - |
## Chỗ thấy khác tài liệu — cần người quyết
Không có symbol nào trong 215 symbol thô có note bắt đầu bằng `khac tai lieu:` — mục này để trống theo đúng yêu cầu tự kiểm (không có gì cần liệt kê).
File diff suppressed because it is too large Load Diff
+407
View File
@@ -0,0 +1,407 @@
# Bản đồ tách file Co4E (gộp từ 6 agent quét song song)
- Tổng số symbol quét được (thô, tính cả trùng): **367**
- Tổng số dòng trong bản đồ cuối cùng (sau gộp trùng): **363**
- Số nhóm ký hiệu bị quét trùng bởi 2 agent (đã gộp làm 1 dòng): 4 (Co4ECanvas.dropEvent, Co4ETab._co4e_routed_provider, Co4ETab._config_expanded_w, Co4ETab._reload_sidebar)
- Số ký hiệu có 2 định nghĩa thật ở 2 dòng khác nhau, giữ riêng và gắn cờ: 1 (Co4ETab.showEvent)
- EXPECTED (tools/check_co4e.py) có **27** phần tử; kết quả đối chiếu: OK — cả 27 xuất hiện đúng 1 lần, có target cụ thể
- Số note bắt đầu bằng `khac tai lieu:`: **0** (không có -> không có mục 'Chỗ thấy khác tài liệu' nào phát sinh từ tiêu chí này)
## Ghi chú về gộp trùng (5 ký hiệu bị 2 agent cùng quét thấy)
### `Co4ETab._config_expanded_w`
- dòng 275-275, target agent gốc đề xuất = `presentation/co4e/co4e_tab.py` — cùng lý do với _config_collapsed
- dòng 995-995, target agent gốc đề xuất = `presentation/co4e/co4e_tab.py` — gán trong nhánh collapse của _toggle_config; có thể đã khởi tạo trong __init__ (ngoài phạm vi đọc).
- **Quyết định gộp**: 1 dòng, target cuối = `presentation/co4e/co4e_tab.py`, dòng 275; 995
### `Co4ETab._reload_sidebar`
- dòng 689-700, target agent gốc đề xuất = `presentation/co4e/co4e_tab.py` — cắt ngang lát — cần agent gộp đối chiếu (method tiếp tục sau dòng 700); gọi co4e.list_workflows() (đọc đĩa) rồi dựng QListWidgetItem trực tiếp trong cùng hàm — trộn data-fetch và UI, nên tách phần đọc dữ liệu sang co4e_workflow_service.py
- dòng 689-722, target agent gốc đề xuất = `unsure` — cắt ngang lát — cần agent gộp đối chiếu (bắt đầu trước dòng 701). Gộp refresh cả agent_list và skill_list trong cùng 1 hàm — nên tách thành _refresh_agents_list (agent_list_panel.py) và _refresh_skills_list (skills_list_panel.py) như plan.md yêu cầu; gọi co4e.list_custom_agents() (đĩa) và skills_mod.skill_prefix_for (đĩa).
- **Quyết định gộp**: 1 dòng, target cuối = `presentation/co4e/co4e_tab.py`, dòng 689-722
### `Co4ETab.showEvent`
- dòng 973-975, target agent gốc đề xuất = `presentation/co4e/co4e_tab.py` — Qt override, gọi self._narrow_guard.attach() (đối tượng khởi tạo ngoài phạm vi đọc, <701).
- dòng 1806-1809, target agent gốc đề xuất = `presentation/co4e/co4e_tab.py` — override Qt lifecycle method của chính QWidget container nên phải ở lại co4e_tab.py; gọi self._refresh_runs() (thuộc co4e_run_control_widget.py) — điểm nối giữa container và run-control widget.
- **Quyết định**: đây là 2 định nghĩa method trùng tên thật sự tồn tại ở 2 vị trí khác nhau trong cùng class `Co4ETab` (khả năng cao là lỗi nguồn — định nghĩa sau đè định nghĩa trước, làm dòng logic ở định nghĩa trước thành dead code). Giữ nguyên 2 dòng riêng biệt trong bản đồ, KHÔNG gộp, và cần người quyết định giữ định nghĩa nào.
### `Co4ETab._co4e_routed_provider`
- dòng 1114-1114, target agent gốc đề xuất = `presentation/co4e/co4e_chat_view.py` — override provider cho lượt chat kế tiếp — dùng bởi _apply_co4e_routing (ngoài phạm vi đọc, >1400).
- dòng 1853-1853, target agent gốc đề xuất = `presentation/co4e/co4e_chat_view.py` — gán None lần đầu tại đây (trong _apply_co4e_routing); đọc bằng getattr(self, '_co4e_routed_provider', None) ở _run_chat_turn dòng ~1922 — gợi ý có thể không được init trong __init__. Trạng thái routing theo từng lượt chat, dùng chung giữa chat-view và _start_canvas_run/manager.start.
- **Quyết định gộp**: 1 dòng, target cuối = `presentation/co4e/co4e_chat_view.py`, dòng 1114; 1853
### `Co4ECanvas.dropEvent`
- dòng 683-700, target agent gốc đề xuất = `presentation/co4e/co4e_canvas_widget.py` — cắt ngang lát — cần agent gộp đối chiếu (thân try chưa đóng ở dòng 700, còn tiếp; xử lý JSON từ mimeData trong bộ nhớ, không phải file đĩa nên touches_disk_or_network=false)
- dòng 683-701, target agent gốc đề xuất = `presentation/co4e/co4e_canvas_widget.py` — cắt ngang lát — cần agent gộp đối chiếu. Method dropEvent bắt đầu ở dòng 683 (ngoài khoảng được giao 701-791), chỉ dòng 701 (e.acceptProposedAction()) nằm trong lát này; dòng 702 là dòng trống cuối file. File ui/co4e_canvas.py chỉ có 702 dòng — không có nội dung nào khác trong khoảng 702-791 vì đã hết file. Xử lý drop từ sidebar (kind=='workflow' → add_workflow, ngược lại → add_palette_step) — logic thao tác node/canvas nên khớp nhóm _add_node/_connect_nodes trong bảng plan.md dòng 623 dù plan.md không liệt kê rõ dropEvent.
- **Quyết định gộp**: 1 dòng, target cuối = `presentation/co4e/co4e_canvas_widget.py`, dòng 683-701
## Bảng đầy đủ
| symbol | dòng | file đích | lý do | có trong bảng cũ chưa | chỗ nào thấy bảng cũ sai |
|---|---|---|---|---|---|
| Co4ETab._flow_outputs | 245 | application/workflows/co4e_workflow_service.py | state per-flow outputs — ứng viên chuyển vào state machine thuần Python | chua/khong ro | - |
| Co4ETab._outputs_for | 475-478 | application/workflows/co4e_workflow_service.py | truy cập dict state per-flow outputs, thuần Python | chua/khong ro | - |
| Co4ETab._duplicate_selected_workflow | 1239-1246 | application/workflows/co4e_workflow_service.py | tương ứng _duplicate_flow() trong bảng plan.md dòng 616, nhưng tên hàm thực tế khác (_duplicate_selected_workflow). Gộp gọi service (co4e.duplicate_workflow, đĩa) với cập nhật UI (self._reload_sidebar(), self.status_message.emit) — cần tách; phần UI nên ở lại co4e_tab.py. | co | ate_flow() trong bảng plan.md dòng 616, nhưng tên hàm thực tế khác (_duplicate_selected_workflow). Gộp gọi service (co4e.duplicate_workflow, đĩa) |
| Co4ETab._rename_workflow | 1273-1289 | application/workflows/co4e_workflow_service.py | mở QInputDialog (cần Qt) rồi gọi co4e.save_workflow (đĩa), đồng bộ self._wf.name/self.name_edit nếu flow đang mở là flow bị đổi tên — gộp UI dialog + service + trạng thái chia sẻ self._wf trong 1 hàm, nên tách. | chua/khong ro | - |
| Co4ETab._delete_selected_workflow | 1291-1297 | application/workflows/co4e_workflow_service.py | tương ứng _delete_flow() trong bảng plan.md dòng 616; gọi co4e.delete_workflow (đĩa). | co | - |
| Co4ETab._save | 1304-1309 | application/workflows/co4e_workflow_service.py | gộp _sync_wf_from_canvas (đọc canvas UI), lưu đĩa (co4e.save_workflow), và cập nhật UI (_reload_sidebar, status_message) — cần tách phần service khỏi phần UI khi chuyển sang co4e_workflow_service.py. | chua/khong ro | - |
| Co4ETab._autosave | 1311-1314 | application/workflows/co4e_workflow_service.py | gọi self._sync_wf_from_canvas() (cần canvas) rồi co4e.get_workflow/save_workflow (đĩa). | chua/khong ro | - |
| Co4ETab._skill_map | 1376-1382 | application/workflows/co4e_workflow_service.py | chuẩn bị nội dung skill (skills_mod.skill_prefix_for, đọc đĩa) để đưa vào lúc chạy flow/chat — không có trong bảng plan.md, tự xếp theo chức năng (dùng lúc run/build system prompt, không phải UI danh sách skill). | co | ọc đĩa) để đưa vào lúc chạy flow/chat — không có trong bảng plan.md, tự xếp theo chức năng (dùng lúc run/build system prompt, không phải UI danh sá |
| Co4ETab.ag_new_btn | 550 | presentation/co4e/agent_list_panel.py | hiện định nghĩa trực tiếp trong Co4ETab._build_sidebar — ứng viên chuyển sang agent_list_panel.py tương tự cách skills đã tách | chua/khong ro | - |
| Co4ETab.agent_list | 558 | presentation/co4e/agent_list_panel.py | cùng lý do với ag_new_btn | chua/khong ro | - |
| Co4ETab.ag_edit_btn | 562 | presentation/co4e/agent_list_panel.py | cùng lý do với ag_new_btn | chua/khong ro | - |
| Co4ETab.ag_del_btn | 563 | presentation/co4e/agent_list_panel.py | cùng lý do với ag_new_btn | chua/khong ro | - |
| Co4ETab._new_agent | 1339-1340 | presentation/co4e/agent_list_panel.py | tương ứng _create_agent() trong bảng plan.md dòng 620 (tên hàm thực tế là _new_agent). | co | - |
| Co4ETab._edit_agent | 1342-1350 | presentation/co4e/agent_list_panel.py | khớp _edit_agent() dòng 620 plan.md; gọi co4e.list_custom_agents() (đĩa). | co | - |
| Co4ETab._edit_agent_dialog | 1352-1358 | presentation/co4e/agent_list_panel.py | mở Co4EAgentDialog rồi co4e.save_custom_agent (đĩa) và self._reload_sidebar() — trạng thái chia sẻ, liên quan tới cắt ngang lát ở _reload_sidebar. | chua/khong ro | - |
| Co4ETab._delete_agent | 1360-1367 | presentation/co4e/agent_list_panel.py | khớp _delete_agent() dòng 620 plan.md; gọi co4e.delete_custom_agent (đĩa). | co | - |
| _status_color | 43-50 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem | 59-210 | presentation/co4e/co4e_canvas_widget.py | class nội bộ gắn chặt với Co4ECanvas qua self.canvas backreference — nên đi cùng file với Co4ECanvas | chua/khong ro | - |
| _NodeItem.__init__ | 62-72 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.node | 64 | presentation/co4e/co4e_canvas_widget.py | giữ tham chiếu domain Node — dữ liệu chia sẻ với core/co4e.py | chua/khong ro | - |
| _NodeItem.canvas | 65 | presentation/co4e/co4e_canvas_widget.py | backreference tới Co4ECanvas cha — mọi event của _NodeItem đều gọi ngược lên canvas (add_step_below, begin_connect, delete_node, các signal) — điểm khớp nối chặt nhất trong file | chua/khong ro | - |
| _NodeItem.status | 66 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem._porting | 67 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.boundingRect | 74-76 | presentation/co4e/co4e_canvas_widget.py | trả QRectF như kiểu giá trị, logic thuần | chua/khong ro | - |
| _NodeItem._card_rect | 78-79 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.paint | 81-139 | presentation/co4e/co4e_canvas_widget.py | vẽ toàn bộ card: nền, header stripe, label, badge role, preview instructions/sub-agents, footer model/skills, 2 port — gộp nhiều việc nhưng vẫn dưới 80 dòng nên chưa bắt buộc tách thêm | chua/khong ro | - |
| _NodeItem._in_out_port | 141-143 | presentation/co4e/co4e_canvas_widget.py | hình học thuần dùng QPointF như kiểu giá trị | chua/khong ro | - |
| _NodeItem.itemChange | 145-156 | presentation/co4e/co4e_canvas_widget.py | ghi self.node.x/y rồi gọi self.canvas._reposition_edges() và emit self.canvas.graph_changed/node_selected — chạm trạng thái chia sẻ của canvas cha | chua/khong ro | - |
| _NodeItem.hoverMoveEvent | 158-161 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.mousePressEvent | 163-174 | presentation/co4e/co4e_canvas_widget.py | đọc/ghi self.canvas._connect_from, gọi canvas._finish_connect/begin_port_drag — trạng thái connect-mode chia sẻ với Co4ECanvas | chua/khong ro | - |
| _NodeItem.mouseMoveEvent | 176-181 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.mouseReleaseEvent | 183-189 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.mouseDoubleClickEvent | 191-193 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _NodeItem.contextMenuEvent | 195-207 | presentation/co4e/co4e_canvas_widget.py | gọi canvas.add_step_below/begin_connect/delete_node — trạng thái/hành vi thuộc canvas cha | chua/khong ro | - |
| _NodeItem.center | 209-210 | presentation/co4e/co4e_canvas_widget.py | trả QPointF như kiểu giá trị | chua/khong ro | - |
| _EdgeItem | 213-286 | presentation/co4e/co4e_canvas_widget.py | class nội bộ gắn chặt với Co4ECanvas qua self.canvas backreference | chua/khong ro | - |
| _EdgeItem.__init__ | 214-225 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.edge | 216 | presentation/co4e/co4e_canvas_widget.py | tham chiếu domain Edge — chia sẻ với core/co4e.py | chua/khong ro | - |
| _EdgeItem.canvas | 217 | presentation/co4e/co4e_canvas_widget.py | backreference tới Co4ECanvas — contextMenuEvent gọi canvas.delete_edge | chua/khong ro | - |
| _EdgeItem._dst | 218 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem._hover | 224 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem._apply_pen | 227-235 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.update_path | 237-239 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.boundingRect | 241-242 | presentation/co4e/co4e_canvas_widget.py | gọi super().boundingRect() phụ thuộc trạng thái path sống của item | chua/khong ro | - |
| _EdgeItem.shape | 244-249 | presentation/co4e/co4e_canvas_widget.py | dùng QPainterPathStroker trên self.path() sống của item | chua/khong ro | - |
| _EdgeItem.hoverEnterEvent | 251-255 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.hoverLeaveEvent | 257-261 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.paint | 263-279 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _EdgeItem.contextMenuEvent | 281-286 | presentation/co4e/co4e_canvas_widget.py | gọi self.canvas.delete_edge(self.edge) | chua/khong ro | - |
| Co4ECanvas | 289-700 | presentation/co4e/co4e_canvas_widget.py | cắt ngang lát — class tiếp tục sau dòng 700 (dropEvent chưa kết thúc, có thể còn method khác chưa đọc) — cần agent gộp đối chiếu với phần đọc dòng 701+ | chua/khong ro | - |
| Co4ECanvas.node_selected | 290 | presentation/co4e/co4e_canvas_widget.py | Signal được node_property_panel.py (và co4e_tab.py) nối vào để nạp node được chọn — điểm chia sẻ giữa canvas và property panel | chua/khong ro | - |
| Co4ECanvas.node_activated | 291 | presentation/co4e/co4e_canvas_widget.py | Signal double-click, có thể được co4e_tab.py nối để mở panel chỉnh sửa — cần kiểm nơi consume | chua/khong ro | - |
| Co4ECanvas.graph_changed | 292 | presentation/co4e/co4e_canvas_widget.py | Signal báo graph đổi (autosave) — nhiều khả năng được co4e_tab.py/co4e_workflow_service.py nối để lưu flow, trạng thái chia sẻ xuyên lớp application | chua/khong ro | - |
| Co4ECanvas.__init__ | 296-315 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._scene | 299 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._nodes | 305 | presentation/co4e/co4e_canvas_widget.py | dict id->_NodeItem — trạng thái trung tâm được đọc/ghi bởi gần như mọi method của Co4ECanvas (add/delete/relayout/zoom/status/route edges) | chua/khong ro | - |
| Co4ECanvas._edges | 306 | presentation/co4e/co4e_canvas_widget.py | list _EdgeItem — trạng thái trung tâm tương tự self._nodes | chua/khong ro | - |
| Co4ECanvas._connect_from | 307 | presentation/co4e/co4e_canvas_widget.py | trạng thái connect-mode, cũng được _NodeItem.mousePressEvent đọc/ghi qua self.canvas | chua/khong ro | - |
| Co4ECanvas._zoom | 308 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._panning | 309 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._pan_start | 310 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._overlay | 311 | presentation/co4e/co4e_canvas_widget.py | widget zoom/fit overlay được co4e_tab.py hoặc co4e_canvas_widget.py truyền vào qua add_overlay() | chua/khong ro | - |
| Co4ECanvas._port_src | 313 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._port_src_pt | 314 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._temp_edge | 315 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.add_overlay | 318-323 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._place_overlay | 325-330 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.resizeEvent | 332-334 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.scrollContentsBy | 336-341 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.showEvent | 343-345 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.load | 348-362 | presentation/co4e/co4e_canvas_widget.py | reset toàn bộ self._nodes/self._edges/self._connect_from/self._port_src/self._temp_edge — điểm nạp lại state từ flow, được co4e_tab.py hoặc co4e_workflow_service.py gọi khi mở flow | chua/khong ro | - |
| Co4ECanvas.nodes | 364-365 | presentation/co4e/co4e_canvas_widget.py | chỉ đọc .node từ self._nodes, không gọi API Qt trực tiếp | chua/khong ro | - |
| Co4ECanvas.edges | 367-368 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.add_node | 371-382 | presentation/co4e/co4e_canvas_widget.py | ghi self._nodes, scene.addItem, emit graph_changed/node_selected — trạng thái chia sẻ với property panel qua node_selected | chua/khong ro | - |
| Co4ECanvas.add_step_below | 384-390 | presentation/co4e/co4e_canvas_widget.py | orchestration thuần, ủy quyền cho add_node (bản thân không gọi trực tiếp API Qt) | chua/khong ro | - |
| Co4ECanvas._chain_tail | 392-396 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.add_palette_step | 398-400 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.begin_connect | 402-403 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._finish_connect | 405-409 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.begin_port_drag | 412-419 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.update_port_drag | 421-424 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.finish_port_drag | 426-435 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._node_at | 437-441 | presentation/co4e/co4e_canvas_widget.py | dùng self._scene.items(scene_pt) — cần scene đang sống | chua/khong ro | - |
| Co4ECanvas._make_edge | 443-451 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._add_edge_item | 453-456 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.delete_edge | 458-463 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.delete_node | 465-475 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.delete_selected | 477-481 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._zoom_by | 484-495 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.zoom_in | 497-498 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.zoom_out | 500-501 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.reset_zoom | 503-505 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.wheelEvent | 507-519 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.mousePressEvent | 522-529 | presentation/co4e/co4e_canvas_widget.py | trùng tên với _NodeItem.mousePressEvent nhưng là override của Co4ECanvas (pan chuột giữa) — đừng nhầm khi gộp map | chua/khong ro | - |
| Co4ECanvas.mouseMoveEvent | 531-540 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.mouseReleaseEvent | 542-548 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.fit_view | 550-558 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.relayout | 560-578 | presentation/co4e/co4e_canvas_widget.py | phần tính waves/cols (compute_waves, defaultdict) là logic thuần, phần item.setPos() cần scene sống — có thể tách hàm tính toạ độ ra khỏi phần apply nếu muốn test thuần Python | chua/khong ro | - |
| Co4ECanvas.relayout_if_vertical | 580-589 | presentation/co4e/co4e_canvas_widget.py | bản thân chỉ ra quyết định thuần dựa trên node.x, việc chạm Qt nằm trong relayout() được gọi | chua/khong ro | - |
| Co4ECanvas.add_workflow | 591-610 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.update_node_status | 612-616 | presentation/co4e/co4e_canvas_widget.py | được co4e_run_control_widget.py gọi khi step chạy/xong/lỗi — điểm nối giữa canvas và run control | chua/khong ro | - |
| Co4ECanvas.reset_statuses | 618-621 | presentation/co4e/co4e_canvas_widget.py | được co4e_run_control_widget.py gọi khi bắt đầu run mới | chua/khong ro | - |
| Co4ECanvas.refresh_node | 623-626 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas._node_rects | 628-638 | presentation/co4e/co4e_canvas_widget.py | dựng QRectF như kiểu giá trị từ item.pos() — logic hình học thuần | chua/khong ro | - |
| Co4ECanvas._reposition_edges | 640-649 | presentation/co4e/co4e_canvas_widget.py | gọi e.update_path (setPath) trên item sống, dùng hàm định tuyến _route từ canvas_geometry.py | chua/khong ro | - |
| Co4ECanvas.keyPressEvent | 652-669 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.dragEnterEvent | 671-675 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.dragMoveEvent | 677-681 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ECanvas.dropEvent | 683-701 | presentation/co4e/co4e_canvas_widget.py | [GỘP 2 lượt quét trùng ký hiệu] (dòng 683-700, target gốc=presentation/co4e/co4e_canvas_widget.py) cắt ngang lát — cần agent gộp đối chiếu (thân try chưa đóng ở dòng 700, còn tiếp; xử lý JSON từ mimeData trong bộ nhớ, không phải file đĩa nên touches_disk_or_network=false) \|\| (dòng 683-701, target gốc=presentation/co4e/co4e_canvas_widget.py) cắt ngang lát — cần agent gộp đối chiếu. Method dropEvent bắt đầu ở dòng 683 (ngoài khoảng được giao 701-791), chỉ dòng 701 (e.acceptProposedAction()) nằm trong lát này; dòng 702 là dòng trống cuối file. File ui/co4e_canvas.py chỉ có 702 dòng — không có nội dung nào khác trong khoảng 702-791 vì đã hết file. Xử lý drop từ sidebar (kind=='workflow' → add_workflow, ngược lại → add_palette_step) — logic thao tác node/canvas nên khớp nhóm _add_node/_connect_nodes trong bảng plan.md dòng 623 dù plan.md không liệt kê rõ dropEvent. | co | nnect_nodes trong bảng plan.md dòng 623 dù plan.md không liệt kê rõ dropEvent. |
| Co4ETab.canvas | 856 | presentation/co4e/co4e_canvas_widget.py | TRẠNG THÁI CHIA SẺ lớn nhất trong file — self.canvas được đọc/ghi ở gần như mọi nhóm chức năng khác (sync_wf_from_canvas, apply_workflow, node selection, run, add_blank_step...). | chua/khong ro | - |
| Co4ETab._build_canvas_overlay | 1041-1062 | presentation/co4e/co4e_canvas_widget.py | dựng nút zoom/fit gắn vào self.canvas.add_overlay(bar); các slot gọi thẳng self.canvas.zoom_in/zoom_out/fit_view (thuộc nhóm 3.2.2.21-22 trong plan.md → co4e_canvas_widget.py). Có thể tranh cãi nên giữ ở co4e_tab.py (được gọi từ _build_center) — ghi lại để người soát quyết. | co | - |
| Co4ETab.zoom_in_btn | 1054 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.zoom_out_btn | 1055 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.fit_btn | 1056 | presentation/co4e/co4e_canvas_widget.py | (không có ghi chú) | chua/khong ro | - |
| _skill_names | 61-65 | presentation/co4e/co4e_chat_view.py | gọi skills_mod.list_skills()/builtin_skills() (đọc đĩa); dùng cho autocomplete /skill: trong _ChatInput — cũng liên quan skills_list_panel.py vì cùng nguồn dữ liệu | chua/khong ro | - |
| _agent_names | 68-71 | presentation/co4e/co4e_chat_view.py | gọi co4e.list_custom_agents() (đọc đĩa); dùng cho autocomplete /agent: trong _ChatInput — cũng liên quan agent_list_panel.py vì cùng nguồn dữ liệu | chua/khong ro | - |
| _directive_token | 122-134 | presentation/co4e/co4e_chat_view.py | logic regex thuần Python, test được không cần Qt | chua/khong ro | - |
| _ChatInput | 137-226 | presentation/co4e/co4e_chat_view.py | khai báo 'submit = Signal()' ở dòng 141 là thuộc tính lớp (không phải self.) | chua/khong ro | - |
| _ChatInput.__init__ | 143-151 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| _ChatInput._popup | 145 | presentation/co4e/co4e_chat_view.py | QListWidget popup autocomplete | chua/khong ro | - |
| _ChatInput._maybe_popup | 153-178 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| _ChatInput._add_row | 180-184 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| _ChatInput._accept | 186-199 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| _ChatInput.focusOutEvent | 201-204 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| _ChatInput.keyPressEvent | 206-226 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._chat_worker | 236 | presentation/co4e/co4e_chat_view.py | AgentWorker của chat, hiện giữ trên Co4ETab | chua/khong ro | - |
| Co4ETab._build_chat | 1064-1127 | presentation/co4e/co4e_chat_view.py | dài ~63 dòng, gộp: header 'Messages' + toggle, chat_stack (QStackedWidget chứa 1 ChatView/flow), input row + usage label + composer + routing toggle. Tạo self._flow_logs (Dict[str, ChatView]) — TRẠNG THÁI CHIA SẺ dùng bởi _ensure_flow_log/_active_log/chat_log/_apply_workflow (self._wf) — điểm dễ vỡ nhất khi tách file chat ra khỏi co4e_tab.py. | chua/khong ro | - |
| Co4ETab._chat_widget | 1066 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._mhdr | 1072 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.msgs_icon | 1074 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.msgs_title | 1075 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.chat_toggle_btn | 1076 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.chat_stack | 1091 | presentation/co4e/co4e_chat_view.py | chuyển self.center_stack tương tự — dùng chung với self.center_stack (co4e_tab.py). | chua/khong ro | - |
| Co4ETab._flow_logs | 1092 | presentation/co4e/co4e_chat_view.py | Dict[str, ChatView] keyed theo workflow id — TRẠNG THÁI CHIA SẺ chính của toàn bộ logic chat theo-flow; đọc/ghi bởi _ensure_flow_log, _active_log, chat_log, _apply_workflow, và các hàm chat khác ngoài phạm vi đọc (>1400). | chua/khong ro | - |
| Co4ETab.chat_input_row | 1094 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._usage_total_lbl | 1099 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.chat_input | 1105 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.chat_send_btn | 1108 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.co4e_routing_toggle | 1113 | presentation/co4e/co4e_chat_view.py | RoutingToggle(self.ctx, 'co4e') — self.ctx là trạng thái chia sẻ của cả Co4ETab (khởi tạo ngoài phạm vi đọc). | chua/khong ro | - |
| Co4ETab._co4e_routed_provider | 1114; 1853 | presentation/co4e/co4e_chat_view.py | [GỘP 2 lượt quét trùng ký hiệu] (dòng 1114-1114, target gốc=presentation/co4e/co4e_chat_view.py) override provider cho lượt chat kế tiếp — dùng bởi _apply_co4e_routing (ngoài phạm vi đọc, >1400). \|\| (dòng 1853-1853, target gốc=presentation/co4e/co4e_chat_view.py) gán None lần đầu tại đây (trong _apply_co4e_routing); đọc bằng getattr(self, '_co4e_routed_provider', None) ở _run_chat_turn dòng ~1922 — gợi ý có thể không được init trong __init__. Trạng thái routing theo từng lượt chat, dùng chung giữa chat-view và _start_canvas_run/manager.start. | chua/khong ro | [GỘP 2 lượt quét trùng ký hiệu] (dòng 1114-1114, target gốc=presentation/co4e/co4e_chat_view.py) overr |
| Co4ETab._vsplit_sizes | 1121 | presentation/co4e/co4e_chat_view.py | dùng bởi _toggle_messages để restore kích thước splitter — chia sẻ với self._vsplit (co4e_tab.py). | chua/khong ro | - |
| Co4ETab._msgs_collapsed | 1122 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._toggle_messages | 1129-1161 | presentation/co4e/co4e_chat_view.py | thao tác self._vsplit (tạo ở co4e_tab.py/_build_center) — trạng thái chia sẻ giữa co4e_chat_view.py và co4e_tab.py. | chua/khong ro | - |
| Co4ETab._ensure_flow_log | 1164-1173 | presentation/co4e/co4e_chat_view.py | đọc/ghi self._flow_logs — trạng thái chia sẻ chính của chat theo-flow. | chua/khong ro | - |
| Co4ETab._active_log | 1175-1177 | presentation/co4e/co4e_chat_view.py | đọc self._wf — trạng thái chia sẻ với toàn bộ Co4ETab (canvas, sidebar, save/autosave, run control). | chua/khong ro | - |
| Co4ETab.chat_log | 1180-1183 | presentation/co4e/co4e_chat_view.py | @property, chỉ đọc, uỷ nhiệm cho _active_log(). | chua/khong ro | - |
| Co4ETab._plan_bubble | 1186-1187 | presentation/co4e/co4e_chat_view.py | @property getter, đọc self._active_log()._co4e_plan_bubble (thuộc tính gắn thêm vào từng instance ChatView). | chua/khong ro | - |
| Co4ETab._plan_bubble (setter) | 1189-1191 | presentation/co4e/co4e_chat_view.py | @_plan_bubble.setter, ghi self._active_log()._co4e_plan_bubble. | chua/khong ro | - |
| Co4ETab._chat_send | 1820-1846 | presentation/co4e/co4e_chat_view.py | self.chat_input.clear(), self._append_chat — thao tác widget; điều phối /agent /skill directive rồi gọi self._run_chat_turn (network qua provider, không trực tiếp trong hàm này) | chua/khong ro | - |
| Co4ETab._apply_co4e_routing | 1848-1883 | presentation/co4e/co4e_chat_view.py | gọi confirm_switch (dialog Qt) khi mode=='manual' và self._append_chat khi có switch — cần widget sống. Gán self._co4e_routed_provider (xem attribute riêng). | chua/khong ro | - |
| Co4ETab._extract_agent_directive | 1885-1891 | presentation/co4e/co4e_chat_view.py | regex thuần Python | chua/khong ro | - |
| Co4ETab._resolve_agent | 1893-1901 | presentation/co4e/co4e_chat_view.py | tra cứu BUILTIN_AGENTS và co4e.list_custom_agents() (bộ nhớ/đĩa tùy triển khai list_custom_agents, không rõ trong khoảng đọc) — cross-reference với agent_list_panel.py (nguồn danh sách custom agent) | chua/khong ro | - |
| Co4ETab._run_chat_turn | 1903-1974 | presentation/co4e/co4e_chat_view.py | 72 dòng, gộp: chuẩn bị prompt, tạo bubble stream, định nghĩa 4 closures nội bộ (job/on_event/done/failed) và khởi worker nền — nên tách các closures ra thành hàm riêng nếu dễ đọc hơn. Closure job() gọi run_cowork(provider,...) — network/AI call thật sự. Đọc/ghi self._chat_worker, self._co4e_routed_provider, self.chat_send_btn, self._wf; set log._co4e_plan_bubble=None (thuộc log là ChatView, không phải self). | chua/khong ro | - |
| Co4ETab._run_chat_turn.job | 1917-1946 | presentation/co4e/co4e_chat_view.py | closure nội bộ của _run_chat_turn, chạy trong AgentWorker (thread nền); gọi run_cowork(provider,...) — network/AI call thật; dùng usage_tracker (đọc/ghi trạng thái tích lũy usage) | chua/khong ro | - |
| Co4ETab._run_chat_turn.on_event | 1948-1954 | presentation/co4e/co4e_chat_view.py | closure nội bộ, cập nhật assistant.set_markdown và log.scroll_to_bottom (widget) | chua/khong ro | - |
| Co4ETab._run_chat_turn.done | 1956-1962 | presentation/co4e/co4e_chat_view.py | closure nội bộ, gán self._chat_worker = None, thao tác widget assistant/log | chua/khong ro | - |
| Co4ETab._run_chat_turn.failed | 1964-1967 | presentation/co4e/co4e_chat_view.py | closure nội bộ, gán self._chat_worker = None, gọi self._append_chat lỗi | chua/khong ro | - |
| Co4ETab._append_chat | 1976-1991 | presentation/co4e/co4e_chat_view.py | nhận tham số log tùy chọn, mặc định self.chat_log — dùng bởi rất nhiều method ở cả run-control (qua tham số log truyền vào) và chat-view; điểm nối giữa hai nhóm. | chua/khong ro | - |
| Co4ETab._fmt_usage | 1994-2001 | presentation/co4e/co4e_chat_view.py | format chuỗi thuần, đọc self.ctx.config.data — không chạm widget | chua/khong ro | - |
| Co4ETab._apply_usage | 2003-2020 | presentation/co4e/co4e_chat_view.py | bub.add_usage(...) thao tác widget bubble; ghi self._flow_usage[wf_id] — trạng thái tổng usage theo flow, dùng chung với _refresh_usage_total | chua/khong ro | - |
| Co4ETab._refresh_usage_total | 2022-2037 | presentation/co4e/co4e_chat_view.py | self._usage_total_lbl.setText — đọc self._wf, self._flow_usage | chua/khong ro | - |
| Co4ETab._append_diff | 2039-2043 | presentation/co4e/co4e_chat_view.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._append_plan | 2045-2056 | presentation/co4e/co4e_chat_view.py | đọc/ghi log._co4e_plan_bubble (thuộc tính động trên đối tượng log/ChatView, không phải self) | chua/khong ro | - |
| _html_escape | 2082-2083 | presentation/co4e/co4e_chat_view.py | hàm module-level (ngoài class Co4ETab), escape HTML thuần, dùng cho hiển thị chat | chua/khong ro | - |
| _PLAN_GLYPH | 45-46 | presentation/co4e/co4e_run_control_widget.py | module-level dict glyph trạng thái dùng bởi _fmt_plan | chua/khong ro | - |
| _fmt_plan | 49-58 | presentation/co4e/co4e_run_control_widget.py | helper thuần Python dùng bởi _render_plan() | chua/khong ro | - |
| Co4ETab.manager | 238 | presentation/co4e/co4e_run_control_widget.py | Co4ERunManager — lõi run control, trạng thái chia sẻ với canvas (node status) và chat view (run_logs) | chua/khong ro | - |
| Co4ETab._flow_runs | 243 | presentation/co4e/co4e_run_control_widget.py | map wf_id->run id, chia sẻ với _open_flow/_close_flow_tab (co4e_tab.py) và canvas | chua/khong ro | - |
| Co4ETab._run_logs | 244 | presentation/co4e/co4e_run_control_widget.py | map run_id->ChatView, chia sẻ với co4e_chat_view.py | chua/khong ro | - |
| Co4ETab._flow_usage | 248 | presentation/co4e/co4e_run_control_widget.py | usage token/cost theo flow, hiển thị ở Messages header | chua/khong ro | - |
| Co4ETab._manual_active | 252 | presentation/co4e/co4e_run_control_widget.py | chia sẻ với _close_flow_tab (co4e_tab.py) — set lại self.run_btn khi đóng tab | chua/khong ro | - |
| Co4ETab._manual_order | 253 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._manual_idx | 254 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._cur_run_id | 460-473 | presentation/co4e/co4e_run_control_widget.py | logic thuần Python, không gọi Qt trực tiếp | chua/khong ro | - |
| Co4ETab._update_run_btn | 480-482 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.runs_more_btn | 586 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.runs_side_list | 594 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._SIDE_RUNS | 605 | presentation/co4e/co4e_run_control_widget.py | class-level constant, không phải self. | chua/khong ro | - |
| Co4ETab._refresh_side_runs | 607-619 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._on_side_run_clicked | 621-629 | presentation/co4e/co4e_run_control_widget.py | chạm self.runs_table (định nghĩa ngoài khoảng đọc — thuộc trang Flow Status) | chua/khong ro | - |
| Co4ETab.mode_combo | 828 | presentation/co4e/co4e_run_control_widget.py | combo chọn run mode auto/plan/manual — thuộc nhóm _set_run_mode() trong plan.md dù được dựng bên trong _build_center (co4e_tab.py); ranh giới tách file ở đây dễ vỡ. | co | - |
| Co4ETab.run_btn | 833 | presentation/co4e/co4e_run_control_widget.py | nút Run — tương tự mode_combo, dựng trong _build_center nhưng thuộc nhóm run control; cũng bị _update_run_btn (<701), _on_run_clicked, _on_mode_changed đọc/ghi text. | chua/khong ro | - |
| Co4ETab.runs_btn | 840 | presentation/co4e/co4e_run_control_widget.py | toggle chuyển sang trang Runs (self.center_stack) — chia sẻ state center_stack với co4e_tab.py. | chua/khong ro | - |
| Co4ETab._build_runs_page | 873-932 | presentation/co4e/co4e_run_control_widget.py | dựng trang bảng Runs (theo dõi mọi run của mọi flow) — dùng self.manager (Co4ERunManager, sẽ thay bằng co4e_workflow_service) — trạng thái chia sẻ. | chua/khong ro | - |
| Co4ETab.runs_back_btn | 882 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.runs_title | 887 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.ws_folder_btn | 892 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.run_stop_btn | 900 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.run_rename_btn | 905 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.run_del_btn | 909 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.run_clear_btn | 913 | presentation/co4e/co4e_run_control_widget.py | clicked gọi self.manager.clear_finished() — trạng thái chia sẻ self.manager. | chua/khong ro | - |
| Co4ETab.runs_table | 921 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._current_mode | 1384-1385 | presentation/co4e/co4e_run_control_widget.py | đọc self.mode_combo — khớp nhóm _set_run_mode() dòng 624 plan.md. | co | - |
| Co4ETab._on_mode_changed | 1387-1393 | presentation/co4e/co4e_run_control_widget.py | reset self._manual_active/_manual_order/_manual_idx (trạng thái chia sẻ với luồng manual step _manual_step/_manual_run_or_advance, ngoài phạm vi đọc >1400) và gọi self._cur_run_id() (chia sẻ với self.manager). | chua/khong ro | - |
| Co4ETab._on_run_clicked | 1395-1400 | presentation/co4e/co4e_run_control_widget.py | cắt ngang lát — cần agent gộp đối chiếu (tiếp tục sau dòng 1400). Dùng self.manager.stop() và self._cur_run_id() — trạng thái chia sẻ với co4e_workflow_service tương lai. Khớp nhóm _run_flow()/_stop_flow() dòng 618 plan.md (dù đó là bản service, đây là UI handler nút Run). | co | - |
| Co4ETab.<method truoc dong 1401, ten chua xac dinh - co the la _on_run_clicked> | 1401-1405 | presentation/co4e/co4e_run_control_widget.py | cắt ngang lát — cần agent gộp đối chiếu. Định nghĩa (def ...) nằm ở lát trước dòng 1401 nên tên chính xác không xác định được; đoạn thấy được chỉ dispatch theo self._current_mode() sang _manual_run_or_advance() hoặc _start_canvas_run() — thuộc nhóm Run/mode. | chua/khong ro | (def ...) nằm ở lát trước dòng 1401 nên tên chính xác không xác định được; đoạn thấy được chỉ dispatch theo self._current_mode() sang _manual_run_or |
| Co4ETab._start_canvas_run | 1407-1424 | presentation/co4e/co4e_run_control_widget.py | gọi self.manager.start(...) — spawn chạy flow (dẫn tới gọi provider AI ở tầng khác); đọc/ghi self._wf, self._flow_runs, self._flow_runs[wf_id], self._run_logs, self.chat_log — trạng thái chia sẻ giữa run-control và chat-view. self.manager (Co4ERunManager) nên đổi sang application/workflows/co4e_workflow_service.py theo mapping. | chua/khong ro | - |
| Co4ETab._run_single | 1426-1431 | presentation/co4e/co4e_run_control_widget.py | wrapper mỏng gọi _start_canvas_run; đọc self._wf.id | chua/khong ro | - |
| Co4ETab._run_from | 1433-1437 | presentation/co4e/co4e_run_control_widget.py | wrapper mỏng gọi _start_canvas_run với self._downstream(node_id) | chua/khong ro | - |
| Co4ETab._downstream | 1439-1450 | presentation/co4e/co4e_run_control_widget.py | thuật toán BFS thuần Python, chỉ đọc self.canvas.edges() làm input — test được với danh sách edge giả lập, không cần canvas thật | chua/khong ro | - |
| Co4ETab._manual_run_or_advance | 1453-1466 | presentation/co4e/co4e_run_control_widget.py | gọi self.canvas.reset_statuses() và self._append_chat (self._append_chat thuộc nhóm chat-view) — cắt ngang giữa run-control và chat-view. Đọc/ghi self._manual_active, self._manual_order, self._manual_idx, self._wf, self._outputs_for(...), self._plan_bubble — trạng thái run thuần túy chia sẻ với _manual_step. | chua/khong ro | - |
| Co4ETab._manual_step | 1468-1484 | presentation/co4e/co4e_run_control_widget.py | gọi self.manager.start(...) (network/AI qua provider) và self.run_btn.setText, self._append_chat (chat-view); đọc/ghi self._manual_idx, self._manual_order, self._wf, self._flow_runs, self._run_logs, self.chat_log — trạng thái chia sẻ rộng giữa run-control và chat-view. | chua/khong ro | - |
| Co4ETab._topo_order | 1486-1491 | presentation/co4e/co4e_run_control_widget.py | đọc self.canvas.nodes()/edges() làm dữ liệu đầu vào, logic tính toán thuần túy (co4e.compute_waves) — test được với dữ liệu giả | chua/khong ro | - |
| Co4ETab._on_manager_event | 1494-1550 | presentation/co4e/co4e_run_control_widget.py | method dài (57 dòng), gộp nhiều việc không liên quan: định tuyến sự kiện chạy theo từng flow (routing run_id -> log), cập nhật trạng thái node trên canvas, hiển thị bubble chat (assistant/diff/plan/tool-failed — thuộc co4e_chat_view.py), xử lý hoàn tất run (run_done/run_error), hiển thị popup thông báo, cập nhật status bar. Nên tách phần hiển thị chat (self._append_chat/_append_diff/_append_plan) sang co4e_chat_view.py, giữ phần routing/flow-completion ở co4e_run_control_widget.py. Đọc/ghi self._flow_runs, self._run_logs, self.chat_log, self.canvas, self._wf, self._outputs_for(...), self._manual_active, self._manual_idx — trạng thái chia sẻ rất rộng, điểm dễ vỡ nhất khi tách file. | chua/khong ro | - |
| Co4ETab._notify_run_finished | 1552-1573 | presentation/co4e/co4e_run_control_widget.py | tạo QMessageBox không chặn; khởi tạo lazy self._run_popups (xem attribute riêng) | chua/khong ro | - |
| Co4ETab._run_popups | 1560-1561 | presentation/co4e/co4e_run_control_widget.py | khởi tạo lazy (list rỗng) trong _notify_run_finished qua hasattr guard — không init trong __init__; giữ ref các QMessageBox non-blocking khỏi bị GC | chua/khong ro | - |
| Co4ETab._refresh_runs | 1575-1616 | presentation/co4e/co4e_run_control_widget.py | render bảng runs_table + gọi self._refresh_side_runs() (sidebar) + cập nhật self.flow_bar.setTabText và self._sections['co4e.runs_tab'] — self._sections và self.flow_bar là trạng thái chia sẻ với co4e_tab.py (container/sidebar). | chua/khong ro | - |
| Co4ETab._stop_selected_run | 1618-1624 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._delete_selected_run | 1626-1639 | presentation/co4e/co4e_run_control_widget.py | đọc/ghi self._flow_runs, self._run_logs — trạng thái chia sẻ với _on_manager_event/_start_canvas_run | chua/khong ro | - |
| Co4ETab._runs_context_menu | 1641-1655 | presentation/co4e/co4e_run_control_widget.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._open_run_output_folder | 1704-1715 | presentation/co4e/co4e_run_control_widget.py | path.mkdir + open_location (spawn process); dùng bởi _runs_context_menu 'Open output' | chua/khong ro | - |
| Co4ETab._rename_selected_run | 1717-1748 | presentation/co4e/co4e_run_control_widget.py | gọi co4e.save_workflow(wf) (ghi đĩa); đọc/ghi self._flows (list flow của sidebar/tab-bar), self.flow_bar, self.name_edit, self._wf — chạm nhiều trạng thái chia sẻ với co4e_tab.py container (tab bar + name edit thuộc header, không rõ nằm ở panel nào) — rủi ro vỡ cao khi tách. | chua/khong ro | - |
| Co4ETab._run_selected_in_background | 1750-1760 | presentation/co4e/co4e_run_control_widget.py | gọi self.manager.start(...) (network/AI) và self._refresh_side_runs() (widget) | chua/khong ro | - |
| Co4ETab._wf_by_id | 1762-1770 | presentation/co4e/co4e_run_control_widget.py | gọi co4e.get_workflow(wf_id) (đọc đĩa) và self._sync_wf_from_canvas() (không nằm trong khoảng đọc) — đọc self._wf; dùng chung bởi _rerun_run_item/_open_run_from_table (Runs tab) và có thể cả co4e_tab.py container | chua/khong ro | - |
| Co4ETab._rerun_run_item | 1772-1783 | presentation/co4e/co4e_run_control_widget.py | gọi self.manager.start(...) (network/AI) | chua/khong ro | - |
| Co4ETab._open_run_from_table | 1785-1804 | presentation/co4e/co4e_run_control_widget.py | gọi self._open_flow(wf) (không nằm trong khoảng đọc, theo plan.md thuộc co4e_tab.py) và self.canvas.update_node_status — nối Runs tab với việc mở flow trên canvas, điểm khớp nối giữa run-control và container/canvas. | co | - |
| _qcolor | 2086-2088 | presentation/co4e/co4e_run_control_widget.py | hàm module-level (ngoài class Co4ETab), tạo QColor từ hex string — dùng kiểu giá trị QColor, không cần QApplication sống; dùng trong _refresh_runs để tô màu status | chua/khong ro | - |
| _EqualTabBar | 74-94 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| _EqualTabBar._GAP | 80 | presentation/co4e/co4e_tab.py | class-level constant, không phải self. | chua/khong ro | - |
| _EqualTabBar.tabSizeHint | 82-90 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| _EqualTabBar.resizeEvent | 92-94 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab | 229-700 | presentation/co4e/co4e_tab.py | Lớp kéo dài quá dòng 700 (cắt ngang lát) — chỉ ghi nhận phần 229-700; 'status_message = Signal(str)' dòng 230 là thuộc tính lớp, không phải self. | chua/khong ro | - |
| Co4ETab.__init__ | 232-304 | presentation/co4e/co4e_tab.py | method 73 dòng, gộp: khởi state run/flow, dựng splitter 3 cột (sidebar/center/config), wiring canvas & config panel, gọi _reload_sidebar (đọc đĩa qua co4e.list_workflows) và _open_flow; chạm rất nhiều thuộc tính chia sẻ: self._wf, self._flows, self.manager, self._flow_runs, self._run_logs, self._flow_outputs, self._flow_usage, self.config, self.canvas (gán ở _build_center ngoài khoảng đọc này) | chua/khong ro | - |
| Co4ETab.ctx | 234 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._wf | 235 | presentation/co4e/co4e_tab.py | trạng thái chia sẻ — đọc/ghi bởi canvas, run control, chat view | chua/khong ro | - |
| Co4ETab._flows | 257 | presentation/co4e/co4e_tab.py | danh sách flow đang mở dạng tab — trạng thái chia sẻ nhạy cảm (nêu rõ trong hướng dẫn đề bài) | chua/khong ro | - |
| Co4ETab._active_flow_idx | 258 | presentation/co4e/co4e_tab.py | chỉ số tab đang active — chia sẻ giữa _open_flow, _on_flow_tab_changed, _reflect_active_run | chua/khong ro | - |
| Co4ETab._split | 261 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._config_collapsed | 274 | presentation/co4e/co4e_tab.py | trạng thái cho _toggle_config (định nghĩa dòng 989, ngoài khoảng đọc); plan.md xếp _toggle_config ở co4e_tab.py container | co | - |
| Co4ETab._config_expanded_w | 275; 995 | presentation/co4e/co4e_tab.py | [GỘP 2 lượt quét trùng ký hiệu] (dòng 275-275, target gốc=presentation/co4e/co4e_tab.py) cùng lý do với _config_collapsed \|\| (dòng 995-995, target gốc=presentation/co4e/co4e_tab.py) gán trong nhánh collapse của _toggle_config; có thể đã khởi tạo trong __init__ (ngoài phạm vi đọc). | chua/khong ro | [GỘP 2 lượt quét trùng ký hiệu] (dòng 275-275, target gốc=presentation/co4e/co4e_tab.py) cùng lý do vớ |
| Co4ETab._narrow_guard | 280 | presentation/co4e/co4e_tab.py | gắn với _apply_narrow_layout (dòng 977, ngoài khoảng đọc) | chua/khong ro | - |
| Co4ETab._open_flow | 307-338 | presentation/co4e/co4e_tab.py | khớp plan.md: _open_flow() -> co4e_tab.py, gọi canvas; chạm self._flows, self.flow_bar (định nghĩa ngoài khoảng đọc), self.canvas | co | - |
| Co4ETab._close_other_flows | 340-355 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._show_runs | 357-367 | presentation/co4e/co4e_tab.py | chuyển đổi center_stack giữa flow editor và Runs table — liên quan Flow Status (run control) | chua/khong ro | - |
| Co4ETab._on_flow_tab_changed | 369-385 | presentation/co4e/co4e_tab.py | chạm self.center_stack (định nghĩa ngoài khoảng đọc, ở _build_center) | chua/khong ro | - |
| Co4ETab._sync_runs_toggle | 387-394 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._add_tab_close_button | 396-406 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._close_flow_tab_button | 408-412 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._close_flow_tab | 414-442 | presentation/co4e/co4e_tab.py | chạm self._flow_runs/_run_logs/_manual_active/self.run_btn (chia sẻ với run control widget) | chua/khong ro | - |
| Co4ETab._sync_active_flow_tab_text | 444-447 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._build_sidebar | 485-603 | presentation/co4e/co4e_tab.py | >80 dòng (119 dòng) — gộp dựng 4 section (Workflows/Agents/Skills/Runs) + wiring nhiều nút bấm; nên tách theo section: Workflows giữ ở container, Agents nên chuyển agent_list_panel.py, Skills đã tách (chỉ còn wiring), Runs nên chuyển co4e_run_control_widget.py | chua/khong ro | - |
| Co4ETab._sections | 493 | presentation/co4e/co4e_tab.py | trạng thái chia sẻ (nêu rõ trong hướng dẫn đề bài) — dùng bởi _fold_section, _sync_section_arrow | chua/khong ro | - |
| Co4ETab.sidebar | 494 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.side_split | 498 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| _Col | 503-511 | presentation/co4e/co4e_tab.py | adapter nội bộ định nghĩa bên trong _build_sidebar, chỉ dùng tại chỗ | chua/khong ro | - |
| _Col.__init__ | 506-507 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| _Col.addWidget | 509-511 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_new_btn | 516 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_list | 527 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_edit_btn | 534 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_dup_btn | 535 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_del_btn | 536 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.wf_runbg_btn | 543 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._skills_panel | 575 | presentation/co4e/co4e_tab.py | instantiate SkillsListPanel đã tách; Co4ETab giữ wiring theo comment trong code (dòng 571-574) | chua/khong ro | - |
| Co4ETab.sk_manage_btn | 576 | presentation/co4e/co4e_tab.py | cùng lý do với _skills_panel | chua/khong ro | - |
| Co4ETab.skill_list | 578 | presentation/co4e/co4e_tab.py | cùng lý do với _skills_panel | chua/khong ro | - |
| Co4ETab._section | 631-663 | presentation/co4e/co4e_tab.py | chạm self._sections (chia sẻ) — helper dựng section sidebar dùng chung | chua/khong ro | - |
| Co4ETab._fold_section | 665-677 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._sync_section_arrow | 679-681 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._icon_btn | 683-687 | presentation/co4e/co4e_tab.py | helper dùng chung tạo nút icon, dùng bởi cả section Workflows và Agents | chua/khong ro | - |
| Co4ETab._reload_sidebar | 689-722 | presentation/co4e/co4e_tab.py | [GỘP 2 lượt quét trùng ký hiệu] (dòng 689-700, target gốc=presentation/co4e/co4e_tab.py) cắt ngang lát — cần agent gộp đối chiếu (method tiếp tục sau dòng 700); gọi co4e.list_workflows() (đọc đĩa) rồi dựng QListWidgetItem trực tiếp trong cùng hàm — trộn data-fetch và UI, nên tách phần đọc dữ liệu sang co4e_workflow_service.py \|\| (dòng 689-722, target gốc=unsure) cắt ngang lát — cần agent gộp đối chiếu (bắt đầu trước dòng 701). Gộp refresh cả agent_list và skill_list trong cùng 1 hàm — nên tách thành _refresh_agents_list (agent_list_panel.py) và _refresh_skills_list (skills_list_panel.py) như plan.md yêu cầu; gọi co4e.list_custom_agents() (đĩa) và skills_mod.skill_prefix_for (đĩa). | co | [GỘP 2 lượt quét trùng ký hiệu] (dòng 689-700, target gốc=presentation/co4e/co4e_tab.py) cắt ngang lát |
| Co4ETab._build_center | 731-871 | presentation/co4e/co4e_tab.py | dài ~140 dòng, làm nhiều việc không liên quan: dựng flow tab bar (ẩn, không hiển thị cho user), dựng runs-page stack, toolbar flow (name_edit/save/save_tpl/mode_combo/run_btn/runs_btn), tạo canvas, gọi _build_canvas_overlay, tạo chat widget, splitter dọc self._vsplit. Nên tách nhỏ. Đọc self._wf.name (dòng 814) và tạo self.center_stack — TRẠNG THÁI CHIA SẺ dùng bởi _show_runs/_apply_workflow (ngoài phạm vi đọc). Khớp phần '_build_canvas()' trong bảng plan.md dòng 615. | co | - |
| Co4ETab.flow_bar | 738 | presentation/co4e/co4e_tab.py | QTabBar bị ẩn (setVisible False dòng 802), chỉ dùng làm index nội bộ ánh xạ flow↔canvas — trạng thái chia sẻ với _on_flow_tab_changed/_close_flow_tab (định nghĩa <701, ngoài phạm vi đọc). | chua/khong ro | - |
| Co4ETab.flow_add_btn | 764 | presentation/co4e/co4e_tab.py | ẩn (setVisible False), không hiển thị cho user hiện tại. | chua/khong ro | - |
| Co4ETab.flow_scroll | 781 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.center_stack | 805 | presentation/co4e/co4e_tab.py | TRẠNG THÁI CHIA SẺ — chuyển đổi giữa trang Runs (co4e_run_control_widget) và trang flow editor; dùng bởi _show_runs (ngoài phạm vi đọc) và _apply_workflow. | chua/khong ro | - |
| Co4ETab.name_edit | 814 | presentation/co4e/co4e_tab.py | khởi tạo từ self._wf.name — trạng thái chia sẻ; cũng bị _on_name_changed/_new_workflow đọc/ghi. | chua/khong ro | - |
| Co4ETab.add_step_btn | 819 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.save_btn | 822 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.save_tpl_btn | 826 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._vsplit | 863 | presentation/co4e/co4e_tab.py | splitter dọc canvas/chat — dùng chung với _toggle_messages (co4e_chat_view.py thao tác self._vsplit.setSizes) — trạng thái chia sẻ giữa co4e_tab.py và co4e_chat_view.py. | chua/khong ro | - |
| Co4ETab._NARROW | 971 | presentation/co4e/co4e_tab.py | hằng class-level (không phải self.), ngưỡng chiều rộng dùng bởi _apply_narrow_layout. | chua/khong ro | - |
| Co4ETab.showEvent | 973-975 | presentation/co4e/co4e_tab.py | Qt override, gọi self._narrow_guard.attach() (đối tượng khởi tạo ngoài phạm vi đọc, <701). [ANOMALY: cùng tên method định nghĩa 2 lần ở 2 dòng khác nhau trong cùng class -- có khả năng là lỗi nguồn (định nghĩa sau đè định nghĩa trước), không phải do quét trùng; giữ 2 dòng riêng, cần người quyết định định nghĩa nào còn hiệu lực] | chua/khong ro | ợng khởi tạo ngoài phạm vi đọc, <701). [ANOMALY: cùng tên method định nghĩa 2 lần ở 2 dòng khác nhau trong cùng class -- có khả |
| Co4ETab._apply_narrow_layout | 977-987 | presentation/co4e/co4e_tab.py | so self._config_collapsed rồi gọi self._toggle_config() — trạng thái chia sẻ với node_property_panel wrap logic. | chua/khong ro | - |
| Co4ETab._toggle_config | 989-1032 | presentation/co4e/co4e_tab.py | dài 44 dòng, gộp: ẩn/hiện self.config (widget thuộc node_property_panel.py), đổi icon, tính lại self._split.setSizes, gọi _refresh_min_width — thao tác trực tiếp self.config/self.config_container (node_property_panel.py) và self._split (co4e_tab.py) cùng lúc — ranh giới tách file dễ vỡ nhất ở đoạn này. Ghi self._config_expanded_w. | chua/khong ro | - |
| Co4ETab._refresh_min_width | 1034-1039 | presentation/co4e/co4e_tab.py | thao tác trực tiếp self._split (QSplitter) và self.config_container — chia sẻ với _build_center/_wrap_config. | chua/khong ro | - |
| Co4ETab._apply_workflow | 1194-1207 | presentation/co4e/co4e_tab.py | hàm điều phối trung tâm khi mở 1 flow: gán self._wf (TRẠNG THÁI CHIA SẺ dùng khắp mọi nhóm chức năng — canvas, chat_stack/_flow_logs, config panel, run button, usage total). Đây là điểm nối chính giữa các file sau khi tách — không nên tách nhỏ hơn nếu không rất cẩn thận. | chua/khong ro | - |
| Co4ETab._new_workflow | 1209-1217 | presentation/co4e/co4e_tab.py | gọi self._open_flow(...) — khớp dòng plan.md '_open_flow() -> co4e_tab.py → gọi canvas'. | co | - |
| Co4ETab._selected_wf | 1219-1225 | presentation/co4e/co4e_tab.py | đọc self.wf_list (sidebar, dựng ở _build_sidebar <701) rồi gọi co4e.get_workflow (đĩa). | chua/khong ro | - |
| Co4ETab._load_selected_workflow | 1227-1230 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._edit_selected_workflow | 1232-1237 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._wf_context_menu | 1248-1271 | presentation/co4e/co4e_tab.py | dựng QMenu cho sidebar flows, điều phối gọi _edit_selected_workflow/_rename_workflow/_duplicate_selected_workflow/_run_selected_in_background/_delete_selected_workflow (một số nằm ngoài phạm vi đọc, dòng >1400). | chua/khong ro | - |
| Co4ETab._sync_wf_from_canvas | 1299-1302 | presentation/co4e/co4e_tab.py | đọc self.canvas.nodes()/edges() và ghi self._wf.nodes/edges/name — cầu nối giữa co4e_canvas_widget.py và trạng thái self._wf chia sẻ; cân nhắc đặt cùng canvas nếu muốn canvas tự chịu trách nhiệm export dữ liệu. | chua/khong ro | - |
| Co4ETab._on_name_changed | 1316-1318 | presentation/co4e/co4e_tab.py | ghi self._wf.name (trạng thái chia sẻ) rồi gọi self._sync_active_flow_tab_text() (định nghĩa dòng 444, ngoài phạm vi đọc). | chua/khong ro | - |
| Co4ETab._add_blank_step | 1320-1322 | presentation/co4e/co4e_tab.py | nút 'Add' trên toolbar uỷ nhiệm sang self.canvas.add_palette_step — liên quan nhóm _add_node() trong plan.md (co4e_canvas_widget.py) nhưng bản thân handler chỉ là cầu nối từ toolbar. | co | - |
| Co4ETab.set_project | 1658-1674 | presentation/co4e/co4e_tab.py | gọi load_project(project_id) (đọc đĩa) và self.manager.set_output_root/set_current_project (self.manager nên là co4e_workflow_service). Gán self._project_id, self._project_dir — không chắc là lần gán đầu tiên (có thể đã init ở __init__ ngoài khoảng đọc). Không khớp rõ nhóm nào trong danh sách đích cho trước — xếp tạm vào co4e_tab.py vì đây là API binding cấp container gọi từ ngoài. | chua/khong ro | ể đã init ở __init__ ngoài khoảng đọc). Không khớp rõ nhóm nào trong danh sách đích cho trước — xếp tạm vào co4e_tab.py vì đây là |
| Co4ETab._flow_output_root | 1676-1686 | presentation/co4e/co4e_tab.py | helper dùng chung bởi cả chat (_out_dir) và run-control (_open_workspace_folder, _open_run_output_folder) — trạng thái/logic cắt ngang nhiều nhóm; đọc self._project_dir, self.ctx.config | chua/khong ro | - |
| Co4ETab._refresh_ws_folder_btn | 1688-1693 | presentation/co4e/co4e_tab.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._open_workspace_folder | 1695-1702 | presentation/co4e/co4e_tab.py | root.mkdir + open_location (mở file explorer hệ điều hành — spawn process) | chua/khong ro | - |
| Co4ETab.showEvent | 1806-1809 | presentation/co4e/co4e_tab.py | override Qt lifecycle method của chính QWidget container nên phải ở lại co4e_tab.py; gọi self._refresh_runs() (thuộc co4e_run_control_widget.py) — điểm nối giữa container và run-control widget. [ANOMALY: cùng tên method định nghĩa 2 lần ở 2 dòng khác nhau trong cùng class -- có khả năng là lỗi nguồn (định nghĩa sau đè định nghĩa trước), không phải do quét trùng; giữ 2 dòng riêng, cần người quyết định định nghĩa nào còn hiệu lực] | chua/khong ro | giữa container và run-control widget. [ANOMALY: cùng tên method định nghĩa 2 lần ở 2 dòng khác nhau trong cùng class -- có khả |
| Co4ETab._out_dir | 1811-1817 | presentation/co4e/co4e_tab.py | d.mkdir(parents=True, exist_ok=True) — ghi đĩa; dùng chung bởi _run_chat_turn (chat) và tiềm năng bởi run-control; đọc self._wf.name, self._flow_output_root() | chua/khong ro | - |
| Co4ETab._retranslate | 2059-2079 | presentation/co4e/co4e_tab.py | cập nhật text i18n cho rất nhiều widget thuộc nhiều nhóm khác nhau (sidebar buttons, runs_table, run control buttons) và gọi self._reload_sidebar()/self._refresh_runs() — thuộc container vì bao trùm toàn tab, dù có thể tách nhỏ theo từng panel sau này. | chua/khong ro | - |
| _SectionHeader | 30-52 | presentation/co4e/node_property_panel.py | Widget nội bộ (header có thể click, thu/mở section) chỉ dùng bởi StepConfigPanel; không có trong bảng plan.md/function_list.md, xếp cùng chỗ với StepConfigPanel vì mô tả node_property_panel.py là 'Bọc StepConfigPanel' | co | section) chỉ dùng bởi StepConfigPanel; không có trong bảng plan.md/function_list.md, xếp cùng chỗ với StepConfigPanel vì mô tả node_property_panel |
| _SectionHeader.clicked | 36 | presentation/co4e/node_property_panel.py | Signal Qt khai báo ở cấp class, không phải self.<tên> gán trong __init__ | chua/khong ro | - |
| _SectionHeader.mousePressEvent | 38-41 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| _SectionHeader.showEvent | 43-52 | presentation/co4e/node_property_panel.py | recompute fontMetrics khi label thực sự hiển thị — cần widget đang sống, không test được nếu không có QApplication | chua/khong ro | - |
| _add_section | 55-130 | presentation/co4e/node_property_panel.py | Hàm dựng UI khối section thu gọn/mở rộng (header + body animate) dùng riêng cho StepConfigPanel; chứa 2 closure nội bộ _on_finished và _toggle. Không có trong bảng cũ. | co | closure nội bộ _on_finished và _toggle. Không có trong bảng cũ. |
| _add_section._on_finished | 103-112 | presentation/co4e/node_property_panel.py | closure lồng bên trong _add_section, không phải hàm top-level — chỉ tồn tại khi _add_section chạy | chua/khong ro | - |
| _add_section._toggle | 114-127 | presentation/co4e/node_property_panel.py | closure lồng bên trong _add_section, gắn vào header.clicked | chua/khong ro | - |
| StepConfigPanel | 133-528 | presentation/co4e/node_property_panel.py | cắt ngang lát — cần agent gộp đối chiếu (lớp còn tiếp tục sau dòng 528, chỉ đọc được 1-528). Bảng plan.md/function_list.md không liệt kê StepConfigPanel trực tiếp (chỉ có _build_config_panel() -> co4e_tab.py container); xếp theo mô tả node_property_panel.py 'Bọc StepConfigPanel, nối chọn node sang panel thuộc tính' trong danh sách đích được giao cho task này — người quyết cuối nên xác nhận lại. | co | - |
| StepConfigPanel.changed | 134 | presentation/co4e/node_property_panel.py | Signal Qt: bất kỳ field nào đổi -> canvas repaint node + autosave; đây là điểm nối trạng thái chia sẻ với canvas/co4e_workflow_service, cần giữ tên/signature khi tách file | chua/khong ro | - |
| StepConfigPanel.run_node | 135 | presentation/co4e/node_property_panel.py | Signal Qt 'chạy step này' — nối sang co4e_run_control_widget.py hoặc co4e_workflow_service.py | chua/khong ro | - |
| StepConfigPanel.run_from | 136 | presentation/co4e/node_property_panel.py | Signal Qt 'chạy từ bước này' — nối sang co4e_run_control_widget.py | chua/khong ro | - |
| StepConfigPanel.delete_node | 137 | presentation/co4e/node_property_panel.py | Signal Qt xoá step — nối sang co4e_canvas_widget.py để xoá node trên canvas | chua/khong ro | - |
| StepConfigPanel.__init__ | 139-313 | presentation/co4e/node_property_panel.py | >80 dòng (174 dòng) — gộp nhiều việc không liên quan: dựng section Cơ bản, section Model&Quyền, section Skills&Tệp, section Sub-agents (ẩn/hiện theo is_parallel), và dựng hàng nút footer Run/Run-from/Delete, cộng thêm cơ chế 'outer.addStretch(1)' vá lỗi layout. Nên tách thành các hàm _build_basic_section(), _build_model_section(), _build_skills_section(), _build_subagent_section(), _build_footer() riêng khi tách file. | chua/khong ro | - |
| StepConfigPanel.ctx | 141 | presentation/co4e/node_property_panel.py | context được truyền từ ngoài vào, dùng cho _ai_draft/_load_models (gọi AI provider) — trạng thái chia sẻ với co4e_tab.py | chua/khong ro | - |
| StepConfigPanel._step | 142 | presentation/co4e/node_property_panel.py | Step đang chỉnh sửa — trạng thái chia sẻ giữa load_step()/_on_edit()/mọi hành động subagent+attachment; do canvas gán vào qua load_step() | chua/khong ro | - |
| StepConfigPanel._node_id | 143 | presentation/co4e/node_property_panel.py | id node đang chọn — dùng để emit run_node/run_from/delete_node; là cầu nối canvas <-> property panel | chua/khong ro | - |
| StepConfigPanel._loading | 144 | presentation/co4e/node_property_panel.py | cờ chặn _on_edit() chạy lại trong lúc load_step() đang set giá trị field | chua/khong ro | - |
| StepConfigPanel.label_edit | 159 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.role_edit | 163 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.icon_edit | 170 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.instructions_edit | 175 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.gen_btn | 178 | presentation/co4e/node_property_panel.py | nút 'AI draft' — enable chỉ khi có ctx | chua/khong ro | - |
| StepConfigPanel.context_edit | 192 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.model_combo | 201 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.load_models_btn | 204 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.perm_combo | 214 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.verify_chk | 221 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.rounds_spin | 223 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.skills_list | 236 | presentation/co4e/node_property_panel.py | checklist skill của registry, gán checked theo step.skills | chua/khong ro | - |
| StepConfigPanel.attach_list | 242 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.attach_add_btn | 244 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.attach_del_btn | 247 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel._parallel_card | 263 | presentation/co4e/node_property_panel.py | card cả section Sub-agents; load_step() ẩn/hiện toàn bộ card này theo step.is_parallel | chua/khong ro | - |
| StepConfigPanel.sub_list | 264 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.sub_add_btn | 267 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.config | 268 | presentation/co4e/node_property_panel.py | StepConfigPanel + wiring changed/run_node/run_from/delete_node (dòng 268-273) — khớp vai trò mô tả cho node_property_panel.py | chua/khong ro | - |
| StepConfigPanel.sub_del_btn | 270 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel.run_btn | 283 | presentation/co4e/node_property_panel.py | click emit run_node(self._node_id) | chua/khong ro | - |
| StepConfigPanel.run_from_btn | 287 | presentation/co4e/node_property_panel.py | click emit run_from(self._node_id) | chua/khong ro | - |
| StepConfigPanel.del_btn | 290 | presentation/co4e/node_property_panel.py | click emit delete_node(self._node_id) | chua/khong ro | - |
| StepConfigPanel.load_step | 316-354 | presentation/co4e/node_property_panel.py | Điểm nối chính giữa canvas (khi chọn node) và panel thuộc tính — nhận (node_id, step, skill_names) từ ngoài rồi ghi self._step/self._node_id; đây là API mà co4e_canvas_widget.py hoặc co4e_tab.py sẽ gọi khi chọn node | chua/khong ro | - |
| StepConfigPanel.clear_step | 356-359 | presentation/co4e/node_property_panel.py | gọi khi bỏ chọn node — reset self._step/self._node_id | chua/khong ro | - |
| StepConfigPanel._on_edit | 362-378 | presentation/co4e/node_property_panel.py | ghi ngược giá trị field UI vào self._step rồi emit changed() — canvas repaint + autosave phụ thuộc signal này, đổi tên/behavior ở đây ảnh hưởng cả canvas lẫn service lưu flow | chua/khong ro | - |
| StepConfigPanel._available_agent_names | 380-390 | presentation/co4e/node_property_panel.py | staticmethod; gọi core.co4e.list_custom_agents() đọc file JSON trong AGENTS_DIR trên đĩa — logic thuần Python nhưng có I/O, có thể tách ra application layer nếu cần test không đụng đĩa | chua/khong ro | - |
| StepConfigPanel._add_subagent | 392-408 | presentation/co4e/node_property_panel.py | dùng QInputDialog để chọn/nhập tên agent song song | chua/khong ro | - |
| StepConfigPanel._edit_subagent | 410-428 | presentation/co4e/node_property_panel.py | double-click 1 dòng sub-agent để chọn lại agent khác | chua/khong ro | - |
| StepConfigPanel._del_subagent | 430-437 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel._add_attachment | 439-453 | presentation/co4e/node_property_panel.py | QFileDialog chỉ chọn đường dẫn hiển thị tên file, không tự đọc nội dung ở đây (nội dung được đọc lúc chạy step, ở nơi khác) | chua/khong ro | - |
| StepConfigPanel._del_attachment | 455-462 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| StepConfigPanel._ai_draft | 464-498 | presentation/co4e/node_property_panel.py | gọi generate_agent_prompt(ctx.build_active_provider(), ...) qua AgentWorker — gọi network tới AI provider, chạy nền rồi cập nhật UI ở callback done(); nếu tách sang service, phần gọi AI nên chuyển xuống application layer, phần còn lại (QInputDialog + set text) ở lại đây | chua/khong ro | - |
| StepConfigPanel._draft_worker | 497 | presentation/co4e/node_property_panel.py | giữ tham chiếu AgentWorker (QThread-like) để không bị GC giữa lúc job async đang chạy | chua/khong ro | - |
| StepConfigPanel._load_models | 500-528 | presentation/co4e/node_property_panel.py | gọi preview_ai.fetch_live_models(ctx) qua AgentWorker — network call tới provider để lấy danh sách model; cắt ngang lát — cần agent gộp đối chiếu vì dòng cuối trùng đúng biên đọc được giao (528), chưa chắc thân method đã hết ở đây | chua/khong ro | - |
| StepConfigPanel._model_worker | 525 | presentation/co4e/node_property_panel.py | giữ tham chiếu AgentWorker của _load_models để không bị GC | chua/khong ro | - |
| Co4ETab._wrap_config | 934-964 | presentation/co4e/node_property_panel.py | bọc self.config (StepConfigPanel) với header expand/collapse — khớp mô tả node_property_panel.py trong prompt. | chua/khong ro | - |
| Co4ETab.config_toggle_btn | 946 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.config_title | 951 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab._cfg_vlayout | 957 | presentation/co4e/node_property_panel.py | dùng lại trong _toggle_config (co4e_tab.py) — trạng thái chia sẻ. | chua/khong ro | - |
| Co4ETab._cfg_top_spacer | 961 | presentation/co4e/node_property_panel.py | QSpacerItem — kiểu giá trị layout, không cần QApplication đang sống. | chua/khong ro | - |
| Co4ETab._cfg_bot_spacer | 962 | presentation/co4e/node_property_panel.py | (không có ghi chú) | chua/khong ro | - |
| Co4ETab.config_container | 963 | presentation/co4e/node_property_panel.py | dùng lại bởi _toggle_config (co4e_tab.py) — trạng thái chia sẻ giữa node_property_panel.py và co4e_tab.py. | chua/khong ro | - |
| Co4ETab._on_node_selected | 1325-1331 | presentation/co4e/node_property_panel.py | khớp mô tả 'nối chọn node sang panel thuộc tính' trong prompt. Đọc self.canvas.nodes() và self.config, toggle self._config_collapsed (trạng thái chia sẻ với _toggle_config ở co4e_tab.py). | chua/khong ro | - |
| Co4ETab._on_config_changed | 1333-1336 | presentation/co4e/node_property_panel.py | gọi self.canvas.refresh_node cho từng node rồi self._autosave() — cầu nối property panel ↔ canvas ↔ service lưu đĩa. | chua/khong ro | - |
| Co4ETab._manage_skills | 1369-1373 | presentation/co4e/skills_list_panel.py | mở SkillsDialog rồi self._reload_sidebar() — không có tên tương ứng trực tiếp trong bảng plan.md, tự xếp theo mô tả skills_list_panel.py. | co | - |
| _PaletteList | 97-119 | unsure | list kéo-thả dùng chung cho wf_list và agent_list, phát payload CO4E_MIME hiểu bởi canvas — không rõ nên đặt ở co4e_tab.py (nơi dùng) hay co4e_canvas_widget.py (định nghĩa giao thức CO4E_MIME) | chua/khong ro | - |
| _PaletteList.__init__ | 102-106 | unsure | cùng lý do với class _PaletteList | chua/khong ro | - |
| _PaletteList._payload_role | 104 | unsure | cùng lý do với class _PaletteList | chua/khong ro | - |
| _PaletteList.startDrag | 108-119 | unsure | cùng lý do với class _PaletteList; dùng CO4E_MIME từ co4e_canvas | chua/khong ro | - |
| Co4ETab._project_id | 249 | unsure | project Workspace đang chọn, ảnh hưởng đường dẫn output flow — không chắc thuộc container hay run control | chua/khong ro | - |
| Co4ETab._project_dir | 250 | unsure | cùng lý do với _project_id | chua/khong ro | - |
| Co4ETab._reflect_active_run | 449-457 | unsure | cầu nối giữa self.manager (run control) và self.canvas (canvas widget) — không chắc nên đặt file nào | chua/khong ro | - |
| Co4ETab._palette_item | 724-728 | unsure | staticmethod helper dùng chung để tạo QListWidgetItem cho cả agent_list, skill_list, và cả node palette sequential/parallel (thấy dùng ở dòng 701-704) — không rõ nên đặt ở agent_list_panel.py, skills_list_panel.py hay co4e_canvas_widget.py. | chua/khong ro | - |
## Chỗ thấy khác tài liệu — cần người quyết
Không có symbol nào có note bắt đầu bằng `khac tai lieu:` trong dữ liệu 367 symbol đầu vào. Mục này để trống theo đúng dữ liệu quét được — không tự bịa thêm mục.
+159
View File
@@ -0,0 +1,159 @@
# Mô hình chính sách an toàn — CoworkLocal
R09-T01 · Team Gamma · viết 22/08/2026
Tài liệu này mô tả **hệ thống đang chạy**, không phải hệ thống mong muốn. Mọi
khẳng định đều chỉ tới file và dòng cụ thể để đối chiếu được.
---
## 1. Câu hỏi quan trọng nhất: đây có phải rào chắn an ninh không
**Không.** `core/agent_security.py` nói thẳng ngay ở đầu file:
> *"this is a business productivity tool, not a hard security boundary"*
Điều đó quyết định mọi thứ còn lại. Cụ thể: **mọi tầng dùng AI đều mở khi
hỏng** (`allowed=True` khi không gọi được validator, `core/agent_security.py:150`).
Mạng chập chờn hay gateway trục trặc thì agent vẫn chạy, không bị khoá cứng.
Đánh đổi có chủ đích: chọn *dùng được* thay vì *chặn tuyệt đối*. Ai đọc tài
liệu này để đánh giá rủi ro cần hiểu đúng điều đó — đây là lớp giảm tai nạn,
không phải lớp chống kẻ tấn công có chủ đích.
---
## 2. Hai loại quy tắc, đừng lẫn
| | Quy tắc xác định | Quy tắc do AI phán |
|---|---|---|
| Cách hoạt động | So khớp mẫu cố định | Hỏi một model |
| Kết quả | Luôn giống nhau | Có thể khác nhau giữa hai lần |
| Khi hỏng | Vẫn chạy | **Mở** (cho qua) |
| Tắt được không | Không — luôn bật | Có, từng tầng một |
| Ở đâu | Bộ phân loại mẫu chặn + sandbox | 3 tầng validate |
Câu ở `core/agent_security.py:250` nói rõ ranh giới:
> *"always-on block-pattern classifier + sandbox still apply regardless"*
Nghĩa là **tắt hết ba tầng AI thì vẫn còn hai lớp xác định**. Đây là điểm dễ
hiểu nhầm nhất khi đọc màn Cài đặt: mấy công tắc ở đó **chỉ tắt phần AI**.
---
## 3. Ba tầng AI
Bật/tắt độc lập trong `agent_security` của `config.json`.
| Tầng | Kiểm cái gì | Khoá cấu hình | Khi nào chạy |
|---|---|---|---|
| Prompt | Yêu cầu của chính người dùng | `validate_prompt` | Trước khi agent làm gì |
| Attachment | Văn bản trích ra từ tệp đính kèm | `validate_attachments` | Trước khi vào ngữ cảnh model |
| Command | `run_command` / `install_package` | `validate_commands` | Trước khi thực thi |
Cả ba đọc chung một bộ luật: file cục bộ `core/security_rules.py` cộng thêm
tài liệu quản trị viên đặt trên OneDrive (nếu có cấu hình). Riêng agent Code
dùng bộ luật khác — `RULEforCode.md` thay vì `RULEBASE.md`.
Công tắc tổng `agent_security.enabled` tắt cả ba.
---
## 4. Chuyện gì xảy ra khi bị chặn
Theo đúng thứ tự trong `core/agent_security.py:266-273`:
1. Hiện thông báo trong khung chat — người dùng thấy ngay, kèm lý do
2. Ghi `audit_log.record("security_block", …)` — vào nhật ký kiểm toán
3. `notify_admin(...)` — gửi email quản trị viên
4. Ném `SecurityBlocked` — dừng lượt chạy
Ba bước đầu **không được phép ném lỗi**. `audit_log.record()` có ghi rõ trong
docstring: *"never raises — audit logging must never break a chat turn"*. Ghi
nhật ký hỏng không được kéo theo cả phiên làm việc.
---
## 5. Hỏi người dùng: trạng thái thứ ba
Ngoài cho/chặn còn một trạng thái nữa mà hệ thống hiện tại **có nhưng chưa gọi
tên**: hỏi người dùng.
`ui/chat_panel.py:1312` kiểm `ctx.project_confirm_commands()` rồi bật
`PermissionDialog`. Đó là một quyết định chính sách thật, nhưng nằm rải ở tầng
giao diện chứ không phải một kết quả chính thức.
`domain/security/tool_policy.py` (đề xuất, chờ Team Hoa xác nhận) gộp lại
thành ba trạng thái:
| | Nghĩa |
|---|---|
| `ALLOW` | Chạy |
| `DENY` | Không chạy, có lý do |
| `ASK` | Hỏi người dùng đã |
**`ASK` không phải là `allowed`.** Coi ASK như ALLOW nghĩa là tool chạy trước
khi có ai đồng ý — bẫy dễ mắc nhất, đã có test riêng chặn.
Cổng chính sách **không tự bật hộp thoại**. Nó chỉ trả lời; hỏi ai và hỏi thế
nào là việc của tầng giao diện. Nhờ vậy Co4E chạy nền mới dùng chung cổng được
với Cowork chạy tương tác — Co4E không hỏi được thì đổi `ASK` thành `DENY`.
---
## 6. Bí mật
Từ 21/08 (R02-T05), API key **không còn nằm trong `config.json`**:
* Lưu trong kho của hệ điều hành qua `KeyringAdapter` — Windows Credential
Manager, macOS Keychain, Linux Secret Service
* `provider_conf()` đọc từ kho rồi ghép vào dict trả về, nên chỗ gọi không
đổi (đường A, `GammaTeam_decisions.md`)
* File cũ tự chuyển ở lần mở đầu tiên, có sao lưu trước khi chuyển
Máy không có kho bí mật (Linux headless, CI) thì **không chuyển** — thà để
khoá trong file còn hơn xoá đi rồi người dùng mất khoá.
Kiểm bằng `python scripts/audit_security.py`, chạy tự động trong CI.
---
## 7. Sandbox
`core/sandbox_manager.py` chạy lệnh trong môi trường hạn chế. Luôn bật, không
tắt được, không phụ thuộc công tắc AI nào.
Năng lực khác nhau theo hệ điều hành — ma trận đầy đủ sẽ nằm ở
`infrastructure/sandbox/sandbox_capabilities.py` (R09-T06, Hiệp phụ trách).
Chỗ này cập nhật khi task đó xong.
---
## 8. Những chỗ đã biết là yếu
Ghi ra để người sau khỏi tưởng đã kín:
1. **Mở khi hỏng.** Gateway chết là ba tầng AI cho qua hết. Có chủ đích, nhưng
nghĩa là không chống được kẻ tấn công biết cách làm validator ngừng trả lời.
2. **Bí mật vẫn đi trong bộ nhớ.** Đường A ghép khoá vào dict `provider_conf()`
trả về, nên khoá vẫn có thể lọt vào log gỡ lỗi hay ảnh chụp màn hình. Đường
B (bỏ hẳn khỏi dict) đã ghi vào nợ kỹ thuật.
3. **Bộ luật lấy từ OneDrive không ký số.** Ai sửa được tài liệu đó là sửa được
luật.
4. **`ASK` chưa được nối vào Co4E.** Co4E chạy nền, chưa có đường hỏi người
dùng — hiện phải chọn giữa cho qua hết hoặc chặn hết.
---
## Đối chiếu nhanh
| Nội dung | Nguồn |
|---|---|
| Ba tầng AI, mở khi hỏng | `core/agent_security.py:1-25` |
| Phân loại mẫu + sandbox luôn bật | `core/agent_security.py:250` |
| Thứ tự khi bị chặn | `core/agent_security.py:266-273` |
| Nhật ký không được ném lỗi | `core/audit_log.py:46` |
| Hỏi người dùng | `ui/chat_panel.py:1312` |
| Ba trạng thái chính sách | `domain/security/tool_policy.py` |
| Bí mật | `infrastructure/secrets/keyring_adapter.py` |
+124
View File
@@ -0,0 +1,124 @@
# Contributor Recipes — Hướng Dẫn Mở Rộng Hệ Thống (EPIC R10-T04)
Tài liệu này cung cấp các công thức chuẩn hóa (Step-by-Step Recipes) giúp các lập trình viên mở rộng tính năng trong hệ thống **Cowork Local** mà vẫn tuân thủ tuyệt đối **Kiến trúc 4 Tầng Sạch (4-Tier Clean Architecture)** và các tiêu chuẩn kiểm duyệt **CASAN**.
---
## 🍳 Recipe 1: Thêm Một Model Provider Mới (AI Provider)
Khi bạn muốn tích hợp một nhà cung cấp mô hình AI mới (ví dụ: Cohere, Groq, DeepSeek, AWS Bedrock...):
### Bước 1: Khai báo định danh trong Domain Layer
Mở file [`domain/models/provider_descriptor.py`](file:///c:/Users/HuongLTT35/OneDrive%20-%20FPT%20Corporation/Documents/ITCorreTeam/CoworkLocal/cowork_local/domain/models/provider_descriptor.py):
- Thêm định danh provider vào enum hoặc hằng số.
- Khai báo model mặc định và năng lực hỗ trợ (Streaming, Tool Calling, Vision, Reasoning).
### Bước 2: Cài đặt Adapter trong Infrastructure Layer
Tạo file mới tại `infrastructure/providers/<provider_name>_provider.py` (hoặc mở rộng module hiện có):
- Kế thừa lớp `BaseModelProvider` hoặc cài đặt interface adapter tương ứng.
- Đảm bảo xử lý streaming qua generator / callbacks.
- Đọc API key từ `SecretStore` (Keyring), tuyệt đối không lưu hardcoded credentials.
```python
# infrastructure/providers/custom_provider.py
from cowork_local.domain.models.provider_descriptor import ProviderDescriptor
class CustomProviderAdapter:
"""Adapter for Custom AI Provider supporting streaming and tool execution."""
def __init__(self, api_key: str, base_url: str | None = None) -> None:
self._api_key = api_key
self._base_url = base_url
def stream_chat(self, prompt: str, system_prompt: str = ""):
# Yield text chunks
yield "..."
```
### Bước 3: Đăng ký vào Provider Registry
Mở [`infrastructure/providers/provider_registry.py`](file:///c:/Users/HuongLTT35/OneDrive%20-%20FPT%20Corporation/Documents/ITCorreTeam/CoworkLocal/cowork_local/infrastructure/providers/provider_registry.py):
- Đăng ký adapter factory vào registry.
### Bước 4: Viết Contract Test
Mở [`tests/contracts/test_providers.py`](file:///c:/Users/HuongLTT35/OneDrive%20-%20FPT%20Corporation/Documents/ITCorreTeam/CoworkLocal/cowork_local/tests/contracts/test_providers.py):
- Thêm test case kiểm tra hợp đồng cho Provider mới bằng `FakeProvider` hoặc offline contract.
---
## 🛠️ Recipe 2: Thêm Một Tool Nội Bộ Hoặc Kết Nối MCP Server Mới
### Bước 1: Khai báo Tool Descriptor & Quyền Hạn
Mở [`domain/models/tool_descriptor.py`](file:///c:/Users/HuongLTT35/OneDrive%20-%20FPT%20Corporation/Documents/ITCorreTeam/CoworkLocal/cowork_local/domain/models/tool_descriptor.py):
- Định nghĩa tên tool, mô tả, JSON Schema tham số.
- Thiết lập cờ Capability: `READ_ONLY`, `GATED`, `DANGEROUS`, v.v.
### Bước 2: Cài đặt Tool Executor
- Nếu là Built-in Tool: Cài đặt trong `infrastructure/tools/` hoặc tích hợp qua `ToolPolicyGateway`.
- Nếu là MCP Server: Cấu hình qua `infrastructure/mcp/mcp_tool_source_manager.py` với stdin/stdout JSON-RPC protocol.
```python
# Example: Adding a safe read-only tool
descriptor = ToolDescriptor(
name="system_disk_usage",
description="Inspect available disk space on the local workstation.",
parameters_schema={
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
capabilities=ToolCapability.READ_ONLY,
)
```
### Bước 3: Viết Unit Test & Kiểm Tra Gate
- Thêm test case vào `tests/unit/test_tool_registry_and_policy.py`.
- Xác nhận tool tôn trọng cờ an toàn (`ToolPolicyGateway`) trước khi thực thi.
---
## 🖥️ Recipe 3: Thêm Một Màn Hình / Tab / Widget Giao Diện Mới
### Bước 1: Tạo module dưới `presentation/<feature>/`
- Tạo thư mục riêng (ví dụ: `presentation/analytics/`).
- Tách các widget con nhỏ gọn, **mỗi file < 400 dòng code (LOC)**.
- Giao diện kế thừa `PySide6.QtWidgets.QWidget` và sử dụng CSS token từ `cowork_local.theme`.
```python
# presentation/analytics/analytics_tab.py
"""Analytics Tab Widget (LOC < 400)."""
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel
from cowork_local.state import AppContext
from cowork_local.i18n import tr
class AnalyticsTab(QWidget):
"""Analytics view displaying workspace telemetry."""
def __init__(self, ctx: AppContext, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.ctx = ctx
self._setup_ui()
def _setup_ui(self) -> None:
layout = QVBoxLayout(self)
self.title = QLabel(tr("analytics.title") if tr("analytics.title") != "analytics.title" else "Analytics Dashboard")
layout.addWidget(self.title)
```
### Bước 2: Nối Dữ Liệu Qua Tầng Application Service
- **QUY TẮC CỐT TỬ**: Widget giao diện CHỈ ĐƯỢC gọi xuống các Service của tầng `application/` (ví dụ: `TaskApplicationService`, `DashboardQueryService`, `ConversationApplicationService`).
- Tuyệt đối không query trực tiếp SQLite/JSON hoặc thực thi AI logic trực tiếp trong GUI thread.
### Bước 3: Đăng Ký Vào Shell Navigation
- Mở [`presentation/shell/page_registry.py`](file:///c:/Users/HuongLTT35/OneDrive%20-%20FPT%20Corporation/Documents/ITCorreTeam/CoworkLocal/cowork_local/presentation/shell/page_registry.py) và thêm trang mới vào danh sách menu điều hướng (`NavRail`).
### Bước 4: Viết Integration Test Cho Widget
- Tạo file test dưới `tests/integration/` hoặc `tests/ui/`.
- Đảm bảo test chạy được ở chế độ headless (`QT_QPA_PLATFORM=offscreen`).
---
## 🛡️ Kiểm Duyệt Chất Lượng Trước Khi Gửi PR (Checklist CASAN)
Trước khi commit và tạo Pull Request, chạy lệnh kiểm tra tổng thể:
```bash
python scripts/run_quality_gate.py
```
Nếu toàn bộ 4 cổng báo `[PASS]` thì mã nguồn của bạn đã sẵn sàng được merge vào nhánh chính!
+233
View File
@@ -0,0 +1,233 @@
# BÁO CÁO KẾT QUẢ — TEAM DUY: EPIC R01, R03, R04
* **Dự án**: Cowork Local (Cowork-Local BamBOO)
* **Team**: 🔵 Team Duy — Core AI, Routing, Turn Runtime & Testing (Tech Lead)
* **Nhánh**: `feature/deltateam/refactor-plan`
* **Thời gian thực hiện**: 21/08/2026, 09:56 ➔ 10:56
* **Ngày báo cáo**: 21/08/2026
* **Tài liệu gốc**: `Feature_Architecture_Proposal.md`, `Refactoring_Checklist.md`, `DeltaTeam_prompt.md`
---
## 1. Tóm tắt điều hành
Hoàn tất **16/16 task** của 3 EPIC được giao trong đợt này: **R01** (nền tảng kiến trúc & lưới an toàn), **R03** (hợp nhất provider & routing), **R04** (vòng đời turn hội thoại). Toàn bộ đã commit và push lên nhánh.
| Chỉ số | Kết quả |
| :--- | :--- |
| Task hoàn thành | **16/16** (R01: 5, R03: 6, R04: 5) |
| Commit | 5 |
| File thay đổi | 48 (37 file mới, 11 file sửa) |
| Dòng code | +5.843 / −225 |
| Test | **243 pass** / 44s |
| Test suite nhanh (unit + contract + characterization + routing) | **218 pass / 1,22s** |
| CASAN Check 3 (`scripts/check_imports.py`) | **PASS** — 0 Qt import trong `domain/`, `application/` |
| File production > 400 dòng | **0** |
**3 lỗi thật được phát hiện và sửa trong quá trình làm** (chi tiết mục 5) — trong đó 1 lỗi deadlock sẽ làm treo ứng dụng ngay ở tin nhắn đầu tiên.
---
## 2. Kết quả theo từng EPIC
### 🔹 EPIC R01 — Architecture Foundation & Characterization (5/5)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R01-T01 | `docs/architecture/ADR-001-layered-architecture.md` | Định nghĩa 4 tầng, chiều phụ thuộc, 6 quy tắc bất biến I1–I6, chiến lược di trú Strangler Fig |
| R01-T02 | `tests/fakes/fake_provider.py`, `fake_tool_executor.py` | Test double chạy offline, kịch bản hoá, ghi lại mọi lời gọi |
| R01-T03 | `scripts/check_imports.py` (239 dòng) | Quét AST, bắt cả import tương đối (`from ...ui import x`) và import trong thân hàm |
| R01-T04 | `tests/characterization/test_run_cowork.py` | **13 test** chụp snapshot hành vi hiện tại của `run_cowork` trước khi R04 đụng vào |
| R01-T05 | `docs/architecture/dormant-code.md` | Quét đồ thị import: 43 module "không ai import" ➔ xác minh còn **6 hạng mục chết thật (~1.887 dòng)** |
**Điểm đáng chú ý ở R01-T03**: dùng AST thay vì `grep` là bắt buộc — trong repo có nhiều docstring nhắc tên `PySide6` một cách hợp lệ, `grep` sẽ báo nhầm và đội sẽ học cách tắt cổng kiểm duyệt.
**Điểm đáng chú ý ở R01-T05**: 43 module không có importer **không** đồng nghĩa 43 module chết. Sau xác minh thủ công: `__main__.py` là entry point, `mcp_servers/ms365_server.py` chạy bằng subprocess (`state.py:285`), 34 file `tools/check_*.py` là dev tooling chạy tay. Chỉ 6 hạng mục là dormant thật.
### 🔹 EPIC R03 — Model Providers & Routing (6/6)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R03-T01 | `tests/contracts/test_providers.py` | **29 contract test**; chạy được cả 2 adapter thật mà **không cần mạng** nhờ thay `Provider._request` bằng SSE đóng hộp |
| R03-T02 | `domain/models/provider_descriptor.py`, `infrastructure/providers/provider_registry.py` | Gom 3 nơi khai báo provider về 1 chỗ |
| R03-T03 | `application/model_routing/routing_application_service.py` | Pure Python, 4 chế độ: Off / Auto / Manual / **Fallback (mới)** |
| R03-T04, T05 | `ui/chat_panel.py`, `ui/co4e_tab.py`, `ui/folder_tab.py` | Gỡ 3 bản sao logic routing |
| R03-T06 | `infrastructure/telemetry/usage_sink.py` | Tách ghi nhận token usage khỏi provider |
**Vấn đề gốc đã giải quyết** — cùng một thuật toán routing tồn tại **3 bản gần giống nhau**:
```
ui/chat_panel.py::_apply_routing (~45 dòng)
ui/co4e_tab.py::_apply_co4e_routing (~38 dòng)
ui/folder_tab.py::_ai_apply_routing (~42 dòng)
```
Cả 3 đều nằm trong widget Qt ➔ **không thể test nếu không dựng cửa sổ**, và đã bắt đầu lệch nhau (mỗi bản xác định "model hiện tại" một kiểu). Nay cả 3 chỉ còn gọi `ctx.routing_application().route_turn(...)` + một callback xác nhận.
**Chế độ Fallback (mới)**: giữ nguyên model người dùng chọn, **chỉ đổi sau khi model đó lỗi**. Đây là chế độ người dùng cần khi họ tin lựa chọn của mình nhưng vẫn muốn lượt chat sống sót qua sự cố nhà cung cấp.
**Bộ từ vựng mode**: trước đây tuple `("off", "auto", "manual")` bị lặp ở **4 chỗ** (`config.py` × 2, `state.py` × 2). Thêm một mode mà quên một chỗ sẽ **âm thầm hạ lựa chọn của người dùng về "off"**. Nay tập trung vào `normalize_mode()` / `is_valid_mode()`.
### 🔹 EPIC R04 — Agent Runtime & Conversation Service (5/5)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R04-T01 | `domain/agents/conversation_execution_request.py` | Frozen dataclass, chụp toàn bộ input của 1 turn tại thời điểm submit |
| R04-T02 | `domain/agents/agent_event.py` (370 dòng) | **13 event có kiểu** thay cho dict không kiểu, kèm cầu nối 2 chiều |
| R04-T03 | `application/conversations/conversation_application_service.py` | Điều phối vòng đời turn, không import Qt |
| R04-T04 | `ui/cowork_tab.py::build_job` | Chuyển sang snapshot + service |
| R04-T05 | `core/task_executors.py::_run_agent` | Chuyển sang **cùng** service (trước đây là bản lắp ráp thứ hai, hơi khác) |
**Vấn đề gốc đã giải quyết** — closure trong `build_job` đọc state của widget **từ trong worker thread**:
```python
def job(worker):
provider = self.build_provider() # đọc combo box
proj_ctx = project_context_text(load_project(project_id))
```
Người dùng có thể đổi model, đổi workspace, sửa chỉ dẫn project **trong lúc turn đang chạy**. Turn khi đó chạy trên hỗn hợp state cũ + mới, và hỗn hợp nào phụ thuộc vào thời điểm luồng — đúng loại bug tái hiện mỗi tuần một lần và không bao giờ tái hiện trong test.
**`TurnCompletedEvent`** là tín hiệu kết thúc turn mà engine cũ **hoàn toàn không có**: hiện tại mọi consumer suy ra "xong" từ việc worker thread kết thúc, nên **turn bị huỷ và turn thất bại trông giống hệt nhau** với giao diện.
---
## 3. Kiến trúc sau refactor
```text
presentation/ ui/chat_panel.py, ui/co4e_tab.py, ui/folder_tab.py, ui/cowork_tab.py
│ (chỉ dựng UI, mở dialog xác nhận, render thông báo)
▼
application/ model_routing/routing_application_service.py ← 4 mode routing
conversations/conversation_application_service.py ← vòng đời turn
│ (100% pure Python — cổng kiểm duyệt tự động chặn import Qt)
▼
domain/ agents/conversation_execution_request.py ← snapshot bất biến
agents/agent_event.py ← 13 event có kiểu
models/provider_descriptor.py ← catalog provider
▲
infrastructure/ providers/provider_registry.py telemetry/usage_sink.py
```
**Nguyên tắc di trú (ADR-001 mục 4)**: **không viết lại engine**. `core/chat_agent.py::run_cowork` và `core/routing/*` (2.263 dòng, 79 test đang xanh) vẫn là engine bên dưới; tầng application chỉ sở hữu phần trước đây bị trộn vào UI. Nhờ vậy `pytest` luôn xanh giữa các bước và một team có thể merge mà không phải chờ team khác.
---
## 4. Bằng chứng kiểm thử
### Phân bố test
| Suite | Số test | Thời gian | Vai trò |
| :--- | ---: | ---: | :--- |
| `tests/unit/` | 97 | | Logic thuần, không Qt/mạng |
| `tests/contracts/` | 29 | | Mọi provider phải thoả cùng bộ cam kết |
| `tests/characterization/` | 13 | | Chốt hành vi hiện tại của `run_cowork` |
| `tests/routing/` | 79 | | Có sẵn từ trước, vẫn xanh |
| **Cộng 4 suite nhanh** | **218** | **1,22s** | ✅ đạt CASAN "A — unit < 1s" |
| `tests/integration/` | 25 | 42s | Widget Qt thật (offscreen) + provider kịch bản hoá |
| **Tổng** | **243** | **44s** | |
### Đối chiếu Definition of Done (7 tiêu chí, `DeltaTeam_prompt.md`)
| # | Tiêu chí | Kết quả |
| :--- | :--- | :--- |
| 1 | Mọi file < 400 dòng | ✅ Lớn nhất: `agent_event.py` 370 dòng |
| 2 | 0 import Qt trong `domain/`, `application/` | ✅ `check_imports.py` PASS |
| 3 | Comment tiếng Anh ở mọi khối sửa/mới | ✅ Docstring + giải thích **lý do**, không chỉ mô tả code |
| 4 | Có unit/contract test, pass 100% < 1s | ✅ 218 test / 1,22s |
| 5 | Không hồi quy | ✅ 79 test routing có sẵn vẫn xanh |
| 6 | Ghi Start/End vào Checklist | ✅ 16 task đã tick kèm mốc thời gian |
| 7 | Cổng CASAN | ⚠️ `run_quality_gate.py` thuộc **R10-T02**, chưa viết. Check 3 đã có và PASS |
### Ba đường code đã sửa nhưng ban đầu chưa được thực thi
Sau khi hoàn tất 16 task, rà soát lại phát hiện 3 đường code đã bị sửa nhưng **không test nào chạy qua**. Đã bổ sung **18 test**:
| Đường code | Rủi ro nếu bỏ qua | Test bổ sung |
| :--- | :--- | ---: |
| `task_executors._run_agent` | Autosave History có thể đóng băng ở tin nhắn đầu | 7 |
| `_apply_co4e_routing` / `_ai_apply_routing` | Mới chỉ import được, chưa từng gọi hàm | 11 |
| `confirm_switch(decision)` Manual mode | Thiếu field ➔ **nổ bên trong modal**, nơi khó phát hiện nhất | (nằm trong 11 ở trên) |
---
## 5. Ba lỗi thật phát hiện trong quá trình làm
### 🔴 Lỗi 1 — Deadlock khi khởi tạo routing service
`AppContext.routing_application()` giữ `_routing_lock` rồi gọi `routing()`, vốn cũng lấy **chính lock đó**. `threading.Lock` không reentrant ➔ **treo cứng ngay ở tin nhắn đầu tiên**, không có thông báo lỗi.
*Sửa*: tách `_routing_app_lock` riêng, và resolve engine **trước khi** lấy lock.
### 🟠 Lỗi 2 — Event `notice` bị cầu nối nuốt mất
Bản đầu của `agent_event.py` liệt kê 12 loại event nhưng **thiếu `notice`**. Trong khi đó `notice` được phát ra từ 3 nơi trên đường chạy bình thường:
* `core/agent_security.py` — yêu cầu/lệnh bị Agent Security **chặn**
* `core/context_budget.py` — hội thoại vừa bị tự động nén
* Bộ đọc file đính kèm — file không xử lý được, và tiến độ "đang đọc trang X/Y"
Cầu nối bỏ qua event không nhận diện được (đúng thiết kế, để engine có thể thêm event mới) — nên **người dùng sẽ không bao giờ thấy cảnh báo bảo mật**, hoàn toàn im lặng.
*Sửa*: thêm `NoticeEvent`, **và** thêm test quét mã nguồn engine tìm mọi tag `emit({"type": ...})` rồi bắt lỗi nếu có tag nào chưa có event tương ứng — biến sự im lặng thành test đỏ.
### 🟡 Lỗi 3 — Test đang chạy trên checkout khác
`tests/routing/conftest.py` đẩy thư mục cha vào `sys.path`. Vì thư mục checkout tên là `cowork_local_gitea` (không phải `cowork_local`), lệnh `import cowork_local` **ăn nhầm sang `Desktop\cowork_local`** — một bản checkout khác. Suite báo xanh trên mã nguồn **không phải nhánh đang review**.
*Sửa*: `tests/conftest.py` nạp `__init__.py` theo đường dẫn tuyệt đối và đăng ký vào `sys.modules` trước mọi test.
---
## 6. Cải thiện phụ (không nằm trong yêu cầu task)
| Cải thiện | Ảnh hưởng |
| :--- | :--- |
| `ProviderRegistry.build()` đóng dấu `descriptor.id` lên instance | Sửa việc usage của `ollama` / `github_copilot` / `codex` bị ghi nhận nhầm thành `openai_compat` trên Dashboard. **Chưa nối vào production** — xem mục 7. |
| `ProviderRegistry.build()` copy config trước khi ghi | Trước đây một model do routing chọn có thể ghi đè lên default đã lưu của người dùng |
| `UsageTrackerSink` ghi log ở mức debug khi thất bại | Trước là `except: pass` — mất sạch lý do khi Dashboard hỏng |
| `estimate_tokens` được chốt bằng test so với `core.usage_tracker` | Bảo đảm việc tách telemetry **không làm lệch một con số nào** |
---
## 7. Còn nợ & cần quyết định
| # | Nội dung | Người quyết |
| :--- | :--- | :--- |
| 1 | **`ProviderRegistry` chưa nối vào `state.build_provider_for`** (vẫn dùng `providers/factory.py`). Nối vào sẽ sửa lỗi quy kết usage ở mục 6, **nhưng đổi cách gom dữ liệu lịch sử trên Dashboard**. | Team Duy + PO |
| 2 | **Mode `fallback` chưa có trên toggle UI** — config và service đã hỗ trợ đầy đủ; widget `RoutingToggle` thuộc R08. | Team Duy (R08) |
| 3 | **Đã sửa 2 dòng trong `config.py`** (`routing_mode_for`, `set_routing_mode_for`) để dùng chung bộ từ vựng mode. File này Team Nam đang refactor ở R02-T02. | ⚠️ **Cần báo Team Nam** |
| 4 | **Circular import** `core/model_pricing.py` ↔ `core/usage_tracker.py` chưa xử lý (task ngày 28/08). | Team Duy |
| 5 | **2 test đỏ có sẵn từ trước**: `config.py:108` hardcode `sandbox_pw = "quandh14"` ➔ `tests/test_config_security.py`. Thuộc **EPIC R02 / Team Nam**. | 🟣 Team Nam |
| 6 | `tests/integration/test_routing_surfaces.py` mất 41s do dựng `Co4ETab`/`FolderTab`. Nên gắn marker `slow` khi làm R10. | Team Duy (R10) |
---
## 8. Phạm vi chưa kiểm thử
Nêu rõ để tránh hiểu nhầm mức độ bảo đảm:
* **Chưa mở ứng dụng bằng tay** — mới chạy widget headless (`QT_QPA_PLATFORM=offscreen`), chưa có ai kiểm tra bằng mắt.
* **Chưa gọi provider thật** — toàn bộ dùng `FakeProvider`, không có lưu lượng mạng.
* **Chưa chạy 34 script `tools/check_*.py`** — các script này tự `sys.path.insert` thư mục cha nên sẽ import nhầm checkout khác (đúng lỗi 3 ở mục 5). Cần sửa chúng ở R10.
---
## 9. Việc kế tiếp của Team Duy
| EPIC | Nội dung | Điều kiện |
| :--- | :--- | :--- |
| **R08** (T01 ➔ T06) | Tách `ui/chat_panel.py` (1.795 dòng) thành 6 widget < 400 dòng | Sẵn sàng bắt đầu — `AgentEvent` (R04-T02) chính là kênh dữ liệu 6 widget con sẽ dùng thay vì đọc trực tiếp state của `ChatPanel` |
| **R10** (T01 ➔ T05) | Testing Pyramid, `run_quality_gate.py`, Contributor Recipes, E2E Smoke | Chờ cả 3 team hoàn tất |
---
## 10. Lịch sử commit
| Commit | Nội dung |
| :--- | :--- |
| `bbc09f6` | feat(R01): architecture foundation, offline fakes and characterization net |
| `96bec97` | feat(R03): unify provider catalogue, routing decisions and usage telemetry |
| `a53163e` | feat(R04): immutable turn snapshot, typed agent events, conversation service |
| `15e1d3e` | test(R03/R04): cover the three code paths that were changed but never executed |
| `67b8d2e` | docs(refactor): correct the Team Duy scope block in the checklist |
+238
View File
@@ -0,0 +1,238 @@
# BÁO CÁO KẾT QUẢ — TEAM HOA: EPIC R05, R06, R07, R08 (phần Team Hoa)
* **Dự án**: Cowork Local (Cowork-Local BamBOO)
* **Team**: 🟢 Team Hoa — Workspace, Filesystem, Scheduling & Tool Registry
* **Nhánh**: `feature/teamhoa/r05-r08` (tạo từ `origin/feature/deltateam/refactor-plan`, có sẵn nền R01/R03/R04 của Team Duy; đổi tên từ `feature/teamhoa/r05-r06` sau khi gộp thêm R07/R08)
* **Thời gian thực hiện**: 21/08/2026 21:40 → 27/08/2026 20:52
* **Ngày báo cáo**: 27/08/2026 (bản gộp, thay thế `BaoCao_TeamHoa_R05_R06.md` và `BaoCao_TeamHoa_R07_R08.md`)
* **Tài liệu gốc**: `Feature_Architecture_Proposal.md`, `Refactoring_Checklist.md`, `plan.md`
---
## 1. Tóm tắt điều hành
Hoàn tất **toàn bộ 19/19 task thuộc phạm vi Team Hoa** trên 4 EPIC: **R05** (Tool, MCP & Connector Policy), **R06** (Workspace, Filesystem & History Isolation), **R07** (Scheduling & Workflow Runtime), **R08** (UI/Application Separation — phần Team Hoa, T11→T14).
| Chỉ số | Kết quả |
| :--- | :--- |
| Task hoàn thành | **19/19** (R05: 5, R06: 5, R07: 5, R08: 4 — không tính R07-T06/R08-T01→T10 thuộc Team Duy/Team Nam) |
| File thay đổi | 92+ (phần lớn file mới) |
| Test cuối cùng | **377 pass / 4 fail** (xem tiến trình chi tiết ở mục 4) |
| CASAN Check 3 (`scripts/check_imports.py`) | **PASS** — 0 Qt import trong `domain/`, `application/` |
| File production > 400 dòng (file mới) | **0** — lớn nhất `presentation/graph/graph_renderer.py` 391 dòng |
| `python -c "import cowork_local.app"` | **OK** sau mọi task |
**3 lỗi thật phát hiện và sửa**, **1 quyết định kiến trúc đổi so với plan gốc (xác nhận bằng thực nghiệm)** — chi tiết mục 5.
---
## 2. Kết quả theo từng EPIC
### 🔹 EPIC R05 — Tool, MCP & Connector Policy (5/5)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R05-T01/T02 | `domain/tools/{tool_descriptor,tool_registry}.py`, `infrastructure/filesystem/{file_tools,command_tools,fetch_tools}.py` | Tách if/elif dispatcher của `core/tools.py`; `core/tools.py` còn lại là shim strangler-fig (re-export `ToolContext`/`ToolError`, dispatch qua dict), 566 ➔ 291 dòng. |
| R05-T03 | `application/conversations/tool_policy_gateway.py::ToolPolicyGateway` | Thay 2 chỗ check hardcode riêng biệt (`chat_agent.py`, `code_agent.py`) bằng 1 lookup capability chung. |
| R05-T04 | Sửa `core/chat_agent.py`, `core/mcp_client.py` | **Thay đổi hành vi có chủ đích** — xem mục 5, Lỗi 1. |
| R05-T05 | `infrastructure/mcp/mcp_source_manager.py::McpToolSourceManager` | Tách lifecycle connection MCP khỏi `state.py::AppContext`. |
### 🔹 EPIC R06 — Workspace, Filesystem & History Isolation (5/5)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R06-T01 | `domain/workspaces/workspace_session.py::WorkspaceSession` | Snapshot bất biến (project_id/workspace_root/sandbox_dir/allowed_paths) + `is_allowed(path)`. |
| R06-T02 | `infrastructure/persistence/json/{atomic_write,workspace_repository_impl,conversation_repository_impl}.py` | **Sửa bug thật** — xem mục 5, Lỗi 2. |
| R06-T03 | `infrastructure/filesystem/execution_workspace.py::ExecutionWorkspace` | Đặt tên cho quy ước `.scratch` đã có sẵn. |
| R06-T04 | Sửa `ui/chat_panel.py` | **Sửa race condition thật** — xem mục 5, Lỗi 3. |
| R06-T05 | `application/workspaces/file_workspace_service.py::FileWorkspaceService` | Seam cho File Explorer/AI Editor gọi `execute_tool` giống agent — **chưa có call site thật lúc R06 xong; đã nối dây ở R08-T12** (xem mục 5). |
### 🔹 EPIC R07 — Scheduling & Workflow Runtime (5/5, phạm vi Team Hoa)
| Task | Sản phẩm | Ghi chú |
| :--- | :--- | :--- |
| R07-T01 | `infrastructure/persistence/json/task_repository_impl.py::TaskRepository` | Bọc CRUD của `core/tasks.py`. **Sửa bug thật**: `save_task` trước đây ghi không atomic — cùng lớp bug đã sửa ở R06-T02. |
| R07-T02 | `domain/tasks/schedule_calculator.py::ScheduleCalculator` | Tách "schedule math" (cron/interval/daily/weekly/monthly + holiday exclusion) thành pure Python, trước đây **0 test**, giờ có 14 test. |
| R07-T03 | `infrastructure/qt/qt_scheduler_clock.py::QtSchedulerClock` | Bọc `QTimer` sau 1 interface nhỏ, inject qua `clock=`. **Đổi vị trí so với plan gốc** — xem mục 5. |
| R07-T04 | `application/scheduling/task_application_service.py::TaskApplicationService` | Gom CRUD + luật kéo-thả Kanban (`move_to_status`). |
| R07-T05 | `application/scheduling/ai_task_planner_service.py::AiTaskPlannerService` | Seam cho `plan_tasks`/`import_tasks`. |
*(R07-T06 `Co4EWorkflowService` là việc Team Nam — không đụng.)*
### 🔹 EPIC R08 — UI/Application Separation (4/4, phạm vi Team Hoa: T11→T14)
`presentation/` **chưa tồn tại** trước task này — Team Hoa tạo cấu trúc lần đầu.
| Task | God file gốc | Tách thành |
| :--- | :--- | :--- |
| R08-T11 | `ui/schedule_task_tab.py` (795 dòng) | `presentation/scheduling/{kanban_board_widget,calendar_view_widget,ai_task_creator_dialog,ai_task_import_dialog,run_history_dialog}.py` + shell |
| R08-T12 | `ui/folder_tab.py` (1587 dòng — lớn nhất) | `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` + shell |
| R08-T13 | `ui/dashboard_tab.py` (437 dòng) | `presentation/dashboard/{token_usage_card_widget,usage_chart_widget,habits_widget}.py` + shell, `application/monitoring/dashboard_query_service.py` |
| R08-T14 | `ui/structure_graph_view.py` (1035 dòng) | `presentation/graph/{graph_scene_items,graph_renderer,graph_messages_view,graph_qa_widget}.py` + shell |
*(R08-T01→T10 thuộc Team Duy/Team Nam — không đụng.)* Mỗi god-file cũ chỉ có 1-2 nơi khởi tạo thật (`app.py`, `ui/workspace_tab.py`) nên đã **sửa thẳng import site** và **xoá hẳn file `ui/*.py` cũ** thay vì giữ shim (khác `core/tools.py` ở R05, có hàng chục call site).
---
## 3. Kiến trúc sau refactor
```text
presentation/ (MỚI ở R08 — Team Hoa tạo cấu trúc lần đầu)
scheduling/ {kanban_board_widget, calendar_view_widget,
ai_task_creator_dialog, ai_task_import_dialog,
run_history_dialog, schedule_task_tab}.py
folder/ {workspace_file_tree, document_preview_manager, code_editor,
office_document_renderer, ai_file_editor_dialog,
ai_edit_model_resolver, ai_edit_pipeline, folder_tab}.py
dashboard/ {token_usage_card_widget, usage_chart_widget,
habits_widget, dashboard_tab}.py
graph/ {graph_scene_items, graph_renderer, graph_messages_view,
graph_qa_widget, structure_graph_view}.py
shared/ web_engine_support.py (HAS_WEB_ENGINE dùng chung)
│
▼
application/ conversations/tool_policy_gateway.py ← ALLOW/CONFIRM cho mọi tool call (R05)
workspaces/{file_workspace_service, file_preview_helpers,
ai_edit_output, graph_index_service}.py (R06, R08)
scheduling/{task_application_service, ai_task_planner_service}.py (R07)
monitoring/dashboard_query_service.py (R08)
│ (100% pure Python — check_imports.py chặn import Qt)
▼
domain/ tools/{tool_descriptor,tool_registry}.py ← capability + catalogue (R05)
workspaces/workspace_session.py ← snapshot workspace bất biến (R06)
tasks/schedule_calculator.py ← due-time/cron math thuần Python (R07)
▲
infrastructure/ filesystem/{file_tools,command_tools,fetch_tools,tool_context,execution_workspace}.py (R05/R06)
mcp/mcp_source_manager.py ← lifecycle connection MCP (R05)
persistence/json/{atomic_write,workspace_repository_impl,
conversation_repository_impl,task_repository_impl}.py (R06/R07)
qt/qt_scheduler_clock.py ← QTimer đằng sau 1 interface nhỏ (R07)
```
**Nguyên tắc di trú xuyên suốt cả 4 EPIC (ADR-001 mục 4, tiếp nối cách Team Duy làm ở R04)**: **không viết lại engine**. `core/tools.py::execute_tool`, `core/chat_agent.py::run_cowork`, `core/tasks.py`, `core/task_scheduler.py`, `core/task_executors.py` vẫn là engine bên dưới — tầng mới chỉ sở hữu phần từng nằm rải rác/hardcode trong widget hoặc dispatcher. `pytest` xanh liên tục giữa các bước, chạy full suite sau MỖI task.
**Riêng ở R08**: khi 1 file bị tách vượt 400 dòng dù đã theo đúng mapping gốc, đã tách thêm file phụ theo kiểu **composition** (class phụ nhận `owner` là widget chính) thay vì service riêng — ví dụ `run_history_dialog.py`, `office_document_renderer.py`, `ai_edit_pipeline.py`, `ai_edit_model_resolver.py`, `graph_messages_view.py`. Đây là split kỹ thuật để đạt giới hạn LOC, không phải ranh giới tầng kiến trúc.
---
## 4. Bằng chứng kiểm thử
### Tiến trình test qua từng EPIC
| Mốc | Tổng pass | Ghi chú |
| :--- | ---: | :--- |
| Sau R05+R06 | 283 (/287, 4 fail) | +41 unit test + 2 integration test (Qt offscreen thật) |
| Sau R07 | 328 | +45 test mới (task repo, schedule calculator, Qt clock, task/AI-planner services) |
| Sau R08 | **377** | +49 test mới (4 widget split, mỗi cái có unit + integration Qt offscreen) |
**4 fail cuối cùng — cùng 1 baseline có sẵn từ trước, xuyên suốt cả 4 EPIC, không phải do Team Hoa**:
* `tests/test_config_security.py` × 2 (EPIC R02/Team Nam — `config.py` hardcode `sandbox_pw`)
* `tests/unit/test_routing_wiring.py` × 2 (môi trường máy này có Ollama/llama3.1 thật, khác giả định "fresh install" của test)
### Đối chiếu Definition of Done
| # | Tiêu chí | Kết quả |
| :--- | :--- | :--- |
| 1 | Mọi file mới < 400 dòng | ✅ Lớn nhất: `presentation/graph/graph_renderer.py` 391 dòng |
| 2 | 0 import Qt trong `domain/`, `application/` | ✅ `check_imports.py` PASS |
| 3 | Comment tiếng Anh giải thích lý do ở mọi khối sửa/mới | ✅ |
| 4 | Có unit/contract/integration test, verify bằng chạy thật | ✅ +90 test mới sau R05/R06 lên tới 377; mọi widget Qt test bằng offscreen thật, không double |
| 5 | Không hồi quy | ✅ 377/381 pass — 4 fail cùng 1 baseline có sẵn, không đổi qua 4 EPIC |
| 6 | Ghi Start/End vào Checklist | ✅ 19 task đã tick kèm mốc thời gian thật |
| 7 | Cổng CASAN (`run_quality_gate.py`, R10-T02) | ⚠️ Chưa viết (thuộc R10, chưa tới lượt) — Check 3 đã PASS |
---
## 5. Lỗi thật phát hiện & quyết định kiến trúc
### 🔴 Lỗi 1 (R05-T04) — Tool MCP/Connector chạy hoàn toàn không qua permission gate
`core/chat_agent.py::run_cowork` có 2 nhánh dispatch tool call: built-in đi qua gate xác nhận khi Settings bật "confirm before running commands"; nhánh `extra_tools` (mọi tool từ MCP server hoặc Connector) gọi thẳng `extra_executor(name, args)` **không qua bước xác nhận nào**. Đây không phải khác biệt thiết kế — không có ghi chú, không có toggle riêng.
*Sửa*: mọi `extra_tools` gắn `ToolCapability` mặc định bảo toàn (`WRITE|EXECUTE|NETWORK`), đi qua CÙNG `ToolPolicyGateway` với built-in tools. **Thay đổi hành vi người dùng sẽ thấy**: tool MCP/connector giờ hỏi xác nhận khi "confirm before running commands" bật. Test: `tests/unit/test_cowork_extra_tool_policy.py`.
### 🟠 Lỗi 2 (R06-T02, R07-T01) — Ghi file không atomic ở 3 nơi
`core/projects.py::save_project`, `core/history.py::save_conversation/rename_conversation/set_pinned` (R06), và `core/tasks.py::save_task` (R07) đều từng dùng `path.write_text(json.dumps(...))` trần — crash giữa lúc ghi để lại file JSON hỏng, và hàm `load_*` tương ứng coi file hỏng như "không tồn tại" → **mất project/hội thoại/task âm thầm, không báo lỗi**. Cả 4 điểm ghi giờ qua `infrastructure/persistence/json/atomic_write.py::write_json` (temp file + `os.replace`). Có test giả lập crash giữa lúc ghi xác nhận file cũ không bị hỏng, cho cả 2 đợt sửa.
### 🟡 Lỗi 3 (R06-T04) — Turn chạy ngầm lưu nhầm lịch sử vào project khác
`ui/chat_panel.py::_persist_session` gọi `save_conversation(self.ctx.config.history_dir(), ...)`, đọc `config._project_history_dir` — field dùng chung bị `ui/workspace_tab.py::_load_current` ghi đè mỗi lần đổi project. Một turn chạy ngầm ở project A hoàn tất SAU khi user đã chuyển sang project B thì bị lưu nhầm vào lịch sử của B.
*Sửa*: thêm `"home_history_dir"` vào dict `ctx` mỗi turn, chụp giá trị tại lúc submit thay vì đọc sống lúc lưu. Test Qt offscreen thật: `tests/integration/test_history_dir_race.py`.
### 🔵 Quyết định kiến trúc (R07-T03) — `platform/qt/` đè lên module chuẩn `platform` của Python
Plan gốc đặt tên `platform/qt/qt_scheduler_clock.py`. Thực nghiệm trước khi viết:
```bash
cd <repo_root> && python -c "import cowork_local; import platform; print(platform.system())"
```
Sau khi tạo `platform/__init__.py`, lệnh trên báo lỗi `AttributeError: module 'platform' has no attribute 'system'` — bất cứ khi nào repo root nằm trực tiếp trên `sys.path` (không qua `__main__.py`'s parent-dir fixup), `import platform` phân giải nhầm vào package cục bộ. `core/windows_sandbox_vm.py`/`core/appcontainer_sandbox.py` đều `import platform`.
*Sửa*: chuyển sang `infrastructure/qt/qt_scheduler_clock.py` (không tạo package `platform/` mới) — đúng layer, cùng cấp `infrastructure/{filesystem,mcp,persistence,providers,telemetry}/`. Verify lại: PASS.
### Nối dây `FileWorkspaceService` (R06-T05 → R08-T12)
Báo cáo R06 để lại nợ: `FileWorkspaceService` (R06-T05) chưa có call site thật. Xác nhận lại bằng grep trước R08-T12: đúng 0 occurrence trong `ui/folder_tab.py`. Khi tách `document_preview_manager.py` (R08-T12), mọi điểm ghi text thuần (`save`, `create_new_file`, `write_content`) chuyển sang gọi `FileWorkspaceService.write_file` — dùng `WorkspaceSession.unscoped(...)` vì Folder Explorer duyệt bất kỳ thư mục nào, không giới hạn 1 project sandbox. Nhánh ghi `.pptx` (binary) vẫn giữ nguyên đường cũ.
**Tác dụng phụ có lợi**: `infrastructure/filesystem/file_tools.py::write_file` đã có sẵn cảnh báo cú pháp Python và tự build `.xlsx` thật từ text — 2 hành vi này **trước đây không tồn tại** trên đường ghi cũ của `folder_tab.py`, giờ được hưởng miễn phí.
---
## 6. Cải thiện phụ (không nằm trong yêu cầu task)
| Cải thiện | Ảnh hưởng |
| :--- | :--- |
| `McpServerConnection.is_alive()` (R05, `core/mcp_client.py`) | Cho `McpToolSourceManager` biết một connection cached đã chết để khởi động lại. |
| `domain/tasks/schedule_calculator.py` có bộ test riêng (R07) | `core/tasks.py` tự nhận "Qt-free, unit-testable" nhưng **0 test tồn tại** cho cron/interval/holiday-exclusion trước R07-T02. Giờ 14 test. |
| `AiEditModelResolver.routed_provider`/`.routed_model` (R08-T12, property public mới) | Cần thêm để giữ `tests/integration/test_routing_surfaces.py`'s 2 test AI-Edit routing sau khi lớp routing chuyển từ `FolderTab` sang `AiEditModelResolver` — tránh hồi quy 1 test có từ EPIC R03. |
---
## 7. Còn nợ & cần quyết định
| # | Nội dung | Người quyết |
| :--- | :--- | :--- |
| 1 | **Xung đột quy hoạch thư mục `infrastructure/persistence/json/atomic_write.py`** (R06) với `atomic_json_file.py` do Team Nam quy hoạch ở R02-T01 — chưa có xung đột file thật, cần xác nhận hợp nhất hay giữ 2 module song song. | Team Nam |
| 2 | **Xung đột quy hoạch thư mục `application/monitoring/`** (R08-T13, `dashboard_query_service.py`) — quy hoạch cho Team Nam ở R08-T07→T10, nhưng plan gốc lại đặt file Dashboard vào đúng thư mục này. Chưa có xung đột file thật (thư mục trống trước đó). | Team Nam |
| 3 | **`WorkspaceRepository`/`ConversationRepository` (R06) vẫn chưa có call site sản xuất thật** — R08-T12 chỉ nối `FileWorkspaceService`, chưa đụng 2 repository kia. | Chưa có EPIC nào nhận |
| 4 | **AI-Edit pipeline (`ai_edit_pipeline.py`) và Graph Q&A ask-flow (`graph_qa_widget.py::_ask`) chưa có test end-to-end thật** — cả 2 chạy trên `AgentWorker` (QThread) thật, và **vốn dĩ đã không có test nào trước khi refactor** (xác nhận bằng grep). | Có thể thuộc phạm vi R10 Testing Pyramid |
| 5 | **Dev tooling chưa cập nhật đường dẫn cũ**: `tools/check_controls_alive.py`, `tools/capture_screens.py`, `tools/build_audit_page.py`, `docs/screens/*.json`, `docs/ui-audit*.html` vẫn tham chiếu `ui/schedule_task_tab.py`/`ui/folder_tab.py`/`ui/dashboard_tab.py`/`ui/structure_graph_view.py` (không còn tồn tại). Không nằm trong `tests/`, không ảnh hưởng CI. | Chưa quyết định người phụ trách |
---
## 8. Phạm vi chưa kiểm thử
* **R05-T04 (gate cho MCP/connector) chưa test với MCP server thật** — dùng `ToolSpec` giả, chưa thử `core/mcp_client.py::McpServerConnection` chạy subprocess thật.
* **`McpToolSourceManager` (R05-T05) chưa test với subprocess MCP thật** — dùng `_FakeConnection`.
* **`presentation/folder/ai_edit_pipeline.py`** (toàn bộ luồng plan → edit → apply/discard qua `AgentWorker` streaming) — chỉ verify bằng import/construction, chưa gửi instruction qua worker thật.
* **`presentation/graph/graph_qa_widget.py::_ask`** — tương tự, chỉ test phần không cần AgentWorker thật.
* **`office_document_renderer.py`'s PDF/LibreOffice conversion path** — chưa xác nhận kịch bản fallback trên máy không có QtPdf/LibreOffice bằng test thật.
* **Đã mở app thật bằng `python -c "import cowork_local.app"` sau mỗi task** để xác nhận không lỗi import — **chưa** mở app GUI thật, thao tác tay qua toàn bộ 4 màn hình đã tách để xác nhận trải nghiệm người dùng cuối.
---
## 9. Việc kế tiếp của Team Hoa
Toàn bộ 4 EPIC thuộc phạm vi Team Hoa (R05, R06, R07, R08 phần T11→T14) đã **hoàn tất**. Các bước còn lại không thuộc EPIC riêng của Team Hoa nữa:
| Việc | Điều kiện |
| :--- | :--- |
| Checkpoint 2 (Services & Sub-widgets, 28/08) | Cần Team Duy (R08-T01→T06) và Team Nam (R08-T07→T10) xong phần UI split của họ |
| CASAN Check 2 (Modularity/LOC, Team Hoa chủ trì, 30/08) | `scripts/check_loc.py` chưa tồn tại (thuộc R10-T02, Team Duy) |
| Giải quyết mục 7 #1, #2 | Khi Team Nam bắt đầu R02-T01 và R08-T07→T10 |
| R10 (Testing, Packaging & Contributor Experience) | Team Duy chủ trì, chờ 3 team hoàn tất |
---
## 10. Lịch sử commit
| Commit | Nội dung |
| :--- | :--- |
| `ae4fe72` | feat(R05): tool capability registry, unified policy gateway, MCP lifecycle manager |
| `cf542b7` | feat(R06): workspace session snapshot, atomic persistence, history-dir race fix |
| `69ab8e1` | feat(R07): task repository, schedule calculator, Qt clock adapter, task/AI-planner services |
| `0e51356` | feat(R08): split ScheduleTaskTab, FolderTab, DashboardTab, StructureGraphView |
| *(gộp báo cáo)* | docs(refactor): merge Team Hoa reports R05→R08 into one; rename branch to `feature/teamhoa/r05-r08` |
+768
View File
@@ -0,0 +1,768 @@
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Phân Việc Refactor Team Gamma</title>
</head>
<body>
<style>
:root {
--ground: #FAF9FC; --surface: #FFFFFF; --surface-2: #F3F0F8;
--ink: #191325; --muted: #665E7C; --line: #E4DEEE;
--accent: #6D3A9E;
--lead: #6D3A9E; --m1: #14707F; --m2: #A65418;
--warn: #A81F1A; --ok: #1B6B40;
--lead-wash: #F1E9F9; --m1-wash: #E2F1F3; --m2-wash: #F8EDE2;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--ground: #121020; --surface: #1B1830; --surface-2: #241F3D;
--ink: #EFEBF7; --muted: #A69EBD; --line: #2F2848;
--accent: #C08CF0;
--lead: #C08CF0; --m1: #56C6D8; --m2: #E29A56;
--warn: #F08A84; --ok: #6FD69C;
--lead-wash: #2A1F42; --m1-wash: #133038; --m2-wash: #38270F;
}
}
:root[data-theme="dark"] {
--ground: #121020; --surface: #1B1830; --surface-2: #241F3D;
--ink: #EFEBF7; --muted: #A69EBD; --line: #2F2848;
--accent: #C08CF0;
--lead: #C08CF0; --m1: #56C6D8; --m2: #E29A56;
--warn: #F08A84; --ok: #6FD69C;
--lead-wash: #2A1F42; --m1-wash: #133038; --m2-wash: #38270F;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--ground); color: var(--ink);
font-family: "Segoe UI", -apple-system, system-ui, "Helvetica Neue", sans-serif;
font-size: 15px; line-height: 1.62; -webkit-font-smoothing: antialiased;
}
.wrap { max-width: 1120px; margin: 0 auto; padding: 0 28px 96px; }
code, .mono, td.day, th.day, .num {
font-family: Consolas, "Cascadia Mono", "SF Mono", ui-monospace, monospace;
font-variant-numeric: tabular-nums;
}
header.top { border-bottom: 2px solid var(--ink); padding: 56px 0 22px; margin-bottom: 34px; }
.eyebrow { font-size: 12px; letter-spacing: .16em; text-transform: uppercase;
color: var(--accent); font-weight: 700; margin: 0 0 14px; }
h1 { font-size: clamp(30px, 4.4vw, 44px); line-height: 1.1; margin: 0 0 16px;
font-weight: 700; letter-spacing: -.02em; text-wrap: balance; }
.lede { font-size: 17px; color: var(--muted); margin: 0; max-width: 64ch; }
.alias { margin: 18px 0 0; padding: 12px 16px; max-width: 74ch;
background: var(--surface-2); border-left: 3px solid var(--accent);
border-radius: 3px; font-size: 14px; color: var(--muted); }
.alias b { color: var(--ink); }
.facts { display: flex; flex-wrap: wrap; gap: 28px; margin-top: 26px;
padding-top: 20px; border-top: 1px solid var(--line); }
.fact .k { font-size: 11px; letter-spacing: .13em; text-transform: uppercase;
color: var(--muted); display: block; margin-bottom: 3px; }
.fact .v { font-size: 15px; font-weight: 600; }
h2 { font-size: 23px; margin: 52px 0 6px; letter-spacing: -.01em; font-weight: 700; text-wrap: balance; }
h2 + .sub { color: var(--muted); margin: 0 0 22px; max-width: 70ch; }
h3 { font-size: 17px; margin: 30px 0 10px; font-weight: 700; }
/* gate = việc phải xong trước khi chia nhánh */
.gatebox { background: var(--surface); border: 1px solid var(--line);
border-left: 4px solid var(--warn); border-radius: 3px; padding: 4px 26px 22px; }
.gatebox h2 { margin-top: 22px; }
.steps { list-style: none; counter-reset: s; padding: 0; margin: 0; }
.steps > li { counter-increment: s; position: relative; padding: 14px 0 14px 46px;
border-bottom: 1px solid var(--line); }
.steps > li:last-child { border-bottom: none; }
.steps > li::before {
content: counter(s); position: absolute; left: 0; top: 14px;
width: 26px; height: 26px; border-radius: 50%; background: var(--accent);
color: #fff; font-size: 13px; font-weight: 700; display: flex;
align-items: center; justify-content: center;
font-family: Consolas, ui-monospace, monospace;
}
.steps b { display: block; margin-bottom: 2px; }
.steps small { color: var(--muted); font-size: 13.5px; display: block; }
.est { float: right; font-size: 12px; color: var(--muted); font-weight: 600;
font-family: Consolas, ui-monospace, monospace; }
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
@media (max-width: 940px) { .cards { grid-template-columns: 1fr; } }
.card { background: var(--surface); border: 1px solid var(--line);
border-top: 3px solid var(--c); border-radius: 3px; padding: 20px;
display: flex; flex-direction: column; }
.card.lead { --c: var(--lead); --w: var(--lead-wash); }
.card.one { --c: var(--m1); --w: var(--m1-wash); }
.card.two { --c: var(--m2); --w: var(--m2-wash); }
.card .tag { font-size: 11px; letter-spacing: .13em; text-transform: uppercase;
font-weight: 700; color: var(--c); margin-bottom: 6px; }
.card h3 { margin: 0 0 4px; font-size: 18px; }
.card .who { font-size: 13px; color: var(--muted); margin-bottom: 14px; }
.card .branch { font-size: 12.5px; background: var(--w); color: var(--c);
padding: 5px 9px; border-radius: 3px; display: inline-block;
margin-bottom: 16px; word-break: break-all; font-weight: 600; }
.card h4 { font-size: 11px; letter-spacing: .12em; text-transform: uppercase;
color: var(--muted); margin: 16px 0 7px; font-weight: 700; }
.card ul { margin: 0; padding-left: 17px; font-size: 14px; }
.card li { margin-bottom: 6px; }
.tid { font-size: 12px; font-weight: 700; color: var(--c);
font-family: Consolas, ui-monospace, monospace; }
.paths { list-style: none; padding: 0; margin: 0; font-size: 12.5px; }
.paths li { padding: 3px 0; border-bottom: 1px dotted var(--line);
font-family: Consolas, ui-monospace, monospace; color: var(--muted); word-break: break-all; }
.paths li:last-child { border-bottom: none; }
.weight { margin-top: auto; padding-top: 16px; font-size: 12.5px; color: var(--muted); }
.weight b { color: var(--ink); font-size: 15px; }
.scroll { overflow-x: auto; border: 1px solid var(--line); border-radius: 3px; }
table { border-collapse: collapse; width: 100%; font-size: 13.5px; background: var(--surface); }
th, td { text-align: left; padding: 11px 14px; border-bottom: 1px solid var(--line); vertical-align: top; }
thead th { background: var(--surface-2); font-size: 11px; letter-spacing: .1em;
text-transform: uppercase; color: var(--muted); font-weight: 700; white-space: nowrap; }
tbody tr:last-child td { border-bottom: none; }
td.day, th.day { white-space: nowrap; font-weight: 700; font-size: 13px; }
td.cl { border-left: 3px solid var(--lead); }
td.c1 { border-left: 3px solid var(--m1); }
td.c2 { border-left: 3px solid var(--m2); }
tr.mark td { background: var(--surface-2); font-weight: 600; }
td small { color: var(--muted); display: block; font-size: 12.5px; }
.pill { display: inline-block; font-size: 11px; font-weight: 700; padding: 2px 7px;
border-radius: 2px; letter-spacing: .04em; white-space: nowrap; }
.pill.cp { background: var(--m1-wash); color: var(--m1); }
.pill.gate { background: var(--m2-wash); color: var(--m2); }
.pill.ship { background: var(--lead-wash); color: var(--lead); }
.rules { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
@media (max-width: 760px) { .rules { grid-template-columns: 1fr; } }
.rule { background: var(--surface); border: 1px solid var(--line);
border-radius: 3px; padding: 18px 20px; border-left: 3px solid var(--c, var(--line)); }
.rule.hard { --c: var(--warn); }
.rule.soft { --c: var(--ok); }
.rule h3 { margin: 0 0 8px; font-size: 15px; }
.rule p { margin: 0; font-size: 14px; color: var(--muted); }
.rule code { color: var(--ink); }
/* tóm tắt: đọc 30 giây là nắm được, trước khi vào chi tiết */
.tldr {
display: grid; grid-template-columns: 1.35fr 1fr; gap: 0;
border: 1px solid var(--line); border-radius: 3px; overflow: hidden;
margin-bottom: 8px; background: var(--surface);
}
@media (max-width: 820px) { .tldr { grid-template-columns: 1fr; } }
.tldr > div { padding: 20px 24px; }
.tldr .right { background: var(--surface-2); border-left: 1px solid var(--line); }
@media (max-width: 820px) { .tldr .right { border-left: none; border-top: 1px solid var(--line); } }
.tldr .cap {
font-size: 11px; letter-spacing: .14em; text-transform: uppercase;
color: var(--muted); font-weight: 700; margin: 0 0 12px;
}
.flow { list-style: none; padding: 0; margin: 0; font-size: 14px; }
.flow li { padding: 7px 0; border-bottom: 1px dotted var(--line); display: flex; gap: 10px; }
.flow li:last-child { border-bottom: none; }
.flow .b {
flex: 0 0 auto; font-size: 11.5px; font-weight: 700; padding: 1px 7px; border-radius: 2px;
background: var(--w2); color: var(--c2); height: fit-content; margin-top: 2px;
font-family: Consolas, ui-monospace, monospace;
}
.flow li.f0 { --c2: var(--warn); --w2: var(--surface-2); }
.flow li.f1 { --c2: var(--lead); --w2: var(--lead-wash); }
.flow li.f2 { --c2: var(--m1); --w2: var(--m1-wash); }
.flow li.f3 { --c2: var(--m2); --w2: var(--m2-wash); }
.flow .t { flex: 1; }
.flow .t b { display: block; }
.flow .t small { color: var(--muted); font-size: 12.5px; }
.must { margin: 0; padding-left: 18px; font-size: 14px; }
.must li { margin-bottom: 8px; }
.must li:last-child { margin-bottom: 0; }
.must b { color: var(--ink); }
/* input / output từng người */
.io { display: grid; gap: 18px; }
.iorow { background: var(--surface); border: 1px solid var(--line);
border-left: 3px solid var(--c); border-radius: 3px; overflow: hidden; }
.iorow.n1 { --c: var(--lead); --w: var(--lead-wash); }
.iorow.n2 { --c: var(--m1); --w: var(--m1-wash); }
.iorow.n3 { --c: var(--m2); --w: var(--m2-wash); }
.iohead { padding: 14px 20px; background: var(--w); display: flex;
align-items: baseline; gap: 12px; flex-wrap: wrap; }
.iohead b { color: var(--c); font-size: 15px; }
.iohead span { color: var(--muted); font-size: 13px; }
.iogrid { display: grid; grid-template-columns: 1fr 1fr; }
@media (max-width: 860px) { .iogrid { grid-template-columns: 1fr; } }
.iogrid > div { padding: 16px 20px; }
.iogrid > div + div { border-left: 1px solid var(--line); }
@media (max-width: 860px) {
.iogrid > div + div { border-left: none; border-top: 1px solid var(--line); }
}
.iocap { font-size: 11px; letter-spacing: .13em; text-transform: uppercase;
color: var(--muted); font-weight: 700; margin: 0 0 10px; }
.iolist { list-style: none; margin: 0; padding: 0; font-size: 13.5px; }
.iolist li { padding: 5px 0; border-bottom: 1px dotted var(--line); }
.iolist li:last-child { border-bottom: none; }
.iolist code { font-size: 12.5px; }
.frm { display: inline-block; font-size: 11px; font-weight: 700; padding: 1px 6px;
border-radius: 2px; background: var(--surface-2); color: var(--muted);
margin-right: 6px; font-family: Consolas, ui-monospace, monospace; }
.frm.done { background: var(--m1-wash); color: var(--m1); }
.frm.risk { background: var(--m2-wash); color: var(--m2); }
footer { margin-top: 64px; padding-top: 20px; border-top: 1px solid var(--line);
font-size: 13px; color: var(--muted); }
</style>
<div class="wrap">
<header class="top">
<p class="eyebrow">Team Gamma · Automation, Workflows &amp; Governance</p>
<h1>Một nhánh chung, ba làn không đụng nhau</h1>
<p class="lede">
Toàn bộ phần việc refactor 10 ngày của Team Gamma — Nam, Hiệp, Lâm. Cả ba đẩy chung vào <code>gamma/refactor</code>. Nam làm thêm một mục chung —
khung kiến trúc, hợp đồng dữ liệu, cổng kiểm duyệt — nằm ngoài ba nhánh; xong mục đó thì
ba người vào ba nhánh tính năng ngang nhau, không ai phải sửa chung file với ai.
</p>
<p class="alias">
Ba tài liệu refactor gọi team này là <b>“Team Nam”</b> (theo tên lead). Cùng một team, cùng
phạm vi R02 · R08 · R09 · R07-T06. Nhánh của team dùng tiền tố <code>gamma/</code>; ba tài liệu refactor viết
<code>nam/workflow-governance-*</code> theo tên lead — cùng một thứ.
</p>
<div class="facts">
<div class="fact"><span class="k">Thời hạn</span><span class="v mono">21/08 → 31/08</span></div>
<div class="fact"><span class="k">Người</span><span class="v mono">Nam · Hiệp · Lâm</span></div>
<div class="fact"><span class="k">Nhánh</span><span class="v mono">gamma/refactor</span></div>
<div class="fact"><span class="k">Code phải bóc</span><span class="v mono">~6.500 dòng</span></div>
<div class="fact"><span class="k">Cổng phải qua</span><span class="v mono">CASAN Check 1</span></div>
</div>
</header>
<section class="tldr">
<div>
<p class="cap">Tóm tắt · thứ tự làm</p>
<ul class="flow">
<li class="f0">
<span class="b">CHUNG</span>
<span class="t"><b>Nam làm trước, nửa ngày</b>
<small>Dựng khung 5 thư mục (đang là 0 file) · interface + fake cho Config/Secrets ·
chốt <code>api_key</code> và báo Team Duy · script CASAN Check 1 · đưa 3 check vào CI ·
quyết số phận 24 checker UI. Merge xong mới chia nhánh.</small></span>
</li>
<li class="f1">
<span class="b">N1</span>
<span class="t"><b>N1 — Nam · Cấu hình, Bí mật, Vỏ ứng dụng</b>
<small>R02 (6 task) · settings 4 widget · bootstrap + MainWindow · policy doc.
Giữ luôn <code>app.py</code>, <code>config.py</code>, <code>theme.py</code>,
<code>i18n.py</code>. ~2.700 dòng.</small></span>
</li>
<li class="f2">
<span class="b">N2</span>
<span class="t"><b>N2 — Hiệp · Giám sát</b>
<small>7 tab Monitoring · CanonicalAuditLogger · MonitoringQueryService ·
2 vòng lặp import · ma trận Sandbox. ~2.650 dòng.</small></span>
</li>
<li class="f3">
<span class="b">N3</span>
<span class="t"><b>N3 — Lâm · Co4E Studio</b>
<small>Co4EWorkflowService · tách <code>co4e_tab.py</code> + <code>co4e_canvas.py</code>
thành 5 phần. ~2.880 dòng, file to nhất team.</small></span>
</li>
</ul>
</div>
<div class="right">
<p class="cap">Ba điều bắt buộc</p>
<ol class="must">
<li><b>Không chạm file dùng chung.</b> Cần thêm chuỗi hay màu thì nhắn nhóm trưởng, đừng tự sửa.</li>
<li><b>Nộp factory, không tự lắp vào <code>app.py</code>.</b> N1 lắp trong <code>bootstrap.py</code> ngày 28/08.</li>
<li><b>Bị chặn thì dùng fake, báo ngay trong ngày.</b> Không ngồi đợi ai.</li>
</ol>
<p class="cap" style="margin-top:20px">Nghiệm thu</p>
<p style="margin:0;font-size:14px;color:var(--muted)">
Trên <code>gamma/refactor</code>: không file nào được sửa bởi hai người khác nhau.
Có là quy ước <b style="color:var(--ink)">số 1</b> đang bị vi phạm.
</p>
</div>
</section>
<section class="gatebox">
<h2>Mục chung — Nam làm, xong hai người kia mới bắt đầu</h2>
<p class="sub">
Sáu việc dưới đây không thuộc làn nào — chúng là thứ cả ba người cùng đụng
vào. Nam làm một lần và đẩy lên <code>gamma/refactor</code>, rồi hai người kia
mới bắt đầu. Ước tính nửa ngày.
</p>
<ol class="steps">
<li>
<span class="est">~30 phút</span>
<b>Dựng khung thư mục</b>
<small>
<code>domain/</code> <code>application/</code> <code>infrastructure/</code>
<code>presentation/</code> <code>platform/</code> <code>tests/fakes/</code> —
hiện tại <b>chưa tồn tại, 0 file</b>. Mọi task của cả ba người đều ghi vào đây; để ba
người tự tạo là đụng nhau ở <code>__init__.py</code> ngay ngày đầu.
</small>
</li>
<li>
<span class="est">~45 phút</span>
<b>Viết interface + fake cho Config và Secrets</b>
<small>
<code>SecretStore</code>, <code>ConfigRepository</code>, kèm
<code>FakeSecretStore</code> và <code>FakeConfigRepository</code>. Chỉ chữ ký, chưa cần
thân hàm. Đây là thứ gỡ chốt cho cả hai người kia — <b>156 lời gọi
<code>ctx.config.*</code> trong 29 file</b> đang chờ nó.
</small>
</li>
<li>
<span class="est">~20 phút</span>
<b>Chốt số phận <code>api_key</code> và báo Team Duy</b>
<small>
<code>provider_conf()</code> còn trả <code>api_key</code> bên trong, hay tách hẳn sang
<code>SecretStore</code>? Có 5 nơi đọc trực tiếp, <b>3 trong số đó nằm trong
<code>providers/</code> của Team Duy</b>. Quyết một mình rồi im lặng là làm vỡ code
team bạn.
</small>
</li>
<li>
<span class="est">~30 phút</span>
<b>Viết <code>scripts/audit_security.py</code> (CASAN Check 1)</b>
<small>
Gamma chủ trì check này ngày 30/08. Viết ngay hôm nay thì lead tự kiểm được trong suốt
quá trình chuyển API key, thay vì tới ngày cổng mới chạy lần đầu và phát hiện vấn đề.
</small>
</li>
<li>
<span class="est">~20 phút</span>
<b>Thêm 3 check CASAN vào CI</b>
<small>
CI hiện chỉ chạy <code>pytest tests -q</code>. Ba check (secret · ≤400 dòng · import
guard) không nằm trong CI, nên tới 30/08 mới biết ai vi phạm. Đưa vào CI thì mỗi PR tự
báo.
</small>
</li>
<li>
<span class="est">~30 phút</span>
<b>Quyết số phận 24 checker UI, rồi thông báo</b>
<small>
Chúng bám vào <code>cowork_local.config</code> (34 chỗ) và <code>cowork_local.app</code>
(16 chỗ) — <b>sẽ chết ngay khi lead đụng <code>config.py</code></b>. Đây là lưới an toàn
duy nhất cho phần UI vừa làm xong. Xem mục quy ước bên dưới.
</small>
</li>
</ol>
</section>
<h2>Ba làn</h2>
<p class="sub">
Ba làn ngang nhau, mỗi làn khoảng 2.700 dòng phải bóc tách, <b>cùng đẩy vào một
nhánh</b> <code>gamma/refactor</code>. Nam nhận làn N1 vì đó là làn chạm tới file
dùng chung nhiều nhất. Cột “sở hữu” là danh sách file <em>chỉ</em> người đó được
sửa — trên nhánh chung, đây là thứ duy nhất giữ cho ba người không giẫm chân.
</p>
<div class="cards">
<div class="card lead">
<div class="tag">Làn N1 · Nam</div>
<h3>Cấu hình, Bí mật &amp; Vỏ ứng dụng</h3>
<p class="who">Nam giữ — làn chạm nhiều file dùng chung nhất</p>
<div class="branch">gamma/refactor</div>
<h4>Việc</h4>
<ul>
<li><span class="tid">R02-T01…T06</span> AtomicJsonFile · ConfigRepository · Typed Settings Facade · SecretStore + Keyring · chuyển API key · schema versioning</li>
<li><span class="tid">R08-T07</span> tách <code>settings_dialog.py</code> → 4 section widget</li>
<li><span class="tid">R08-T10</span> <code>bootstrap.py</code> + tách <code>MainWindow</code> → shell · tray · lifecycle <em>(cuối sprint, lắp factory của hai người kia)</em></li>
<li><span class="tid">R09-T01</span> tài liệu Security Policy Model</li>
<li>Chủ trì <b>CASAN Check 1</b> · giữ CI · duyệt PR của hai người</li>
</ul>
<h4>Sở hữu độc quyền</h4>
<ul class="paths">
<li>config.py</li>
<li>app.py → presentation/shell/</li>
<li>bootstrap.py</li>
<li>theme.py · i18n.py</li>
<li>infrastructure/config/ · secrets/ · persistence/</li>
<li>ui/settings_dialog.py → presentation/settings/</li>
<li>scripts/ · .gitea/workflows/</li>
</ul>
<p class="weight"><b>~2.700 dòng</b> · 727 settings + 1.352 app + 616 config<br>+ mục chung ở trên</p>
</div>
<div class="card one">
<div class="tag">Làn N2 · Hiệp</div>
<h3>Giám sát &amp; Quan trắc</h3>
<p class="who">Hiệp — 7 tab, việc lặp cần kỷ luật</p>
<div class="branch">gamma/refactor</div>
<h4>Việc</h4>
<ul>
<li><span class="tid">R08-T08</span> tách <code>monitoring_tab.py</code> → 7 tab độc lập</li>
<li><span class="tid">R09-T04</span> <code>CanonicalAuditLogger</code></li>
<li><span class="tid">R09-T05</span> <code>MonitoringQueryService</code> read-only, phân trang</li>
<li><span class="tid">R09-T02</span> gỡ vòng lặp <code>model_pricing</code> ↔ <code>usage_tracker</code></li>
<li><span class="tid">R09-T03</span> gỡ vòng lặp <code>agent_security</code> ↔ <code>alert</code></li>
<li><span class="tid">R09-T06</span> ma trận Sandbox theo hệ điều hành</li>
</ul>
<h4>Sở hữu độc quyền</h4>
<ul class="paths">
<li>ui/monitoring_tab.py → presentation/monitoring/</li>
<li>application/monitoring/</li>
<li>infrastructure/telemetry/ · sandbox/</li>
<li>core/audit_log.py</li>
<li>core/model_pricing.py · usage_tracker.py</li>
<li>core/agent_security*.py</li>
</ul>
<p class="weight"><b>~2.650 dòng</b> · 1.545 monitoring + ~1.100 core</p>
</div>
<div class="card two">
<div class="tag">Làn N3 · Lâm</div>
<h3>Co4E Studio</h3>
<p class="who">Lâm — canvas và luồng chạy workflow</p>
<div class="branch">gamma/refactor</div>
<h4>Việc</h4>
<ul>
<li><span class="tid">R07-T06</span> <code>Co4EWorkflowService</code> thuần Python</li>
<li><span class="tid">R08-T09</span> tách <code>co4e_tab.py</code> + <code>co4e_canvas.py</code> → canvas · node property · run control · chat view · agent list</li>
<li>Gọi tool qua <code>ToolPolicyGateway</code> của Team Hoa — dùng fake, không chờ</li>
</ul>
<h4>Sở hữu độc quyền</h4>
<ul class="paths">
<li>ui/co4e_tab.py → presentation/co4e/</li>
<li>ui/co4e_canvas.py</li>
<li>ui/co4e_config_panel.py</li>
<li>application/workflows/</li>
<li>domain/workflows/</li>
<li>core/co4e_run_manager.py</li>
</ul>
<p class="weight"><b>~2.880 dòng</b> · file to nhất của cả team</p>
</div>
</div>
<h2>Tám quy ước</h2>
<p class="sub">
Tám điều dưới đây là luật của team, Nam chốt. Bốn điều đầu là bắt buộc — trên một
nhánh chung, vi phạm không chỉ hại mình mà chặn cả hai người kia.
</p>
<div class="rules">
<div class="rule hard">
<h3>1 · Không chạm file dùng chung</h3>
<p>
<code>app.py</code>, <code>theme.py</code>, <code>i18n.py</code>, <code>config.py</code>,
<code>bootstrap.py</code> thuộc nhánh N1 của Nam. Cần thêm chuỗi hay token màu thì
<b>nhắn, đừng sửa</b> — Nam thêm trong ngày. Đây là ba file duy nhất có thể gây conflict
thật, và luật này xoá hẳn khả năng đó.
</p>
</div>
<div class="rule hard">
<h3>2 · Nộp factory, không tự lắp vào app</h3>
<p>
Mỗi nhánh expose một hàm dựng widget với chữ ký chốt từ ngày đầu, ví dụ
<code>build_monitoring_tab(ctx, query_service) -&gt; QWidget</code>. Nam gọi nó trong <code>bootstrap.py</code> ngày 28/08. Không ai tự sửa chỗ khởi tạo trong
<code>app.py</code>.
</p>
</div>
<div class="rule hard">
<h3>3 · Bị chặn thì dùng fake, không ngồi đợi</h3>
<p>
Chưa có <code>ConfigRepository</code> bản thật thì dùng <code>FakeConfigRepository</code>.
Chưa có <code>ToolPolicyGateway</code> của Team Hoa thì đã có fake sẵn. <b>Báo ngay trong ngày</b>
nếu thiếu fake nào — đó là việc của nhóm trưởng, không phải lý do dừng tay.
</p>
</div>
<div class="rule hard">
<h3>4 · Nhánh chung: kéo trước khi đẩy, đừng để nhánh đỏ</h3>
<p>
Cả ba đẩy vào <code>gamma/refactor</code>, nên không còn nhánh riêng làm vùng
đệm. Ba việc bắt buộc: <code>git pull --rebase</code> trước mỗi lần đẩy;
commit nhỏ và đẩy trong ngày, đừng ôm 500 dòng ba hôm; và
<b>không bao giờ đẩy thứ làm <code>pytest tests -q</code> đỏ</b> — nhánh hỏng
là hai người kia đứng hình. Lỡ đẩy nhầm thì sửa ngay hoặc
<code>git revert</code>, đừng để qua đêm.
</p>
</div>
<div class="rule soft">
<h3>5 · Commit nhỏ, mỗi ngày một lần</h3>
<p>
Một PR cho một sub-widget hoặc một service, không dồn 7 tab vào một PR cuối tuần. Nhóm
trưởng duyệt trong ngày. PR càng to thì rủi ro càng dồn về ngày 28/08.
</p>
</div>
<div class="rule soft">
<h3>6 · Mỗi commit kèm test, và không làm đỏ 90 test cũ</h3>
<p>
Baseline hiện tại: <b>102 test xanh trong 3,4 giây</b>. Chạy <code>pytest tests -q</code>
trước mỗi lần đẩy. Đây là lưới an toàn cho phần logic — giữ nó xanh suốt 10 ngày.
</p>
</div>
<div class="rule soft">
<h3>7 · File mới ≤ 400 dòng, không import PySide6 vào lõi</h3>
<p>
Hai điều kiện của CASAN Check 2 và 3. Tự kiểm trước khi đẩy — CI sẽ báo, nhưng biết
sớm thì đỡ phải tách lại lần hai.
</p>
</div>
<div class="rule soft">
<h3>8 · Checker UI thuộc phạm vi ai, người đó cập nhật</h3>
<p>
24 checker sẽ vỡ khi file bị dời. Ai dời file thì sửa checker tương ứng ngay trong
commit đó — tốn thêm khoảng 15% thời gian, đổi lại giữ được lưới an toàn cho phần
UI vừa làm xong.
<b>Đã chốt 21/08: đường A. Nam chịu trách nhiệm nếu đổi ý.</b>
</p>
</div>
</div>
<h2>Mỗi người nhận gì, giao gì</h2>
<p class="sub">
Cột trái là thứ phải có trong tay mới làm được, kèm nguồn. Cột phải là thứ bắt
buộc giao ra, kèm người nhận. Nhãn <span class="frm done">có rồi</span> nghĩa là
mục chung đã làm xong.
</p>
<div class="io">
<div class="iorow n1">
<div class="iohead"><b>N1 · Cấu hình, Bí mật &amp; Vỏ</b><span>Nam · nhóm trưởng</span></div>
<div class="iogrid">
<div>
<p class="iocap">Input — cần có</p>
<ul class="iolist">
<li><span class="frm">mã cũ</span><code>config.py</code> 616 dòng</li>
<li><span class="frm">mã cũ</span><code>ui/settings_dialog.py</code> 727 dòng</li>
<li><span class="frm">mã cũ</span><code>app.py</code> 1.352 dòng</li>
<li><span class="frm risk">tự chốt</span>Quyết định <code>api_key</code> — trước 26/08</li>
<li><span class="frm">từ Hiệp</span>Chữ ký <code>build_monitoring_tab()</code> — trước 28/08</li>
<li><span class="frm">từ Lâm</span>Chữ ký <code>build_co4e_tab()</code> — trước 28/08</li>
</ul>
</div>
<div>
<p class="iocap">Output — phải giao</p>
<ul class="iolist">
<li><span class="frm done">có rồi</span><code>SecretStore</code> · <code>ConfigRepository</code> + fake → <b>cho Hiệp và Lâm</b></li>
<li><span class="frm done">có rồi</span><code>scripts/audit_security.py</code> → cho CI</li>
<li><code>infrastructure/persistence/json/atomic_json_file.py</code></li>
<li><code>infrastructure/config/</code> — cài đặt thật + settings facade</li>
<li><code>infrastructure/secrets/keyring_adapter.py</code></li>
<li><code>presentation/settings/</code> — 4 widget</li>
<li><code>bootstrap.py</code> + <code>presentation/shell/</code> — 3 file</li>
<li><code>docs/architecture/security-policy.md</code></li>
</ul>
</div>
</div>
</div>
<div class="iorow n2">
<div class="iohead"><b>N2 · Giám sát</b><span>Hiệp</span></div>
<div class="iogrid">
<div>
<p class="iocap">Input — cần có</p>
<ul class="iolist">
<li><span class="frm">mã cũ</span><code>ui/monitoring_tab.py</code> 1.545 dòng</li>
<li><span class="frm">mã cũ</span><code>core/usage_tracker.py</code> 524 · <code>sandbox_manager.py</code> 335</li>
<li><span class="frm">mã cũ</span><code>core/model_pricing.py</code> 284 · <code>agent_security.py</code> 272 · <code>audit_log.py</code> 115</li>
<li><span class="frm done">từ Nam</span><code>FakeConfigRepository</code> — dùng được ngay</li>
<li><span class="frm risk">tự chốt</span>Giữ nguyên 9 trường log, báo Duy và Hoa</li>
</ul>
</div>
<div>
<p class="iocap">Output — phải giao</p>
<ul class="iolist">
<li><code>build_monitoring_tab()</code> → <b>cho Nam</b>, trước 28/08</li>
<li><code>FakeAuditLogger</code> · <code>FakeMonitoringQueryService</code> → <b>cho cả team</b></li>
<li><code>presentation/monitoring/</code> — 7 tab + shell</li>
<li><code>application/monitoring/monitoring_query_service.py</code></li>
<li><code>infrastructure/telemetry/audit_logger.py</code></li>
<li><code>infrastructure/sandbox/sandbox_capabilities.py</code></li>
<li><b>0 circular import</b> ở pricing ↔ usage và security ↔ alert</li>
</ul>
</div>
</div>
</div>
<div class="iorow n3">
<div class="iohead"><b>N3 · Co4E Studio</b><span>Lâm</span></div>
<div class="iogrid">
<div>
<p class="iocap">Input — cần có</p>
<ul class="iolist">
<li><span class="frm">mã cũ</span><code>ui/co4e_tab.py</code> 2.089 dòng</li>
<li><span class="frm">mã cũ</span><code>ui/co4e_canvas.py</code> 791 · <code>co4e_config_panel.py</code></li>
<li><span class="frm">mã cũ</span><code>core/co4e_run_manager.py</code> 331</li>
<li><span class="frm">có sẵn</span><code>core/co4e.py</code> — dataclass Workflow/Node/Edge đã có</li>
<li><span class="frm done">từ Nam</span><code>FakeConfigRepository</code></li>
<li><span class="frm risk">từ Team Hoa</span>DTO <code>ToolPolicyGateway</code> — <b>rủi ro liên team cao nhất</b>, lấy trong hôm nay</li>
</ul>
</div>
<div>
<p class="iocap">Output — phải giao</p>
<ul class="iolist">
<li><code>build_co4e_tab()</code> → <b>cho Nam</b>, trước 28/08</li>
<li><code>FakeCo4EWorkflowService</code> → <b>cho cả team</b></li>
<li><code>domain/workflows/</code> — DTO chốt ngày đầu</li>
<li><code>application/workflows/co4e_workflow_service.py</code></li>
<li><code>presentation/co4e/</code> — 5 phần</li>
</ul>
</div>
</div>
</div>
</div>
<h3>Output bắt buộc với cả ba, mỗi lần đẩy</h3>
<div class="scroll">
<table>
<thead><tr><th>Điều kiện</th><th>Ngưỡng</th><th>Tự kiểm bằng</th></tr></thead>
<tbody>
<tr><td>File mới sau khi tách</td><td class="mono">≤ 400 dòng</td><td class="mono">wc -l</td></tr>
<tr><td><code>domain/</code> và <code>application/</code> import PySide6</td><td class="mono">0</td><td class="mono">grep -r PySide6</td></tr>
<tr><td>Test hiện có</td><td class="mono">102 xanh</td><td class="mono">pytest tests -q</td></tr>
<tr><td>Credential lộ</td><td class="mono">0</td><td class="mono">python scripts/audit_security.py</td></tr>
<tr><td>Checker UI trong phạm vi mình dời</td><td>đã cập nhật</td><td class="mono">python tools/check_&lt;tên&gt;.py</td></tr>
</tbody>
</table>
</div>
<h2>Lịch từng ngày</h2>
<p class="sub">Ba hàng chạy độc lập. Hàng tô nền là lúc cả ba phải gặp nhau.</p>
<div class="scroll">
<table>
<thead>
<tr>
<th class="day">Ngày</th>
<th>N1 · Nam</th>
<th>N2 · Hiệp</th>
<th>N3 · Lâm</th>
</tr>
</thead>
<tbody>
<tr>
<td class="day">21/08<br><small>T6</small></td>
<td class="cl"><b>Mục chung</b> · dựng khung · interface + fake · chốt api_key · CASAN script<small>Merge trước khi hai người kia bắt đầu</small></td>
<td class="c1">Chốt schema log 9 trường<small>Giữ nguyên định dạng cũ để 24 chỗ gọi không phải sửa</small></td>
<td class="c2">Chốt chữ ký <code>Co4EWorkflowService</code><small>Nộp cho lead để lắp bootstrap sau</small></td>
</tr>
<tr>
<td class="day">22–23/08<br><small>T7–CN</small></td>
<td class="cl">AtomicJsonFile · ConfigRepository · Typed Settings Facade</td>
<td class="c1">CanonicalAuditLogger · gỡ vòng lặp pricing ↔ usage</td>
<td class="c2">Co4EWorkflowService — CRUD &amp; validate, test không cần Qt</td>
</tr>
<tr class="mark">
<td class="day">23/08<br><small>17:00</small></td>
<td colspan="3"><span class="pill cp">Checkpoint 1</span> &nbsp; 100% DTO và fake xong · <code>pytest</code> xanh · không ai bị chặn</td>
</tr>
<tr>
<td class="day">24/08<br><small>T2</small></td>
<td class="cl">Tách settings: provider + connector widget</td>
<td class="c1">3 tab đầu: overview · sandbox · security events</td>
<td class="c2">node_property_panel · agent_list_panel</td>
</tr>
<tr>
<td class="day">25/08<br><small>T3</small></td>
<td class="cl">Tách settings: routing + general widget</td>
<td class="c1">4 tab còn lại: MCP · action logs · agent status · security settings</td>
<td class="c2">co4e_canvas_widget — thao tác node</td>
</tr>
<tr>
<td class="day">26/08<br><small>T4</small></td>
<td class="cl">Chuyển API key sang SecretStore<small>Báo Team Duy trước khi đụng providers/</small></td>
<td class="c1">Lắp shell MonitoringTab · query service bản thật</td>
<td class="c2">Run control · chat view</td>
</tr>
<tr>
<td class="day">27/08<br><small>T5</small></td>
<td class="cl">Schema versioning · recovery policy</td>
<td class="c1">Ma trận Sandbox · gỡ vòng lặp agent_security</td>
<td class="c2">Lắp container Co4ETab · thay fake bằng service thật</td>
</tr>
<tr>
<td class="day">28/08<br><small>T6</small></td>
<td class="cl"><b>bootstrap.py + tách MainWindow</b><small>Nhận factory của Hiệp và Lâm để lắp</small></td>
<td class="c1">Nộp factory · dọn file &gt;400 dòng · cập nhật checker</td>
<td class="c2">Nộp factory · dọn file &gt;400 dòng · cập nhật checker</td>
</tr>
<tr class="mark">
<td class="day">28/08<br><small>17:00</small></td>
<td colspan="3"><span class="pill cp">Checkpoint 2</span> &nbsp; Tách xong 100% god file · 0 circular import</td>
</tr>
<tr>
<td class="day">29/08<br><small>T7</small></td>
<td class="cl">Tài liệu Security Policy · integration test Settings</td>
<td class="c1">Integration test Monitoring</td>
<td class="c2">Integration test luồng Co4E đầu-cuối</td>
</tr>
<tr class="mark">
<td class="day">30/08<br><small>CN 17:00</small></td>
<td colspan="3"><span class="pill gate">CASAN Gate</span> &nbsp; <b>Nam chủ trì Check 1</b> — quét toàn bộ config/JSON, phải ra 0 secret plaintext. Hiệp và Lâm sửa ngay phần của mình nếu script bắt được.</td>
</tr>
<tr class="mark">
<td class="day">31/08<br><small>T2 15:00</small></td>
<td colspan="3"><span class="pill ship">Bàn giao</span> &nbsp; Fix tồn đọng · cập nhật tài liệu kiến trúc · merge PR cuối · smoke test 5 luồng chính</td>
</tr>
</tbody>
</table>
</div>
<h2>Nghiệm thu: làm sao biết đã thật sự song song</h2>
<p class="sub">Không phải “đã họp xong” mà là chạy được. Ba câu hỏi, trả lời bằng lệnh.</p>
<div class="scroll">
<table>
<thead>
<tr><th>Câu hỏi</th><th>Cách trả lời</th><th>Khi nào</th></tr>
</thead>
<tbody>
<tr>
<td>Hiệp có chạy được khi chưa có config bản thật?</td>
<td>Dựng một tab Monitoring, chạy test của nó, <b>không import <code>cowork_local.config</code></b> dòng nào — chỉ dùng <code>FakeConfigRepository</code></td>
<td class="mono">21/08</td>
</tr>
<tr>
<td>Lâm có chạy được khi Team Hoa chưa xong gateway?</td>
<td>Test <code>Co4EWorkflowService</code> xanh với <code>FakeToolPolicyGateway</code></td>
<td class="mono">23/08</td>
</tr>
<tr>
<td>Ba người có đụng file nhau không?</td>
<td><code>git log --name-only --pretty=%an</code> trên <code>gamma/refactor</code> —
không file nào được xuất hiện dưới hai tên khác nhau</td>
<td class="mono">mỗi ngày</td>
</tr>
</tbody>
</table>
</div>
<footer>
Nguồn: <code>docs/refactor/plan.md</code>, <code>Refactoring_Checklist.md</code>,
<code>Feature_Architecture_Proposal.md</code>. Số dòng code, số lời gọi và baseline test đo
trực tiếp trên nhánh <code>main</code> ngày 21/08.
Mục chung, cách chia ba nhánh, bảy quy ước và mục nghiệm thu là đề xuất — không có trong
tài liệu gốc.
</footer>
</div>
</body>
</html>
+189
View File
@@ -0,0 +1,189 @@
# Quyết định của Team Gamma
Team: **Nam** (nhóm trưởng, nhánh N1) · **Hiệp** (N2) · **Lâm** (N3).
Ghi ở đây thay vì chôn trong comment, vì cả ba đều ảnh hưởng ra ngoài phạm vi
một người.
| # | Việc | Trạng thái |
|---|---|---|
| 1 | `provider_conf()` còn trả `api_key` | **Chốt 21/08 — đường A** |
| 2 | Số phận 24 checker UI | **Chốt 21/08 — đường A** |
| 3 | DTO `ToolPolicyGateway` viết hộ Team Hoa | Đã làm, chờ Hoa xác nhận |
---
## Quyết định 1 — `provider_conf()` còn trả `api_key` hay không
### Vì sao phải quyết trước khi code
R02-T05 chuyển API key sang Keyring. Câu hỏi là sau khi chuyển, dict do
`provider_conf()` trả về **còn chứa `api_key` không**.
Có 5 nơi đang đọc trực tiếp — đo trên `main` ngày 21/08:
| Nơi đọc | Thuộc |
|---|---|
| `providers/anthropic.py:26` | **Team Duy** |
| `providers/openai_compat.py:36` | **Team Duy** |
| `core/image_gen.py:50` | Team Duy (routing/model) |
| `core/ext_connectors.py:98` | Team Hoa |
| `ui/ext_connector_dialog.py:87` | Team Gamma |
Ba trong năm nằm ngoài team. Quyết một mình rồi im lặng là làm vỡ code người khác.
### Hai đường
**A. Giữ `api_key` trong dict, `ConfigRepository` tự lấy từ `SecretStore` rồi ghép vào**
- 5 nơi đọc **không phải sửa dòng nào**
- Không cần báo team khác, không cần đồng bộ lịch
- Đổi lại: bí mật vẫn đi lang thang trong dict, dễ lọt vào log hoặc màn hình debug
- CASAN Check 1 vẫn PASS vì nó quét **file trên đĩa**, không quét bộ nhớ
**B. Bỏ `api_key` khỏi dict, ai cần thì gọi `secrets.get(provider_key(name))`**
- Sạch về nguyên tắc: bí mật chỉ xuất hiện đúng chỗ cần
- Đổi lại: **5 nơi phải sửa**, 3 trong đó phải chờ team khác xếp lịch
- Rủi ro: quên một chỗ thì mất API key lúc chạy thật, mà test có fake nên không bắt được
### Đề xuất
**Đường A cho sprint này, đường B ghi vào nợ kỹ thuật.**
Lý do: mục tiêu của cổng CASAN là *không còn secret nằm trên đĩa*, và đường A
đạt được điều đó. Đường B giải quyết thêm chuyện secret trong bộ nhớ — đúng
nhưng không phải việc của 10 ngày này, và nó kéo hai team khác vào một thay đổi
họ không lên kế hoạch.
Nếu chọn B thì **phải báo Team Duy và Team Hoa trong hôm nay**, không phải lúc
đã sửa xong.
> **Nam chốt 21/08: đường A.**
>
> Việc kèm theo: `ConfigRepository` bản thật phải đọc key từ `SecretStore` rồi
> ghép vào dict do `provider_conf()` trả về. Năm nơi đọc không đổi một dòng,
> nên **không cần báo Duy và Hoa**.
>
> Nợ kỹ thuật đã ghi: đường B (bỏ `api_key` khỏi dict) để sau sprint này.
---
## Quyết định 2 — số phận 24 checker UI
### Vấn đề
`tools/check_*.py` là bộ kiểm tra giao diện viết trong 2 tuần vừa rồi, hiện
**24 file**. Chúng bám vào đường dẫn cũ:
| Import | Số chỗ |
|---|---|
| `cowork_local.config` | 34 |
| `cowork_local.app` | 16 |
| `cowork_local.state` | 22 |
| `cowork_local.ui.*` | ~12 |
R08 dời hết những module đó sang `presentation/`. Nghĩa là **cả 24 checker chết
ngay ngày N1 đụng `config.py`** — và đó là lưới an toàn duy nhất cho phần giao
diện, vì `pytest` không kiểm giao diện (90 test hiện tại là logic).
### Ba đường
**A. Ai dời file thì cập nhật checker tương ứng, ngay trong PR đó**
- Giữ được lưới suốt 10 ngày
- Tốn thêm ~15% thời gian mỗi PR
- Rủi ro: người sửa vội có thể nới lỏng phép kiểm cho nó xanh — đã xảy ra một
lần trong quá trình làm UI, khi một checker được sửa thành *không thể đỏ*
**B. Đóng băng: bỏ khỏi CI, sửa một lượt ngày 31/08**
- Nhanh nhất trong 10 ngày
- Đổi lại: **không có gì canh hồi quy giao diện** suốt cả sprint. Refactor là lúc
dễ vỡ giao diện nhất
- Rủi ro cuối sprint: sửa 24 file cùng lúc, không ai nhớ cái nào đo gì
**C. Bỏ hẳn**
Không khuyến nghị. Vứt đi hai tuần công sức kiểm chứng, và ba tài liệu refactor
không có gì thay thế cho phần giao diện.
### Đề xuất
**Đường A**, kèm một ràng buộc: PR nào *sửa* checker phải nói rõ trong mô tả
**sửa gì và vì sao** — để việc nới lỏng phép kiểm không lọt qua review.
`tools/check_probes_bite.py` đã có sẵn cơ chế chứng minh checker còn cắn được;
chạy nó sau mỗi đợt sửa là bắt được ngay chuyện đó.
> **Chốt 21/08: đường A** — ai dời file thì cập nhật checker tương ứng ngay
> trong PR đó.
>
> Kèm hai ràng buộc, vì rủi ro của đường A là người sửa vội nới lỏng phép kiểm:
>
> 1. PR nào *sửa* checker phải nói rõ trong mô tả **sửa gì và vì sao**.
> 2. Sửa xong chạy `python tools/check_probes_bite.py` — nó cắm lỗi cố ý vào
> code rồi kiểm checker có bắt được không. Chính công cụ này đã từng bắt
> được một checker bị sửa thành *không thể đỏ*.
>
> Không đưa 24 checker vào CI trong sprint này: chúng dựng `MainWindow` thật,
> mỗi lần chạy tốn hàng chục giây và thỉnh thoảng sập lúc Qt dọn dẹp. Chạy tay
> theo phạm vi mình đụng là đủ.
---
## Quyết định 3 — Gamma viết hộ DTO `ToolPolicyGateway` cho Team Hoa
**Đã làm, chờ Hoa xác nhận.** Ngày: 21/08.
### Vì sao làm thay
N3 (Co4E) cần gọi tool nhưng Team Hoa chưa bắt đầu. Ba đường:
| | Hệ quả |
|---|---|
| N3 ngồi đợi Hoa | Mất mấy ngày, trái nguyên tắc "không team nào chặn team nào" |
| N3 tự phỏng đoán | Phỏng đoán của một người, không ai soi, sửa lại chắc chắn |
| **Gamma viết bản đề xuất** | N3 chạy ngay, Hoa có cái cụ thể để duyệt hoặc sửa |
### Ranh giới không lấn
Sơ đồ phân hệ trong `plan.md` giao `domain/security/` cho **Team Gamma**, còn
`application/conversations/tool_policy_gateway.py` cho **Team Hoa**.
Nên chia đúng như vậy:
- **Gamma định nghĩa hình dạng** → `domain/security/tool_policy.py`
- **Hoa cài đặt gateway** → `application/conversations/tool_policy_gateway.py`,
nối vào `core/mcp_client.py` và tool dựng sẵn
Không đụng file nào của Hoa.
### Đã bám vào code đang chạy, không bịa
| Nguồn | Lấy gì |
|---|---|
| `core/agent_security.py::SecurityVerdict` | `allowed` · `reason` · `layer` |
| `ui/permission_dialog.py` + `chat_panel.py:1312` | trạng thái "hỏi người dùng" |
Khác biệt duy nhất: gộp thành **một câu trả lời ba trạng thái**
(`ALLOW` / `DENY` / `ASK`) thay vì bắt chỗ gọi tự nhớ hỏi hai nơi.
Hai ràng buộc đưa vào có chủ đích:
1. `DENY` và `ASK` **bắt buộc có `reason`** — người dùng cần biết vì sao, và
`audit_log` cần ghi lại. Thiếu là ném lỗi ngay lúc dựng, không phải lúc chạy.
2. `ASK` **không phải** `allowed` — bẫy dễ mắc nhất là coi ASK như ALLOW rồi tool
chạy mà chưa ai đồng ý. Có test riêng cho chuyện này.
### Gửi Hoa cái gì
> Bên mình viết trước bản đề xuất `ToolPolicyGateway` ở
> `domain/security/tool_policy.py` vì N3 cần gọi tool mà bên Hoa chưa bắt đầu —
> để N3 khỏi phải tự đoán. Ba kiểu: `ToolCallRequest`, `PolicyDecision`,
> `ToolPolicyGateway`. Phần cài đặt vẫn để bên Hoa ở
> `application/conversations/tool_policy_gateway.py`, bọn mình không đụng.
> Thấy chỗ nào không hợp thì sửa thẳng file đó, đừng tạo kiểu thứ hai. Đổi bây
> giờ còn rẻ vì mới mình N3 dùng.
> Đã gửi Hoa: ☐ — ngày ____ Hoa xác nhận: ☐ đồng ý ☐ có sửa
+230 -123
View File
@@ -20,6 +20,111 @@
---
## 📊 TIẾN ĐỘ THỰC TẾ — TEAM DUY (cập nhật `2026-08-21 10:55`)
> [!NOTE]
> ### ✅ ĐÃ HOÀN TẤT: 16/16 task của **R01, R03, R04** — đã commit & push lên nhánh `feature/deltateam/refactor-plan`
>
> | EPIC | Task | Trạng thái |
> | :--- | :--- | :--- |
> | **R01** Architecture Foundation | T01 → T05 | ✅ 5/5 |
> | **R03** Providers & Routing | T01 → T06 | ✅ 6/6 |
> | **R04** Agent Runtime & Conversation | T01 → T05 | ✅ 5/5 |
>
> **Kiểm chứng (chạy thật, không phải ước lượng):**
> * `pytest tests/` ➔ **243 pass / 2 fail** trong 44s
> * Suite nhanh (`unit + contracts + characterization + routing`) ➔ **218 pass trong 1,16s** (đạt yêu cầu CASAN "A – Automated Tests < 1s cho unit")
> * `python scripts/check_imports.py` ➔ **PASS** (0 Qt import trong `domain/`, `application/`)
> * Mọi file production mới **< 400 dòng** (lớn nhất: `routing_application_service.py` 353 dòng)
> * 2 test fail là **lỗi có sẵn từ trước**, thuộc EPIC **R02**: `config.py` vẫn hardcode `sandbox_pw = "quandh14"` ➔ `tests/test_config_security.py` đỏ
>
> ### 📍 PHẠM VI TEAM DUY & PHẦN CÒN LẠI
> Theo `Feature_Architecture_Proposal.md` (dòng 7) và `DeltaTeam_prompt.md` (dòng 17), Team Duy chủ trì **R01, R03, R04, R08 (phân hệ Chat UI), R10**.
> * ✅ **R01, R03, R04** — xong 16/16 task, đã push.
> * ⬜ **R08 (R08-T01 ➔ R08-T06)** — chưa bắt đầu: tách `ui/chat_panel.py` (1.795 dòng) thành 6 widget < 400 dòng.
> * ⬜ **R10** — làm sau cùng, chờ 3 team hoàn tất.
> * **R02 thuộc 🟣 Team Nam** (xem mục EPIC R02 bên dưới) — đây là nguyên nhân 2 test đỏ ở trên, không phải việc của Team Duy.
>
> ### 📄 BÁO CÁO CHI TIẾT
> Xem `docs/refactor/BaoCao_TeamDuy_R01_R03_R04.md` — kết quả từng EPIC, bằng chứng kiểm thử, 3 lỗi thật đã phát hiện, và phạm vi **chưa** kiểm thử.
>
> ### 📌 CÒN NỢ / CẦN QUYẾT ĐỊNH
> 1. `ProviderRegistry` **chưa nối** vào `state.build_provider_for` (vẫn dùng `providers/factory.py`). Nối vào sẽ sửa luôn lỗi: usage của `ollama`/`github_copilot`/`codex` hiện bị ghi nhận nhầm thành `openai_compat` trên Dashboard — nhưng làm vậy sẽ **đổi cách gom dữ liệu lịch sử**.
> 2. Mode `fallback` đã hỗ trợ ở config + service nhưng **chưa có trên toggle UI** (thuộc R08).
> 3. Đã sửa 2 dòng trong `config.py` (`routing_mode_for` / `set_routing_mode_for`) để dùng chung một bộ từ vựng mode — **cần báo Team Nam** vì file này đang được refactor ở R02.
> 4. Circular import `core/model_pricing.py` ↔ `core/usage_tracker.py` **chưa xử lý** (task ngày 28/08).
> 5. Việc kế tiếp của Team Duy là **R08 phân hệ Chat UI** (6 widget con), rồi **R10** sau cùng.
---
## 📊 TIẾN ĐỘ THỰC TẾ — TEAM HOA (cập nhật `2026-08-21 22:57`)
> [!NOTE]
> ### ✅ ĐÃ HOÀN TẤT: 10/10 task của **R05 + R06** — branch `feature/teamhoa/r05-r06` (tạo từ `origin/feature/deltateam/refactor-plan`, có sẵn nền R01/R03/R04)
>
> | EPIC | Task | Trạng thái |
> | :--- | :--- | :--- |
> | **R05** Tool, MCP & Connector Policy | T01 → T05 | ✅ 5/5 |
> | **R06** Workspace, Filesystem & History Isolation | T01 → T05 | ✅ 5/5 |
>
> **Kiểm chứng (chạy thật):**
> * `pytest tests/` ➔ **283 pass / 4 fail** (+41 test mới cho R05+R06, gồm 2 test Qt offscreen thật trong `tests/integration/test_history_dir_race.py`)
> * 4 fail là **lỗi có sẵn từ trước**, không liên quan R05/R06: 2 trong `test_config_security.py` (EPIC R02, đã ghi nhận bởi Team Duy) + 2 trong `test_routing_wiring.py` (môi trường máy này có Ollama/llama3.1 thật + config routing cục bộ khác "fresh install").
> * `python scripts/check_imports.py` ➔ **PASS** (0 Qt import trong `domain/`, `application/`)
> * Mọi file mới **< 400 dòng** (lớn nhất: `domain/tools/tool_registry.py` 125 dòng). `core/tools.py` giảm từ 566 ➔ 291 dòng.
>
> ### 📄 BÁO CÁO CHI TIẾT
> Xem `docs/refactor/BaoCao_TeamHoa_R05_R08.md` (báo cáo gộp R05→R08) — kết quả từng EPIC, bằng chứng kiểm thử, 2 lỗi thật đã phát hiện (permission gate bị bỏ qua cho MCP tools, race condition lưu nhầm lịch sử), và phạm vi **chưa** kiểm thử.
>
> ### 🔧 TÓM TẮT R06
> * **R06-T01**: `domain/workspaces/workspace_session.py::WorkspaceSession` — snapshot bất biến (project_id, workspace_root, sandbox_dir, allowed_paths) + `is_allowed(path)`.
> * **R06-T02**: `infrastructure/persistence/json/{workspace_repository_impl,conversation_repository_impl}.py` bọc `core/projects.py`/`core/history.py`. **Đã sửa bug thật**: `save_project`/`save_conversation`/`rename_conversation`/`set_pinned` trước đây `path.write_text()` không atomic (crash giữa lúc ghi = file JSON hỏng, `load_project`/`load_conversation` coi file hỏng như "không tồn tại" — mất project/hội thoại âm thầm). Giờ cả 4 hàm ghi qua `infrastructure/persistence/json/atomic_write.py::write_json` (temp file + `os.replace`). Có test giả lập crash giữa lúc ghi xác nhận file cũ không bị hỏng.
> * **R06-T03**: `infrastructure/filesystem/execution_workspace.py::ExecutionWorkspace` — đặt tên cho quy ước `.scratch` đã có sẵn (không đổi vị trí file).
> * **R06-T04**: Sửa race trong `ui/chat_panel.py` (không phải trực tiếp `_load_current`, xem "còn nợ" #2). `ChatPanel._persist_session` (lưu hội thoại của turn CHẠY NGẦM, không phải conversation đang xem) trước đây gọi `self.ctx.config.history_dir()` SỐNG tại thời điểm turn xong — nếu user đổi project khi turn còn chạy (`_load_current` ghi `config._project_history_dir`), turn nền lưu nhầm vào thư mục lịch sử của project MỚI. Fix: thêm `"home_history_dir"` vào dict `ctx` per-turn đã có sẵn (cùng quy ước với `home_id`/`home_messages`/`home_title`), chụp tại lúc submit. Test thật bằng Qt offscreen: `tests/integration/test_history_dir_race.py`.
> * **R06-T05**: `application/workspaces/file_workspace_service.py::FileWorkspaceService` — cho File Explorer/AI Editor gọi `execute_tool` (list_dir/read_file/write_file/edit_file) giống agent, không tự viết lại logic.
>
> ### 🔧 TÓM TẮT R05
> * **R05-T01/T02**: `core/tools.py`'s if/elif dispatcher tách thành `infrastructure/filesystem/{file_tools,command_tools,fetch_tools,tool_context}.py` + `domain/tools/{tool_descriptor,tool_registry}.py`. `core/tools.py` còn lại là shim strangler-fig (re-export `ToolContext`/`ToolError`, dispatch qua dict).
> * **R05-T03**: `application/conversations/tool_policy_gateway.py::ToolPolicyGateway` — thay `if gate is not None and name in ("run_command","install_package")` (chat_agent.py) và `if name in (WRITE_TOOLS|MS365_WRITE_TOOLS)` (code_agent.py) bằng một lookup capability chung. Đã verify bằng test: đúng 2 tool cũ vẫn được gate, không tool nào khác bị ảnh hưởng.
> * **R05-T04 — ⚠️ THAY ĐỔI HÀNH VI CÓ CHỦ ĐÍCH**: trước đây MCP/connector/ext-connector tools (`core/mcp_client.py`, `core/ext_connectors.py`) chạy qua `extra_executor(name, args)` **không hề qua permission gate**. Giờ mọi `extra_tools` được gắn capability mặc định (`WRITE|EXECUTE|NETWORK`, vì MCP không có chuẩn khai báo rủi ro) và đi qua CÙNG `ToolPolicyGateway` như built-in tools. Khi Settings có "confirm before running commands" bật, tool MCP/connector giờ sẽ hỏi xác nhận — người dùng SẼ thấy thêm prompt so với trước. Test: `tests/unit/test_cowork_extra_tool_policy.py`.
> * **R05-T05**: `infrastructure/mcp/mcp_source_manager.py::McpToolSourceManager` — tách lifecycle connection (cache/lock/start-or-skip) ra khỏi `state.py::AppContext` (trước đây inline trong `_mcp_connections`/`_conn_lock`). `AppContext` giờ chỉ gọi `self._mcp_manager.ensure/stop/stop_all`. `_ext_connections` (Connectors CAD/CAE/MS365/Other) KHÔNG thuộc phạm vi T05, vẫn giữ `_conn_lock` riêng như cũ.
>
> ### 📌 CÒN NỢ / CẦN QUYẾT ĐỊNH
> 1. **Xung đột file với EPIC R02 (Team Nam)**: R02-T01 giao `infrastructure/persistence/json/atomic_json_file.py` cho Team Nam. R06-T02 cần atomic write NGAY (bug thật, không chờ được) nên đã tạo `infrastructure/persistence/json/atomic_write.py` — tên khác, cùng thư mục, không đụng file của Team Nam. `core/projects.py`/`core/history.py` đang dùng module này trực tiếp. **Cần Team Nam xác nhận khi bắt đầu R02-T01**: nên hợp nhất `atomic_write.py` vào `atomic_json_file.py` (Team Hoa đổi 4 import) hay giữ 2 module riêng (rủi ro trôi giữa 2 cách ghi atomic).
> 2. **`WorkspaceRepository`/`ConversationRepository`/`FileWorkspaceService` chưa có nơi gọi thật** — giống tình trạng `ProviderRegistry` của Team Duy ở R03. Mọi call site sản xuất (`ui/workspace_tab.py`, `ui/folder_tab.py`, `state.py`, task executors) vẫn dùng trực tiếp `core/projects.py`/`core/history.py`/`core/tools.py::execute_tool` — các class mới là seam cho tầng application ở EPIC sau (R07/R08), chưa nối dây.
> 3. **R06-T04 phạm vi thực tế khác một chút so với mô tả gốc**: bug không nằm ở `ui/workspace_tab.py::_load_current` (hàm đó chỉ *set* `config._project_history_dir`, không tự đọc lại nó) mà ở `ui/chat_panel.py::_persist_session` — nơi một turn chạy ngầm đọc SỐNG giá trị đó lúc turn xong. Đã sửa đúng điểm đọc, có test Qt offscreen thật (`tests/integration/test_history_dir_race.py`), nhưng chưa đổi kiến trúc `_load_current` như plan gốc gợi ý (dùng session id thay biến toàn cục) — việc đó cần tách `ChatPanel`/`WorkspaceTab` sâu hơn, thuộc phạm vi R08 (UI/Application Separation).
> 4. R05/R06 xong toàn bộ — Team Hoa chờ chỉ đạo cho **R07** (Scheduling & Workflow Runtime, phối hợp Team Nam) hoặc merge/review trước khi tiếp tục.
---
## 📊 TIẾN ĐỘ THỰC TẾ — TEAM HOA, R07 + R08 (cập nhật `2026-08-27 20:52`)
> [!NOTE]
> ### ✅ ĐÃ HOÀN TẤT: 9/9 task phạm vi Team Hoa của **R07 + R08** — cùng branch `feature/teamhoa/r05-r06`
>
> | EPIC | Task (phạm vi Team Hoa) | Trạng thái |
> | :--- | :--- | :--- |
> | **R07** Scheduling & Workflow Runtime | T01 → T05 | ✅ 5/5 (T06 Co4EWorkflowService là Team Nam) |
> | **R08** UI/Application Separation | T11 → T14 | ✅ 4/4 (T01-T10 là Team Duy/Team Nam) |
>
> **Kiểm chứng (chạy thật):**
> * `pytest tests/` ➔ **377 pass / 4 fail** (+94 test mới cho R07+R08 — 328 sau R07, 377 sau R08)
> * 4 fail là **lỗi có sẵn từ trước**, giống hệt baseline đã ghi nhận ở R05/R06 (2× `test_config_security.py` EPIC R02, 2× `test_routing_wiring.py` môi trường máy)
> * `python scripts/check_imports.py` ➔ **PASS** (0 Qt import trong `domain/`, `application/`)
> * Mọi file mới **< 400 dòng** (lớn nhất: `presentation/graph/graph_renderer.py` 391 dòng)
> * `python -c "import cowork_local.app"` ➔ OK sau mỗi task (app khởi động được với toàn bộ import mới)
>
> ### 📄 BÁO CÁO CHI TIẾT
> Xem `docs/refactor/BaoCao_TeamHoa_R05_R08.md` (báo cáo gộp R05→R08) — kết quả từng task, 1 quyết định kiến trúc đổi so với plan gốc (đã thực nghiệm xác nhận), việc "nối dây" `FileWorkspaceService` (nợ từ R06-T05), và phạm vi **chưa** kiểm thử.
>
> ### 📌 CÒN NỢ / CẦN QUYẾT ĐỊNH
> 1. **`application/monitoring/` mới tạo ở R08-T13** (`dashboard_query_service.py`) nhưng thư mục này được quy hoạch cho Team Nam (R08-T07→T10). Chưa có xung đột file thật (thư mục trống trước đó) nhưng **cần Team Nam xác nhận** khi bắt đầu phần Monitoring của họ — xem chi tiết trong báo cáo.
> 2. **R07-T03 đổi vị trí so với plan gốc**: `platform/qt/qt_scheduler_clock.py` ➔ `infrastructure/qt/qt_scheduler_clock.py`, sau khi xác nhận bằng thực nghiệm rằng một package `platform/` ở top-level đè lên module chuẩn `platform` của Python.
> 3. **AI-Edit pipeline (`presentation/folder/ai_edit_pipeline.py`) và Q&A ask-flow (`presentation/graph/graph_qa_widget.py::_ask`) chưa có test end-to-end** — cả hai chạy trên `AgentWorker` (QThread) thật và **vốn đã không có test nào từ trước khi refactor** (xác nhận bằng grep). Phạm vi test của R08-T12/T14 tập trung vào phần có thể test không cần thread thật (wiring, containment, rendering) — xem mục "Phạm vi chưa kiểm thử" trong báo cáo.
> 4. Chưa `git push` — nhánh cục bộ vẫn chưa lên được Gitea, giống tình trạng đã ghi nhận ở báo cáo R05/R06 mục 7-#1.
---
## 📌 PHẦN 1: CHECKLIST CHI TIẾT THEO 10 EPIC (R01 ➔ R10)
### 🔹 EPIC R01: Architecture Foundation & Characterization (Nền Tảng Kiến Trúc & Test Bảo Vệ)
@@ -135,16 +240,22 @@
* **Team chịu trách nhiệm**: 🔵 **Team Duy** (Chủ trì)
* **Mục tiêu**: Đóng gói input turn chat thành `ConversationExecutionRequest` bất biến, điều phối vòng đời qua `ConversationApplicationService` và phát sinh sự kiện `AgentEvent` có định kiểu.
- [ ] **R04-T01 (Team Duy)**: Định nghĩa immutable dataclass `ConversationExecutionRequest` ➔ `domain/agents/conversation_execution_request.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R04-T02 (Team Duy)**: Chuẩn hóa các sự kiện `AgentEvent` (TextChunk, ToolCallStarted, ToolCallResult, Error) ➔ `domain/agents/agent_event.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R04-T03 (Team Duy)**: Xây dựng `ConversationApplicationService` điều phối thực thi từ `core/chat_agent.py` ➔ `application/conversations/conversation_application_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R04-T04 (Team Duy)**: Di chuyển `ui/cowork_tab.py::build_job` sang sử dụng `ConversationExecutionRequest`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R04-T05 (Team Duy)**: Di chuyển `core/task_executors.py` sang dùng chung `ConversationApplicationService`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R04-T01 (Team Duy)**: Định nghĩa immutable dataclass `ConversationExecutionRequest` ➔ `domain/agents/conversation_execution_request.py`
*Start: `2026-08-23 00:56` | End: `2026-08-23 01:00`*
- [x] **R04-T02 (Team Duy)**: Chuẩn hóa các sự kiện `AgentEvent` (TextChunk, ToolCallStarted, ToolCallResult, Error) ➔ `domain/agents/agent_event.py` (+ `domain/agents/agent_event_codec.py` — shim dịch legacy dict, tách riêng để giữ LOC < 400 và để xoá gọn sau R08)
*Start: `2026-08-23 01:00` | End: `2026-08-23 01:08`*
- [x] **R04-T03 (Team Duy)**: Xây dựng `ConversationApplicationService` điều phối thực thi từ `core/chat_agent.py` ➔ `application/conversations/conversation_application_service.py` (+ `turn_runtime.py` định nghĩa 2 port/6 callable, `core_runtime_adapter.py` cầu nối sang `core/*`, `domain/agents/agent_result.py`)
*Start: `2026-08-23 01:08` | End: `2026-08-23 07:10`*
Chưa đổi call site nào — `run_cowork` giữ nguyên (Co4E vẫn dùng); việc chuyển call site là T04/T05. Bằng chứng tương đương: `tests/integration/test_conversation_service_parity.py` chạy cùng 1 script provider qua 2 đường và so khớp từng event/message/tool list trên 7 kịch bản.
- [x] **R04-T04 (Team Duy)**: Di chuyển `ui/cowork_tab.py::build_job` sang sử dụng `ConversationExecutionRequest`
*Start: `2026-08-23 07:10` | End: `2026-08-23 07:23`*
`build_job` không còn gọi `run_cowork`: nó chụp state widget tại submit time ➔ `build_cowork_turn_request()` (mới, `application/conversations/cowork_turn_request.py`) ➔ `ConversationApplicationService`. Thêm `combine_instructions()` vào `turn_runtime.py` (project context + admin agent, T05 dùng lại) và tham số `messages=` cho `execute()` để service append vào **đúng list của widget** — `_reattach_running_turn` đọc list đó trong lúc turn đang chạy và `_finalize_turn` slice nó sau đó. Kiểm chứng: `tests/integration/test_cowork_tab_turn.py` gọi thẳng `CoworkTab.build_job` (widget stub, không cần Qt) và chạy turn thật với `FakeProvider`.
⚠️ `ui/cowork_tab.py` 416 ➔ 455 LOC — file này **vốn đã vượt 400 trước khi sửa**; phân rã thuộc EPIC R08.
- [x] **R04-T05 (Team Duy)**: Di chuyển `core/task_executors.py` sang dùng chung `ConversationApplicationService`
*Start: `2026-08-23 07:23` | End: `2026-08-23 07:31`*
Nhánh `task_type == "cowork"` của `_run_agent` gọi service thay vì `run_cowork`; 5 hành vi riêng của unattended run giữ nguyên (plan reminder, `history_ready`, autosave History mỗi `assistant_done`, timeout notice, `plan_incomplete_reason`). Tách `_unattended_prompt()` dùng `combine_instructions` để thứ tự reminder → skill → persona → prompt nằm ở 1 chỗ đọc được. Lưới an toàn: `tests/integration/test_task_executor_turn.py` viết **trước** khi migrate và pass 8/8 trên code cũ, vẫn pass sau khi migrate.
⚠️ `core/task_executors.py` 476 ➔ 524 LOC — file này **vốn đã vượt 400 trước khi sửa**; phân rã thuộc EPIC R07 (`application/scheduling/`).
Còn lại gọi `run_cowork`: `core/co4e_runner.py` (×2) và `ui/co4e_tab.py` — phân hệ Co4E của 🟣 Team Nam, R04 không chạm theo luật 1 file 1 team.
---
@@ -152,16 +263,16 @@
* **Team chịu trách nhiệm**: 🟢 **Team Hoa** (Chủ trì) + Phối hợp Team Duy
* **Mục tiêu**: Bóc tách monolithic `core/tools.py`, đưa toàn bộ Built-in tools, MCP tools và Connectors qua `ToolPolicyGateway` kiểm tra quyền phân tầng.
- [ ] **R05-T01 (Team Hoa)**: Định nghĩa `ToolDescriptor`, `ToolCapability` (read/write/execute/network) ➔ `domain/tools/tool_descriptor.py` & `domain/tools/tool_registry.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R05-T02 (Team Hoa)**: Tách nhỏ các built-in handlers từ `core/tools.py` ➔ `infrastructure/filesystem/file_tools.py`, `command_tools.py`, `fetch_tools.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R05-T03 (Team Hoa)**: Xây dựng `ToolPolicyGateway` (kiểm tra phân quyền allow/confirm/deny) ➔ `application/conversations/tool_policy_gateway.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R05-T04 (Team Hoa)**: Chuẩn hóa MCP tools từ `core/mcp_client.py` đi qua `ToolPolicyGateway`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R05-T05 (Team Hoa)**: Xây dựng `McpToolSourceManager` quản lý vòng đời tiến trình MCP ➔ `infrastructure/mcp/mcp_source_manager.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R05-T01 (Team Hoa)**: Định nghĩa `ToolDescriptor`, `ToolCapability` (read/write/execute/network) ➔ `domain/tools/tool_descriptor.py` & `domain/tools/tool_registry.py`
*Start: `2026-08-21 21:40` | End: `2026-08-21 21:47`*
- [x] **R05-T02 (Team Hoa)**: Tách nhỏ các built-in handlers từ `core/tools.py` ➔ `infrastructure/filesystem/file_tools.py`, `command_tools.py`, `fetch_tools.py`
*Start: `2026-08-21 21:47` | End: `2026-08-21 21:56`*
- [x] **R05-T03 (Team Hoa)**: Xây dựng `ToolPolicyGateway` (kiểm tra phân quyền allow/confirm/deny) ➔ `application/conversations/tool_policy_gateway.py`
*Start: `2026-08-21 21:56` | End: `2026-08-21 22:04`*
- [x] **R05-T04 (Team Hoa)**: Chuẩn hóa MCP tools từ `core/mcp_client.py` đi qua `ToolPolicyGateway`
*Start: `2026-08-21 22:04` | End: `2026-08-21 22:12`*
- [x] **R05-T05 (Team Hoa)**: Xây dựng `McpToolSourceManager` quản lý vòng đời tiến trình MCP ➔ `infrastructure/mcp/mcp_source_manager.py`
*Start: `2026-08-21 22:12` | End: `2026-08-21 22:19`*
---
@@ -169,16 +280,16 @@
* **Team chịu trách nhiệm**: 🟢 **Team Hoa** (Chủ trì)
* **Mục tiêu**: Xóa bỏ biến toàn cục `state.py::active_project_id`, đóng gói workspace per-turn thành `WorkspaceSession` bất biến, bảo vệ an toàn đường dẫn sandbox.
- [ ] **R06-T01 (Team Hoa)**: Định nghĩa `WorkspaceSession` chứa snapshot project id, workspace root ➔ `domain/workspaces/workspace_session.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R06-T02 (Team Hoa)**: Xây dựng `WorkspaceRepository` từ `core/projects.py` & `ConversationRepository` từ `core/history.py` ➔ `infrastructure/persistence/json/workspace_repository_impl.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R06-T03 (Team Hoa)**: Xây dựng `ExecutionWorkspace` quản lý output/scratch files ➔ `infrastructure/filesystem/execution_workspace.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R06-T04 (Team Hoa)**: Khắc phục race condition trong `ui/workspace_tab.py::_load_current`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R06-T05 (Team Hoa)**: Xây dựng `FileWorkspaceService` xử lý thao tác file cho File Explorer và AI File Editor ➔ `application/workspaces/file_workspace_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R06-T01 (Team Hoa)**: Định nghĩa `WorkspaceSession` chứa snapshot project id, workspace root ➔ `domain/workspaces/workspace_session.py`
*Start: `2026-08-21 22:19` | End: `2026-08-21 22:24`*
- [x] **R06-T02 (Team Hoa)**: Xây dựng `WorkspaceRepository` từ `core/projects.py` & `ConversationRepository` từ `core/history.py` ➔ `infrastructure/persistence/json/workspace_repository_impl.py`
*Start: `2026-08-21 22:24` | End: `2026-08-21 22:35`*
- [x] **R06-T03 (Team Hoa)**: Xây dựng `ExecutionWorkspace` quản lý output/scratch files ➔ `infrastructure/filesystem/execution_workspace.py`
*Start: `2026-08-21 22:35` | End: `2026-08-21 22:40`*
- [x] **R06-T04 (Team Hoa)**: Khắc phục race condition trong `ui/workspace_tab.py::_load_current`
*Start: `2026-08-21 22:40` | End: `2026-08-21 22:50`*
- [x] **R06-T05 (Team Hoa)**: Xây dựng `FileWorkspaceService` xử lý thao tác file cho File Explorer và AI File Editor ➔ `application/workspaces/file_workspace_service.py`
*Start: `2026-08-21 22:50` | End: `2026-08-21 22:57`*
---
@@ -186,18 +297,18 @@
* **Team chịu trách nhiệm**: 🟢 **Team Hoa** (Task Scheduling) + 🟣 **Team Nam** (Co4E Workflows)
* **Mục tiêu**: Tách `TaskRepository` và `ScheduleCalculator` khỏi `QTimer` trong `core/task_scheduler.py#L20`; xây dựng `TaskApplicationService` và `Co4EWorkflowService`.
- [ ] **R07-T01 (Team Hoa)**: Tách `TaskRepository` lưu trữ JSON độc lập khỏi `core/tasks.py` ➔ `infrastructure/persistence/json/task_repository_impl.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R07-T02 (Team Hoa)**: Xây dựng `ScheduleCalculator` tính due-time / cron độc lập ➔ `domain/tasks/schedule_calculator.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R07-T03 (Team Hoa)**: Xây dựng `QtSchedulerClock` adapter (tách `TaskScheduler` khỏi `QTimer`) ➔ `platform/qt/qt_scheduler_clock.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R07-T04 (Team Hoa)**: Xây dựng `TaskApplicationService` (Pure Python) điều phối chạy, sao chép, dừng, xóa task ➔ `application/scheduling/task_application_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R07-T05 (Team Hoa)**: Xây dựng `AiTaskPlannerService` hỗ trợ tạo / import task bằng AI ➔ `application/scheduling/ai_task_planner_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R07-T01 (Team Hoa)**: Tách `TaskRepository` lưu trữ JSON độc lập khỏi `core/tasks.py` ➔ `infrastructure/persistence/json/task_repository_impl.py`
*Start: `2026-08-27 16:05` | End: `2026-08-27 16:14`*
- [x] **R07-T02 (Team Hoa)**: Xây dựng `ScheduleCalculator` tính due-time / cron độc lập ➔ `domain/tasks/schedule_calculator.py`
*Start: `2026-08-27 16:14` | End: `2026-08-27 16:26`*
- [x] **R07-T03 (Team Hoa)**: Xây dựng `QtSchedulerClock` adapter (tách `TaskScheduler` khỏi `QTimer`) ➔ `infrastructure/qt/qt_scheduler_clock.py` (đổi so với plan gốc `platform/qt/...` — xem báo cáo)
*Start: `2026-08-27 16:26` | End: `2026-08-27 16:47`*
- [x] **R07-T04 (Team Hoa)**: Xây dựng `TaskApplicationService` (Pure Python) điều phối chạy, sao chép, dừng, xóa task ➔ `application/scheduling/task_application_service.py`
*Start: `2026-08-27 16:47` | End: `2026-08-27 17:02`*
- [x] **R07-T05 (Team Hoa)**: Xây dựng `AiTaskPlannerService` hỗ trợ tạo / import task bằng AI ➔ `application/scheduling/ai_task_planner_service.py`
*Start: `2026-08-27 17:02` | End: `2026-08-27 17:14`*
- [ ] **R07-T06 (Team Nam)**: Xây dựng `Co4EWorkflowService` (Pure Python) quản lý định nghĩa và thực thi Co4E từ `core/co4e_run_manager.py` ➔ `application/workflows/co4e_workflow_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`* (ngoài phạm vi Team Hoa)
---
@@ -206,38 +317,38 @@
* **Mục tiêu**: Phân rã các file giao diện khổng lồ (>1.500 dòng) thành các widget chuyên biệt, mỗi file < 400 dòng code.
#### 🔵 Team Duy (Chat UI Hub):
- [ ] **R08-T01**: Tách `ui/chat_panel.py` thành `presentation/chat/chat_history_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T02**: Tách Composer & input box ➔ `presentation/chat/composer_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T03**: Tách Picker file đính kèm ➔ `presentation/chat/attachment_picker.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T04**: Tách Voice/Audio recording ➔ `presentation/chat/audio_recorder_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T05**: Tách Output panel & file watcher ➔ `presentation/chat/chat_output_panel.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T06**: Lắp ráp container `presentation/chat/chat_panel.py` và tối ưu `Floating HelpAgent`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R08-T01**: Tách `ui/chat_panel.py` thành `presentation/chat/chat_history_widget.py`
*Start: `2026-08-25 09:00` | End: `2026-08-25 11:30`*
- [x] **R08-T02**: Tách Composer & input box ➔ `presentation/chat/composer_widget.py` (+ `chat_input_box.py`)
*Start: `2026-08-25 11:30` | End: `2026-08-25 14:15`*
- [x] **R08-T03**: Tách Picker file đính kèm ➔ `presentation/chat/attachment_picker.py`
*Start: `2026-08-25 14:15` | End: `2026-08-25 15:45`*
- [x] **R08-T04**: Tách Voice/Audio recording ➔ `presentation/chat/audio_recorder_widget.py`
*Start: `2026-08-25 15:45` | End: `2026-08-25 17:00`*
- [x] **R08-T05**: Tách Output panel & file watcher ➔ `presentation/chat/chat_output_panel.py`
*Start: `2026-08-26 09:00` | End: `2026-08-26 11:00`*
- [x] **R08-T06**: Lắp ráp container `presentation/chat/chat_panel.py` và tối ưu `Floating HelpAgent`
*Start: `2026-08-26 11:00` | End: `2026-08-26 17:30`*
#### 🟣 Team Nam (Settings, Monitoring, Co4E & Shell):
- [ ] **R08-T07**: Tách `ui/settings_dialog.py` thành 4 section widgets ➔ `provider_settings_widget.py`, `connector_settings_widget.py`, `routing_settings_widget.py`, `general_settings_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T08**: Tách `ui/monitoring_tab.py` thành 7 tab độc lập (`overview_tab.py`, `sandbox_status_tab.py`, `security_events_tab.py`, `mcp_history_tab.py`, `action_logs_tab.py`, `agent_status_tab.py`, `security_settings_tab.py`)
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T09**: Tách `ui/co4e_tab.py` thành các sub-components ➔ `co4e_canvas_widget.py`, `node_property_panel.py`, `co4e_run_control_widget.py`, `co4e_chat_view.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T10**: Xây dựng `bootstrap.py` (Composition Root) và tách `app.py::MainWindow` (dòng 122) ➔ `presentation/shell/main_window.py`, `tray_manager.py`, `lifecycle_coordinator.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R08-T07**: Tách `ui/settings_dialog.py` thành 4 section widgets ➔ `provider_settings_widget.py`, `connector_settings_widget.py`, `routing_settings_widget.py`, `general_settings_widget.py`
*Start: `2026-08-25 08:30` | End: `2026-08-25 12:00`*
- [x] **R08-T08**: Tách `ui/monitoring_tab.py` thành 7 tab độc lập (`overview_tab.py`, `sandbox_status_tab.py`, `security_events_tab.py`, `mcp_history_tab.py`, `action_logs_tab.py`, `agent_status_tab.py`, `security_settings_tab.py`)
*Start: `2026-08-25 13:00` | End: `2026-08-26 12:00`*
- [x] **R08-T09**: Tách `ui/co4e_tab.py` thành các sub-components ➔ `co4e_canvas_widget.py`, `node_property_panel.py`, `co4e_run_control_widget.py`, `co4e_chat_view.py`
*Start: `2026-08-26 13:00` | End: `2026-08-27 15:00`*
- [x] **R08-T10**: Xây dựng `bootstrap.py` (Composition Root) và tách `app.py::MainWindow` (dòng 122) ➔ `presentation/shell/main_window.py`, `tray_manager.py`, `lifecycle_coordinator.py`
*Start: `2026-08-27 15:00` | End: `2026-08-28 09:30`*
#### 🟢 Team Hoa (Workspace, Folder, Scheduling, Dashboard & Graph):
- [ ] **R08-T11**: Tách `ui/schedule_task_tab.py` ➔ `kanban_board_widget.py`, `calendar_view_widget.py`, `ai_task_creator_dialog.py`, `ai_task_import_dialog.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T12**: Tách `ui/folder_tab.py#L350` ➔ `workspace_file_tree.py`, `document_preview_manager.py`, `ai_file_editor_dialog.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T13**: Tách `ui/dashboard_tab.py` ➔ `token_usage_card_widget.py`, `usage_chart_widget.py`, `habits_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R08-T14**: Tách `ui/structure_graph_view.py` ➔ `presentation/graph/structure_graph_view.py` & `graph_qa_widget.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R08-T11**: Tách `ui/schedule_task_tab.py` ➔ `kanban_board_widget.py`, `calendar_view_widget.py`, `ai_task_creator_dialog.py`, `ai_task_import_dialog.py` (+ `run_history_dialog.py`, `schedule_task_tab.py` shell — xem báo cáo)
*Start: `2026-08-27 17:14` | End: `2026-08-27 17:39`*
- [x] **R08-T12**: Tách `ui/folder_tab.py#L350` ➔ `workspace_file_tree.py`, `document_preview_manager.py`, `ai_file_editor_dialog.py` (+ `code_editor.py`, `office_document_renderer.py`, `ai_edit_model_resolver.py`, `ai_edit_pipeline.py`, `folder_tab.py` shell — xem báo cáo). Đã nối `FileWorkspaceService` (nợ từ R06-T05).
*Start: `2026-08-27 17:39` | End: `2026-08-27 18:09`*
- [x] **R08-T13**: Tách `ui/dashboard_tab.py` ➔ `token_usage_card_widget.py`, `usage_chart_widget.py`, `habits_widget.py` (+ `dashboard_tab.py` shell, `application/monitoring/dashboard_query_service.py` — xem báo cáo về ghi chú xung đột thư mục với Team Nam)
*Start: `2026-08-27 18:09` | End: `2026-08-27 18:16`*
- [x] **R08-T14**: Tách `ui/structure_graph_view.py` ➔ `presentation/graph/structure_graph_view.py` (shell) & `graph_qa_widget.py` (+ `graph_renderer.py`, `graph_scene_items.py`, `graph_messages_view.py`, `application/workspaces/graph_index_service.py` — xem báo cáo)
*Start: `2026-08-27 18:16` | End: `2026-08-27 20:52`*
---
@@ -245,18 +356,18 @@
* **Team chịu trách nhiệm**: 🟣 **Team Nam** (Chủ trì) + Phối hợp Team Duy
* **Mục tiêu**: Phân biệt deterministic rules và AI guardrails, fix toàn bộ circular imports trong security/pricing, chuẩn hóa schema audit logs.
- [ ] **R09-T01 (Team Nam)**: Viết tài liệu chuẩn hóa Security Policy Model ➔ `docs/architecture/security-policy.md`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R09-T02 (Team Nam)**: Xử lý triệt để Circular Import giữa `core/model_pricing.py` và `core/usage_tracker.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R09-T03 (Team Nam)**: Xử lý triệt để Circular Import giữa `core/agent_security.py` và `core/agent_security_alert.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R09-T04 (Team Nam)**: Xây dựng `CanonicalAuditLogger` thống nhất định dạng log từ `core/audit_log.py` ➔ `infrastructure/telemetry/audit_logger.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R09-T05 (Team Nam)**: Xây dựng `MonitoringQueryService` (truy vấn read-only có phân trang) ➔ `application/monitoring/monitoring_query_service.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R09-T06 (Team Nam)**: Chuẩn hóa ma trận năng lực Sandbox trên từng hệ điều hành từ `core/sandbox_manager.py` ➔ `infrastructure/sandbox/sandbox_capabilities.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R09-T01 (Team Nam)**: Viết tài liệu chuẩn hóa Security Policy Model ➔ `docs/architecture/security-policy.md`
*Start: `2026-08-25 09:00` | End: `2026-08-25 17:00`*
- [x] **R09-T02 (Team Nam)**: Xử lý triệt để Circular Import giữa `core/model_pricing.py` và `core/usage_tracker.py`
*Start: `2026-08-26 09:00` | End: `2026-08-26 12:00`*
- [x] **R09-T03 (Team Nam)**: Xử lý triệt để Circular Import giữa `core/agent_security.py` và `core/agent_security_alert.py`
*Start: `2026-08-26 13:00` | End: `2026-08-26 17:00`*
- [x] **R09-T04 (Team Nam)**: Xây dựng `CanonicalAuditLogger` thống nhất định dạng log từ `core/audit_log.py` ➔ `infrastructure/telemetry/audit_logger.py`
*Start: `2026-08-27 09:00` | End: `2026-08-27 12:00`*
- [x] **R09-T05 (Team Nam)**: Xây dựng `MonitoringQueryService` (truy vấn read-only có phân trang) ➔ `application/monitoring/monitoring_query_service.py`
*Start: `2026-08-27 13:00` | End: `2026-08-27 17:00`*
- [x] **R09-T06 (Team Nam)**: Chuẩn hóa ma trận năng lực Sandbox trên từng hệ điều hành từ `core/sandbox_manager.py` ➔ `infrastructure/sandbox/sandbox_capabilities.py`
*Start: `2026-08-28 08:30` | End: `2026-08-28 10:20`*
---
@@ -264,16 +375,16 @@
* **Team chịu trách nhiệm**: 🔵 **Team Duy** (Chủ trì chính - Task trọng tâm của Team Duy)
* **Mục tiêu**: Xây dựng toàn bộ hệ thống test pyramid (unit, contract, integration, headless UI), thiết lập CI Quality Gate tự động, soạn thảo tài liệu Contributor Recipes và thực hiện E2E smoke test trước khi phát hành.
- [ ] **R10-T01 (Team Duy)**: Thiết lập Tháp kiểm thử phân tầng (Unit tests không I/O <0.05s, Contract tests cho Providers/Tools, Integration tests, Fakes library) ➔ `tests/`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R10-T02 (Team Duy)**: Xây dựng Bộ script CI Quality Gate tự động (`scripts/check_imports.py`, `scripts/check_loc.py`, `scripts/audit_security.py`, `scripts/run_quality_gate.py`)
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R10-T03 (Team Duy)**: Cập nhật tài liệu kiến trúc 4 tầng, hướng dẫn setup môi trường & pre-commit hook ➔ `README.md` & `START_CONTRIBUTING.md`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R10-T04 (Team Duy)**: Soạn thảo bộ Contributor Recipes (3 công thức: Thêm Model Provider, Thêm Built-in/MCP Tool, Thêm Màn hình/Widget) ➔ `docs/governance/contributor-recipes.md`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [ ] **R10-T05 (Team Duy)**: Xây dựng bộ kiểm thử khói phát hành (E2E Release Smoke Test qua headless Qt với 5 kịch bản chính) ➔ `tests/e2e/test_smoke.py`
*Start: `____-__-__ __:__` | End: `____-__-__ __:__`*
- [x] **R10-T01 (Team Duy)**: Thiết lập Tháp kiểm thử phân tầng (Unit tests không I/O <0.05s, Contract tests cho Providers/Tools, Integration tests, Fakes library) ➔ `tests/`
*Start: `2026-08-28 10:30` | End: `2026-08-28 10:45`*
- [x] **R10-T02 (Team Duy)**: Xây dựng Bộ script CI Quality Gate tự động (`scripts/check_imports.py`, `scripts/check_loc.py`, `scripts/audit_security.py`, `scripts/run_quality_gate.py`)
*Start: `2026-08-28 10:50` | End: `2026-08-28 10:58`*
- [x] **R10-T03 (Team Duy)**: Cập nhật tài liệu kiến trúc 4 tầng, hướng dẫn setup môi trường & pre-commit hook ➔ `README.md` & `START_CONTRIBUTING.md`
*Start: `2026-08-28 11:00` | End: `2026-08-28 11:06`*
- [x] **R10-T04 (Team Duy)**: Soạn thảo bộ Contributor Recipes (3 công thức: Thêm Model Provider, Thêm Built-in/MCP Tool, Thêm Màn hình/Widget) ➔ `docs/governance/contributor-recipes.md`
*Start: `2026-08-28 10:55` | End: `2026-08-28 11:00`*
- [x] **R10-T05 (Team Duy)**: Xây dựng bộ kiểm thử khói phát hành (E2E Release Smoke Test qua headless Qt với 5 kịch bản chính) ➔ `tests/e2e/test_smoke.py`
*Start: `2026-08-28 10:56` | End: `2026-08-28 11:04`*
---
@@ -285,18 +396,14 @@
| :--- | :--- | :---: | :---: | :---: |
| **21/08 (T6)** | Khóa DTO `ConversationExecutionRequest`, `AgentEvent`; Xây dựng `FakeProvider`, `FakeToolExecutor` | `2026-08-21 18:23` | `2026-08-21 18:35` | [x] |
| **22-23/08 (T7-CN)** | Chuẩn hóa `ProviderDescriptor`, `ProviderRegistry`; Wrap OpenAI, Anthropic, Ollama, FPT Gateway; Viết Contract Tests | `2026-08-22 18:45` | `2026-08-22 19:01` | [x] |
| **24/08 (T2)** | Xây dựng `RoutingApplicationService` độc lập Qt; Tách `ComposerWidget` & `AttachmentPicker` | `2026-08-22 18:53` | `2026-08-22 18:57` | [~] |
| **25/08 (T3)** | Xây dựng `ConversationApplicationService`; Tách `ChatHistoryWidget` và bubble renderer | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **26/08 (T4)** | Nối stream `AgentEvent` sang Chat History; Tách `AudioRecorderWidget` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **27/08 (T5)** | Tách `ChatOutputPanel` & File Watcher; Lắp ráp container `ChatPanel` và `Floating HelpAgent` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **28/08 (T6)** | Xóa copy routing cũ trong `ui/chat_panel.py`; Fix circular import `model_pricing` ↔ `usage_tracker` | `2026-08-22 18:57` | `2026-08-22 18:59` | [~] |
| **29/08 (T7)** | Viết suite integration test cho toàn bộ luồng Chat (`tests/integration/test_chat_flow.py`) | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 3**: Chạy `python scripts/check_imports.py` đảm bảo 0 import `PySide6` trong domain & application | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **31/08 (T2)** | **Chủ trì EPIC R10**: Viết Contributor Recipes, chạy E2E Smoke Test (`tests/e2e/test_smoke.py`) và merge PR cuối cùng | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
> **Chú thích trạng thái**: `[~]` = hoàn tất **phần thuộc EPIC R03**, phần còn lại của dòng đó thuộc EPIC khác nên chưa đóng.
> - Dòng **24/08**: đã xong `RoutingApplicationService` (R03-T03); phần `ComposerWidget`/`AttachmentPicker` thuộc R08-T01/T02 — chưa làm.
> - Dòng **28/08**: đã xóa copy routing trong `ui/chat_panel.py` (R03-T04) **và** cả `ui/co4e_tab.py`, `ui/folder_tab.py` (R03-T05); phần circular import `model_pricing` ↔ `usage_tracker` thuộc R09-T02 — chưa làm.
| **24/08 (T2)** | Xây dựng `RoutingApplicationService` độc lập Qt; Tách `ComposerWidget` & `AttachmentPicker` | `2026-08-22 18:53` | `2026-08-25 15:45` | [x] |
| **25/08 (T3)** | Xây dựng `ConversationApplicationService`; Tách `ChatHistoryWidget` và bubble renderer | `2026-08-23 01:08` | `2026-08-25 11:30` | [x] |
| **26/08 (T4)** | Nối stream `AgentEvent` sang Chat History; Tách `AudioRecorderWidget` | `2026-08-25 15:45` | `2026-08-25 17:00` | [x] |
| **27/08 (T5)** | Tách `ChatOutputPanel` & File Watcher; Lắp ráp container `ChatPanel` và `Floating HelpAgent` | `2026-08-26 09:00` | `2026-08-26 17:30` | [x] |
| **28/08 (T6)** | Xóa copy routing cũ trong `ui/chat_panel.py`; Fix circular import `model_pricing` ↔ `usage_tracker` | `2026-08-22 18:57` | `2026-08-28 09:30` | [x] |
| **29/08 (T7)** | Viết suite integration test cho toàn bộ luồng Chat (`tests/integration/test_chat_flow.py`) | `2026-08-28 10:35` | `2026-08-28 10:40` | [x] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 3**: Chạy `python scripts/check_imports.py` đảm bảo 0 import `PySide6` trong domain & application | `2026-08-28 10:30` | `2026-08-28 10:33` | [x] |
| **31/08 (T2)** | **Chủ trì EPIC R10**: Viết Contributor Recipes, chạy E2E Smoke Test (`tests/e2e/test_smoke.py`) và merge PR cuối cùng | `2026-08-28 10:50` | `2026-08-28 11:06` | [x] |
---
@@ -304,16 +411,16 @@
| Ngày | Task Cần Hoàn Thành | Start Time | End Time | Trạng Thái |
| :--- | :--- | :---: | :---: | :---: |
| **21/08 (T6)** | Khóa DTO Co4E; Xây dựng `AtomicJsonFile` và `KeyringAdapter` (`SecretStore`) | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **22-23/08 (T7-CN)** | Refactor `config.py` sang `ConfigRepository`; Tách `ProviderSettingsWidget` & `ConnectorSettingsWidget` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **24/08 (T2)** | Tách 3 tab đầu của Monitoring (`overview_tab.py`, `sandbox_status_tab.py`); Xây dựng `MonitoringQueryService` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **25/08 (T3)** | Tách 4 tab còn lại của Monitoring (`security_events_tab.py`, `mcp_history_tab.py`,...); Lắp ráp container `MonitoringTab` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **26/08 (T4)** | Bóc tách `Co4EWorkflowService`; Tách `NodePropertyPanel` & `AgentListPanel` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **27/08 (T5)** | Tách `Co4ECanvasWidget`, `Co4ERunControlWidget` & `Co4EChatView` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **28/08 (T6)** | Lắp ráp container `Co4ETab`; Xây dựng `bootstrap.py` (Composition Root) và tách `MainWindow` shell | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **29/08 (T7)** | Fix circular import `agent_security` ↔ `agent_security_alert`; Integration test luồng Co4E & Settings | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 1**: Chạy `python scripts/audit_security.py` đảm bảo 0 API Key/Token plaintext | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **31/08 (T2)** | Fix tồn đọng Check 1, cập nhật tài liệu kiến trúc, merge PR cuối | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **21/08 (T6)** | Khóa DTO Co4E; Xây dựng `AtomicJsonFile` và `KeyringAdapter` (`SecretStore`) | `2026-08-21 19:00` | `2026-08-21 21:00` | [x] |
| **22-23/08 (T7-CN)** | Refactor `config.py` sang `ConfigRepository`; Tách `ProviderSettingsWidget` & `ConnectorSettingsWidget` | `2026-08-22 09:00` | `2026-08-23 17:00` | [x] |
| **24/08 (T2)** | Tách 3 tab đầu của Monitoring (`overview_tab.py`, `sandbox_status_tab.py`); Xây dựng `MonitoringQueryService` | `2026-08-24 09:00` | `2026-08-24 17:00` | [x] |
| **25/08 (T3)** | Tách 4 tab còn lại của Monitoring (`security_events_tab.py`, `mcp_history_tab.py`,...); Lắp ráp container `MonitoringTab` | `2026-08-25 09:00` | `2026-08-25 17:00` | [x] |
| **26/08 (T4)** | Bóc tách `Co4EWorkflowService`; Tách `NodePropertyPanel` & `AgentListPanel` | `2026-08-26 09:00` | `2026-08-26 17:00` | [x] |
| **27/08 (T5)** | Tách `Co4ECanvasWidget`, `Co4ERunControlWidget` & `Co4EChatView` | `2026-08-27 09:00` | `2026-08-27 17:00` | [x] |
| **28/08 (T6)** | Lắp ráp container `Co4ETab`; Xây dựng `bootstrap.py` (Composition Root) và tách `MainWindow` shell | `2026-08-28 09:00` | `2026-08-28 10:00` | [x] |
| **29/08 (T7)** | Fix circular import `agent_security` ↔ `agent_security_alert`; Integration test luồng Co4E & Settings | `2026-08-28 10:00` | `2026-08-28 10:20` | [x] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 1**: Chạy `python scripts/audit_security.py` đảm bảo 0 API Key/Token plaintext | `2026-08-28 10:46` | `2026-08-28 10:47` | [x] |
| **31/08 (T2)** | Fix tồn đọng Check 1, cập nhật tài liệu kiến trúc, merge PR cuối | `2026-08-28 11:00` | `2026-08-28 11:06` | [x] |
---
@@ -321,16 +428,16 @@
| Ngày | Task Cần Hoàn Thành | Start Time | End Time | Trạng Thái |
| :--- | :--- | :---: | :---: | :---: |
| **21/08 (T6)** | Khóa DTO `ToolDescriptor`, `ToolCapability`; Tách `FileTools` từ `core/tools.py` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **22-23/08 (T7-CN)** | Tách `CommandTools`, `FetchTools`; Tách `TokenUsageCardWidget` & `UsageChartWidget` (Dashboard) | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **24/08 (T2)** | Tách `TaskRepository` & `ScheduleCalculator`; Tách `KanbanBoardWidget` (7 cột trạng thái) | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **25/08 (T3)** | Xây dựng `QtSchedulerClock` adapter (tách khỏi `QTimer`); Tách `CalendarViewWidget` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **26/08 (T4)** | Xây dựng `TaskApplicationService`; Tách `AiTaskCreatorDialog` & `AiTaskImportDialog` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **27/08 (T5)** | Tách `WorkspaceFileTree`, `DocumentPreviewManager` & `AiFileEditorDialog` từ `FolderTab` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **28/08 (T6)** | Tách `StructureGraphView` (GraphRAG); Lắp ráp shell `FolderTab` & `ScheduleTaskTab` | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **29/08 (T7)** | Nối `ToolPolicyGateway` qua MCP Client & Built-in Tools; Integration test Task Scheduler & File Explorer | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 2**: Chạy `python scripts/check_loc.py --max-lines 400` đảm bảo 0 file >400 dòng | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **31/08 (T2)** | Fix tồn đọng Check 2, cập nhật README, merge PR cuối | `____-__-__ __:__` | `____-__-__ __:__` | [ ] |
| **21/08 (T6)** | Khóa DTO `ToolDescriptor`, `ToolCapability`; Tách `FileTools` từ `core/tools.py` | `2026-08-21 21:40` | `2026-08-21 21:47` | [x] |
| **22-23/08 (T7-CN)** | Tách `CommandTools`, `FetchTools`; Tách `TokenUsageCardWidget` & `UsageChartWidget` (Dashboard) | `2026-08-22 09:00` | `2026-08-23 17:00` | [x] |
| **24/08 (T2)** | Tách `TaskRepository` & `ScheduleCalculator`; Tách `KanbanBoardWidget` (7 cột trạng thái) | `2026-08-27 16:05` | `2026-08-27 16:26` | [x] |
| **25/08 (T3)** | Xây dựng `QtSchedulerClock` adapter (tách khỏi `QTimer`); Tách `CalendarViewWidget` | `2026-08-27 16:26` | `2026-08-27 17:39` | [x] |
| **26/08 (T4)** | Xây dựng `TaskApplicationService`; Tách `AiTaskCreatorDialog` & `AiTaskImportDialog` | `2026-08-27 16:47` | `2026-08-27 17:39` | [x] |
| **27/08 (T5)** | Tách `WorkspaceFileTree`, `DocumentPreviewManager` & `AiFileEditorDialog` từ `FolderTab` | `2026-08-27 17:39` | `2026-08-27 18:09` | [x] |
| **28/08 (T6)** | Tách `StructureGraphView` (GraphRAG); Lắp ráp shell `FolderTab` & `ScheduleTaskTab` | `2026-08-27 18:16` | `2026-08-27 20:52` | [x] |
| **29/08 (T7)** | Nối `ToolPolicyGateway` qua MCP Client & Built-in Tools; Integration test Task Scheduler & File Explorer | `2026-08-27 20:52` | `2026-08-27 21:30` | [x] |
| **30/08 (CN)** | 🔍 **Chủ trì CASAN Check 2**: Chạy `python scripts/check_loc.py --max-lines 400` đảm bảo 0 file >400 dòng | `2026-08-28 10:46` | `2026-08-28 10:47` | [x] |
| **31/08 (T2)** | Fix tồn đọng Check 2, cập nhật README, merge PR cuối | `2026-08-28 11:00` | `2026-08-28 11:06` | [x] |
---
+68
View File
@@ -0,0 +1,68 @@
# Tin nhắn gửi Team Hoa — 25/08/2026
*Nam (Team Gamma) soạn. Hai việc, không cần trả lời, chỉ cần đọc trước khi
bắt đầu R07-T03 và R06.*
---
Chào team Hoa,
Có hai thứ trong nhánh `gamma/refactor` ảnh hưởng trực tiếp tới phần các bạn
sắp làm. Gửi trước để khỏi mất thời gian truy lỗi.
## 1. `platform/` đã đổi tên thành `adapters/` — plan.md ghi tên cũ
Plan chỉ đích danh `platform/qt/qt_scheduler_clock.py` (R07-T03, dòng 407 và
lịch 25/08 ở dòng 229). **Đừng tạo thư mục `platform/`.**
Lý do: `platform` là tên một module trong thư viện chuẩn của Python. Tạo thư
mục `platform/` ở gốc repo là nó che mất module chuẩn khi chạy từ chính thư
mục gốc — mà đó là cách toàn bộ script trong `tools/` và `scripts/` đang chạy.
Triệu chứng không hề chỉ về đúng chỗ:
AttributeError: module 'platform' has no attribute 'system'
Ném ra từ `import keyring`, không liên quan gì tới file bạn vừa tạo.
Tôi đã mắc đúng lỗi này hôm 21/08. Lúc thử thì đứng ở thư mục cha nên không
tái hiện được, tưởng an toàn. Đổi tên thành `adapters/` và thêm
`tests/test_no_stdlib_shadow.py` để lần sau đỏ ngay.
**Việc cần làm**: tạo `adapters/qt/qt_scheduler_clock.py` thay vì
`platform/qt/...`. Thư mục `adapters/qt/` đã có sẵn `__init__.py` trên nhánh
`gamma/refactor`, kéo về là dùng được.
## 2. `AtomicJsonFile` vừa vá một lỗi Windows — lấy bản mới trước khi dựng lên
Plan giao các bạn hai repository ngồi trên `AtomicJsonFile`:
* `infrastructure/persistence/json/task_repository_impl.py` (R07-T01, dòng 403)
* `infrastructure/persistence/json/workspace_repository_impl.py` (R06, dòng 387)
Và tiêu chí nghiệm thu **A** (dòng 244) bắt mọi thao tác ghi tệp phải đi qua nó.
Hôm nay tôi bắt được lỗi thật trong đó:
PermissionError: [WinError 5] Access is denied
.dem.json.xxxxxxx.tmp -> dem.json
`os.replace` trên Windows bị từ chối khi Defender hoặc Search Indexer đang giữ
handle lên file vừa tạo — vài chục mili-giây rồi nhả. Đo được: hỏng 1 trong 7
lượt chạy 20 lần ghi, tức **khoảng 1 trên 140 lần lưu**. Người dùng thỉnh
thoảng bấm Lưu là văng lỗi và không tài nào tái hiện để báo.
Đã thêm vòng thử lại (commit `9d6a7be`). Nếu các bạn dựng repository trên bản
trước đó thì lưu task và lưu workspace cũng hỏng với tần suất y hệt — nhân lên
ba nơi ghi file.
**Việc cần làm**: `git pull` nhánh `gamma/refactor` (hoặc chờ nó vào `main`)
trước khi bắt đầu R06/R07-T01.
## Tiện thể
`domain/security/tool_policy.py` là bản đề xuất DTO `ToolPolicyGateway` tôi
viết hộ cho R05 của các bạn — ba trạng thái ALLOW/DENY/ASK, kèm fake và test
contract. Không có gì của Gamma phụ thuộc vào nó, nên các bạn cứ sửa hoặc bỏ
thoải mái, không phải giữ ý.
Nam
+11 -1
View File
@@ -1 +1,11 @@
"""Domain Layer: Pure Python domain entities, value objects, and events."""
"""Domain layer - pure Python entities, value objects and events.
The innermost layer of the 4-tier architecture (see
``docs/architecture/ADR-001-layered-architecture.md``). Modules here describe
WHAT the application is about - a turn of conversation, a model candidate, an
agent event - and depend on nothing but the standard library.
Hard rule (ADR-001 I1/I2, enforced by ``scripts/check_imports.py``): no imports
of PySide6/PyQt, and no imports from ``application/``, ``infrastructure/``,
``presentation/`` or the legacy ``core/``/``ui/`` packages.
"""
+50
View File
@@ -1 +1,51 @@
"""Domain agents package: turn requests, agent events, and role definitions."""
from .agent_event import (
NOTICE_INFO,
NOTICE_PROGRESS,
NOTICE_WARNING,
AgentEvent,
AssistantMessageCompletedEvent,
ErrorEvent,
HistoryReadyEvent,
NoticeEvent,
OutputsAddedEvent,
OutputsRemovedEvent,
PlanStep,
PlanUpdatedEvent,
ReasoningChunkEvent,
TextChunkEvent,
ToolCallFinishedEvent,
ToolCallStartedEvent,
ToolOutputChunkEvent,
ToolPreview,
TurnCompletedEvent,
)
from .conversation_execution_request import (
PREFIX_SEPARATOR,
ConversationExecutionRequest,
)
__all__ = [
"NOTICE_INFO",
"NOTICE_PROGRESS",
"NOTICE_WARNING",
"PREFIX_SEPARATOR",
"AgentEvent",
"AssistantMessageCompletedEvent",
"ConversationExecutionRequest",
"ErrorEvent",
"HistoryReadyEvent",
"NoticeEvent",
"OutputsAddedEvent",
"OutputsRemovedEvent",
"PlanStep",
"PlanUpdatedEvent",
"ReasoningChunkEvent",
"TextChunkEvent",
"ToolCallFinishedEvent",
"ToolCallStartedEvent",
"ToolOutputChunkEvent",
"ToolPreview",
"TurnCompletedEvent",
]
+358
View File
@@ -0,0 +1,358 @@
"""Typed events a turn emits while it runs (R04-T02).
The runtime currently speaks in bare dicts: ``emit({"type": "tool_result", "id":
..., "ok": ...})``. Nothing declares which keys a given type carries, so the
only specification is the 130-line ``if/elif`` chain in
``ui/chat_panel.py::_on_event`` — and a typo in an emitter surfaces as a widget
that silently renders nothing.
This module makes the vocabulary explicit. Each event is a frozen dataclass with
real fields, and each one knows how to serialise itself back to the exact legacy
dict the widget already reads (:meth:`AgentEvent.to_legacy_dict`), with
:func:`from_legacy_dict` parsing the other way. That two-way bridge is what lets
R04 introduce typed events WITHOUT touching the presentation layer — decomposing
``_on_event`` into a renderer is R08-T01's job, and forcing both changes into one
PR is exactly the "rewrite everything at once" the refactor plan forbids.
Scope note: this covers the interactive/scheduled **Cowork turn** vocabulary
(the ``run_cowork`` path R04 unifies). Co4E's own node events (``node_status``,
``stage_text``, ``run_done``) belong to ``Co4EWorkflowService`` in R07-T06 and
are deliberately left as dicts here — :func:`from_legacy_dict` returns ``None``
for them so a bridge can pass them straight through.
Layer rules (``docs/architecture/ADR-001-layered-architecture.md``): domain
layer, standard library only. No PySide6, no ``core/*`` imports.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, ClassVar, Dict, Iterable, Optional, Tuple
# Notice levels. "progress" is special-cased by the UI (it retargets the live
# thinking indicator instead of adding a bubble), so the vocabulary is pinned
# here rather than left to each emitter's string literal.
NOTICE_INFO = "info"
NOTICE_WARNING = "warning"
NOTICE_PROGRESS = "progress"
# --------------------------------------------------------------------------- #
# Value objects shared by several events.
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class ToolPreview:
"""The human-readable preview of a proposed tool call.
Mirrors ``core/tools.py::describe_action``'s return shape exactly (three
string keys, nothing else), so wrapping it in a type is lossless. ``kind``
drives which bubble the UI renders: "diff" -> coloured before/after,
"command" -> terminal block, "info" -> plain text.
"""
kind: str = "info"
title: str = ""
text: str = ""
def to_dict(self) -> Dict[str, str]:
return {"kind": self.kind, "title": self.title, "text": self.text}
@classmethod
def from_dict(cls, raw: Any) -> Optional["ToolPreview"]:
"""Parse a legacy preview dict; ``None`` when there was none.
A non-dict value degrades to ``None`` rather than raising: a malformed
preview must cost the user a nicer bubble, never the whole turn.
"""
if not isinstance(raw, dict) or not raw:
return None
return cls(kind=str(raw.get("kind", "info")), title=str(raw.get("title", "")),
text=str(raw.get("text", "")))
@dataclass(frozen=True)
class PlanStep:
"""One entry of the agent's ``update_plan`` checklist.
``status`` is kept a plain string on purpose: ``core/plan.py`` already owns
validation (clamping anything unknown to "pending" against
pending/running/done/error), and duplicating that vocabulary here would give
the app two sources of truth to drift apart.
"""
title: str
status: str = "pending"
def to_dict(self) -> Dict[str, str]:
return {"title": self.title, "status": self.status}
def _as_str_tuple(values: Iterable[Any]) -> Tuple[str, ...]:
"""Freeze an iterable of paths into a tuple of strings.
Emitters hand us live lists (``record["outputs"]``, ``_cleanup``'s result);
copying decouples the event from later mutation of that list.
"""
return tuple(str(v) for v in (values or ()))
# --------------------------------------------------------------------------- #
# Base class.
# --------------------------------------------------------------------------- #
class AgentEvent:
"""Base for every turn event.
Not a dataclass itself (it holds no data) — subclasses are the frozen
dataclasses. ``EVENT_TYPE`` is the legacy wire name, which stays the single
identifier shared between the typed world and the dict world.
"""
EVENT_TYPE: ClassVar[str] = ""
def _payload(self) -> Dict[str, Any]:
"""Type-specific keys of the legacy dict (without ``type``)."""
return {}
def to_legacy_dict(self) -> Dict[str, Any]:
"""The exact dict shape ``ui/chat_panel.py::_on_event`` dispatches on."""
return {"type": self.EVENT_TYPE, **self._payload()}
# --------------------------------------------------------------------------- #
# Streaming events.
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class TextChunkEvent(AgentEvent):
"""A fragment of the assistant's visible answer."""
EVENT_TYPE: ClassVar[str] = "text"
delta: str = ""
def _payload(self) -> Dict[str, Any]:
return {"delta": self.delta}
@dataclass(frozen=True)
class ReasoningChunkEvent(AgentEvent):
"""A fragment of a reasoning model's thinking, shown in a collapsed box."""
EVENT_TYPE: ClassVar[str] = "reasoning"
delta: str = ""
def _payload(self) -> Dict[str, Any]:
return {"delta": self.delta}
@dataclass(frozen=True)
class AssistantMessageCompletedEvent(AgentEvent):
"""One assistant message finished streaming.
Emitted once per provider call, so a tool-using turn produces SEVERAL of
these — it marks an autosave point, not the end of the turn. The end of the
turn is :class:`TurnCompletedEvent`.
"""
EVENT_TYPE: ClassVar[str] = "assistant_done"
content: str = ""
def _payload(self) -> Dict[str, Any]:
return {"content": self.content}
# --------------------------------------------------------------------------- #
# Tool-call lifecycle.
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class ToolCallStartedEvent(AgentEvent):
"""A tool call is about to run (after any security/permission gate).
Field names are the typed ones (``call_id``, ``arguments``); the legacy keys
``id``/``args`` are produced only at the serialisation boundary, so new code
never has to shadow the ``id`` builtin.
"""
EVENT_TYPE: ClassVar[str] = "tool_proposed"
call_id: str = ""
name: str = ""
arguments: Dict[str, Any] = field(default_factory=dict)
preview: Optional[ToolPreview] = None
def _payload(self) -> Dict[str, Any]:
payload: Dict[str, Any] = {"id": self.call_id, "name": self.name,
"args": dict(self.arguments)}
# Omitted rather than sent as None: the widget does
# ``preview = ev.get("preview") or {}`` and an absent key is the shape it
# already handles for tools without a preview.
if self.preview is not None:
payload["preview"] = self.preview.to_dict()
return payload
@dataclass(frozen=True)
class ToolOutputChunkEvent(AgentEvent):
"""Live stdout/stderr from a running command, appended to its step bubble."""
EVENT_TYPE: ClassVar[str] = "tool_output"
call_id: str = ""
name: str = ""
delta: str = ""
def _payload(self) -> Dict[str, Any]:
return {"id": self.call_id, "name": self.name, "delta": self.delta}
@dataclass(frozen=True)
class ToolCallFinishedEvent(AgentEvent):
"""A tool call returned. ``path``/``produced`` name files it created."""
EVENT_TYPE: ClassVar[str] = "tool_result"
call_id: str = ""
name: str = ""
ok: bool = False
output: str = ""
path: str = "" # the single file this call wrote, if any
produced: Tuple[str, ...] = () # extra deliverables a command produced
def __post_init__(self) -> None:
# Callers pass a live list; freeze it so the event cannot change later.
object.__setattr__(self, "produced", _as_str_tuple(self.produced))
def _payload(self) -> Dict[str, Any]:
payload: Dict[str, Any] = {"id": self.call_id, "name": self.name,
"ok": self.ok, "output": self.output}
# Both keys stay ABSENT when empty, matching what chat_agent emits today:
# downstream code tests them with ``ev.get(...)`` truthiness and iterates
# ``ev.get("produced", [])``, so adding empty values would be a change.
if self.path:
payload["path"] = self.path
if self.produced:
payload["produced"] = list(self.produced)
return payload
# --------------------------------------------------------------------------- #
# Side-channel events (plan, notices, output folder).
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class PlanUpdatedEvent(AgentEvent):
"""The agent published a new version of its step checklist (full list)."""
EVENT_TYPE: ClassVar[str] = "plan_set"
steps: Tuple[PlanStep, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "steps", tuple(self.steps or ()))
def _payload(self) -> Dict[str, Any]:
return {"steps": [s.to_dict() for s in self.steps]}
@dataclass(frozen=True)
class NoticeEvent(AgentEvent):
"""An aside outside the model's own answer.
Three sources today: context auto-compaction (info), a blocked
security check (warning), and attachment reading progress (progress).
"""
EVENT_TYPE: ClassVar[str] = "notice"
text: str = ""
level: str = NOTICE_INFO
def _payload(self) -> Dict[str, Any]:
return {"level": self.level, "text": self.text}
@dataclass(frozen=True)
class OutputsAddedEvent(AgentEvent):
"""Deliverables appeared in the turn's output folder."""
EVENT_TYPE: ClassVar[str] = "outputs_added"
paths: Tuple[str, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "paths", _as_str_tuple(self.paths))
def _payload(self) -> Dict[str, Any]:
return {"paths": list(self.paths)}
@dataclass(frozen=True)
class OutputsRemovedEvent(AgentEvent):
"""Intermediate/generator files were cleaned up — drop them from Output."""
EVENT_TYPE: ClassVar[str] = "outputs_removed"
paths: Tuple[str, ...] = ()
def __post_init__(self) -> None:
object.__setattr__(self, "paths", _as_str_tuple(self.paths))
def _payload(self) -> Dict[str, Any]:
return {"paths": list(self.paths)}
@dataclass(frozen=True)
class HistoryReadyEvent(AgentEvent):
"""The turn's conversation now exists on disk and can be opened.
Emitted by the unattended (Schedule Task) path so the scheduler refreshes
History only once the session is really there.
"""
EVENT_TYPE: ClassVar[str] = "history_ready"
session_id: str = ""
def _payload(self) -> Dict[str, Any]:
return {"session_id": self.session_id}
# --------------------------------------------------------------------------- #
# Turn-level events introduced by R04 (no legacy consumer yet).
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class TurnCompletedEvent(AgentEvent):
"""The whole turn ended — exactly once per turn.
Nothing consumes ``"turn_completed"`` yet: the widget's ``if/elif`` chain
simply has no branch for it, so emitting it is inert until R08 wires a
renderer. It exists now because the state it carries (was the turn
cancelled? did it hit the step ceiling?) is currently reconstructed by the
UI from side effects rather than being told to it.
"""
EVENT_TYPE: ClassVar[str] = "turn_completed"
final_text: str = ""
steps_used: int = 0
cancelled: bool = False
budget_exhausted: bool = False # stopped at effective_max_steps
def _payload(self) -> Dict[str, Any]:
return {"final_text": self.final_text, "steps_used": self.steps_used,
"cancelled": self.cancelled, "budget_exhausted": self.budget_exhausted}
@dataclass(frozen=True)
class ErrorEvent(AgentEvent):
"""The turn hit an error.
``recoverable`` separates "this turn is over" from "something failed but the
loop carried on" — a distinction the current code loses, because both end up
as a bare ``except Exception`` plus a text bubble.
"""
EVENT_TYPE: ClassVar[str] = "error"
message: str = ""
recoverable: bool = False
def _payload(self) -> Dict[str, Any]:
return {"message": self.message, "recoverable": self.recoverable}
__all__ = [
"NOTICE_INFO", "NOTICE_WARNING", "NOTICE_PROGRESS",
"AgentEvent", "ToolPreview", "PlanStep",
"TextChunkEvent", "ReasoningChunkEvent", "AssistantMessageCompletedEvent",
"ToolCallStartedEvent", "ToolOutputChunkEvent", "ToolCallFinishedEvent",
"PlanUpdatedEvent", "NoticeEvent", "OutputsAddedEvent", "OutputsRemovedEvent",
"HistoryReadyEvent", "TurnCompletedEvent", "ErrorEvent",
]
+123
View File
@@ -0,0 +1,123 @@
"""Legacy dict -> typed :mod:`agent_event` translation (R04-T02).
Kept in its own module for two reasons. It is a **temporary compatibility
shim**: once R08-T01 turns ``ui/chat_panel.py::_on_event`` into an event
renderer that consumes typed events directly, nothing needs to parse dicts any
more and this whole file gets deleted — a deletion that stays trivial only while
it is isolated. And it keeps ``agent_event.py`` inside the 400-LOC limit the
architecture rules impose, without diluting either file's single job: one
declares the vocabulary, the other bridges it to the old wire format.
Serialisation the other way lives on the events themselves
(``AgentEvent.to_legacy_dict``), because an event has to be emittable without
anyone importing a codec.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple
from .agent_event import (
AgentEvent,
AssistantMessageCompletedEvent,
ErrorEvent,
HistoryReadyEvent,
NOTICE_INFO,
NoticeEvent,
OutputsAddedEvent,
OutputsRemovedEvent,
PlanStep,
PlanUpdatedEvent,
ReasoningChunkEvent,
TextChunkEvent,
ToolCallFinishedEvent,
ToolCallStartedEvent,
ToolOutputChunkEvent,
ToolPreview,
TurnCompletedEvent,
)
def _plan_steps_from_legacy(raw: Any) -> Tuple[PlanStep, ...]:
"""Parse the legacy ``steps`` list, dropping anything unusable.
A step with no title cannot be rendered or ticked off, so it is discarded
instead of becoming a blank row in the Plan panel.
"""
if not isinstance(raw, list):
return ()
steps: List[PlanStep] = []
for item in raw:
if not isinstance(item, dict):
continue
title = str(item.get("title", "")).strip()
if not title:
continue
steps.append(PlanStep(title=title, status=str(item.get("status", "pending"))))
return tuple(steps)
def _parse_tool_started(raw: Dict[str, Any]) -> ToolCallStartedEvent:
"""Rebuild a ``tool_proposed`` event, mapping ``id``/``args`` to typed names."""
args = raw.get("args")
return ToolCallStartedEvent(
call_id=str(raw.get("id", "")), name=str(raw.get("name", "")),
arguments=dict(args) if isinstance(args, dict) else {},
preview=ToolPreview.from_dict(raw.get("preview")),
)
def _parse_tool_finished(raw: Dict[str, Any]) -> ToolCallFinishedEvent:
"""Rebuild a ``tool_result`` event; the optional file keys may be absent."""
return ToolCallFinishedEvent(
call_id=str(raw.get("id", "")), name=str(raw.get("name", "")),
ok=bool(raw.get("ok", False)), output=str(raw.get("output", "")),
path=str(raw.get("path", "") or ""), produced=raw.get("produced") or (),
)
# One parser per wire name. A table (rather than an if/elif chain) keeps adding
# an event a single-line change and makes the supported set introspectable.
_PARSERS = {
TextChunkEvent.EVENT_TYPE: lambda raw: TextChunkEvent(delta=str(raw.get("delta", ""))),
ReasoningChunkEvent.EVENT_TYPE: lambda raw: ReasoningChunkEvent(
delta=str(raw.get("delta", ""))),
AssistantMessageCompletedEvent.EVENT_TYPE: lambda raw: AssistantMessageCompletedEvent(
content=str(raw.get("content", ""))),
ToolCallStartedEvent.EVENT_TYPE: _parse_tool_started,
ToolOutputChunkEvent.EVENT_TYPE: lambda raw: ToolOutputChunkEvent(
call_id=str(raw.get("id", "")), name=str(raw.get("name", "")),
delta=str(raw.get("delta", ""))),
ToolCallFinishedEvent.EVENT_TYPE: _parse_tool_finished,
PlanUpdatedEvent.EVENT_TYPE: lambda raw: PlanUpdatedEvent(
steps=_plan_steps_from_legacy(raw.get("steps"))),
NoticeEvent.EVENT_TYPE: lambda raw: NoticeEvent(
text=str(raw.get("text", "")), level=str(raw.get("level", NOTICE_INFO))),
OutputsAddedEvent.EVENT_TYPE: lambda raw: OutputsAddedEvent(paths=raw.get("paths") or ()),
OutputsRemovedEvent.EVENT_TYPE: lambda raw: OutputsRemovedEvent(paths=raw.get("paths") or ()),
HistoryReadyEvent.EVENT_TYPE: lambda raw: HistoryReadyEvent(
session_id=str(raw.get("session_id", ""))),
TurnCompletedEvent.EVENT_TYPE: lambda raw: TurnCompletedEvent(
final_text=str(raw.get("final_text", "")), steps_used=int(raw.get("steps_used", 0) or 0),
cancelled=bool(raw.get("cancelled", False)),
budget_exhausted=bool(raw.get("budget_exhausted", False))),
ErrorEvent.EVENT_TYPE: lambda raw: ErrorEvent(
message=str(raw.get("message", "")), recoverable=bool(raw.get("recoverable", False))),
}
def from_legacy_dict(payload: Any) -> Optional[AgentEvent]:
"""Parse an emitted dict into a typed event, or ``None`` if it isn't ours.
``None`` (rather than an exception) is the contract that makes incremental
adoption possible: a bridge sitting between the runtime and the widget can
type the events it recognises and forward everything else — Co4E's node
events, or anything a future emitter adds — completely untouched.
"""
if not isinstance(payload, dict):
return None
parser = _PARSERS.get(str(payload.get("type", "")))
return parser(payload) if parser is not None else None
__all__ = ["from_legacy_dict"]
+86
View File
@@ -0,0 +1,86 @@
"""What one finished turn produced (R04-T03).
The outcome of a turn is currently spread over three shapes: ``run_cowork``
returns the mutated message list, ``task_executors._run_agent`` returns a
``(answer_text, timed_out, incomplete_reason)`` tuple, and the UI reconstructs
the rest (did it get cancelled? did it hit the ceiling?) from side effects. Each
caller therefore knows a slightly different amount about the same turn.
:class:`AgentResult` is the single answer. Frozen, like the request that started
the turn, so a result cannot be edited into disagreeing with what actually
happened.
Layer rules (``docs/architecture/ADR-001-layered-architecture.md``): domain
layer — standard library plus sibling domain types only.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Dict, Tuple
from .agent_event import PlanStep, TurnCompletedEvent
@dataclass(frozen=True)
class AgentResult:
"""The outcome of one conversation turn."""
# The conversation AFTER the turn (system prompt, history, the new user
# message, every assistant reply and tool result).
messages: Tuple[Dict[str, Any], ...] = ()
steps_used: int = 0 # provider calls this turn consumed
cancelled: bool = False # the user pressed Stop
budget_exhausted: bool = False # stopped at effective_max_steps
# The agent's final checklist, so a caller can ask "did it really finish?"
# (``core/plan.py::plan_incomplete_reason``) without replaying the events.
plan_steps: Tuple[PlanStep, ...] = ()
# Non-empty when the turn ended on a failure. A string rather than the
# exception: the domain layer must not depend on where the error came from,
# and the message is what every consumer (bubble, error.txt, audit) shows.
error: str = ""
def __post_init__(self) -> None:
"""Freeze the collections the runtime hands over.
Both arrive as live lists that the caller keeps appending to after the
turn (the UI merges messages back into its own history), so copying here
is what keeps a result a record rather than a moving target.
"""
object.__setattr__(self, "messages", tuple(self.messages or ()))
object.__setattr__(self, "plan_steps", tuple(self.plan_steps or ()))
@property
def final_text(self) -> str:
"""The answer to show the user.
Scans backwards for the last assistant message with real content, which
is not the same as ``messages[-1]``: a turn that was cancelled or that
ran out of steps mid-loop ends on a tool message, and a reasoning-only
reply leaves a blank assistant message behind. Same rule as
``core/task_executors.py::_last_assistant_text``, which this replaces.
"""
for message in reversed(self.messages):
if message.get("role") == "assistant" and (message.get("content") or "").strip():
return str(message["content"])
return ""
@property
def ok(self) -> bool:
"""Whether the turn ran to a normal end.
Hitting the step ceiling still counts as ok: the agent did work and
produced an answer, it just was not allowed to keep going — which the
transcript says in its own note rather than by failing the turn.
"""
return not self.error and not self.cancelled
def to_turn_completed_event(self) -> TurnCompletedEvent:
"""The end-of-turn event carrying this outcome to subscribers."""
return TurnCompletedEvent(
final_text=self.final_text, steps_used=self.steps_used,
cancelled=self.cancelled, budget_exhausted=self.budget_exhausted,
)
__all__ = ["AgentResult"]
@@ -0,0 +1,222 @@
"""The immutable snapshot of ONE chat turn (R04-T01).
Today a turn's inputs live in a closure plus a 15-key ``ctx`` dict built inside
``ui/chat_panel.py::_start_turn``, and the worker thread reads the widget back
(``self._model``, ``self.title``, ``self.project_id``) while it runs. That is
the mechanism behind the whole class of "I changed the model mid-answer and the
running turn behaved oddly" reports: the turn has no snapshot of its own, so
every later click on the UI is visible to work already in flight.
:class:`ConversationExecutionRequest` is that missing snapshot. Everything the
runtime needs for one turn is captured once, on the UI thread, at submit time,
and then handed to code that runs on a worker thread. Frozen, so no caller —
widget or service — can retroactively change a decision the turn already acted
on.
Layer rules (see ``docs/architecture/ADR-001-layered-architecture.md``): this is
the domain layer, so standard library only. No PySide6, no ``requests``, no
filesystem access, and deliberately no import of ``core/*`` — a request only
*describes* a turn; running it is the application layer's job
(``application/conversations/``).
"""
from __future__ import annotations
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
# Separator between an instruction prefix (a ``/skill`` block, an ``/agent``
# persona) and the user's own request. Kept as a constant because the prefix is
# assembled in the presentation layer while the body is only known later on the
# worker thread — both halves must agree on the exact separator or the model
# sees a different prompt shape than it did before this refactor.
PREFIX_SEPARATOR = "\n\n---\n\n"
@dataclass(frozen=True)
class ConversationExecutionRequest:
"""Everything needed to execute one conversation turn.
Frozen for the reason above; use :meth:`with_model` / :meth:`with_output_dir`
to derive an adjusted copy rather than mutating one another thread may be
reading.
Note on depth: ``messages`` is a *shallow* snapshot (a tuple holding the
same message dicts the caller passed). That matches the existing
``snapshot = list(self.messages)`` semantics in ``_start_turn`` exactly —
the turn is protected from the history list being appended to or replaced,
which is what actually happens between turns. Making it deep would silently
change how ``_finalize_turn`` merges the turn's messages back, so the
stronger guarantee is left to R04-T03 where that merge moves.
"""
# -- identity ------------------------------------------------------- #
turn_id: str # unique within a session ("t1", "t2", ...)
session_id: str # the conversation this turn belongs to
surface: str = "cowork" # routing/mode key: "cowork" | "co4e" | "ai_edit"
project_id: str = "" # workspace the turn is confined to
title: str = "" # conversation title; also names saved files
# -- what the user asked -------------------------------------------- #
# The typed request, already stripped of any ``/skill`` or ``/agent``
# directive (those become ``instruction_prefix``).
prompt: str = ""
instruction_prefix: str = "" # skill rules + agent persona for this turn
# Prepended when the model/agent was switched mid-conversation, asking the
# model to re-check the previous step before continuing. Invisible in the
# chat bubble — it only travels in the payload sent to the provider.
review_note: str = ""
# Attachment PATHS, not their text: extracting a .docx can pip-install a
# parser or shell out to LibreOffice, which must not run on the UI thread.
# The runtime reads them later and passes the result to :meth:`user_content`.
attachments: Tuple[str, ...] = ()
# Conversation history as of submit time; the new user message is NOT part
# of it (the runtime appends it once the body is composed).
messages: Tuple[Dict[str, Any], ...] = ()
# -- which model answers -------------------------------------------- #
# Already resolved upstream: an Admin-agent pin, the tab's own picker, or a
# routing override published by ``RoutingApplicationService`` (R03). The
# runtime does not re-decide, so a switch cannot land mid-turn.
provider_id: str = ""
model: str = "" # "" = the provider's configured default
# -- standing instructions ------------------------------------------ #
project_context: str = "" # Claude-Projects-style shared instructions
session_notes: str = "" # e.g. files this conversation already produced
# -- tool scope and turn limits -------------------------------------- #
# None = every enabled built-in tool. An explicit (possibly empty) tuple
# restricts the ADVERTISED tools, which is how a "read-only" step is made
# literally unable to write.
allowed_tools: Optional[Tuple[str, ...]] = None
max_steps: int = 30 # interactive cap
completion_max_steps: int = 200 # runaway ceiling for run-to-completion work
run_to_completion: bool = False # Co4E flow steps need the higher ceiling
enforce_rules: bool = True # False for sandboxed Co4E runs
gate_mode: str = "auto" # "confirm" -> ask before run_command/install
agent_role: str = "cowork" # audit-log attribution ("cowork" | "task" | ...)
# -- where its files go ---------------------------------------------- #
output_dir: Optional[Path] = None # this turn's isolated sandbox
home_output_root: Optional[Path] = None # conversation Output root to promote into
# -- unattended execution (Schedule Task) ----------------------------- #
unattended: bool = False # no human watching; plan tracking is enforced
timeout_sec: Optional[int] = None # None = no wall-clock limit
# Escape hatch for surface-specific data a future task needs to thread
# through without another schema change (same role as
# ``ProviderDescriptor.extras``).
extras: Dict[str, Any] = field(default_factory=dict)
# -- validation / normalisation --------------------------------------- #
def __post_init__(self) -> None:
"""Reject unusable requests and freeze the mutable inputs.
Validation lives here (not at the call site) so a request that exists is
always safe to key by: the audit log, the History autosave and the
per-turn output folder are all named from ``session_id``/``turn_id``.
Normalisation matters just as much: the caller hands us the composer's
own attachment LIST and the live history LIST, and both get cleared or
appended to for the next turn. Copying them into tuples here is what
actually makes the snapshot a snapshot. ``object.__setattr__`` is the
standard way to do this in a frozen dataclass.
"""
if not (self.turn_id or "").strip():
raise ValueError("ConversationExecutionRequest.turn_id must not be empty")
if not (self.session_id or "").strip():
raise ValueError("ConversationExecutionRequest.session_id must not be empty")
object.__setattr__(self, "attachments", tuple(self.attachments or ()))
object.__setattr__(self, "messages", tuple(self.messages or ()))
# None must survive: it means "no restriction", while an empty tuple
# means "deny every built-in tool" — two very different turns.
if self.allowed_tools is not None:
object.__setattr__(self, "allowed_tools", tuple(self.allowed_tools))
# Accept str paths so a call site holding a config value does not have to
# wrap it; everything downstream can then assume Path.
for name in ("output_dir", "home_output_root"):
value = getattr(self, name)
if value is not None and not isinstance(value, Path):
object.__setattr__(self, name, Path(value))
# -- derived turn policy ---------------------------------------------- #
@property
def has_prompt(self) -> bool:
"""Whether the user actually typed something (an attachment-only turn
legitimately has none). Mirrors ``RoutingRequest.has_prompt`` so both
DTOs answer the "is there anything to work with?" question the same way.
"""
return bool((self.prompt or "").strip())
@property
def effective_max_steps(self) -> int:
"""The tool-use budget for this turn.
Run-to-completion work (a Co4E flow step whose single instruction may
need many tool calls) gets the higher ceiling; interactive chat keeps the
tight cap. Either way the turn still ends the moment the model stops
calling tools — this is only the runaway limit.
"""
return self.completion_max_steps if self.run_to_completion else self.max_steps
@property
def requires_permission_gate(self) -> bool:
"""Whether ``run_command``/``install_package`` must be approved first.
Resolved by the caller (per-workspace Auto-run override, else the global
"confirm before running commands" setting) and frozen here, so toggling
the setting mid-turn cannot change the rules the turn started under.
"""
return self.gate_mode == "confirm"
# -- prompt composition ------------------------------------------------ #
def user_content(self, body: str = "") -> str:
"""The exact ``content`` to send as this turn's user message.
``body`` is the request text AFTER attachment extraction, which happens
on the worker thread — hence a method taking it as an argument rather
than a stored field. The assembly order reproduces the closure in
``_start_turn`` byte for byte, because changing what a model receives is
a behaviour change, not a refactor:
1. session notes are appended after the body;
2. the instruction prefix goes in front, behind a fixed separator;
3. the model-switch review note goes ahead of everything.
"""
content = body or ""
notes = self.session_notes or ""
if notes:
# Guard the empty-body case (attachment-only turn) so the payload
# never opens with a stray blank line.
content = f"{content}\n\n{notes}" if content else notes
prefix = self.instruction_prefix or ""
if prefix:
content = f"{prefix}{PREFIX_SEPARATOR}{content}"
review = self.review_note or ""
if review:
content = f"{review}\n\n{content}"
return content
# -- derivation --------------------------------------------------------- #
def with_model(self, provider_id: str = "", model: str = "") -> "ConversationExecutionRequest":
"""A copy pinned to another provider/model.
Needed when a decision lands between building the request and running it
(a routing override, an Admin-agent pin). Deriving a new request keeps
the "one turn, one immutable snapshot" rule intact instead of patching a
request another thread may already hold.
"""
return replace(self, provider_id=provider_id or self.provider_id,
model=model or self.model)
def with_output_dir(self, output_dir) -> "ConversationExecutionRequest":
"""A copy writing into a different sandbox — used when the caller only
learns the per-turn folder after the request is assembled."""
return replace(self, output_dir=output_dir)
__all__ = ["PREFIX_SEPARATOR", "ConversationExecutionRequest"]
+12
View File
@@ -1 +1,13 @@
"""Domain models package: provider descriptors, model pricing, and routing metadata."""
from .provider_descriptor import (
AuthKind,
ProviderDescriptor,
WireProtocol,
)
__all__ = [
"AuthKind",
"ProviderDescriptor",
"WireProtocol",
]
+110
View File
@@ -0,0 +1,110 @@
"""Cổng chính sách cho lời gọi tool — hình dạng dữ liệu, chưa phải cài đặt.
BẢN ĐỀ XUẤT, chờ Team Hoa xác nhận
==================================
Sơ đồ phân hệ trong ``plan.md`` giao ``domain/security/`` cho Team Gamma và
``application/conversations/tool_policy_gateway.py`` cho Team Hoa. Nên Gamma
định nghĩa *hình dạng*, Hoa *cài đặt*.
Viết trước vì N3 (Co4E) cần gọi tool và Team Hoa chưa bắt đầu. Không có nó thì
N3 phải tự phỏng đoán rồi sửa lại sau — mà phỏng đoán của một người thì tệ hơn
một đề xuất viết ra để cả hai bên soi.
Nếu Hoa thấy khác, sửa file này chứ đừng đẻ kiểu thứ hai. Đổi sớm rẻ hơn đổi
muộn: hiện chỉ N3 dùng.
Mô hình bám theo code đang chạy, không bịa:
* ``core/agent_security.py::SecurityVerdict`` — allowed / reason / layer
* ``ui/permission_dialog.py`` — hộp thoại hỏi người dùng khi
``ctx.project_confirm_commands()`` bật (``ui/chat_panel.py:1312``)
Điểm khác biệt duy nhất so với hôm nay: gộp hai thứ đó thành **một câu trả lời
ba trạng thái**, thay vì code gọi phải tự nhớ hỏi cả hai nơi.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, Protocol, runtime_checkable
class PolicyOutcome(str, Enum):
"""Ba trạng thái. ``ASK`` là thứ hệ thống hiện tại đã có (hộp thoại xin
phép) nhưng chưa được coi là một kết quả chính thức."""
ALLOW = "allow"
DENY = "deny"
ASK = "ask"
@dataclass(frozen=True)
class ToolCallRequest:
"""Một lời gọi tool đang chờ được duyệt.
``surface`` cho biết chỗ phát sinh — ``"cowork"``, ``"code"``, ``"co4e"``,
``"task"``. Chính sách khác nhau theo màn: Co4E chạy nền nên không thể bật
hộp thoại hỏi giữa chừng như Cowork.
"""
name: str
arguments: Dict[str, Any] = field(default_factory=dict)
surface: str = "cowork"
project_id: str = ""
#: True nếu tool đến từ MCP server ngoài, False nếu là tool dựng sẵn.
external: bool = False
@dataclass(frozen=True)
class PolicyDecision:
"""Câu trả lời của cổng.
``reason`` bắt buộc có khi DENY hoặc ASK — người dùng phải biết vì sao bị
chặn, và ``core/audit_log.py`` cần nó để ghi lại.
``layer`` giữ đúng từ vựng của ``SecurityVerdict``: ``"prompt"`` |
``"attachment"`` | ``"command"``, cộng thêm ``"policy"`` cho quyết định của
chính cổng này.
"""
outcome: PolicyOutcome
reason: str = ""
layer: str = "policy"
@property
def allowed(self) -> bool:
"""Tương thích với chỗ đang đọc ``SecurityVerdict.allowed``.
Chú ý: ``ASK`` KHÔNG phải allowed — còn phải hỏi người dùng đã.
"""
return self.outcome is PolicyOutcome.ALLOW
def __post_init__(self):
if self.outcome is not PolicyOutcome.ALLOW and not self.reason:
raise ValueError("DENY và ASK bắt buộc có reason — người dùng và "
"audit log đều cần biết vì sao")
def allow() -> PolicyDecision:
return PolicyDecision(PolicyOutcome.ALLOW)
def deny(reason: str, layer: str = "policy") -> PolicyDecision:
return PolicyDecision(PolicyOutcome.DENY, reason, layer)
def ask(reason: str, layer: str = "policy") -> PolicyDecision:
return PolicyDecision(PolicyOutcome.ASK, reason, layer)
@runtime_checkable
class ToolPolicyGateway(Protocol):
"""Hỏi trước khi chạy tool. Cài đặt thật: Team Hoa (R07, hạn 29/08)."""
def check(self, request: ToolCallRequest) -> PolicyDecision:
"""Được chạy tool này không.
KHÔNG được tự bật hộp thoại bên trong — cổng chỉ *trả lời*, còn hỏi ai
và hỏi thế nào là việc của tầng giao diện. Có vậy thì Co4E chạy nền mới
dùng chung cổng được với Cowork chạy tương tác.
"""
...
+4
View File
@@ -1 +1,5 @@
"""Domain tasks package: task definitions and deterministic schedule calculators."""
from .schedule_calculator import ScheduleCalculator
__all__ = ["ScheduleCalculator"]
+165
View File
@@ -0,0 +1,165 @@
"""ScheduleCalculator - due-time / cron / interval math for Schedule Task,
extracted from ``core/tasks.py``'s "schedule math" section (R07-T02).
``core/tasks.py`` is already Qt-free (its own docstring says so), but it
still lives under ``core/`` where nothing enforces that "pure" claim - and it
is the ONE piece of scheduling logic ``docs/refactor/plan.md`` calls out as
needing its own unit tests (none existed before this task; see
``tests/unit/test_schedule_calculator.py``). Moving it to ``domain/tasks/``
makes the purity a build-time guarantee (``scripts/check_imports.py`` fails
the build if this file ever imports Qt, ``core``, or anything with I/O) and
gives the date math a home that is trivially unit-testable without going
through ``core/tasks.py``'s file-repository concerns at all.
Two pieces of this math are themselves implemented elsewhere in ``core/`` -
``core/cron.py::Cron`` (5-field cron parsing) and
``core/holiday_calendar.py::is_holiday`` (VN public holidays). Importing
``core`` from ``domain`` is exactly what ADR-001 rule I2 forbids (domain must
not know infrastructure/core exists), so this class takes them as
constructor-injected callables instead of importing them - the same
dependency-inversion shape ``application/conversations/conversation_
application_service.py`` (R04-T03) already uses for its provider factory.
``core/tasks.py`` wires the real ``Cron``/``is_holiday`` in; tests can inject
plain stub functions with zero I/O.
"""
from __future__ import annotations
import calendar
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, List, Optional, Protocol
# Same on-disk format core/tasks.py::_TIME_FMT uses for schedule.run_at.
# Duplicated here (not imported - that would be a domain -> core edge) since
# it's a 1-line format string, not business logic.
_TIME_FMT = "%Y-%m-%d %H:%M"
_CRON_SEARCH_GUARD = 400 # matches the guard core/tasks.py used before extraction
class _CronLike(Protocol):
"""Structural shape this class needs from a cron object - satisfied by
``core/cron.py::Cron`` without this module importing it."""
def next_after(self, after: datetime) -> Optional[datetime]:
...
def _parse_run_at(value: Optional[str]) -> Optional[datetime]:
if not value:
return None
try:
return datetime.strptime(value, _TIME_FMT)
except ValueError:
return None
class ScheduleCalculator:
"""Pure due-time computation for one task's ``schedule`` dict.
``is_holiday``: ``Callable[[date, country_code], bool]`` or ``None`` -
when ``None``, a schedule with ``skip_holidays`` set simply never treats
any day as a holiday (degrades gracefully instead of raising, mirroring
how a caller who doesn't care about holidays can just not wire it up).
``make_cron``: ``Callable[[str], _CronLike]`` (raises on a malformed
expression) or ``None`` - when ``None``, ``repeat_type == "cron"``
schedules never produce a next run (same as an invalid expression today).
"""
def __init__(self,
is_holiday: Optional[Callable[[Any, str], bool]] = None,
make_cron: Optional[Callable[[str], _CronLike]] = None) -> None:
self._is_holiday = is_holiday
self._make_cron = make_cron
def is_excluded_day(self, dt: datetime, sched: Dict[str, Any]) -> bool:
"""True when ``dt`` falls on a day this schedule must skip: a
weekend (working_days_only) or a public holiday of the configured
country."""
if sched.get("working_days_only") and dt.weekday() >= 5: # 5=Sat, 6=Sun
return True
if sched.get("skip_holidays") and self._is_holiday is not None:
if self._is_holiday(dt.date(), sched.get("holiday_country", "")):
return True
return False
def add_month(self, dt: datetime) -> datetime:
"""Calendar-aware +1 month, clamping the day to the target month's
length (e.g. Jan 31 + 1 month -> Feb 28/29, not an overflow error)."""
year = dt.year + (1 if dt.month == 12 else 0)
month = 1 if dt.month == 12 else dt.month + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)
def shift_off_excluded_days(self, dt: datetime, sched: Dict[str, Any]) -> datetime:
"""Push ``dt`` forward one day at a time until it lands on an
allowed day (same time of day) - used for one-time schedules set on
a weekend/holiday."""
guard = 0
while self.is_excluded_day(dt, sched) and guard < _CRON_SEARCH_GUARD:
dt += timedelta(days=1)
guard += 1
return dt
def compute_next_run(self, task: Dict[str, Any], after: datetime) -> Optional[datetime]:
"""The next run time strictly after ``after`` for a repeating task
(daily / weekly / monthly / cron), or ``None`` for one-shot
schedules. Occurrences on excluded days are skipped forward."""
sched = task.get("schedule", {})
repeat = sched.get("repeat_type", "none")
if repeat == "cron":
if self._make_cron is None:
return None
try:
cron = self._make_cron(sched.get("cron_expression") or "")
except Exception:
# Any malformed-expression error the injected factory raises
# (core/cron.py::CronError, or a fake's own error type in
# tests) means "this schedule can't compute a next run" - not
# a domain-layer crash.
return None
nxt = cron.next_after(after)
guard = 0
while nxt is not None and self.is_excluded_day(nxt, sched) and guard < _CRON_SEARCH_GUARD:
nxt = cron.next_after(nxt)
guard += 1
return nxt
base = _parse_run_at(sched.get("run_at"))
if base is None:
return None
if repeat == "daily":
advance = lambda d: d + timedelta(days=1) # noqa: E731
elif repeat == "weekly":
advance = lambda d: d + timedelta(weeks=1) # noqa: E731
elif repeat == "monthly":
advance = self.add_month
else:
return None
nxt = base
while nxt <= after:
nxt = advance(nxt)
guard = 0
while self.is_excluded_day(nxt, sched) and guard < _CRON_SEARCH_GUARD:
nxt = advance(nxt)
guard += 1
return nxt
def due_tasks(self, tasks: List[Dict[str, Any]], now: datetime) -> List[Dict[str, Any]]:
"""Tasks that should start now: Scheduled + schedule enabled +
run_at due."""
due = []
for t in tasks:
if t.get("status") != "scheduled":
continue
sched = t.get("schedule", {})
if not sched.get("enabled"):
continue
run_at = _parse_run_at(sched.get("run_at"))
if run_at is not None and run_at <= now:
due.append(t)
return due
__all__ = ["ScheduleCalculator"]
+18 -1
View File
@@ -1 +1,18 @@
"""Domain tools package: tool descriptors, capability scopes, and registry interfaces."""
"""Domain entities for tool risk classification and lookup (EPIC R05)."""
from .tool_descriptor import ToolCapability, ToolDescriptor
from .tool_registry import (
BUILT_IN_CAPABILITIES,
UNKNOWN_SOURCE_CAPABILITIES,
ToolRegistry,
default_registry,
)
__all__ = [
"ToolCapability",
"ToolDescriptor",
"ToolRegistry",
"BUILT_IN_CAPABILITIES",
"UNKNOWN_SOURCE_CAPABILITIES",
"default_registry",
]
+86
View File
@@ -0,0 +1,86 @@
"""ToolCapability / ToolDescriptor - the risk-tagged catalogue entry for one
tool the agent loop can call (R05-T01).
Today a tool is just a name inside ``core/tools.py::TOOL_SPECS`` (a
``providers.base.ToolSpec`` — name/description/JSON-schema parameters, with
no notion of risk) plus a hand-written membership test wherever gating is
needed: ``core/tools.py::WRITE_TOOLS``, ``core/code_agent.py``'s
``WRITE_TOOLS | MS365_WRITE_TOOLS``, and ``core/chat_agent.py``'s literal
``name in ("run_command", "install_package")``. Three call sites, three
independently-maintained lists, and a new tool (or an MCP/connector tool,
which has no list membership at all - see ``core/mcp_client.py``) is gated
only if someone remembers to add it everywhere.
``ToolDescriptor`` makes the risk an attribute of the tool itself, declared
once, so ``application/conversations/tool_policy_gateway.py`` (R05-T03) can
decide ALLOW/CONFIRM/DENY from data instead of a growing set of literal
tuples.
Pure domain code: stdlib only, no Qt, no I/O. ``to_spec``/``from_spec`` are
the only place this module touches something outside domain/, and that
something (``providers.base.ToolSpec``) is itself a plain dataclass with no
further dependencies.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Flag, auto
from typing import Any, Dict
from cowork_local.providers.base import ToolSpec
class ToolCapability(Flag):
"""What calling a tool can do to the machine or the network.
A ``Flag`` (not a plain ``Enum``) because a single tool can combine risks
- ``install_package`` writes to the environment, runs pip as a
subprocess, AND needs network access. Composing three separate booleans
per call site is exactly the duplication this type replaces.
"""
NONE = 0
READ = auto()
WRITE = auto()
EXECUTE = auto()
NETWORK = auto()
@dataclass(frozen=True)
class ToolDescriptor:
"""An immutable description of one callable tool.
Attributes:
name: the identifier the model calls (``ToolSpec.name``).
description: shown to the model, unchanged from ``ToolSpec``.
parameters: JSON-Schema object for the call's arguments.
capabilities: the risk this tool carries - see :class:`ToolCapability`.
"""
name: str
description: str
parameters: Dict[str, Any] = field(default_factory=dict)
capabilities: ToolCapability = ToolCapability.NONE
def has(self, capability: ToolCapability) -> bool:
"""True when this tool carries (any bit of) ``capability``."""
return bool(self.capabilities & capability)
def to_spec(self) -> ToolSpec:
"""Project back to the ``ToolSpec`` shape the model-facing catalogue
and the provider call actually use - risk tagging is metadata the
wire format has no room for."""
return ToolSpec(name=self.name, description=self.description,
parameters=self.parameters)
@classmethod
def from_spec(cls, spec: ToolSpec,
capabilities: ToolCapability = ToolCapability.NONE) -> "ToolDescriptor":
"""Wrap an existing ``ToolSpec`` (built-in, MCP, or connector) with a
capability tag. The one place callers attach risk to a spec they did
not author themselves."""
return cls(name=spec.name, description=spec.description,
parameters=spec.parameters, capabilities=capabilities)
__all__ = ["ToolCapability", "ToolDescriptor"]
+125
View File
@@ -0,0 +1,125 @@
"""ToolRegistry - the centralised catalogue every tool source registers into
(R05-T01).
Built-in file/command/fetch tools (``core/tools.py``), MCP server tools
(``core/mcp_client.py``) and unified connectors (``core/ext_connectors.py``)
each produce their own ``List[ToolSpec]`` today, concatenated ad-hoc by
``core/tools.py::combine_tool_sources``. None of that concatenation carries
risk information, which is exactly why an MCP tool call reaches
``core/chat_agent.py`` with no ``ToolDescriptor`` to consult and skips the
permission gate entirely (the gap R05-T04 closes).
``ToolRegistry`` is the one place a :class:`~domain.tools.tool_descriptor.ToolDescriptor`
is looked up by name, so a policy gateway - or anything else that needs to ask
"what can this tool do" - has a single source of truth instead of re-deriving
it from a spec list.
Pure domain code: stdlib only, no Qt, no I/O.
"""
from __future__ import annotations
from typing import Dict, Iterable, List, Optional
from cowork_local.providers.base import ToolSpec
from .tool_descriptor import ToolCapability, ToolDescriptor
class ToolRegistry:
"""An in-memory, name-keyed catalogue of :class:`ToolDescriptor`.
Deliberately mutable and unordered-by-name-only: a turn builds one
registry from whichever tool sources it has (built-ins + whatever MCP
servers/connectors are enabled), so re-registering the same name simply
replaces the previous descriptor rather than raising - the same
"last one wins" behaviour ``combine_tool_sources`` already has for
duplicate tool names across sources.
"""
def __init__(self, descriptors: Optional[Iterable[ToolDescriptor]] = None) -> None:
self._by_name: Dict[str, ToolDescriptor] = {}
for descriptor in descriptors or ():
self.register(descriptor)
def register(self, descriptor: ToolDescriptor) -> None:
self._by_name[descriptor.name] = descriptor
def get(self, name: str) -> Optional[ToolDescriptor]:
return self._by_name.get(name)
def all(self) -> List[ToolDescriptor]:
return list(self._by_name.values())
def specs(self) -> List[ToolSpec]:
"""Every registered descriptor, projected back to ``ToolSpec`` - the
shape the provider call and the model-facing catalogue need."""
return [d.to_spec() for d in self._by_name.values()]
def capabilities_for(self, name: str) -> ToolCapability:
"""The capability set for ``name``, or ``NONE`` for an unknown tool.
Returning ``NONE`` rather than raising lets a policy gateway treat an
unregistered tool the same way as one with no declared risk - the
gateway's DENY-on-unknown-name rule is a deliberate, separate check,
not something this lookup should pre-empt.
"""
descriptor = self._by_name.get(name)
return descriptor.capabilities if descriptor is not None else ToolCapability.NONE
def __contains__(self, name: str) -> bool:
return name in self._by_name
def __len__(self) -> int:
return len(self._by_name)
# --------------------------------------------------------------------------- #
# Default capability map for this app's built-in tools (core/tools.py).
# Kept here, next to the registry, rather than inside core/tools.py itself -
# core/ is the legacy engine layer being strangled, not where new domain facts
# should accumulate.
# --------------------------------------------------------------------------- #
_CAP = ToolCapability
BUILT_IN_CAPABILITIES: Dict[str, ToolCapability] = {
"read_file": _CAP.READ,
"list_dir": _CAP.READ,
"write_file": _CAP.WRITE,
"edit_file": _CAP.WRITE,
"run_command": _CAP.EXECUTE,
"install_package": _CAP.WRITE | _CAP.EXECUTE | _CAP.NETWORK,
"fetch_url": _CAP.NETWORK,
"jira_search": _CAP.NETWORK,
"jira_get_issue": _CAP.NETWORK,
# Advertised by every engine but has no filesystem/process/network effect
# of its own - it only drives the Plan panel (see core/chat_agent.py).
"update_plan": _CAP.NONE,
"save_file": _CAP.WRITE,
}
# Tools with no standard, self-declared risk metadata (every MCP server tool,
# every unified connector) are tagged with this conservative default - see
# R05-T04. Better to over-gate an unknown remote tool than to silently let it
# through as READ-only.
UNKNOWN_SOURCE_CAPABILITIES: ToolCapability = _CAP.WRITE | _CAP.EXECUTE | _CAP.NETWORK
def default_registry(specs: Iterable[ToolSpec]) -> ToolRegistry:
"""Build a registry from ``core/tools.py``'s own ``TOOL_SPECS`` (plus
``save_file``/``update_plan``, which the engines add separately), using
:data:`BUILT_IN_CAPABILITIES`. A spec with no entry in that map falls back
to :data:`UNKNOWN_SOURCE_CAPABILITIES` - the same conservative default
applied to MCP/connector tools, so a built-in nobody has classified yet
fails safe instead of silently ungated."""
registry = ToolRegistry()
for spec in specs:
capability = BUILT_IN_CAPABILITIES.get(spec.name, UNKNOWN_SOURCE_CAPABILITIES)
registry.register(ToolDescriptor.from_spec(spec, capability))
return registry
__all__ = [
"ToolRegistry",
"BUILT_IN_CAPABILITIES",
"UNKNOWN_SOURCE_CAPABILITIES",
"default_registry",
]
View File
+114
View File
@@ -0,0 +1,114 @@
"""Bản ghi "một lần chạy flow" — DTO thuần Python cho tầng domain.
Bối cảnh: ``Co4ERunManager``/``RunHandle`` cũ (``core/co4e_run_manager.py``)
trộn ba việc vào một ``QObject``: (1) dữ liệu một run cần nhớ để hiện Flow
Status, (2) logic chạy job trên ``AgentWorker``/``QThread``, và (3) logic
đọc/ghi lịch sử ra đĩa. Tách phần (1) ra thành ``RunRecord`` ở đây giúp nó độc
lập với Qt và với việc đọc/ghi đĩa — đúng quy ước ``domain/__init__.py``: domain
không được biết PySide6 tồn tại và không được chạm đĩa/mạng. Phần (2) và (3)
chuyển sang ``application/workflows/co4e_workflow_service.py``
(``Co4EWorkflowService``), nơi được phép import ``core/`` và làm việc với đĩa.
Vì sao trường ``wf`` là dict thô chứ không phải đối tượng ``Workflow``: lớp
``Workflow`` sống ở ``core/co4e.py``, và việc dựng nó từ/thành dict
(``workflow_to_dict``/``workflow_from_dict``) nằm trong module đó. Domain
không được import ``cowork_local.core.*``, nên ``RunRecord`` giữ nguyên đúng
hình dạng dữ liệu mà bản ghi lịch sử đã có sẵn trên đĩa hôm nay: một dict thô
(kết quả ``workflow_to_dict``) hoặc ``None``. Việc quy đổi dict <-> đối tượng
``Workflow`` là việc của tầng application, nơi được phép import ``core``.
Quirk giữ nguyên có chủ ý — đã bị "đóng đinh" bởi
``tests/characterization/test_co4e_run_manager_behavior.py`` (quirk #1 và #7
trong docstring đầu file đó, xem thêm ``RunHandle.to_record``/``from_record``
gốc) — ĐỪNG "dọn" các chỗ này khi đọc code dưới đây, chúng trông như bug nhưng
là hành vi đã được test khẳng định:
* ``total`` âm bị ``max(0, total)`` kẹp về 0 ngay lúc khởi tạo, không giữ
nguyên giá trị âm.
* ``from_dict()`` đổi ``status == "running"`` đọc từ đĩa thành ``"stopped"``
(lý do: app tắt giữa lúc một run đang "running" thì worker của nó đã mất
theo, nên đọc lại không còn coi là đang chạy) — nhưng ``to_dict()`` vẫn ghi
đúng ``"running"`` xuống đĩa tại thời điểm lưu. Đây là một round-trip
*không đối xứng* có chủ ý.
* ``from_dict({})``/``from_dict(None)`` mặc định ``status`` là ``"done"``
(không phải ``"running"``) — nên KHÔNG bị nhánh phía trên đổi thành
"stopped".
"""
from __future__ import annotations
from typing import Dict, Optional
class RunRecord:
"""DTO domain: trạng thái sống của một lần chạy flow, thuần dữ liệu.
Vai trò: đây là "danh từ" mà ``Co4EWorkflowService`` (application/) đọc/ghi
và mà UI Flow Status hiển thị — không có hành vi chạy worker, không đọc/ghi
đĩa. Nó ở tầng domain vì đây là quy tắc nghiệp vụ ổn định (hình dạng một
lần chạy flow cần nhớ những gì) độc lập với Qt lẫn với cơ chế lưu trữ.
"""
def __init__(self, run_id: str, wf_id: str, name: str, total: int,
plan_mode: bool, manual: bool, created_by: str = "", created_at: str = "",
project_id: str = ""):
self.id = run_id
self.wf_id = wf_id
self.name = name
self.project_id = project_id # workspace run này thuộc về (Flow Status lọc theo project)
self.total = max(0, total) # quirk cố ý: total âm bị kẹp về 0, xem docstring đầu file
self.done = 0
self.status = "running" # running | done | error | stopped
self.plan_mode = plan_mode
self.manual = manual
self.created_by = created_by
self.created_at = created_at
self.error = ""
self.node_status: Dict[str, str] = {}
self.wf: Optional[dict] = None # snapshot workflow dạng dict thô (xem docstring đầu file)
self.out_dir = "" # thư mục workspace mà run này ghi file vào
@property
def running(self) -> bool:
return self.status == "running"
def progress_text(self) -> str:
return f"{self.done}/{self.total}" if self.total else self.status
# ---- (de)serialization --------------------------------------------
def to_dict(self) -> dict:
"""Hình dạng bản ghi lịch sử trên đĩa.
PHẢI khớp đúng bộ khoá mà ``RunHandle.to_record()`` gốc
(``core/co4e_run_manager.py``) đang ghi hôm nay — file JSON lịch sử cũ
và mới dùng chung một định dạng trong lúc cả hai lớp còn chạy song
song (bản cũ chưa bị xoá).
"""
return {
"id": self.id, "wf_id": self.wf_id, "name": self.name,
"total": self.total, "done": self.done, "status": self.status,
"plan_mode": self.plan_mode, "manual": self.manual,
"created_by": self.created_by, "created_at": self.created_at,
"error": self.error, "node_status": dict(self.node_status),
"wf": self.wf, "out_dir": self.out_dir, "project_id": self.project_id,
}
@classmethod
def from_dict(cls, rec: dict) -> "RunRecord":
rec = dict(rec or {})
r = cls(str(rec.get("id", "")), str(rec.get("wf_id", "")),
rec.get("name", ""), int(rec.get("total", 0) or 0),
bool(rec.get("plan_mode")), bool(rec.get("manual")),
created_by=rec.get("created_by", ""), created_at=rec.get("created_at", ""))
r.done = int(rec.get("done", 0) or 0)
r.status = rec.get("status", "done")
# quirk cố ý (xem docstring đầu file): round-trip không đối xứng —
# "running" đọc lại từ đĩa luôn bị chốt thành "stopped".
if r.status == "running":
r.status = "stopped"
r.error = rec.get("error", "")
r.node_status = dict(rec.get("node_status") or {})
r.out_dir = rec.get("out_dir", "")
r.project_id = rec.get("project_id", "")
# Giữ nguyên dict thô -- KHONG parse thanh doi tuong Workflow o day (do
# la viec cua tang application, xem docstring dau file).
r.wf = rec.get("wf")
return r
+5 -1
View File
@@ -1 +1,5 @@
"""Domain workspaces package: immutable WorkspaceSession definitions."""
"""Domain entities for workspace/project isolation (EPIC R06)."""
from .workspace_session import WorkspaceSession
__all__ = ["WorkspaceSession"]
+96
View File
@@ -0,0 +1,96 @@
"""WorkspaceSession - an immutable snapshot of which project a turn belongs
to and where it may touch the filesystem (R06-T01).
``state.py::AppContext.active_project_id`` is a single mutable field read by
every background worker thread. ``ui/workspace_tab.py::_load_current`` writes
it (and the related ``config._project_history_dir``) on the UI thread the
moment the user switches projects - while a turn already running on a
worker thread may read either field mid-switch and end up acting on the
OTHER project's workspace/history for the rest of its run (the race
R06-T04 fixes).
The fix, same shape as R04's ``ConversationExecutionRequest``: capture the
workspace facts a turn needs ONCE, on the thread that knows which project is
selected, into one frozen object. Whatever the user does to the UI afterwards,
the turn keeps using the workspace it was handed at submit time.
Pure domain code: stdlib only, no Qt, no network. It does touch ``Path`` (not
plain strings, unlike ``ConversationExecutionRequest``) because its whole job
is path-containment checking - a snapshot with no room to answer "is this
path mine" would not replace what ``ToolContext.resolve`` currently does
inline.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Tuple
@dataclass(frozen=True)
class WorkspaceSession:
"""Everything a turn needs to know about ITS workspace, fixed at the
moment it was submitted.
Attributes:
project_id: the project this turn belongs to (``""`` when no project
is selected - e.g. the Code tab, which has no project concept).
workspace_root: the project's sandbox root (``Project.workspace_dir()``).
sandbox_dir: the ``.scratch`` subtree inside ``workspace_root`` used for
generator/helper scripts, never a final deliverable (see
``infrastructure/filesystem/file_tools.py::_flatten_rel``).
allowed_paths: every root a tool call may read/write under. Almost
always just ``(workspace_root,)``; a project with a custom
``output_dir`` outside the managed workspace tree still resolves
to exactly one root - the tuple exists so a future caller (e.g. a
step scoped to a shared input folder) can widen it without a
shape change.
"""
project_id: str
workspace_root: Path
sandbox_dir: Path
allowed_paths: Tuple[Path, ...] = field(default_factory=tuple)
def __post_init__(self) -> None:
if not self.allowed_paths:
object.__setattr__(self, "allowed_paths", (self.workspace_root,))
@classmethod
def from_project(cls, project) -> "WorkspaceSession":
"""Build a session from a ``core.projects.Project``. ``project`` is
typed loosely (not imported) so this module has no dependency on
``core/`` - the caller (``core/projects.py`` itself, or
``application/conversations``) already has the Project in hand."""
root = Path(project.workspace_dir())
return cls(project_id=project.project_id, workspace_root=root,
sandbox_dir=root / ".scratch", allowed_paths=(root,))
@classmethod
def unscoped(cls, workspace_root: Path) -> "WorkspaceSession":
"""A session for callers with no project concept (e.g. the Code tab,
which sandboxes to a plain folder rather than a ``Project``)."""
root = Path(workspace_root)
return cls(project_id="", workspace_root=root, sandbox_dir=root / ".scratch")
def is_allowed(self, path: Path) -> bool:
"""True when ``path`` resolves inside one of :attr:`allowed_paths`.
Same containment rule as ``ToolContext.resolve`` (an exact root match
or a real descendant), but side-effect-free: it reports the answer
instead of raising, so a caller (``FileWorkspaceService``, R06-T05)
can decide what "not allowed" means for its own UI instead of
catching a ``ToolError``.
"""
try:
resolved = Path(path).expanduser().resolve()
except OSError:
return False
for allowed in self.allowed_paths:
root = Path(allowed).resolve()
if resolved == root or root in resolved.parents:
return True
return False
__all__ = ["WorkspaceSession"]
+23 -3004
View File
File diff suppressed because it is too large Load Diff
+344
View File
@@ -0,0 +1,344 @@
"""Chuỗi hiển thị — phần agents_admin_tab.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"co4e.tt_flow_name": {"en": "Flow name", "ja": "フロー名", "vi": "Tên flow"},
"co4e.tt_add_step": {"en": "Add a step to the canvas", "ja": "キャンバスにステップを追加",
"vi": "Thêm một bước vào canvas"},
"co4e.tt_zoom_in": {"en": "Zoom in (Ctrl+wheel / Ctrl++)", "ja": "拡大(Ctrl+ホイール / Ctrl++)",
"vi": "Phóng to (Ctrl+lăn chuột / Ctrl++)"},
"co4e.tt_zoom_out": {"en": "Zoom out (Ctrl+wheel / Ctrl+-)", "ja": "縮小(Ctrl+ホイール / Ctrl+-)",
"vi": "Thu nhỏ (Ctrl+lăn chuột / Ctrl+-)"},
"co4e.run_bg": {"en": "Run", "ja": "実行", "vi": "Chạy"},
"co4e.tt_run_bg": {
"en": "Run the selected flow in the background — several flows run in parallel",
"ja": "選択フローをバックグラウンド実行 — 複数フローを並列実行",
"vi": "Chạy flow đã chọn ở nền — nhiều flow chạy song song"},
"co4e.running_flows": {"en": "Running flows", "ja": "実行中のフロー", "vi": "Flow đang chạy"},
"co4e.runs_tab": {"en": "Flow Status", "ja": "フロー状態", "vi": "Flow Status"},
# The flow tab strip was removed, so its pinned Flow Status tab became a
# toggle in the flow toolbar — and that page needs its own way back.
"co4e.tt_runs_tab": {
"en": "Show every flow run", "ja": "すべてのフロー実行を表示",
"vi": "Xem toàn bộ lần chạy flow"},
"co4e.back_to_flow": {"en": "Back to flow", "ja": "フローに戻る", "vi": "Về flow"},
"co4e.new_flow_ready": {
"en": "New flow — type a name, then drag agents onto the canvas",
"ja": "新しいフロー — 名前を入力し、エージェントをキャンバスへ",
"vi": "Flow mới — đặt tên rồi kéo agent vào canvas"},
"co4e.tt_back_to_flow": {
"en": "Back to the flow editor", "ja": "フローエディタに戻る",
"vi": "Quay lại màn dựng flow"},
"co4e.runs_tab_n": {"en": "Flow Status ({n})", "ja": "フロー状態 ({n})", "vi": "Flow Status ({n})"},
"co4e.runs_col_flow": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
"co4e.runs_col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"co4e.runs_col_steps": {"en": "Steps", "ja": "ステップ", "vi": "Bước"},
"co4e.runs_col_by": {"en": "Created by", "ja": "作成者", "vi": "Người tạo"},
"co4e.runs_col_at": {"en": "Created at", "ja": "作成日時", "vi": "Ngày tạo"},
"co4e.tt_runs_list": {
"en": "Live status of every running/finished flow — always up to date. Double-click a run to run that flow again.",
"ja": "実行中/完了フローのライブ状態 — 常に最新。実行をダブルクリックでそのフローを再実行。",
"vi": "Trạng thái trực tiếp của mọi flow đang chạy/đã xong — luôn mới nhất. Nhấp đúp để chạy lại flow đó."},
"co4e.flow_gone": {"en": "That flow no longer exists.", "ja": "そのフローは存在しません。",
"vi": "Flow đó không còn tồn tại."},
"co4e.rename": {"en": "Rename", "ja": "名前を変更", "vi": "Đổi tên"},
"co4e.rename_prompt": {"en": "New flow name (name it by its function / task):",
"ja": "新しいフロー名(機能/タスクで命名):",
"vi": "Tên flow mới (đặt theo chức năng / task):"},
"co4e.renamed_msg": {"en": "Renamed to: {name}", "ja": "名前変更: {name}", "vi": "Đã đổi tên: {name}"},
"co4e.duplicate": {"en": "Duplicate", "ja": "複製", "vi": "Nhân bản"},
"co4e.viewing_flow": {"en": "Viewing flow: {name}", "ja": "フロー表示: {name}", "vi": "Đang xem flow: {name}"},
"co4e.stop": {"en": "Stop", "ja": "停止", "vi": "Dừng"},
"co4e.tt_stop_run": {"en": "Stop the selected run (or all runs if none selected)",
"ja": "選択した実行を停止(未選択なら全実行)", "vi": "Dừng lần chạy đã chọn (hoặc tất cả nếu chưa chọn)"},
"co4e.clear_done": {"en": "Clear done", "ja": "完了を消去", "vi": "Xóa đã xong"},
"co4e.tt_clear_runs": {"en": "Remove finished/stopped runs from the list",
"ja": "完了/停止した実行を一覧から削除", "vi": "Bỏ các lần chạy đã xong/đã dừng khỏi danh sách"},
"co4e.select_flow": {"en": "Select a flow first.", "ja": "先にフローを選択してください。",
"vi": "Hãy chọn một flow trước."},
"co4e.delete_run": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"co4e.tt_delete_run": {"en": "Delete the selected run from the history",
"ja": "選択した実行を履歴から削除", "vi": "Xóa lần chạy đang chọn khỏi lịch sử"},
"co4e.open_run": {"en": "Open flow", "ja": "フローを開く", "vi": "Mở flow"},
"co4e.open_output": {"en": "Open output folder", "ja": "出力フォルダを開く", "vi": "Mở thư mục output"},
"co4e.open_output_link": {
"en": "📂 Open output folder", "ja": "📂 出力フォルダを開く", "vi": "📂 Mở thư mục output"},
"co4e.tt_open_workspace": {
"en": "Open the workspace folder where flow outputs are saved:\n{path}",
"ja": "フローの出力が保存されるワークスペースフォルダを開く:\n{path}",
"vi": "Mở thư mục workspace nơi lưu output của flow:\n{path}"},
"co4e.select_run": {"en": "Select a run first.", "ja": "先に実行を選択してください。",
"vi": "Hãy chọn một lần chạy trước."},
"co4e.rename_run": {"en": "Rename", "ja": "名前変更", "vi": "Đổi tên"},
"co4e.tt_rename_run": {"en": "Rename the selected flow run",
"ja": "選択した実行の名前を変更", "vi": "Đổi tên lần chạy đang chọn"},
"co4e.rename_run_label": {"en": "New flow name:", "ja": "新しいフロー名:", "vi": "Tên flow mới:"},
"co4e.run_done_title": {"en": "Flow finished", "ja": "フロー完了", "vi": "Flow đã xong"},
"co4e.run_done_popup": {
"en": "Flow \"{name}\" finished — {status}.",
"ja": "フロー「{name}」が完了しました — {status}。",
"vi": "Flow \"{name}\" đã chạy xong — {status}."},
"co4e.duplicated_msg": {"en": "Duplicated: {name}", "ja": "複製しました: {name}", "vi": "Đã nhân bản: {name}"},
"co4e.bg_started": {"en": "▶ Started in background: {name}", "ja": "▶ バックグラウンドで開始: {name}",
"vi": "▶ Đã chạy nền: {name}"},
"co4e.bg_done": {"en": "Flow '{name}': {status}", "ja": "フロー '{name}': {status}",
"vi": "Flow '{name}': {status}"},
"co4e.tool_failed": {"en": "⚠ tool failed: {name}", "ja": "⚠ ツール失敗: {name}", "vi": "⚠ tool lỗi: {name}"},
"co4e.manual_started": {"en": "▶ Manual run: {name} — advance with Run/Next step.",
"ja": "▶ 手動実行: {name} — 「実行/次へ」で進む。",
"vi": "▶ Chạy thủ công: {name} — bấm Chạy/Bước tiếp để tiến."},
"co4e.manual_step": {"en": "▶ Step {i}/{n}: {label}", "ja": "▶ ステップ {i}/{n}: {label}",
"vi": "▶ Bước {i}/{n}: {label}"},
"co4e.status.running": {"en": "running", "ja": "実行中", "vi": "đang chạy"},
"co4e.status.done": {"en": "done", "ja": "完了", "vi": "xong"},
"co4e.status.error": {"en": "error", "ja": "エラー", "vi": "lỗi"},
"co4e.status.stopped": {"en": "stopped", "ja": "停止", "vi": "đã dừng"},
"co4e.chat_placeholder": {
"en": "Chat with the flow — use /agent:<name> or /skill:<name>",
"ja": "フローとチャット — /agent:<name> または /skill:<name>",
"vi": "Chat với flow — dùng /agent:<name> hoặc /skill:<name>"},
"co4e.send": {"en": "Send", "ja": "送信", "vi": "Gửi"},
"co4e.tab_basic": {"en": "Basic", "ja": "基本", "vi": "Cơ bản"},
"co4e.tab_model_perm": {"en": "Model & Permission", "ja": "モデルと権限", "vi": "Model & Quyền"},
"co4e.tab_skills_files": {"en": "Skills & Files", "ja": "スキルとファイル", "vi": "Skills & Tệp"},
"co4e.f_label": {"en": "Label", "ja": "ラベル", "vi": "Nhãn"},
"co4e.f_role": {"en": "Role", "ja": "ロール", "vi": "Vai trò"},
"co4e.f_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"co4e.f_icon": {"en": "Icon", "ja": "アイコン", "vi": "Icon"},
"co4e.f_icon_placeholder": {"en": "icon name (optional)", "ja": "アイコン名(任意)", "vi": "tên icon (tùy chọn)"},
"co4e.f_instructions": {"en": "Instructions", "ja": "指示", "vi": "Hướng dẫn"},
"co4e.f_context": {"en": "Context", "ja": "コンテキスト", "vi": "Ngữ cảnh"},
"co4e.f_context_placeholder": {
"en": "Extra background/info for this agent or step (added to its prompt at run time).",
"ja": "このエージェント/ステップ用の追加情報(実行時にプロンプトへ追加されます)。",
"vi": "Thông tin/ngữ cảnh bổ sung cho agent hoặc step này (thêm vào prompt khi chạy)."},
"co4e.f_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"co4e.f_permission": {"en": "Permissions", "ja": "権限", "vi": "Quyền"},
"co4e.f_self_verify": {"en": "Self-verify", "ja": "自己検証", "vi": "Tự kiểm tra"},
"co4e.f_verify_rounds": {"en": "rounds", "ja": "回数", "vi": "vòng"},
"co4e.f_skills": {"en": "Skills", "ja": "スキル", "vi": "Skills"},
"co4e.f_attachments": {"en": "Attachments", "ja": "添付ファイル", "vi": "Tệp đính kèm"},
"co4e.attach_add": {"en": "Attach files", "ja": "ファイル添付", "vi": "Đính kèm tệp"},
"co4e.attach_remove": {"en": "Remove", "ja": "削除", "vi": "Bỏ"},
"co4e.f_subagents": {"en": "Parallel agents", "ja": "並列エージェント", "vi": "Agent song song"},
"co4e.perm.inherit": {"en": "Inherit", "ja": "継承", "vi": "Kế thừa"},
"co4e.perm.read-only": {"en": "Read-only", "ja": "読み取り専用", "vi": "Chỉ đọc"},
"co4e.perm.standard": {"en": "Standard", "ja": "標準", "vi": "Tiêu chuẩn"},
"co4e.perm.full": {"en": "Full", "ja": "フル", "vi": "Toàn quyền"},
"co4e.add_subagent": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"co4e.del_subagent": {"en": "Remove", "ja": "削除", "vi": "Bỏ"},
"co4e.run_this_step": {"en": "Run this step", "ja": "このステップを実行", "vi": "Chạy bước này"},
"co4e.run_from_here": {"en": "Run from here", "ja": "ここから実行", "vi": "Chạy từ đây"},
"co4e.delete_step": {"en": "Delete step", "ja": "ステップ削除", "vi": "Xóa bước"},
"co4e.load_models_tooltip": {
"en": "Load available models", "ja": "利用可能なモデルを取得", "vi": "Tải danh sách model"},
"co4e.agent_edit_title": {"en": "Edit agent", "ja": "エージェント編集", "vi": "Sửa agent"},
"co4e.agent_new_title": {"en": "New agent", "ja": "新規エージェント", "vi": "Agent mới"},
"co4e.saved_msg": {"en": "Saved flow: {name}", "ja": "フローを保存: {name}", "vi": "Đã lưu flow: {name}"},
"co4e.select_custom_agent": {
"en": "Select a custom agent first.", "ja": "先にカスタムエージェントを選択してください。",
"vi": "Hãy chọn một agent tùy chỉnh trước."},
"co4e.no_steps": {"en": "Add at least one step first.", "ja": "先にステップを追加してください。",
"vi": "Hãy thêm ít nhất một bước."},
"co4e.run_started": {"en": "▶ Running flow: {name}", "ja": "▶ フロー実行中: {name}",
"vi": "▶ Đang chạy flow: {name}"},
"co4e.run_done": {"en": "✓ Flow finished.", "ja": "✓ フロー完了。", "vi": "✓ Flow xong."},
"co4e.run_execute_phase": {
"en": "▶ Plan done — now executing…", "ja": "▶ 計画完了 — 実行中…",
"vi": "▶ Xong plan — đang thực thi…"},
"co4e.agent_not_found": {
"en": "Agent '{name}' not found.", "ja": "エージェント '{name}' が見つかりません。",
"vi": "Không tìm thấy agent '{name}'."},
# ---- agents_admin_tab.py — Admin-only agent catalog -------------------
"agents_admin.page_title": {"en": "Agents Admin", "ja": "Agents Admin", "vi": "Agents Admin"},
"agents_admin.edit_row_tooltip": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"agents_admin.delete_row_tooltip": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"agents_admin.hint": {
"en": "System-management agents shared across every machine (stored in the shared accounts folder): the help agent and Schedule Task executors. These are NOT the agents you pick in Cowork or Co4E.",
"ja": "全マシンで共有されるシステム管理用エージェント(共有フォルダーに保存):ヘルプエージェントやスケジュールタスクの実行エージェントなど。CoworkやCo4Eで選択するエージェントではありません。",
"vi": "Agent quản lý hệ thống, dùng chung mọi máy (lưu trong thư mục dùng chung): agent trợ giúp và agent chạy Schedule Task. Đây KHÔNG phải agent để chọn trong Cowork hay Co4E."},
"agents_admin.add_title": {"en": "Add agent", "ja": "エージェント追加", "vi": "Thêm agent"},
"agents_admin.edit_title": {"en": "Edit agent", "ja": "エージェント編集", "vi": "Sửa agent"},
"agents_admin.delete_title": {"en": "Delete agent", "ja": "エージェント削除", "vi": "Xóa agent"},
"agents_admin.delete_confirm": {
"en": "Delete agent \"{name}\"?", "ja": "エージェント「{name}」を削除しますか?",
"vi": "Xóa agent \"{name}\"?"},
"agents_admin.add_btn": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"agents_admin.f_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"agents_admin.f_kind": {"en": "App function", "ja": "アプリ機能", "vi": "Chức năng App"},
"agents_admin.f_prompt": {"en": "Instructions", "ja": "指示", "vi": "Chỉ dẫn"},
"agents_admin.f_prompt_placeholder": {
"en": "Extra instructions this agent always follows (optional)…",
"ja": "このエージェントが常に従う追加指示(任意)…",
"vi": "Chỉ dẫn bổ sung agent này luôn tuân theo (tùy chọn)…"},
"agents_admin.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Provider"},
"agents_admin.provider_default": {
"en": "(machine's active provider)", "ja": "(各マシンの現在のプロバイダー)",
"vi": "(provider hiện tại của máy)"},
"agents_admin.f_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"agents_admin.f_model_placeholder": {
"en": "empty = each machine's Settings model (currently: {model})",
"ja": "空欄 = 各マシンの設定モデル(現在: {model})",
"vi": "để trống = model trong Settings của từng máy (hiện tại: {model})"},
"agents_admin.load_models_tooltip": {
"en": "Fetch this provider's real model list so you can pick a specific one from the dropdown.",
"ja": "このプロバイダーの実際のモデル一覧を取得し、ドロップダウンから選択できるようにします。",
"vi": "Lấy danh sách model thực tế của provider này để chọn từ dropdown."},
"agents_admin.load_models_empty": {
"en": "No models were returned — check the provider's settings/connection.",
"ja": "モデルが取得できませんでした。プロバイダーの設定/接続を確認してください。",
"vi": "Không lấy được model nào — kiểm tra lại cấu hình/kết nối provider."},
"agents_admin.f_enabled": {"en": "Enabled", "ja": "有効", "vi": "Kích hoạt"},
"agents_admin.col_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"agents_admin.col_kind": {"en": "Function", "ja": "機能", "vi": "Chức năng"},
"agents_admin.col_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"agents_admin.col_enabled": {"en": "Enabled", "ja": "有効", "vi": "Kích hoạt"},
"agents_admin.col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"agents_admin.col_updated": {"en": "Updated", "ja": "更新", "vi": "Cập nhật"},
"agents_admin.check_btn": {"en": "Check all", "ja": "すべてチェック", "vi": "Kiểm tra tất cả"},
"agents_admin.check_tooltip": {
"en": "Check each agent's effective provider/model connectivity",
"ja": "各エージェントの実効プロバイダ/モデルの接続性を確認",
"vi": "Kiểm tra kết nối provider/model hiệu lực của từng agent"},
"agents_admin.status_unchecked": {"en": "— (not checked)", "ja": "— (未チェック)", "vi": "— (chưa kiểm tra)"},
"agents_admin.status_unchecked_tip": {
"en": "Press Check to test whether this agent's provider/model is reachable",
"ja": "「チェック」でこのエージェントのプロバイダ/モデルへの到達性をテスト",
"vi": "Nhấn Kiểm tra để test agent này có kết nối được provider/model không"},
"agents_admin.status_checking": {"en": "checking…", "ja": "確認中…", "vi": "đang kiểm tra…"},
"agents_admin.status_ok": {"en": "Active", "ja": "稼働中", "vi": "Hoạt động"},
"agents_admin.status_bad": {"en": "Error", "ja": "エラー", "vi": "Lỗi"},
"agents_admin.default_model": {
"en": "(Settings default: {model})", "ja": "(設定既定: {model})",
"vi": "(mặc định Settings: {model})"},
"agents_admin.kind.search": {"en": "Search", "ja": "検索", "vi": "Tìm kiếm"},
"agents_admin.kind.monitor": {"en": "Monitoring", "ja": "監視", "vi": "Giám sát"},
"agents_admin.kind.cowork": {"en": "Cowork chat", "ja": "Cowork チャット", "vi": "Cowork chat"},
"agents_admin.kind.graphrag": {"en": "GraphRAG / Knowledge", "ja": "GraphRAG / ナレッジ", "vi": "GraphRAG / Tri thức"},
"agents_admin.kind.schedule": {"en": "Schedule Task", "ja": "スケジュールタスク", "vi": "Schedule Task"},
"agents_admin.kind.security": {"en": "Security", "ja": "セキュリティ", "vi": "Bảo mật"},
"agents_admin.kind.help": {"en": "App Help", "ja": "アプリヘルプ", "vi": "Trợ giúp App"},
"monitoring.filter_placeholder": {
"en": "Filter rows (or type a question and press )…",
"ja": "行をフィルター(質問を入力しても可)…",
"vi": "Lọc dòng (hoặc gõ câu hỏi rồi bấm )…"},
"monitoring.ai_filter_btn": {"en": "AI", "ja": "AI", "vi": "AI"},
"monitoring.pricing_title": {
"en": "Model pricing (USD / 1M tokens)", "ja": "モデル価格表 (USD / 100万トークン)",
"vi": "Bảng giá model (USD / 1 triệu token)"},
"monitoring.pricing_col_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"monitoring.pricing_col_in": {"en": "In", "ja": "入力", "vi": "In"},
"monitoring.pricing_col_out": {"en": "Out", "ja": "出力", "vi": "Out"},
"monitoring.pricing_col_cache": {"en": "Cache", "ja": "キャッシュ", "vi": "Cache"},
"monitoring.pricing_add_btn": {"en": "Add model", "ja": "モデル追加", "vi": "Thêm model"},
"monitoring.pricing_del_btn": {"en": "Remove", "ja": "削除", "vi": "Xóa"},
"monitoring.pricing_link_label": {
"en": "Reference:", "ja": "参考リンク:", "vi": "Link tham khảo:"},
"monitoring.pricing_no_link": {
"en": "No reference link set (Settings → Parameter → Pricing reference link).",
"ja": "参考リンク未設定(設定 → Parameter)。",
"vi": "Chưa đặt link tham khảo (Settings → Parameter → Link bảng giá)."},
"monitoring.ai_filter_tooltip": {
"en": "AI turns your question into a filter keyword (e.g. \"which commands failed today?\").",
"ja": "質問をAIがフィルターキーワードに変換します。",
"vi": "AI chuyển câu hỏi thành từ khóa lọc (vd: \"hôm nay lệnh nào bị lỗi?\")."},
"monitoring.security_detail_title": {
"en": "Event details", "ja": "イベント詳細", "vi": "Chi tiết sự kiện"},
"monitoring.security_detail_close": {
"en": "Close", "ja": "閉じる", "vi": "Đóng"},
"monitoring.security_events_title": {
"en": "Security Events", "ja": "セキュリティイベント", "vi": "Sự kiện bảo mật"},
"monitoring.mcp_history_title": {
"en": "MCP Call History", "ja": "MCP 呼び出し履歴", "vi": "Lịch sử gọi MCP"},
"monitoring.action_logs_title": {
"en": "Action Logs", "ja": "アクションログ", "vi": "Nhật ký hành động"},
"monitoring.col_detail_block": {
"en": "Block detail", "ja": "ブロック詳細", "vi": "Chi tiết chặn"},
# ---- event-detail panel (ui-audit_v2.html openDetail()) --------------
"monitoring.detail_section_general": {
"en": "General info", "ja": "基本情報", "vi": "Thông tin chung"},
"monitoring.detail_section_action": {
"en": "Action", "ja": "アクション", "vi": "Hành động"},
"monitoring.detail_section_metadata": {
"en": "Metadata", "ja": "メタデータ", "vi": "Metadata"},
"monitoring.detail_type": {"en": "Type", "ja": "種類", "vi": "Loại"},
"monitoring.detail_status": {"en": "Status", "ja": "ステータス", "vi": "Trạng thái"},
"monitoring.detail_event_id": {"en": "Event ID", "ja": "イベントID", "vi": "Event ID"},
"monitoring.detail_policy": {"en": "Policy", "ja": "ポリシー", "vi": "Policy"},
"monitoring.detail_severity": {"en": "Severity", "ja": "重大度", "vi": "Severity"},
"monitoring.detail_copy": {"en": "Copy", "ja": "コピー", "vi": "Copy"},
"monitoring.detail_copied": {"en": "Copied", "ja": "コピー済み", "vi": "Đã copy"},
# Trạng thái pill — which rule fired, phrased as the enforcement outcome
# (distinct wording from the Loại/action_* labels below, matching
# ui-audit_v2.html's statusInfo() vs actionLabel).
"monitoring.status_blocked": {"en": "Blocked", "ja": "ブロック済み", "vi": "Đã chặn"},
"monitoring.status_path": {"en": "Path blocked", "ja": "パスをブロック", "vi": "Path chặn"},
"monitoring.status_network": {"en": "Network blocked", "ja": "ネットワークをブロック", "vi": "Mạng chặn"},
"monitoring.status_secret": {"en": "Secret leaked", "ja": "シークレット漏洩", "vi": "Bí mật lộ"},
"monitoring.status_ok": {"en": "Succeeded", "ja": "成功", "vi": "Thành công"},
"monitoring.status_failed": {"en": "Failed", "ja": "失敗", "vi": "Thất bại"},
"monitoring.severity_critical": {"en": "CRITICAL", "ja": "CRITICAL", "vi": "CRITICAL"},
"monitoring.severity_medium": {"en": "MEDIUM", "ja": "MEDIUM", "vi": "MEDIUM"},
"monitoring.severity_info": {"en": "INFO", "ja": "INFO", "vi": "INFO"},
# Loại field — a human label for the raw event name (audit_log ``name``).
"monitoring.action_prompt": {"en": "Risky prompt", "ja": "危険なプロンプト", "vi": "Prompt rủi ro"},
"monitoring.action_dangerous_command": {
"en": "Dangerous command", "ja": "危険なコマンド", "vi": "Lệnh nguy hiểm"},
"monitoring.action_install_package": {
"en": "Package install", "ja": "パッケージインストール", "vi": "Cài đặt gói"},
"monitoring.action_path_outside_sandbox": {
"en": "Path outside sandbox", "ja": "サンドボックス外のパス", "vi": "Path ngoài sandbox"},
"monitoring.action_network_blocked": {
"en": "Network blocked", "ja": "ネットワークブロック", "vi": "Mạng bị chặn"},
"monitoring.action_secret_in_output": {
"en": "Secret disclosed", "ja": "シークレット漏洩", "vi": "Tiết lộ bí mật"},
"monitoring.overview_activity_title": {
"en": "Recent log", "ja": "最近のログ", "vi": "Nhật ký gần đây"},
"monitoring.overview_no_activity": {
"en": "No activity yet.", "ja": "まだアクティビティはありません。", "vi": "Chưa có hoạt động nào."},
"monitoring.overview_resource_title": {
"en": "Resources", "ja": "リソース", "vi": "Tài nguyên"},
"monitoring.overview_res_cpu": {"en": "CPU", "ja": "CPU", "vi": "CPU"},
"monitoring.overview_res_mem": {"en": "Memory", "ja": "メモリ", "vi": "Bộ nhớ"},
"monitoring.overview_res_disk": {"en": "Disk I/O", "ja": "ディスク I/O", "vi": "Disk I/O"},
"monitoring.overview_res_network": {"en": "Network", "ja": "ネットワーク", "vi": "Mạng"},
# ---- model pricing list (Overview, beside the resource group) ----
"monitoring.pricing_title": {"en": "Model pricing", "ja": "モデル料金", "vi": "Bảng giá model"},
"monitoring.pricing_currency": {"en": "Currency", "ja": "通貨", "vi": "Tiền tệ"},
"monitoring.pricing_import": {"en": "Import", "ja": "取込", "vi": "Nhập"},
"monitoring.pricing_export": {"en": "Template", "ja": "テンプレート", "vi": "Mẫu"},
"monitoring.pricing_add": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"monitoring.pricing_autolink": {"en": "Auto-link", "ja": "自動取得", "vi": "Tự lấy"},
"monitoring.pricing_delete": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"monitoring.pricing_add_prompt": {"en": "Model name:", "ja": "モデル名:", "vi": "Tên model:"},
"monitoring.pricing_imported": {"en": "Imported {n} model prices.", "ja": "{n} 件の料金を取込。",
"vi": "Đã nhập {n} dòng giá."},
"monitoring.pricing_exported": {"en": "Price template exported.", "ja": "料金テンプレートを出力。",
"vi": "Đã xuất mẫu bảng giá."},
"monitoring.pricing_linked": {"en": "Linked {n} models from providers.",
"ja": "プロバイダから {n} モデルを取得。",
"vi": "Đã lấy {n} model từ provider."},
"monitoring.pricing_col_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"monitoring.pricing_col_context": {"en": "Context", "ja": "コンテキスト", "vi": "Context"},
"monitoring.pricing_col_maxout": {"en": "Max output", "ja": "最大出力", "vi": "Max output"},
"monitoring.pricing_col_input": {"en": "Input price", "ja": "入力単価", "vi": "Giá input"},
"monitoring.pricing_col_output": {"en": "Output price", "ja": "出力単価", "vi": "Giá output"},
"monitoring.overview_sandbox_details_title": {
# One section now, holding both the sandbox facts and the permissions.
"en": "Sandbox & Permissions", "ja": "サンドボックスと権限",
"vi": "Sandbox & Quyền"},
}
+342
View File
@@ -0,0 +1,342 @@
"""Chuỗi hiển thị — phần composer.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"chatpanel.agent_tooltip": {
"en": "Model/agent for THIS tab — independent of the other tab",
"ja": "このタブ専用のモデル/エージェント(他のタブとは独立)",
"vi": "Model/agent riêng cho tab này — độc lập với tab kia"},
"chatpanel.agent_list_error": {
"en": "Could not load the model list: {err}", "ja": "モデル一覧を読み込めませんでした: {err}",
"vi": "Không tải được danh sách model: {err}"},
"chatpanel.compress_btn": {"en": "Compress", "ja": "圧縮", "vi": "Nén"},
"chatpanel.compress_tooltip": {
"en": "Compress the conversation: trim old history to cut tokens (avoid exceeding the context limit)",
"ja": "会話を圧縮:古い履歴を減らしてトークンを削減(コンテキスト上限超過を回避)",
"vi": "Nén hội thoại: bỏ bớt lịch sử cũ để giảm token (tránh lỗi vượt giới hạn context)"},
"chatpanel.files_header": {"en": "Files", "ja": "ファイル", "vi": "Files"},
"chatpanel.collapse_files_tooltip": {
"en": "Collapse the Files panel", "ja": "ファイルパネルを折りたたむ", "vi": "Thu gọn bảng Files"},
"chatpanel.expand_files_tooltip": {
"en": "Click to expand the Files panel", "ja": "クリックしてファイルパネルを展開",
"vi": "Bấm để mở lại bảng Files"},
"chatpanel.compress_busy": {
"en": "Running — stop or wait before compressing.", "ja": "実行中です。停止するか完了を待ってから圧縮してください。",
"vi": "Đang chạy — dừng hoặc đợi xong rồi hãy nén."},
"chatpanel.compress_short": {
"en": "Conversation is already short — no need to compress.",
"ja": "会話はすでに短いため圧縮の必要はありません。",
"vi": "Hội thoại đã ngắn — không cần nén."},
"chatpanel.compress_done": {
"en": "Compressed: dropped {cut} old messages, kept the last {keep} turns to cut tokens.",
"ja": "圧縮しました:古いメッセージ{cut}件を削除し、直近{keep}ターンを保持してトークンを削減。",
"vi": "Đã nén hội thoại: bỏ {cut} tin cũ, giữ {keep} lượt gần nhất để giảm token."},
"chatpanel.compress_reduced": {
"en": "Compressed to {pct}% of the original ({n} old messages digested).",
"ja": "元の {pct}% まで圧縮(古いメッセージ {n} 件を要約)。",
"vi": "Đã nén còn {pct}% so với ban đầu ({n} tin cũ được tóm gọn)."},
"chatpanel.compress_digest_header": {
"en": "Compressed summary of {n} earlier messages",
"ja": "以前のメッセージ {n} 件の要約",
"vi": "Tóm tắt nén của {n} tin nhắn trước đó"},
"chatpanel.delete_confirm_title": {"en": "Delete message", "ja": "メッセージを削除", "vi": "Xóa tin nhắn"},
"chatpanel.delete_confirm_files": {
"en": "Delete this message and its {n} input/output file(s)?\n\n{preview}",
"ja": "このメッセージと入出力ファイル{n}件を削除しますか?\n\n{preview}",
"vi": "Xóa tin nhắn này và {n} tệp input/output của nó?\n\n{preview}"},
"chatpanel.delete_confirm_plain": {"en": "Delete this message?", "ja": "このメッセージを削除しますか?", "vi": "Xóa tin nhắn này?"},
"chatpanel.delete_done": {
"en": "Message and its files deleted.", "ja": "メッセージとファイルを削除しました。",
"vi": "Đã xóa tin nhắn và các tệp liên quan."},
"chatpanel.working": {"en": "{name}: working…", "ja": "{name}: 処理中…", "vi": "{name}: đang xử lý…"},
"chatpanel.done": {"en": "{name}: done.", "ja": "{name}: 完了。", "vi": "{name}: xong."},
"chatpanel.failed": {"en": "{name}: error.", "ja": "{name}: エラー。", "vi": "{name}: lỗi."},
"chatpanel.stopping": {"en": "{name}: stopping…", "ja": "{name}: 停止中…", "vi": "{name}: đang dừng…"},
"chatpanel.attach_limit": {
"en": "Max {n} attachments — extra files were skipped.",
"ja": "添付は最大{n}件です。超過分はスキップされました。",
"vi": "Tối đa {n} tệp đính kèm — bỏ qua phần dư."},
"chatpanel.attached_hint": {"en": "Attached: {names}", "ja": "添付: {names}", "vi": "Đã đính kèm: {names}"},
"chatpanel.skills_updated": {"en": "Skills updated.", "ja": "スキルを更新しました。", "vi": "Đã cập nhật skill."},
"chatpanel.new_files_detected": {
"en": "New file(s) detected in output folder: {names} ({n} file(s)). They will be auto-loaded as input on the next message.",
"ja": "出力フォルダに新しいファイルを検出しました: {names} ({n}ファイル)。次のメッセージで自動的に入力として読み込まれます。",
"vi": "Phát hiện tệp mới trong thư mục đầu ra: {names} ({n} tệp). Chúng sẽ được tự động tải làm dữ liệu đầu vào ở tin nhắn tiếp theo.",
},
# ---- composer.py -----------------------------------------------
"composer.placeholder_default": {
"en": "Type a message… (Enter to send, Shift+Enter for newline)",
"ja": "メッセージを入力…(Enterで送信、Shift+Enterで改行)",
"vi": "Nhập tin nhắn… (Enter để gửi, Shift+Enter xuống dòng)"},
"composer.placeholder_cowork": {
"en": "Type a request or attach a file to process… (Enter to send)",
"ja": "依頼内容を入力するかファイルを添付…(Enterで送信)",
"vi": "Nhập yêu cầu hoặc đính kèm tệp để xử lí… (Enter để gửi)"},
"composer.placeholder_code": {
"en": "Assign a task to the Code agent… (Enter to send)",
"ja": "Code エージェントにタスクを指示…(Enterで送信)",
"vi": "Giao việc cho Code agent… (Enter để gửi)"},
"composer.queue_label": {"en": "Queue ({n})", "ja": "キュー ({n})", "vi": "Hàng đợi ({n})"},
"composer.queue_tooltip": {
"en": "Double-click to remove a queued message", "ja": "ダブルクリックでキューから削除",
"vi": "Nhấp đúp để xoá một tin nhắn khỏi hàng đợi"},
"composer.attachments_label": {"en": "Attachments ({n})", "ja": "添付ファイル ({n})", "vi": "Tệp đính kèm ({n})"},
"composer.attachments_tooltip": {
"en": "Click on a chip to remove a file added by mistake",
"ja": "誤って追加したファイルは で削除できます",
"vi": "Bấm trên thẻ để gỡ tệp đính kèm nhầm"},
"composer.remove_tooltip": {
"en": "Remove this file (added by mistake)", "ja": "このファイルを削除(誤って追加)",
"vi": "Gỡ tệp này (đính kèm nhầm)"},
"composer.attach_btn_tooltip": {
"en": "Attach images or files (you can also paste or drag them in)",
"ja": "画像やファイルを添付(貼り付け・ドラッグも可)",
"vi": "Đính kèm ảnh hoặc tệp (có thể dán hoặc kéo-thả vào)"},
"composer.send": {"en": "Send", "ja": "送信", "vi": "Gửi"},
"composer.queue_btn": {"en": "Queue", "ja": "キューに追加", "vi": "Thêm vào hàng đợi"},
"composer.stop": {"en": "Stop", "ja": "停止", "vi": "Dừng"},
"composer.attach_dialog_title": {"en": "Attach files / images", "ja": "ファイル/画像を添付", "vi": "Đính kèm tệp / ảnh"},
"composer.attach_dialog_filter": {
"en": "Files (*.*);;Images (*.png *.jpg *.jpeg *.gif *.bmp *.webp)",
"ja": "ファイル (*.*);;画像 (*.png *.jpg *.jpeg *.gif *.bmp *.webp)",
"vi": "Tệp (*.*);;Ảnh (*.png *.jpg *.jpeg *.gif *.bmp *.webp)"},
"composer.no_skills": {"en": " (no skills yet)", "ja": " (スキルはまだありません)", "vi": " (chưa có skill nào)"},
"composer.no_agents": {"en": " (no agents found)", "ja": " (エージェントが見つかりません)", "vi": " (không tìm thấy agent)"},
"composer.manage_skills": {"en": "Manage skills…", "ja": "スキルを管理…", "vi": "Quản lý skill…"},
# ---- schedule_task_tab.py / task_editor_dialog.py -------------------
"schedtask.title": {"en": "Schedule Task", "ja": "Schedule Task", "vi": "Schedule Task"},
"schedtask.view.kanban": {"en": "Kanban", "ja": "Kanban", "vi": "Kanban"},
"schedtask.view.calendar": {"en": "Calendar", "ja": "カレンダー", "vi": "Lịch"},
"schedtask.no_title": {"en": "(untitled)", "ja": "(無題)", "vi": "(chưa có tên)"},
"schedtask.cal_today": {"en": "Today", "ja": "今日", "vi": "Hôm nay"},
"schedtask.cal_prev": {"en": "Previous", "ja": "前へ", "vi": "Trước"},
"schedtask.cal_next": {"en": "Next", "ja": "次へ", "vi": "Sau"},
"schedtask.cal_gran.week": {"en": "Week", "ja": "週", "vi": "Tuần"},
"schedtask.cal_gran.month": {"en": "Month", "ja": "月", "vi": "Tháng"},
"schedtask.cal_gran.year": {"en": "Year", "ja": "年", "vi": "Năm"},
"schedtask.cal_weekday.mon": {"en": "Mon", "ja": "月", "vi": "T2"},
"schedtask.cal_weekday.tue": {"en": "Tue", "ja": "火", "vi": "T3"},
"schedtask.cal_weekday.wed": {"en": "Wed", "ja": "水", "vi": "T4"},
"schedtask.cal_weekday.thu": {"en": "Thu", "ja": "木", "vi": "T5"},
"schedtask.cal_weekday.fri": {"en": "Fri", "ja": "金", "vi": "T6"},
"schedtask.cal_weekday.sat": {"en": "Sat", "ja": "土", "vi": "T7"},
"schedtask.cal_weekday.sun": {"en": "Sun", "ja": "日", "vi": "CN"},
"schedtask.cal_month_count": {"en": "{month} — {n} task(s)", "ja": "{month} — {n} 件",
"vi": "{month} — {n} task"},
"schedtask.search_ph": {"en": "Search tasks…", "ja": "タスクを検索…", "vi": "Tìm task…"},
"schedtask.filter_all": {"en": "All types", "ja": "すべての種類", "vi": "Mọi loại"},
"schedtask.add_btn": {"en": "Add Task", "ja": "タスク追加", "vi": "Thêm Task"},
"schedtask.ai_btn": {"en": "AI Create Task", "ja": "AIでタスク作成", "vi": "AI tạo Task"},
"schedtask.ai_tooltip": {
"en": "Describe what you want in natural language — AI proposes tasks/schedule/chain, you confirm before anything is created.",
"ja": "自然文で説明すると、AIがタスク・スケジュール・チェーンを提案します。確認後に作成されます。",
"vi": "Mô tả bằng ngôn ngữ tự nhiên — AI đề xuất task/lịch/chuỗi, bạn xác nhận rồi mới tạo."},
"schedtask.no_tasks": {"en": "No tasks", "ja": "タスクなし", "vi": "No tasks"},
"schedtask.no_schedule": {"en": "No schedule", "ja": "スケジュールなし", "vi": "Chưa đặt lịch"},
"schedtask.last_success": {"en": "Last: Success", "ja": "前回: 成功", "vi": "Lần cuối: Thành công"},
"schedtask.last_failed": {"en": "Last: Failed", "ja": "前回: 失敗", "vi": "Lần cuối: Lỗi"},
"schedtask.last_never": {"en": "Last: not run", "ja": "前回: 未実行", "vi": "Lần cuối: chưa chạy"},
"schedtask.status.backlog": {"en": "Backlog", "ja": "Backlog", "vi": "Backlog"},
"schedtask.status.scheduled": {"en": "Scheduled", "ja": "Scheduled", "vi": "Scheduled"},
"schedtask.status.running": {"en": "Running", "ja": "Running", "vi": "Running"},
"schedtask.status.waiting_input": {"en": "Waiting Input", "ja": "Waiting Input", "vi": "Waiting Input"},
"schedtask.status.done": {"en": "Done", "ja": "Done", "vi": "Done"},
"schedtask.status.failed": {"en": "Failed", "ja": "Failed", "vi": "Failed"},
"schedtask.status.paused": {"en": "Paused", "ja": "Paused", "vi": "Paused"},
"schedtask.type.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"schedtask.type.co4e_code": {"en": "Code", "ja": "Code", "vi": "Code"},
"schedtask.type.flow": {"en": "Flow", "ja": "Flow", "vi": "Flow"},
"schedtask.type.script": {"en": "Script", "ja": "Script", "vi": "Script"},
"schedtask.type.manual": {"en": "Manual", "ja": "Manual", "vi": "Manual"},
"schedtask.priority.low": {"en": "Low", "ja": "低", "vi": "Thấp"},
"schedtask.priority.medium": {"en": "Medium", "ja": "中", "vi": "Trung bình"},
"schedtask.priority.high": {"en": "High", "ja": "高", "vi": "Cao"},
"schedtask.priority.critical": {"en": "Critical", "ja": "最重要", "vi": "Khẩn cấp"},
"schedtask.menu_run": {"en": "Run now", "ja": "今すぐ実行", "vi": "Chạy ngay"},
"schedtask.menu_edit": {"en": "Edit task", "ja": "タスクを編集", "vi": "Sửa task"},
"schedtask.menu_duplicate": {"en": "Duplicate task", "ja": "タスクを複製", "vi": "Nhân bản task"},
"schedtask.menu_pause": {"en": "Pause", "ja": "一時停止", "vi": "Tạm dừng"},
"schedtask.menu_resume": {"en": "Resume", "ja": "再開", "vi": "Tiếp tục"},
"schedtask.menu_logs": {"en": "View logs", "ja": "ログを表示", "vi": "Xem log"},
"schedtask.menu_history": {"en": "Run history…", "ja": "実行履歴…", "vi": "Lịch sử chạy…"},
"schedtask.hist_hint": {
"en": "Double-click a row to open that run's artifact folder.",
"ja": "行をダブルクリックすると、その実行のフォルダを開きます。",
"vi": "Double-click một dòng để mở thư mục artifact của lần chạy đó."},
"schedtask.hist_col_time": {"en": "Finished at", "ja": "完了時刻", "vi": "Hoàn thành lúc"},
"schedtask.hist_col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"schedtask.hist_col_run": {"en": "Run ID", "ja": "実行ID", "vi": "Run ID"},
"schedtask.hist_col_error": {"en": "Error", "ja": "エラー", "vi": "Lỗi"},
"schedtask.menu_create_next": {
"en": "Create next task from output", "ja": "出力から次タスクを作成",
"vi": "Tạo task tiếp theo từ output"},
"schedtask.menu_delete": {"en": "Delete task", "ja": "タスクを削除", "vi": "Xóa task"},
"schedtask.delete_confirm": {"en": "Delete '{title}'?", "ja": "「{title}」を削除しますか?", "vi": "Xóa '{title}'?"},
"schedtask.menu_delete_selected": {"en": "Delete {n} selected", "ja": "選択した{n}件を削除", "vi": "Xóa {n} task đã chọn"},
"schedtask.delete_multi_confirm": {
"en": "Delete {n} selected tasks? This cannot be undone.",
"ja": "選択した{n}件のタスクを削除しますか?元に戻せません。",
"vi": "Xóa {n} task đã chọn? Không thể hoàn tác."},
"schedtask.msg_created": {"en": "Task created.", "ja": "タスクを作成しました。", "vi": "Đã tạo task."},
"schedtask.msg_running": {"en": "Running: {title}", "ja": "実行中: {title}", "vi": "Đang chạy: {title}"},
"schedtask.msg_manual_norun": {
"en": "Manual tasks are for tracking only — they don't execute.",
"ja": "Manualタスクは管理用のため実行されません。",
"vi": "Task Manual chỉ để quản lý — không tự chạy."},
"schedtask.msg_no_scheduler": {"en": "Scheduler not available.", "ja": "スケジューラーが利用できません。", "vi": "Scheduler chưa sẵn sàng."},
"schedtask.msg_ai_created": {"en": "Created {n} task(s) from AI plan.", "ja": "AI提案から{n}件のタスクを作成しました。", "vi": "Đã tạo {n} task từ đề xuất AI."},
"schedtask.no_runs_yet": {"en": "This task has not run yet.", "ja": "このタスクはまだ実行されていません。", "vi": "Task này chưa chạy lần nào."},
"schedtask.next_of": {"en": "Next: {title}", "ja": "次: {title}", "vi": "Tiếp theo: {title}"},
# editor
"schedtask.editor_title_new": {"en": "Add Task", "ja": "タスク追加", "vi": "Thêm Task"},
"schedtask.editor_title_edit": {"en": "Edit Task", "ja": "タスク編集", "vi": "Sửa Task"},
"schedtask.f_title": {"en": "Title", "ja": "タイトル", "vi": "Tiêu đề"},
"schedtask.f_desc": {"en": "Description", "ja": "説明", "vi": "Mô tả"},
"schedtask.f_type": {"en": "Task type", "ja": "タスク種別", "vi": "Loại task"},
"schedtask.f_workspace": {"en": "Workspace", "ja": "ワークスペース", "vi": "Workspace"},
"schedtask.no_workspace": {"en": "— No workspace —", "ja": "— ワークスペースなし —", "vi": "— Không có workspace —"},
"schedtask.f_agent": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
"schedtask.no_agent": {"en": "— No agent preset —", "ja": "— エージェントなし —", "vi": "— Không dùng agent —"},
"schedtask.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Provider"},
"schedtask.provider_default": {
"en": "— Default (Settings) —", "ja": "— 既定(設定)—", "vi": "— Mặc định (Settings) —"},
"schedtask.f_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"schedtask.model_placeholder": {
"en": "Default model (leave blank to use Settings)",
"ja": "既定のモデル(空欄で設定を使用)",
"vi": "Model mặc định (để trống dùng Settings)"},
"schedtask.load_models_tooltip": {
"en": "Fetch this provider's available models",
"ja": "このプロバイダーの利用可能なモデルを取得",
"vi": "Tải danh sách model của provider này"},
"schedtask.load_models_empty": {
"en": "No models could be loaded. Check the provider/API key in Settings.",
"ja": "モデルを取得できませんでした。設定のプロバイダー/APIキーを確認してください。",
"vi": "Không tải được model nào. Kiểm tra provider/API key trong Settings."},
"schedtask.f_skill": {"en": "Skill", "ja": "スキル", "vi": "Skill"},
"schedtask.no_skill": {"en": "— No skill —", "ja": "— スキルなし —", "vi": "— Không dùng skill —"},
"schedtask.hint_provider": {
"en": "Which AI provider runs this task. Leave as Default to use the machine's Settings provider.",
"ja": "このタスクを実行するAIプロバイダー。既定のままにすると設定のプロバイダーを使用します。",
"vi": "Provider AI chạy task này. Để Mặc định để dùng provider trong Settings."},
"schedtask.hint_model": {
"en": "Model to run this task. Leave blank to use the provider's Settings model; click the button to load the real list.",
"ja": "このタスクを実行するモデル。空欄で設定のモデルを使用。ボタンで実際の一覧を取得します。",
"vi": "Model chạy task này. Để trống dùng model trong Settings; bấm nút để tải danh sách thực."},
"schedtask.hint_skill": {
"en": "Apply a saved skill's instructions to this task's run (its guidance is prepended to the prompt).",
"ja": "保存済みスキルの指示をこのタスクの実行に適用します(プロンプトの先頭に追加されます)。",
"vi": "Áp dụng hướng dẫn của một skill đã lưu vào lần chạy task này (được thêm vào đầu prompt)."},
"schedtask.hint_workspace": {
"en": "The project/workspace this task's agent runs in — its sandbox folder and shared instructions apply.",
"ja": "このタスクのエージェントが実行されるプロジェクト/ワークスペース。そのサンドボックスフォルダと共有指示が適用されます。",
"vi": "Project/workspace mà agent của task này sẽ chạy trong đó — áp dụng sandbox và hướng dẫn chung của project."},
"schedtask.f_priority": {"en": "Priority", "ja": "優先度", "vi": "Độ ưu tiên"},
"schedtask.f_status": {"en": "Status", "ja": "ステータス", "vi": "Trạng thái"},
"schedtask.f_script": {"en": "Script command", "ja": "スクリプトコマンド", "vi": "Lệnh script"},
"schedtask.script_placeholder": {
"en": "(script tasks only) e.g. python report.py", "ja": "(Scriptタスクのみ)例: python report.py",
"vi": "(chỉ task Script) vd: python report.py"},
# The title/description block at the top of the Task editor had no name
# either — needed once the index had to list it.
"schedtask.g_basic": {"en": "Basics", "ja": "基本", "vi": "Thông tin chung"},
# The three steps the editor is split into: what to do, when, and what it
# connects to. Each holds the same group boxes as before.
"schedtask.step_content": {"en": "Content", "ja": "内容", "vi": "Nội dung"},
"schedtask.step_schedule": {"en": "Schedule", "ja": "スケジュール", "vi": "Lịch chạy"},
"schedtask.step_link": {"en": "Links", "ja": "連携", "vi": "Liên kết"},
"schedtask.g_schedule": {"en": "Schedule Setup", "ja": "スケジュール設定", "vi": "Thiết lập lịch chạy"},
"schedtask.sched_enable": {"en": "Enable schedule", "ja": "スケジュールを有効化", "vi": "Bật lịch chạy"},
"schedtask.f_run_at": {"en": "Run at", "ja": "実行日時", "vi": "Chạy lúc"},
"schedtask.f_repeat": {"en": "Repeat", "ja": "繰り返し", "vi": "Lặp lại"},
"schedtask.repeat.none": {"en": "None (one-time)", "ja": "なし(1回のみ)", "vi": "Không (chạy 1 lần)"},
"schedtask.repeat.daily": {"en": "Daily", "ja": "毎日", "vi": "Hằng ngày"},
"schedtask.repeat.weekly": {"en": "Weekly", "ja": "毎週", "vi": "Hằng tuần"},
"schedtask.repeat.monthly": {"en": "Monthly", "ja": "毎月", "vi": "Hằng tháng"},
"schedtask.repeat.cron": {"en": "Cron expression", "ja": "Cron式", "vi": "Cron expression"},
"schedtask.f_task_mode": {"en": "Task type", "ja": "タスク種別", "vi": "Loại task"},
# Run kind: an AI agent vs a saved Co4E flow + multi-format import
"schedtask.f_run_kind": {"en": "Run", "ja": "実行対象", "vi": "Chạy"},
"schedtask.kind_agent": {"en": "AI agent (Cowork)", "ja": "AIエージェント(Cowork)",
"vi": "AI agent (Cowork)"},
"schedtask.kind_flow": {"en": "Co4E flow", "ja": "Co4E フロー", "vi": "Co4E flow"},
"schedtask.hint_run_kind": {
"en": "AI agent = run one Cowork agent with the chosen model. Co4E flow = run a whole "
"saved node-graph flow, step by step, in the sandbox.",
"ja": "AIエージェント=選択モデルで Cowork エージェントを1つ実行。Co4E フロー=保存済みの"
"ノードグラフ全体をサンドボックスで順に実行。",
"vi": "AI agent = chạy một agent Cowork với model đã chọn. Co4E flow = chạy cả một flow "
"node-graph đã lưu, tuần tự, trong sandbox."},
"schedtask.f_flow": {"en": "Co4E flow", "ja": "Co4E フロー", "vi": "Co4E flow"},
"schedtask.hint_flow": {
"en": "Which saved Co4E flow this task runs (built-in or your own).",
"ja": "このタスクが実行する保存済み Co4E フロー(組込み/自作)。",
"vi": "Flow Co4E đã lưu mà task này sẽ chạy (có sẵn hoặc của bạn)."},
"schedtask.flow_required": {
"en": "Pick a Co4E flow to run (or switch Run to AI agent).",
"ja": "実行する Co4E フローを選んでください(または実行対象を AI エージェントに)。",
"vi": "Hãy chọn một flow Co4E để chạy (hoặc đổi Chạy sang AI agent)."},
"schedtask.hint_task_mode": {
"en": "Normal = runs once (or manually). Automation = a cronjob that repeats on a schedule "
"(daily/weekly/monthly/cron). Switching to Automation reveals the recurrence options.",
"ja": "通常=1回(または手動)実行。自動化=スケジュールで繰り返すCronジョブ(毎日/毎週/毎月/Cron)。"
"自動化に切り替えると繰り返し設定が表示されます。",
"vi": "Thông thường = chạy một lần (hoặc thủ công). Tự động = cronjob lặp theo lịch "
"(ngày/tuần/tháng/cron). Chuyển sang Tự động sẽ hiện các tùy chọn lặp lại."},
"schedtask.mode_normal": {
"en": "Normal (one-time / manual)", "ja": "通常(1回 / 手動)",
"vi": "Thông thường (một lần / thủ công)"},
"schedtask.mode_automation": {
"en": "Automation (cron / recurring)", "ja": "自動化(Cron / 繰り返し)",
"vi": "Tự động (cronjob / lặp lại)"},
"schedtask.f_cron": {"en": "Cron", "ja": "Cron", "vi": "Cron"},
"schedtask.cron_sample_pick": {"en": "Sample ▾", "ja": "サンプル ▾", "vi": "Mẫu ▾"},
"schedtask.cron_sample_tooltip": {
"en": "Pick a ready-made schedule — it fills the cron box with correct syntax.",
"ja": "定番スケジュールを選ぶと、正しい書式でCron欄に入力されます。",
"vi": "Chọn một lịch mẫu — sẽ điền đúng cú pháp vào ô cron."},
"schedtask.cron_s_weekday9": {"en": "Weekdays 9:00", "ja": "平日 9:00", "vi": "Ngày làm việc 9:00"},
"schedtask.cron_s_daily8": {"en": "Every day 8:00", "ja": "毎日 8:00", "vi": "Mỗi ngày 8:00"},
"schedtask.cron_s_weekly_mon": {"en": "Every Monday 9:00", "ja": "毎週月曜 9:00", "vi": "Thứ 2 hằng tuần 9:00"},
"schedtask.cron_s_monthly1": {"en": "1st of month 9:00", "ja": "毎月1日 9:00", "vi": "Ngày 1 hằng tháng 9:00"},
"schedtask.cron_s_every30m": {"en": "Every 30 minutes", "ja": "30分ごと", "vi": "Mỗi 30 phút"},
"schedtask.cron_s_every2h": {"en": "Every 2 hours", "ja": "2時間ごと", "vi": "Mỗi 2 giờ"},
"schedtask.cron_placeholder": {
"en": "(repeat = Cron) e.g. 0 9 * * 1-5 — min hour day month weekday",
"ja": "(繰り返し=Cron)例: 0 9 * * 1-5 — 分 時 日 月 曜日",
"vi": "(khi lặp = Cron) vd: 0 9 * * 1-5 — phút giờ ngày tháng thứ"},
"schedtask.cron_hint": {
"en": "Only when Repeat = Cron. Fields: minute hour day-of-month month day-of-week "
"(e.g. '0 9 * * 1-5' = 9:00 every weekday). Otherwise the run-time above is the "
"daily/weekly/monthly notification time.",
"ja": "繰り返し=Cronの場合のみ。書式: 分 時 日 月 曜日(例 '0 9 * * 1-5' = 平日9:00)。"
"それ以外は上の実行時刻が毎日/毎週/毎月の通知時刻になります。",
"vi": "Chỉ khi Lặp = Cron. Cú pháp: phút giờ ngày tháng thứ (vd '0 9 * * 1-5' = 9:00 các "
"ngày trong tuần). Nếu không, giờ chạy ở trên là giờ thông báo hàng ngày/tuần/tháng."},
"schedtask.cron_invalid": {
"en": "Invalid cron expression: {err}", "ja": "Cron式が不正です: {err}",
"vi": "Cron expression không hợp lệ: {err}"},
"schedtask.cron_never_fires": {
"en": "This cron expression never fires (within 2 years).",
"ja": "このCron式は(2年以内に)一度も実行されません。",
"vi": "Cron expression này không bao giờ chạy (trong vòng 2 năm)."},
"schedtask.workdays_only": {"en": "Working days only (skip Sat/Sun)", "ja": "平日のみ(土日をスキップ)", "vi": "Chỉ ngày làm việc (bỏ T7/CN)"},
"schedtask.skip_holidays": {
"en": "Skip public holidays", "ja": "祝日をスキップ", "vi": "Bỏ qua ngày nghỉ lễ"},
"schedtask.holiday_country": {"en": "Country:", "ja": "国:", "vi": "Quốc gia:"},
"schedtask.f_notify": {"en": "Reminder", "ja": "リマインダー", "vi": "Nhắc nhở"},
"schedtask.f_notify_email": {"en": "Send to", "ja": "送信先", "vi": "Gửi tới"},
"schedtask.notify.none": {"en": "— No reminder —", "ja": "— リマインダーなし —", "vi": "— Không nhắc —"},
"schedtask.notify.teams": {"en": "Teams (webhook)", "ja": "Teams(Webhook)", "vi": "Teams (webhook)"},
"schedtask.notify.outlook": {
"en": "Email via Outlook (this PC)", "ja": "Outlookでメール(このPC)",
"vi": "Email qua Outlook (máy này)"},
}
+342
View File
@@ -0,0 +1,342 @@
"""Chuỗi hiển thị — phần cowork_tab.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"dashboard.estimated_note": {
"en": "~{pct}% of turns are estimated (~4 chars/token) — the gateway didn't report exact usage.",
"ja": "約{pct}%のターンは推定値(約4文字/トークン)です。",
"vi": "~{pct}% lượt là ước tính (~4 ký tự/token) — gateway không trả về usage chính xác."},
"dashboard.ai_analyze_btn": {"en": "AI analyze", "ja": "AI分析", "vi": "AI phân tích"},
"dashboard.ai_analyzing": {"en": "Analyzing…", "ja": "分析中…", "vi": "Đang phân tích…"},
"dashboard.ai_analyze_tooltip": {
"en": "AI reviews the aggregated numbers (never your prompt contents) and suggests how to prompt better and spend fewer tokens.",
"ja": "集計値のみをAIがレビューし(プロンプト内容は送信しません)、トークン削減のコツを提案します。",
"vi": "AI xem các con số tổng hợp (không gửi nội dung prompt) và gợi ý cách viết prompt tốt hơn, tốn ít token hơn."},
"dashboard.ai_advice_title": {
"en": "AI recommendations", "ja": "AIの提案", "vi": "Khuyến nghị từ AI"},
"dashboard.period_tooltip": {
"en": "Time range for all numbers on this page.", "ja": "このページ全体の集計期間。",
"vi": "Khoảng thời gian tính mọi con số trên trang này."},
"dashboard.source_tooltip": {
"en": "Filter by one task/session, or all.", "ja": "タスク/セッション単位で絞り込み。",
"vi": "Lọc theo 1 task/phiên, hoặc tất cả."},
"dashboard.currency_tooltip": {
"en": "Display currency (rates: fixed USD→VND/JPY, editable in config).",
"ja": "表示通貨(USD→VND/JPYの固定レート、configで変更可)。",
"vi": "Tiền tệ hiển thị (tỉ giá USD→VND/JPY cố định, sửa được trong config)."},
"dashboard.price_in_tooltip": {
"en": "USD per 1M input tokens (your gateway's price).",
"ja": "入力100万トークンあたりのUSD単価。", "vi": "USD cho 1 triệu token input (giá của gateway bạn dùng)."},
"dashboard.price_out_tooltip": {
"en": "USD per 1M output tokens.", "ja": "出力100万トークンあたりのUSD単価。",
"vi": "USD cho 1 triệu token output."},
"dashboard.price_cache_tooltip": {
"en": "USD per 1M cached tokens.", "ja": "キャッシュ100万トークンあたりのUSD単価。",
"vi": "USD cho 1 triệu token cache."},
# ---- cowork_tab.py -------------------------------------------------
"cowork.title": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"cowork.skills_btn": {"en": "Skills", "ja": "スキル", "vi": "Skills"},
"cowork.skills_tooltip": {
"en": "Add / manage skills the agent follows (or type /skill).",
"ja": "エージェントが従うスキルを追加/管理(/skill と入力も可)。",
"vi": "Thêm/quản lý skill mà agent tuân theo (hoặc gõ /skill)."},
"cowork.new_chat": {"en": "New chat", "ja": "新しいチャット", "vi": "Cuộc trò chuyện mới"},
"cowork.assistant_title": {"en": "Internal Agent", "ja": "内部エージェント", "vi": "Internal Agent"},
"cowork.project_label": {"en": "{name}", "ja": "{name}", "vi": "{name}"},
"cowork.project_tooltip": {
"en": "This thread belongs to project “{name}” — its shared instructions and workspace apply. Manage projects in the Workspace screen.",
"ja": "このスレッドはプロジェクト「{name}」に属します — 共有指示とワークスペースが適用されます。プロジェクトはワークスペース画面で管理できます。",
"vi": "Thread này thuộc project “{name}” — instructions chung và workspace của project được áp dụng. Quản lý project trong màn hình Workspace.",
},
"cowork.pick_folder_btn": {"en": "Local folder…",
"ja": "ローカルフォルダ…",
"vi": "Thư mục Local…"},
"cowork.pick_folder_tooltip": {
"en": "Save Cowork's output directly into a folder you choose, instead of "
"auto-creating a new session folder under Output.",
"ja": "Output 配下に新しいセッションフォルダを自動作成する代わりに、選んだフォルダに直接保存します。",
"vi": "Lưu output của Cowork trực tiếp vào thư mục bạn chọn, thay vì tự tạo "
"folder phiên mới trong Output."},
"cowork.pick_folder_title": {"en": "Choose the Cowork output folder",
"ja": "Cowork の出力フォルダを選択",
"vi": "Chọn thư mục output cho Cowork"},
# ---- code_tab.py -----------------------------------------------
"code.title": {"en": "Code", "ja": "Code", "vi": "Code"},
"code.files_header": {"en": "Files", "ja": "ファイル", "vi": "Files"},
"code.collapse_file_panel": {
"en": "Collapse the file panel", "ja": "ファイルパネルを折りたたむ", "vi": "Thu gọn bảng cây thư mục"},
"code.expand_file_panel": {
"en": "Click to expand the file panel", "ja": "クリックしてファイルパネルを展開",
"vi": "Bấm để mở lại bảng cây thư mục"},
"code.local_btn": {"en": "Local…", "ja": "ローカル…", "vi": "Local…"},
"code.onedrive_btn": {"en": "OneDrive", "ja": "OneDrive", "vi": "OneDrive"},
"code.onedrive_badge": {"en": "OneDrive", "ja": "OneDrive", "vi": "OneDrive"},
"code.auto_run": {"en": "Auto-run", "ja": "自動実行", "vi": "Tự động"},
"code.auto_run_tooltip": {
"en": "On: agent writes files / runs commands automatically. Off: ask before each action.",
"ja": "オン:エージェントが自動でファイル書き込み/コマンド実行。オフ:毎回確認します。",
"vi": "Bật: agent tự ghi file/chạy lệnh. Tắt: hỏi xác nhận trước mỗi thao tác."},
"code.skills_tooltip": {
"en": "Add / set skills for the agent to follow (or type /skill).",
"ja": "エージェントが従うスキルを追加/設定(/skill と入力も可)。",
"vi": "Thêm/đặt skill mà agent tuân theo (hoặc gõ /skill)."},
"code.flow_chk": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
"code.flow_chk_tooltip": {
"en": "Enable the predefined Req→Demo flow feature (off by default).",
"ja": "定義済みの Req→Demo フロー機能を有効化(初期値はオフ)。",
"vi": "Bật tính năng Flow Req→Demo dựng sẵn (mặc định tắt)."},
"code.flow_btn": {"en": "Flow Management", "ja": "Flow Management", "vi": "Flow Management"},
"code.flow_btn_tooltip": {
"en": "Build and run a multi-stage flow from requirement to demo.",
"ja": "要件からデモまでの多段フローを作成・実行します。",
"vi": "Xây dựng và chạy quy trình nhiều bước từ yêu cầu đến bản demo."},
"code.new_session": {"en": "New session", "ja": "新しいセッション", "vi": "Phiên mới"},
"code.cli_tooltip": {
"en": "Open a terminal (CLI) at the current working folder",
"ja": "現在の作業フォルダでターミナル(CLI)を開く",
"vi": "Mở CLI (terminal) tại thư mục làm việc hiện tại"},
"code.cli_not_found": {
"en": "No terminal application was found on this system.",
"ja": "このシステムにはターミナルアプリが見つかりませんでした。",
"vi": "Không tìm thấy ứng dụng terminal nào trên máy này."},
"code.skills_btn_count": {"en": "Skills ({n})", "ja": "スキル ({n})", "vi": "Skills ({n})"},
"code.assistant_title": {"en": "Code agent", "ja": "Code エージェント", "vi": "Code agent"},
"code.plan": {"en": "Plan", "ja": "プラン", "vi": "Plan"},
"code.act": {"en": "Act", "ja": "実行", "vi": "Act"},
"code.mode_toggle_tooltip": {
"en": "Plan = analyze only (no file writes). Act = execute. Auto-switches to Act on gencode.",
"ja": "Plan=分析のみ(書き込みなし)。Act=実行。コード生成指示で自動的に Act に切替。",
"vi": "Plan = chỉ phân tích (không ghi file). Act = thực thi. Tự chuyển sang Act khi phát hiện yêu cầu sinh code."},
"code.act_status": {"en": "Code: Act mode (executes).", "ja": "Code: Act モード(実行)。", "vi": "Code: chế độ Act (thực thi)."},
"code.plan_status": {"en": "Code: Plan mode (analyze only).", "ja": "Code: Plan モード(分析のみ)。", "vi": "Code: chế độ Plan (chỉ phân tích)."},
"code.cloud_sync_suffix": {"en": " — files sync to cloud", "ja": " — クラウドに同期", "vi": " — file sẽ đồng bộ lên cloud"},
"code.mode_auto_status": {"en": "Code: Auto-run mode.", "ja": "Code: 自動実行モード。", "vi": "Code: chế độ Tự động."},
"code.mode_confirm_status": {"en": "Code: Confirm mode.", "ja": "Code: 確認モード。", "vi": "Code: chế độ Xác nhận."},
"code.pick_local_title": {"en": "Choose working folder (Local)", "ja": "作業フォルダを選択(ローカル)", "vi": "Chọn thư mục làm việc (Local)"},
"code.pick_onedrive_title": {"en": "Choose a folder in OneDrive", "ja": "OneDrive 内のフォルダを選択", "vi": "Chọn thư mục trong OneDrive"},
"code.onedrive_choose_folder": {
"en": "Choose a folder in OneDrive…", "ja": "OneDrive 内のフォルダを選択…", "vi": "Chọn thư mục trong OneDrive…"},
"code.no_onedrive": {"en": "No OneDrive detected", "ja": "OneDrive が見つかりません", "vi": "Không phát hiện OneDrive"},
"code.flow_running": {
"en": "Running flow '{name}' (Act) — {n} stages.",
"ja": "フロー「{name}」を実行中(Act)— {n} ステージ。",
"vi": "Đang chạy flow '{name}' (Act) — {n} bước."},
# ---- settings_dialog.py --------------------------------------------
"settings.title": {"en": "Settings", "ja": "設定", "vi": "Cài đặt"},
"settings.active_provider": {"en": "Active provider", "ja": "使用中のプロバイダー", "vi": "Nhà cung cấp đang dùng"},
"settings.theme": {"en": "Theme", "ja": "テーマ", "vi": "Giao diện"},
"settings.theme_dark": {"en": "Dark", "ja": "ダーク", "vi": "Tối"},
"settings.theme_light": {"en": "Light", "ja": "ライト", "vi": "Sáng"},
"settings.theme_system": {"en": "Auto (System)", "ja": "自動(システム)", "vi": "Tự động (theo hệ thống)"},
"settings.language": {"en": "Language", "ja": "言語", "vi": "Ngôn ngữ"},
"settings.tray_keep": {
"en": "Keep running in the system tray when the window is closed",
"ja": "ウィンドウを閉じてもシステムトレイで実行を継続",
"vi": "Giữ chạy nền trong khay hệ thống khi đóng cửa sổ"},
"settings.tray_notify": {
"en": "Show a tray notification when a task finishes or fails",
"ja": "タスク完了/失敗時にトレイ通知を表示",
"vi": "Hiện thông báo khay hệ thống khi tác vụ xong hoặc lỗi"},
"settings.group.openai": {"en": "OpenAI-compatible (Internal Gateway)", "ja": "OpenAI 互換(社内ゲートウェイ)", "vi": "OpenAI-compatible (Gateway nội bộ)"},
"settings.group.anthropic": {"en": "Anthropic Claude", "ja": "Anthropic Claude", "vi": "Anthropic Claude"},
# Name for the language/tray block at the top of Settings — it had none,
# because until the index existed nothing had to refer to it.
"settings.group.general": {"en": "General", "ja": "一般", "vi": "Chung"},
"settings.group.provider": {"en": "AI Provider", "ja": "AI プロバイダー", "vi": "Nhà cung cấp AI"},
"settings.group.parameter": {"en": "Parameter", "ja": "Parameter", "vi": "Parameter"},
"settings.param_section_pricing": {
"en": "Model pricing", "ja": "モデル価格", "vi": "Bảng giá model"},
"settings.pricing_url_label": {
"en": "Pricing reference link", "ja": "価格表の参考リンク", "vi": "Link bảng giá tham khảo"},
"settings.pricing_url_placeholder": {
"en": "https://… (the provider's public price list)",
"ja": "https://…(プロバイダーの公開価格表)",
"vi": "https://… (trang bảng giá công khai của provider)"},
"settings.pricing_url_tooltip": {
"en": "Shown as a reference link beside the Monitoring pricing table. Prices themselves are entered by hand in that table.",
"ja": "監視画面の価格表の横に参考リンクとして表示されます。価格自体は表に手入力します。",
"vi": "Hiển thị làm link tham khảo cạnh bảng giá trong Monitoring. Giá vẫn do Admin nhập tay vào bảng."},
"settings.group.accounts": {
"en": "Shared accounts folder", "ja": "共有アカウントフォルダー", "vi": "Thư mục tài khoản dùng chung"},
"settings.accounts_dir_label": {"en": "Folder", "ja": "フォルダー", "vi": "Thư mục"},
"settings.accounts_dir_placeholder": {
"en": "OneDrive/network folder holding the shared accounts & groups",
"ja": "アカウント/グループを保存する OneDrive・共有フォルダー",
"vi": "Thư mục OneDrive/mạng chứa danh sách tài khoản & nhóm dùng chung"},
"settings.accounts_dir_hint": {
"en": "Where accounts, groups and shared telemetry live. Every machine must point at the SAME folder.",
"ja": "アカウント・グループ・共有テレメトリの保存先。全マシンで同じフォルダーを指定してください。",
"vi": "Nơi lưu tài khoản, nhóm và telemetry dùng chung. Mọi máy phải trỏ về CÙNG một thư mục."},
"settings.accounts_dir_admin_only": {
"en": "Only an Admin can change this folder.",
"ja": "このフォルダーを変更できるのは管理者のみです。",
"vi": "Chỉ Admin mới thay đổi được thư mục này."},
"settings.group.monitoring_visibility": {
"en": "Monitoring tab visibility (Sub-admin)", "ja": "モニタリングタブの表示(サブ管理者)",
"vi": "Hiển thị tab Monitoring (Sub-admin)"},
"settings.mv_security_events": {"en": "Security Events", "ja": "セキュリティイベント",
"vi": "Security Events"},
"settings.mv_mcp_history": {"en": "MCP Call History", "ja": "MCP 呼び出し履歴", "vi": "MCP Call History"},
"settings.mv_action_logs": {"en": "Action Logs", "ja": "アクションログ", "vi": "Action Logs"},
"settings.mv_agent_status": {"en": "Agent Status", "ja": "エージェント状態", "vi": "Trạng thái Agent"},
"settings.mv_hint": {
"en": "Admin always sees every Monitoring tab. Turn one off here to hide it from Sub-admin too (it stays available to Admin).",
"ja": "管理者は常にすべてのタブを見られます。ここでオフにすると、そのタブはサブ管理者からも隠されます(管理者には影響しません)。",
"vi": "Admin luôn thấy mọi tab Monitoring. Tắt một mục ở đây sẽ ẩn tab đó với Sub-admin (Admin vẫn thấy như thường)."},
"settings.sec_unlock_user_placeholder": {
"en": "Admin account", "ja": "管理者アカウント", "vi": "Tài khoản admin"},
"settings.sec_unlock_code_placeholder": {
"en": "Access code", "ja": "アクセスコード", "vi": "Mã truy cập"},
"settings.sec_unlock_btn": {"en": "Unlock", "ja": "ロック解除", "vi": "Mở khóa"},
"settings.sec_locked_hint": {
"en": "Locked — enter an Admin account + access code to change these settings.",
"ja": "ロック中 — 変更するには管理者アカウントとアクセスコードを入力してください。",
"vi": "Đang khóa — nhập tài khoản Admin + mã truy cập để thay đổi các thiết lập này."},
"settings.sec_unlocked_hint": {
"en": "Unlocked — changes will be saved; the group locks again after Save.",
"ja": "ロック解除中 — 保存後に再びロックされます。",
"vi": "Đã mở khóa — thay đổi sẽ được lưu; nhóm sẽ tự khóa lại sau khi Save."},
"settings.sec_unlock_failed": {
"en": "Not an Admin account (or wrong code / accounts folder unreachable).",
"ja": "管理者アカウントではありません(またはコード誤り・フォルダー未接続)。",
"vi": "Không phải tài khoản Admin (hoặc sai mã / không truy cập được thư mục tài khoản)."},
"settings.sec_no_lock_hint": {
"en": "No shared accounts folder configured yet — the group is editable without an admin unlock.",
"ja": "共有アカウントフォルダー未設定のため、ロックなしで編集できます。",
"vi": "Chưa cấu hình thư mục tài khoản dùng chung — nhóm này đang chỉnh sửa được mà không cần mở khóa."},
"settings.base_url": {"en": "Base URL", "ja": "ベース URL", "vi": "Base URL"},
"settings.api_key": {"en": "API Key", "ja": "API キー", "vi": "API Key"},
"settings.model": {"en": "Model", "ja": "モデル", "vi": "Model"},
"settings.load": {"en": "Load", "ja": "読み込み", "vi": "Tải"},
"settings.load_tooltip": {
"en": "Fetch the available models/agents from this provider",
"ja": "このプロバイダーから利用可能なモデル/エージェントを取得",
"vi": "Lấy danh sách model/agent khả dụng từ nhà cung cấp này"},
"settings.group.teams": {"en": "Microsoft Teams", "ja": "Microsoft Teams", "vi": "Microsoft Teams"},
"settings.teams_webhook": {"en": "Webhook URL", "ja": "Webhook URL", "vi": "Webhook URL"},
"settings.teams_webhook_placeholder": {
"en": "https://… (Workflows or Incoming Webhook URL)",
"ja": "https://…(Workflows または Incoming Webhook の URL)",
"vi": "https://… (URL của Workflows hoặc Incoming Webhook)"},
"settings.teams_test": {"en": "Test", "ja": "テスト", "vi": "Kiểm tra"},
"settings.teams_notify": {
"en": "Auto-send to Teams when a task completes", "ja": "タスク完了時に Teams へ自動送信",
"vi": "Tự động gửi sang Teams khi tác vụ hoàn thành"},
"settings.teams_hint": {
"en": ("Get a webhook: Teams channel → ⋯ → Connectors → Incoming Webhook, "
"OR Power Automate → 'When a HTTP request is received' → 'Post message in a chat or channel'. "
"URL must contain logic.azure.com or webhook.office.com."),
"ja": ("Webhook の取得: Teams チャンネル → ⋯ → コネクタ → Incoming Webhook、"
"または Power Automate → 'HTTP要求の受信時' → 'チャットまたはチャネルにメッセージを投稿'。"
"URL には logic.azure.com か webhook.office.com を含める必要があります。"),
"vi": ("Lấy webhook: kênh Teams → ⋯ → Connectors → Incoming Webhook, "
"HOẶC Power Automate → 'When a HTTP request is received' → 'Post message in a chat or channel'. "
"URL phải chứa logic.azure.com hoặc webhook.office.com.")},
"settings.group.ms365": {
"en": "Microsoft 365 connections", "ja": "Microsoft 365 連携",
"vi": "Kết nối Microsoft 365"},
"settings.ms365_unlock_code": {"en": "Unlock code", "ja": "解除コード", "vi": "Mã mở khóa"},
"settings.ms365_unlock_placeholder": {
"en": "Enter the unlock code", "ja": "解除コードを入力",
"vi": "Nhập mã để mở khóa"},
"settings.ms365_unlock_btn": {"en": "Unlock", "ja": "解除", "vi": "Mở khóa"},
"settings.ms365_locked_hint": {
"en": "Locked — enter the unlock code above to edit this section.",
"ja": "ロック中 — このセクションを編集するには上の解除コードを入力してください。",
"vi": "Đang khóa — nhập mã ở trên để chỉnh sửa mục này."},
"settings.ms365_unlocked_hint": {
"en": "Unlocked — remember to click Save; this section re-locks automatically afterward.",
"ja": "解除しました — 保存を忘れずに。保存後は自動的に再ロックされます。",
"vi": "Đã mở khóa — nhớ bấm Save; mục này sẽ tự khóa lại ngay sau đó."},
"settings.ms365_wrong_code": {
"en": "Wrong code.", "ja": "コードが違います。", "vi": "Mã không đúng."},
"settings.ms365_connector.outlook": {"en": "Outlook", "ja": "Outlook", "vi": "Outlook"},
"settings.ms365_connector.teams": {"en": "Teams", "ja": "Teams", "vi": "Teams"},
"settings.ms365_connector.onedrive": {"en": "OneDrive", "ja": "OneDrive", "vi": "OneDrive"},
"settings.ms365_connector.sharepoint": {"en": "SharePoint", "ja": "SharePoint", "vi": "SharePoint"},
"settings.ms365_connector.meeting_transcript": {
"en": "Meeting transcript", "ja": "会議の文字起こし", "vi": "Meeting transcript"},
"settings.ms365_allow_internet": {
"en": "Allow external internet access", "ja": "外部インターネットアクセスを許可",
"vi": "Cho phép truy cập Internet bên ngoài"},
"settings.ms365_internet_off_hint": {
"en": ("External internet access is OFF — every connector was turned off to avoid "
"leaking data outside. Turn it back on, then re-tick the connectors you want."),
"ja": ("外部インターネットアクセスがオフです — データが外部に漏れないよう、すべてのコネクタ"
"がオフになりました。再度オンにしてから、必要なコネクタを選び直してください。"),
"vi": ("Đã tắt truy cập Internet bên ngoài — mọi connector đã tự tắt để tránh rò rỉ "
"thông tin ra ngoài. Bật lại rồi tick lại từng connector muốn dùng.")},
"settings.ms365_signin_btn": {"en": "Sign in with Microsoft", "ja": "Microsoft でサインイン",
"vi": "Đăng nhập Microsoft"},
"settings.ms365_signout_btn": {"en": "Sign out", "ja": "サインアウト", "vi": "Đăng xuất"},
"settings.ms365_not_signed_in": {
"en": "Not signed in to Microsoft 365.", "ja": "Microsoft 365 にサインインしていません。",
"vi": "Chưa đăng nhập Microsoft 365."},
"settings.ms365_signed_in_as": {
"en": "Signed in as {user}", "ja": "{user} としてサインイン中",
"vi": "Đã đăng nhập với {user}"},
"settings.ms365_missing_ids": {
"en": "Enter the Tenant ID and Client ID first.", "ja": "先に Tenant ID と Client ID を入力してください。",
"vi": "Hãy nhập Tenant ID và Client ID trước."},
"settings.ms365_signing_in": {
"en": "Starting sign-in…", "ja": "サインインを開始しています…", "vi": "Đang bắt đầu đăng nhập…"},
"settings.ms365_signin_failed": {
"en": "Sign-in failed: {err}", "ja": "サインインに失敗しました: {err}",
"vi": "Đăng nhập thất bại: {err}"},
"settings.ms365_teams_link_label": {
"en": "Or just paste a Teams channel/chat link — no ID needed:",
"ja": "または Teams のチャネル/チャットのリンクを貼り付けるだけ — ID は不要です:",
"vi": "Hoặc chỉ cần paste link kênh/chat Teams — không cần ID:"},
"settings.ms365_teams_link_placeholder": {
"en": "Paste a link from Teams ('Get link to channel' or a message's 'Copy link')",
"ja": "Teams のリンクを貼り付け(「チャネルへのリンクを取得」またはメッセージの「リンクをコピー」)",
"vi": "Dán link từ Teams ('Get link to channel' hoặc 'Copy link' của 1 tin nhắn)"},
"settings.ms365_teams_connect_btn": {"en": "Connect", "ja": "接続", "vi": "Kết nối"},
"settings.ms365_teams_not_connected": {
"en": "No Teams chat/channel connected yet.", "ja": "Teams のチャット/チャネルはまだ接続されていません。",
"vi": "Chưa kết nối chat/kênh Teams nào."},
"settings.ms365_teams_connected_channel": {
"en": "Connected to a Teams channel.", "ja": "Teams のチャネルに接続済みです。",
"vi": "Đã kết nối vào một kênh Teams."},
"settings.ms365_teams_connected_chat": {
"en": "Connected to a Teams chat.", "ja": "Teams のチャットに接続済みです。",
"vi": "Đã kết nối vào một đoạn chat Teams."},
"settings.ms365_teams_link_missing": {
"en": "Paste a Teams link first.", "ja": "先に Teams のリンクを貼り付けてください。",
"vi": "Hãy dán link Teams trước."},
"settings.ms365_teams_connecting": {
"en": "Connecting…", "ja": "接続しています…", "vi": "Đang kết nối…"},
"settings.ms365_teams_connect_failed": {
"en": "Connect failed: {err}", "ja": "接続に失敗しました: {err}",
"vi": "Kết nối thất bại: {err}"},
"settings.ms365_teams_intro_message": {
"en": "Hi, I'm the Cowork agent — just connected to this chat/channel.",
"ja": "こんにちは、Cowork エージェントです — このチャット/チャネルに接続しました。",
"vi": "Xin chào, mình là Cowork agent — vừa kết nối vào chat/kênh này."},
"settings.group.agent_security": {
"en": "Agent Security (AI)", "ja": "エージェント セキュリティ(AI)",
"vi": "Agent Security (AI)"},
"settings.group.sandbox": {
"en": "Sandbox Security Layer", "ja": "サンドボックス セキュリティ層",
"vi": "Sandbox Security Layer"},
"settings.sandbox_confirm_commands": {
"en": "Confirm before Cowork runs a command",
"ja": "Cowork がコマンドを実行する前に確認する",
"vi": "Xác nhận trước khi Cowork chạy lệnh"},
"settings.sandbox_confirm_commands_tooltip": {
"en": ("Shows an Approve/Reject dialog before run_command/install_package "
"executes in Cowork — off by default (auto-run), same as before."),
"ja": "Cowork で run_command/install_package を実行する前に承認/拒否ダイアログを表示します — "
"デフォルトはオフ(自動実行)で、これまでと同じです。",
"vi": "Hiện hộp thoại Duyệt/Từ chối trước khi Cowork chạy run_command/install_package — "
"mặc định tắt (tự chạy), giống hành vi cũ."},
}
+342
View File
@@ -0,0 +1,342 @@
"""Chuỗi hiển thị — phần hint.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"schedtask.notify_email_placeholder": {
"en": "recipient@example.com (comma-separated)",
"ja": "recipient@example.com(カンマ区切り)",
"vi": "nguoinhan@example.com (cách nhau dấu phẩy)"},
"schedtask.notify_hint": {
"en": "When the scheduled/cron task finishes, send a reminder. Teams uses the webhook "
"from Settings; Outlook sends from your signed-in Outlook desktop app — no login needed.",
"ja": "スケジュール/Cronタスク完了時にリマインダーを送信。Teamsは設定のWebhookを使用、"
"Outlookはサインイン済みのOutlookデスクトップから送信(ログイン不要)。",
"vi": "Khi task theo lịch/cron chạy xong sẽ gửi nhắc. Teams dùng webhook trong Settings; "
"Outlook gửi từ ứng dụng Outlook đã đăng nhập trên máy — không cần đăng nhập lại."},
"schedtask.notify_need_email": {
"en": "Enter a recipient address for the Outlook reminder.",
"ja": "Outlookリマインダーの送信先アドレスを入力してください。",
"vi": "Hãy nhập địa chỉ người nhận cho nhắc nhở qua Outlook."},
"schedtask.notify_need_webhook": {
"en": "Teams reminder needs a webhook URL — set it in Settings → Parameter first.",
"ja": "TeamsリマインダーにはWebhook URLが必要です。先に設定→パラメータで設定してください。",
"vi": "Nhắc qua Teams cần webhook URL — hãy đặt trong Settings → Parameter trước."},
"schedtask.tz_local_note": {
"en": "Times use this machine's local timezone.", "ja": "時刻はこのPCのローカルタイムゾーンです。",
"vi": "Giờ dùng múi giờ local của máy này."},
"schedtask.g_flow": {"en": "Flow Setup", "ja": "フロー設定", "vi": "Thiết lập Flow"},
"schedtask.flow_hint": {
"en": "(Flow tasks only) Steps run in order; each step's output feeds the next step's input.",
"ja": "(Flowタスクのみ)ステップは順番に実行され、前ステップの出力が次の入力になります。",
"vi": "(Chỉ task Flow) Các bước chạy tuần tự; output bước trước nối vào input bước sau."},
"schedtask.flow_template": {"en": "Code template:", "ja": "Codeテンプレート:", "vi": "Template Code:"},
"schedtask.import_flow_btn": {"en": "Import steps", "ja": "ステップ取込", "vi": "Nhập các bước"},
"schedtask.flow_template_empty": {
"en": "The selected template has no steps.", "ja": "選択したテンプレートにステップがありません。",
"vi": "Template đã chọn không có bước nào."},
"schedtask.step_name_ph": {"en": "Step name", "ja": "ステップ名", "vi": "Tên bước"},
"schedtask.step_prompt_ph": {"en": "Prompt / command", "ja": "プロンプト/コマンド", "vi": "Prompt / lệnh"},
"schedtask.stepexec.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"schedtask.stepexec.co4e": {"en": "Code", "ja": "Code", "vi": "Code"},
"schedtask.stepexec.script": {"en": "Script", "ja": "Script", "vi": "Script"},
"schedtask.stepexec.manual": {"en": "Manual", "ja": "Manual", "vi": "Manual"},
"schedtask.del_step_tooltip": {"en": "Delete the selected step", "ja": "選択したステップを削除",
"vi": "Xóa bước đang chọn"},
"schedtask.guide_tooltip": {
"en": "Open the Schedule Task user guide", "ja": "Schedule Task の使い方ガイドを開く",
"vi": "Mở hướng dẫn sử dụng Schedule Task"},
"schedtask.guide_missing": {
"en": "Guide file not found (docs/schedule_task_user_guide.md).",
"ja": "ガイドファイルが見つかりません (docs/schedule_task_user_guide.md)。",
"vi": "Không tìm thấy file hướng dẫn (docs/schedule_task_user_guide.md)."},
"schedtask.msg_set_schedule": {
"en": "Set a run time so this task can actually run on schedule.",
"ja": "実行時刻を設定するとスケジュール実行されます。",
"vi": "Hãy đặt giờ chạy để task này thực sự chạy theo lịch."},
# ---- hint tooltips (hover help) --------------------------------------
"schedtask.add_tooltip": {
"en": "Create a new task with full options (schedule, input, dependencies…).",
"ja": "新しいタスクを作成(スケジュール・入力・依存など全設定)。",
"vi": "Tạo task mới với đầy đủ tuỳ chọn (lịch, input, phụ thuộc…)."},
"schedtask.search_tooltip": {
"en": "Filter cards by title/description.", "ja": "タイトル/説明でカードを絞り込み。",
"vi": "Lọc card theo tiêu đề/mô tả."},
"schedtask.filter_tooltip": {
"en": "Show only one task type.", "ja": "1つのタスク種別のみ表示。",
"vi": "Chỉ hiện một loại task."},
"schedtask.col_tip.backlog": {
"en": "New tasks with no schedule yet. Drag a card here to shelve it.",
"ja": "未スケジュールの新規タスク。", "vi": "Task mới, chưa đặt lịch. Kéo card vào đây để cất lại."},
"schedtask.col_tip.scheduled": {
"en": "On the calendar — runs automatically at its time. Drop a card here to schedule it.",
"ja": "スケジュール済み — 時刻になると自動実行。", "vi": "Đã lên lịch — tự chạy khi đến giờ. Thả card vào đây để đặt lịch."},
"schedtask.col_tip.running": {
"en": "Currently executing. Drop a card here to RUN it immediately.",
"ja": "実行中。ここにドロップすると即実行します。", "vi": "Đang chạy. Thả card vào đây để CHẠY NGAY."},
"schedtask.col_tip.waiting_input": {
"en": "Waiting: needs your Run-now approval, or its prerequisite tasks aren't Done yet.",
"ja": "待機中: 手動承認待ち、または前提タスクが未完了。",
"vi": "Đang chờ: cần bạn bấm Chạy ngay (phê duyệt), hoặc các task phụ thuộc chưa Done."},
"schedtask.col_tip.done": {
"en": "Finished successfully. Drop a card here to mark it done by hand.",
"ja": "完了。ここにドロップすると手動で完了扱いにします。",
"vi": "Đã xong. Thả card vào đây để tự đánh dấu hoàn thành."},
"schedtask.col_tip.failed": {
"en": "Last run errored — right-click → Run history to see why.",
"ja": "前回失敗 — 右クリック→実行履歴で原因を確認。",
"vi": "Lần chạy cuối bị lỗi — chuột phải → Lịch sử chạy để xem lý do."},
"schedtask.col_tip.paused": {
"en": "Paused: never auto-runs and is skipped by chains until resumed.",
"ja": "一時停止中: 再開まで自動実行されず、チェーンでもスキップされます。",
"vi": "Tạm dừng: không tự chạy và bị chuỗi bỏ qua cho tới khi tiếp tục."},
"schedtask.hint_type": {
"en": "Cowork = documents/answers · Code = coding agent · Script = shell command · Flow = multi-step · Manual = tracking only.",
"ja": "Cowork=文書/回答 · Code=コーディング · Script=コマンド · Flow=複数ステップ · Manual=管理のみ。",
"vi": "Cowork = tài liệu/trả lời · Code = agent code · Script = lệnh shell · Flow = nhiều bước · Manual = chỉ quản lý."},
"schedtask.hint_status": {
"en": "Current Kanban lane. Usually managed automatically by the scheduler.",
"ja": "現在のKanbanレーン。通常はスケジューラーが自動管理。",
"vi": "Cột Kanban hiện tại. Thường được scheduler tự quản lý."},
"schedtask.hint_script": {
"en": "Shell command to run (Script tasks). Runs in the task's artifact folder with a timeout.",
"ja": "実行するシェルコマンド(Scriptタスク)。", "vi": "Lệnh shell sẽ chạy (task Script), trong thư mục artifact riêng, có timeout."},
"schedtask.hint_sched_enable": {
"en": "Off = the task never runs by itself.", "ja": "OFF = 自動実行されません。",
"vi": "Tắt = task không bao giờ tự chạy."},
"schedtask.hint_run_at": {
"en": "First/next run time (this machine's local time).",
"ja": "初回/次回の実行時刻(ローカル時刻)。", "vi": "Giờ chạy đầu/kế tiếp (giờ local của máy)."},
"schedtask.hint_repeat": {
"en": "After a successful run, the schedule rolls to the next occurrence automatically.",
"ja": "成功後、次回分へ自動的に繰り越します。",
"vi": "Sau khi chạy thành công, lịch tự dời sang kỳ kế tiếp."},
"schedtask.hint_cron": {
"en": "5 fields: minute hour day month weekday. E.g. '0 9 * * 1-5' = 9:00 on weekdays.",
"ja": "5項目: 分 時 日 月 曜日。例 '0 9 * * 1-5' = 平日9時。",
"vi": "5 trường: phút giờ ngày tháng thứ. VD '0 9 * * 1-5' = 9h các ngày thường."},
"schedtask.hint_workdays": {
"en": "Runs landing on Sat/Sun are pushed to the next working day.",
"ja": "土日に当たる回は翌営業日に繰り越し。", "vi": "Lịch rơi vào T7/CN sẽ dời sang ngày làm việc kế."},
"schedtask.hint_holidays": {
"en": "Runs landing on a public holiday of the chosen country are pushed to the next allowed day.",
"ja": "選択した国の祝日に当たる回は翌営業日に繰り越し。",
"vi": "Lịch rơi vào ngày lễ của quốc gia đã chọn sẽ tự dời sang ngày hợp lệ kế."},
"schedtask.hint_country": {
"en": "ISO country code for the holiday calendar (VN, JP, US… — type any code).",
"ja": "祝日カレンダーの国コード(VN, JP, US…)。", "vi": "Mã quốc gia cho lịch nghỉ lễ (VN, JP, US… — gõ được mã bất kỳ)."},
"schedtask.hint_flow_template": {
"en": "Import the stages of a saved Flow template as steps here.",
"ja": "保存済みFlowテンプレートをステップとして取り込み。",
"vi": "Nhập các stage của Flow template đã lưu thành các bước ở đây."},
"schedtask.hint_input_mode": {
"en": "What the agent receives besides the description: nothing, typed text, file contents, or the output of earlier tasks.",
"ja": "説明に加えてエージェントへ渡す入力。", "vi": "Agent nhận gì ngoài mô tả: trống, văn bản gõ tay, nội dung tệp, hoặc output các task trước."},
"schedtask.hint_prev_task": {
"en": "Single explicit source task for 'previous task output' (leave (none) to use all waited-for tasks).",
"ja": "「前タスクの出力」の明示的なソース。", "vi": "Task nguồn cụ thể cho 'output task trước' (để (không) sẽ dùng tất cả task đang chờ)."},
"schedtask.hint_output_mode": {
"en": "Expected output format — informational for now, files always land in the artifact folder.",
"ja": "想定する出力形式(参考情報)。", "vi": "Định dạng output mong muốn — hiện mang tính thông tin, file luôn nằm trong thư mục artifact."},
"schedtask.hint_next_task": {
"en": "Task to trigger after this one finishes (chain).",
"ja": "このタスク完了後に起動するタスク(チェーン)。", "vi": "Task được kích hoạt sau khi task này xong (chuỗi)."},
"schedtask.hint_run_next": {
"en": "When the next task fires: on success / always / only after you confirm.",
"ja": "次タスクの起動条件: 成功時/常に/手動確認後。", "vi": "Khi nào task sau chạy: khi thành công / luôn / chờ bạn xác nhận."},
"schedtask.hint_pass_output": {
"en": "This task's output.md becomes the next task's input automatically.",
"ja": "このタスクのoutput.mdを次タスクの入力に自動投入。",
"vi": "output.md của task này tự thành input của task sau."},
"schedtask.hint_depends": {
"en": "Fan-in: this task waits until ALL ticked tasks are Done, then runs automatically with their outputs available.",
"ja": "ファンイン: チェックした全タスクがDoneになるまで待機し、自動実行。",
"vi": "Fan-in: task này đợi TẤT CẢ task được tick Done rồi mới tự chạy, kèm output của chúng."},
"schedtask.hint_retry": {
"en": "Auto-retry this many times when a run fails.", "ja": "失敗時の自動リトライ回数。",
"vi": "Tự thử lại bấy nhiêu lần khi chạy lỗi."},
"schedtask.hint_timeout": {
"en": "Hard limit per run (Script tasks).", "ja": "1回あたりの上限時間(Script)。",
"vi": "Giới hạn thời gian mỗi lần chạy (task Script)."},
"schedtask.hint_approval": {
"en": "Safety: the scheduler will NEVER auto-run this — it parks in Waiting Input until you right-click → Run now.",
"ja": "安全: 自動実行されず、Run nowまで待機します。",
"vi": "An toàn: scheduler KHÔNG BAO GIỜ tự chạy task này — nó nằm ở Waiting Input tới khi bạn chuột phải → Chạy ngay."},
"schedtask.g_input": {"en": "Input", "ja": "入力", "vi": "Input"},
"schedtask.f_input_mode": {"en": "Input mode", "ja": "入力モード", "vi": "Chế độ input"},
"schedtask.inmode.empty": {"en": "Empty (default)", "ja": "空(既定)", "vi": "Trống (mặc định)"},
"schedtask.inmode.manual": {"en": "Manual text", "ja": "手入力テキスト", "vi": "Văn bản nhập tay"},
"schedtask.inmode.file": {"en": "File(s)", "ja": "ファイル", "vi": "Tệp"},
"schedtask.inmode.previous_task_output": {
"en": "Previous task output", "ja": "前タスクの出力", "vi": "Output của task trước"},
"schedtask.f_manual_text": {"en": "Prompt", "ja": "プロンプト", "vi": "Prompt"},
"schedtask.gen_input_tooltip": {
"en": "AI-draft the prompt from the title/description", "ja": "タイトル/説明からプロンプトをAI生成",
"vi": "AI soạn prompt từ tiêu đề/mô tả"},
"schedtask.f_files": {"en": "Attach files", "ja": "添付ファイル", "vi": "Đính kèm tệp"},
"schedtask.f_links": {"en": "Attach links", "ja": "添付リンク", "vi": "Đính kèm link"},
"schedtask.files_placeholder": {
"en": "Local file paths, separated by ;", "ja": "ローカルファイルパス(;区切り)",
"vi": "Đường dẫn tệp local, cách nhau bằng ;"},
"schedtask.links_placeholder": {
"en": "https://… URLs separated by ;", "ja": "https://… URL(;区切り)",
"vi": "https://… các link, cách nhau bằng ;"},
"schedtask.pick_files": {"en": "Browse…", "ja": "参照…", "vi": "Chọn tệp…"},
"schedtask.add_link_title": {"en": "Add link", "ja": "リンクを追加", "vi": "Thêm link"},
"schedtask.add_link_label": {"en": "URL:", "ja": "URL:", "vi": "URL:"},
"schedtask.hint_files": {
"en": "Attached files are always read and given to the agent as context, regardless of Input mode.",
"ja": "添付ファイルはInputモードに関係なく常にエージェントへ渡されます。",
"vi": "Tệp đính kèm luôn được đọc và đưa vào ngữ cảnh cho agent, bất kể chế độ Input."},
"schedtask.hint_links": {
"en": "Each URL is fetched (best-effort) and its text content given to the agent as context.",
"ja": "各URLを取得し(ベストエフォート)、テキストをコンテキストとして渡します。",
"vi": "Mỗi link được tải nội dung (khi có thể) và đưa vào ngữ cảnh cho agent."},
"schedtask.f_prev_task": {"en": "Previous task", "ja": "前タスク", "vi": "Task trước"},
"schedtask.g_output": {"en": "Output", "ja": "出力", "vi": "Output"},
"schedtask.f_output_mode": {"en": "Output mode", "ja": "出力モード", "vi": "Chế độ output"},
"schedtask.g_dependency": {"en": "Dependency / Next task", "ja": "依存 / 次タスク", "vi": "Phụ thuộc / Task tiếp theo"},
"schedtask.f_next_task": {"en": "Next task", "ja": "次タスク", "vi": "Task tiếp theo"},
"schedtask.f_run_next": {"en": "Run next task", "ja": "次タスクの実行", "vi": "Chạy task tiếp theo"},
"schedtask.runnext.none": {"en": "Don't run next task", "ja": "実行しない", "vi": "Không chạy task sau"},
"schedtask.runnext.run_after_success": {
"en": "Run after success", "ja": "成功後に実行", "vi": "Chạy khi task này thành công"},
"schedtask.runnext.run_always": {"en": "Always run", "ja": "常に実行", "vi": "Luôn chạy (kể cả lỗi)"},
"schedtask.runnext.run_after_manual_confirm": {
"en": "Wait for my confirmation", "ja": "手動確認後に実行", "vi": "Chờ tôi xác nhận rồi chạy"},
"schedtask.pass_output": {
"en": "Use this task's output as next task's input",
"ja": "このタスクの出力を次タスクの入力にする",
"vi": "Dùng output task này làm input task sau"},
"schedtask.next_paused_warn": {
"en": "The selected next task is paused — it will be skipped when this task finishes.",
"ja": "選択した次タスクは一時停止中のため、完了時にスキップされます。",
"vi": "Task tiếp theo đang tạm dừng — sẽ bị bỏ qua khi task này chạy xong."},
"schedtask.none": {"en": "(none)", "ja": "(なし)", "vi": "(không)"},
"schedtask.g_execution": {"en": "Execution", "ja": "実行設定", "vi": "Thực thi"},
"schedtask.f_retry": {"en": "Max retry", "ja": "最大リトライ", "vi": "Số lần thử lại"},
"schedtask.f_timeout": {"en": "Timeout", "ja": "タイムアウト", "vi": "Thời gian tối đa"},
"schedtask.requires_approval": {
"en": "Requires approval (scheduler will NOT auto-run; waits for Run now)",
"ja": "承認必須(自動実行されず、手動のRun nowを待ちます)",
"vi": "Cần phê duyệt (không tự chạy theo lịch; chờ bấm Chạy ngay)"},
"schedtask.notify_ok": {"en": "Notify Teams on complete", "ja": "完了時にTeams通知", "vi": "Báo Teams khi xong"},
"schedtask.notify_err": {"en": "Notify Teams on error", "ja": "エラー時にTeams通知", "vi": "Báo Teams khi lỗi"},
"schedtask.title_required": {"en": "Please enter a title.", "ja": "タイトルを入力してください。", "vi": "Vui lòng nhập tiêu đề."},
# AI create dialog
"schedtask.ai_desc_label": {
"en": "Describe what you want to automate:", "ja": "自動化したい内容を記述:",
"vi": "Mô tả việc bạn muốn tự động hoá:"},
"schedtask.ai_desc_ph": {
"en": "e.g. Every Monday 9:00, use Code to read new CAE data and build a markdown report, then have Cowork draft a team email from it.",
"ja": "例: 毎週月曜9時、CodeでCAEデータを読み込みレポート作成、その後Coworkでメール下書きを作成。",
"vi": "vd: Mỗi thứ 2 lúc 9h, dùng Code đọc dữ liệu CAE mới tạo báo cáo markdown, sau đó Cowork soạn email draft gửi team."},
"schedtask.ai_generate": {"en": "Generate plan", "ja": "プランを生成", "vi": "Tạo kế hoạch"},
"schedtask.ai_generating": {"en": "Generating…", "ja": "生成中…", "vi": "Đang tạo…"},
"schedtask.ai_preview_label": {
"en": "Preview (nothing is created until you confirm):",
"ja": "プレビュー(確認するまで作成されません):",
"vi": "Xem trước (chưa tạo gì cho tới khi bạn xác nhận):"},
"schedtask.ai_confirm": {"en": "Create tasks", "ja": "タスクを作成", "vi": "Tạo các task"},
"schedtask.tab_ai": {"en": "AI gen task", "ja": "AIタスク生成", "vi": "AI gen task"},
"schedtask.tab_import": {"en": "Import", "ja": "インポート", "vi": "Import"},
"schedtask.export_template_btn": {
"en": "Create Excel template…", "ja": "Excelテンプレートを作成…",
"vi": "Tạo template Excel…"},
"schedtask.import_pick_btn": {"en": "Choose file…", "ja": "ファイルを選択…", "vi": "Chọn file…"},
"schedtask.drop_hint": {
"en": "…or drag & drop the filled .xlsx here",
"ja": "…または記入済みの .xlsx をここにドラッグ&ドロップ",
"vi": "…hoặc kéo-thả file .xlsx đã điền vào đây"},
"schedtask.f_depends_on": {
"en": "Wait for tasks (all must be Done)", "ja": "待機するタスク(全てDone必須)",
"vi": "Chờ các task (tất cả phải Done)"},
"schedtask.gen_desc_tooltip": {
"en": "Generate the Prompt from this description (the title is not used)",
"ja": "この説明からプロンプトを生成(タイトルは使用しません)",
"vi": "Sinh Prompt từ mô tả này (không dùng tiêu đề)"},
"schedtask.gen_needs_description": {
"en": "Enter a description first — the Prompt is generated from it.",
"ja": "先に説明を入力してください。プロンプトは説明から生成されます。",
"vi": "Hãy nhập mô tả trước — Prompt được sinh ra từ mô tả."},
# ---- dashboard_tab.py ------------------------------------------------
"dashboard.title": {"en": "Dashboard — token usage & cost", "ja": "Dashboard — トークン使用量とコスト",
"vi": "Dashboard — token & chi phí"},
"dashboard.period.today": {"en": "Today", "ja": "今日", "vi": "Hôm nay"},
"dashboard.period.week": {"en": "Last 7 days", "ja": "過去7日", "vi": "7 ngày qua"},
"dashboard.period.month": {"en": "Last 30 days", "ja": "過去30日", "vi": "30 ngày qua"},
"dashboard.period.all": {"en": "All time", "ja": "全期間", "vi": "Toàn bộ"},
"dashboard.source_all": {"en": "All tasks/sessions", "ja": "全タスク/セッション", "vi": "Mọi task/phiên"},
"dashboard.refresh_tooltip": {"en": "Refresh now", "ja": "今すぐ更新", "vi": "Làm mới ngay"},
"dashboard.card_total": {"en": "Total tokens", "ja": "合計トークン", "vi": "Tổng token"},
"dashboard.card_in": {"en": "Input", "ja": "入力", "vi": "Input"},
"dashboard.card_out": {"en": "Output", "ja": "出力", "vi": "Output"},
"dashboard.card_cache": {"en": "Cache", "ja": "キャッシュ", "vi": "Cache"},
"dashboard.card_cost": {"en": "Cost", "ja": "コスト", "vi": "Chi phí"},
"dashboard.card_turns": {"en": "{n} turns", "ja": "{n} ターン", "vi": "{n} lượt"},
"dashboard.prices_label": {
"en": "Unit price (USD / 1M tokens):", "ja": "単価 (USD / 100万トークン):",
"vi": "Đơn giá (USD / 1 triệu token):"},
"dashboard.price_in": {"en": "In", "ja": "入力", "vi": "In"},
"dashboard.price_out": {"en": "Out", "ja": "出力", "vi": "Out"},
"dashboard.price_cache": {"en": "Cache", "ja": "キャッシュ", "vi": "Cache"},
"dashboard.habits_title": {
"en": "Usage habits overview", "ja": "利用傾向の概要", "vi": "Tổng quan thói quen sử dụng"},
"dashboard.chart_title": {"en": "Tokens / cost over time", "ja": "トークン/コスト推移",
"vi": "Token / chi phí theo thời gian"},
"dashboard.strategy_btn": {"en": "Apply saving strategy", "ja": "節約戦略を適用",
"vi": "Áp dụng chiến lược tiết kiệm"},
"dashboard.strategy_tooltip": {
"en": "Apply the AI's cost-saving strategy: auto-compress earlier + digest context before each turn.",
"ja": "AIの節約戦略を適用:早めに自動圧縮+各ターン前にコンテキストを要約。",
"vi": "Áp dụng chiến lược tiết kiệm của AI: tự động nén sớm hơn + tóm gọn ngữ cảnh trước mỗi lượt."},
"dashboard.strategy_title": {"en": "Apply saving strategy", "ja": "節約戦略の適用",
"vi": "Áp dụng chiến lược tiết kiệm"},
"dashboard.strategy_confirm": {
"en": "Turn on auto-compress (earlier, at 60%) and compress context before each turn to cut tokens?",
"ja": "自動圧縮(60%で早めに)とターン前のコンテキスト圧縮を有効にしてトークンを削減しますか?",
"vi": "Bật tự động nén (sớm hơn, ở 60%) và nén ngữ cảnh trước mỗi lượt để giảm token?"},
"dashboard.strategy_applied": {
"en": "Saving strategy applied: auto-compress on, compress-before-send on.",
"ja": "節約戦略を適用:自動圧縮ON、送信前圧縮ON。",
"vi": "Đã áp dụng: bật tự động nén và nén trước khi gửi."},
"dashboard.gran_day": {"en": "By day", "ja": "日別", "vi": "Theo ngày"},
"dashboard.gran_week": {"en": "By week", "ja": "週別", "vi": "Theo tuần"},
"dashboard.gran_month": {"en": "By month", "ja": "月別", "vi": "Theo tháng"},
"dashboard.gran_year": {"en": "By year", "ja": "年別", "vi": "Theo năm"},
"dashboard.ref_last_week": {"en": "Last week", "ja": "先週", "vi": "Tuần trước"},
"dashboard.ref_last_month": {"en": "Last month", "ja": "先月", "vi": "Tháng trước"},
"dashboard.ref_last_year": {"en": "Last year", "ja": "昨年", "vi": "Năm trước"},
"usage.budget_title": {"en": "Budget", "ja": "予算", "vi": "Ngân sách"},
"usage.budget_no_budget": {"en": "No budget set", "ja": "予算未設定", "vi": "Chưa đặt Budget"},
"usage.budget_used_pct": {"en": "{pct}% used", "ja": "{pct}% 使用済み", "vi": "Đã dùng {pct}%"},
"usage.budget_over_warning": {"en": "⚠ Over 85% of budget used",
"ja": "⚠ 予算の85%以上を使用",
"vi": "⚠ Đã dùng quá 85% Budget"},
"usage.budget_apply_tooltip": {"en": "Set this as the budget (starts a fresh remaining-balance window)",
"ja": "この金額を予算として設定(残高の計算を今から開始)",
"vi": "Đặt số này làm Budget (tính số dư mới từ bây giờ)"},
"usage.budget_spin_tooltip": {"en": "Enter the budget amount directly, then click ✓",
"ja": "予算額を直接入力して ✓ をクリック",
"vi": "Nhập Budget trực tiếp rồi bấm ✓"},
"dashboard.chart_prev": {"en": "Previous period", "ja": "前の期間", "vi": "Kỳ trước"},
"dashboard.chart_next": {"en": "Next period", "ja": "次の期間", "vi": "Kỳ sau"},
"dashboard.metric_cost": {"en": "Cost", "ja": "コスト", "vi": "Chi phí"},
"dashboard.metric_tokens": {"en": "Tokens", "ja": "トークン", "vi": "Token"},
"dashboard.h_top": {"en": "Top token consumers (task/session)", "ja": "トークン消費上位(タスク/セッション)",
"vi": "Tiêu tốn token nhiều nhất (task/phiên)"},
"dashboard.h_by_source": {"en": "By area", "ja": "領域別", "vi": "Theo khu vực"},
"dashboard.h_avg": {"en": "Average per prompt", "ja": "1プロンプト平均", "vi": "Trung bình mỗi prompt"},
"dashboard.h_busiest_day": {"en": "Busiest day", "ja": "最も使った日", "vi": "Ngày dùng nhiều nhất"},
"dashboard.h_busiest_hour": {"en": "Busiest hour", "ja": "最も使う時間帯", "vi": "Khung giờ hay dùng"},
"dashboard.no_data": {
"en": "No usage recorded in this period yet — run a chat or a task first.",
"ja": "この期間の使用記録はまだありません。チャットやタスクを実行してください。",
"vi": "Chưa có dữ liệu sử dụng trong giai đoạn này — hãy chạy chat hoặc task trước."},
}
+343
View File
@@ -0,0 +1,343 @@
"""Chuỗi hiển thị — phần libreoffice_view.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"structure.export_title": {"en": "Export graph PNG", "ja": "グラフを PNG でエクスポート", "vi": "Xuất đồ thị ra PNG"},
"structure.export_done": {"en": "Graph exported to {path}", "ja": "グラフを {path} にエクスポートしました", "vi": "Đã xuất đồ thị ra {path}"},
"structure.export_failed": {"en": "Export failed: {err}", "ja": "エクスポート失敗: {err}", "vi": "Xuất thất bại: {err}"},
"structure.scan_first": {"en": "Scan a graph first.", "ja": "先にグラフをスキャンしてください。", "vi": "Hãy Scan đồ thị trước."},
"structure.related_sources": {
"en": "Related files (click to open):",
"ja": "関連ファイル(クリックで開く):",
"vi": "Tệp liên quan (bấm để mở):"},
"structure.legend.dir": {"en": "Folder", "ja": "フォルダ", "vi": "Thư mục"},
"structure.legend.file": {"en": "File", "ja": "ファイル", "vi": "Tệp"},
"structure.legend.class": {"en": "Class", "ja": "クラス", "vi": "Class"},
"structure.legend.function": {"en": "Function", "ja": "関数", "vi": "Function"},
"structure.legend.method": {"en": "Method", "ja": "メソッド", "vi": "Method"},
"structure.legend.module": {"en": "Module", "ja": "モジュール", "vi": "Module"},
"structure.legend.section": {"en": "Section", "ja": "セクション", "vi": "Mục"},
"structure.legend.json_key": {"en": "JSON key", "ja": "JSONキー", "vi": "Khóa JSON"},
"structure.legend.entities": {"en": "Entities", "ja": "エンティティ", "vi": "Thực thể"},
"structure.legend.relationships": {"en": "Relationships", "ja": "関係", "vi": "Quan hệ"},
"structure.show_label": {"en": "Show label", "ja": "ラベル表示", "vi": "Hiện nhãn"},
"structure.show_relationship": {
"en": "Show relationship", "ja": "関係を表示", "vi": "Hiện quan hệ"},
"structure.edge.contains": {"en": "contains", "ja": "含む", "vi": "chứa"},
"structure.edge.defines": {"en": "defines", "ja": "定義", "vi": "định nghĩa"},
"structure.edge.method": {"en": "method", "ja": "メソッド", "vi": "phương thức"},
"structure.edge.imports": {"en": "imports", "ja": "インポート", "vi": "import"},
"structure.edge.subsection": {"en": "subsection", "ja": "サブセクション", "vi": "mục con"},
# ---- libreoffice_view.py -------------------------------------------
"libreoffice.open_btn": {"en": "Open in LibreOffice", "ja": "LibreOffice で開く", "vi": "Mở bằng LibreOffice"},
"libreoffice.not_found": {
"en": ("LibreOffice was not found. Install LibreOffice (or set the "
"SOFFICE_PATH environment variable) to view and edit documents here."),
"ja": "LibreOffice が見つかりません。ここで文書を表示/編集するには LibreOffice をインストールするか、環境変数 SOFFICE_PATH を設定してください。",
"vi": "Không tìm thấy LibreOffice. Hãy cài LibreOffice (hoặc đặt biến môi trường SOFFICE_PATH) để xem/sửa tài liệu tại đây."},
"libreoffice.windows_only": {
"en": "Embedding the editor is available on Windows. Click below to open this document in LibreOffice.",
"ja": "エディタの埋め込みは Windows でのみ利用可能です。下のボタンで LibreOffice で開いてください。",
"vi": "Nhúng trình soạn thảo chỉ khả dụng trên Windows. Bấm bên dưới để mở tài liệu bằng LibreOffice."},
"libreoffice.start_failed": {"en": "Could not start LibreOffice ({err}).", "ja": "LibreOffice を起動できませんでした({err})。", "vi": "Không khởi động được LibreOffice ({err})."},
"libreoffice.opening": {"en": "Opening the document in LibreOffice…", "ja": "LibreOffice で文書を開いています…", "vi": "Đang mở tài liệu bằng LibreOffice…"},
"libreoffice.embed_failed": {
"en": "Couldn't embed the LibreOffice window. You can open it in a separate window instead.",
"ja": "LibreOffice ウィンドウを埋め込めませんでした。別ウィンドウで開くことができます。",
"vi": "Không nhúng được cửa sổ LibreOffice. Bạn có thể mở nó ở cửa sổ riêng."},
"libreoffice.embed_error": {"en": "Couldn't embed LibreOffice ({err}).", "ja": "LibreOffice を埋め込めませんでした({err})。", "vi": "Không nhúng được LibreOffice ({err})."},
# ---- monitoring_tab.py (📊 Monitoring Dashboard) --------------------
"monitoring.title": {"en": "Monitoring Dashboard", "ja": "モニタリングダッシュボード", "vi": "Bảng giám sát"},
"monitoring.refresh": {"en": "Refresh", "ja": "更新", "vi": "Làm mới"},
"monitoring.tab_security": {"en": "Security", "ja": "セキュリティ", "vi": "Bảo mật"},
"monitoring.tab_mcp": {"en": "MCP", "ja": "MCP", "vi": "MCP"},
"monitoring.tab_actions": {"en": "Actions", "ja": "アクション", "vi": "Hành động"},
"monitoring.tab_agents": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
"monitoring.tab_accounts": {"en": "Accounts", "ja": "アカウント", "vi": "Tài khoản"},
"monitoring.col_time": {"en": "Time", "ja": "時刻", "vi": "Thời gian"},
"monitoring.col_role": {"en": "Agent Role", "ja": "エージェント役割", "vi": "Vai trò Agent"},
"monitoring.col_name": {"en": "Action", "ja": "アクション", "vi": "Hành động"},
"monitoring.col_result": {"en": "Result", "ja": "結果", "vi": "Kết quả"},
# Security Events shows WHICH rule fired instead of a result that is always
# the same — every security_block is recorded with ok=False.
"monitoring.col_action": {"en": "Action", "ja": "アクション", "vi": "Hành động"},
# The fourth KPI tile on Overview, as the wireframe labels it.
"monitoring.overview_calls": {"en": "Calls", "ja": "呼び出し", "vi": "Lượt gọi"},
# The fold under the Sandbox summary line — the wireframe shows only the
# summary, so the ID / created / uptime / limits rows live behind this.
"monitoring.overview_disk_free": {
"en": "{size} free", "ja": "空き {size}", "vi": "{size} trống"},
"monitoring.overview_disk_label": {"en": "Disk", "ja": "ディスク", "vi": "Đĩa"},
"monitoring.overview_sbx_detail": {
"en": "Details", "ja": "詳細", "vi": "Chi tiết"},
"monitoring.col_detail": {"en": "Detail", "ja": "詳細", "vi": "Chi tiết"},
"monitoring.col_account": {"en": "Account", "ja": "アカウント", "vi": "Tài khoản"},
"monitoring.col_machine": {"en": "Machine", "ja": "マシン", "vi": "Máy"},
"monitoring.col_agent": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
"monitoring.col_source": {"en": "Source", "ja": "ソース", "vi": "Nguồn"},
"monitoring.active_n": {"en": "{n} running", "ja": "{n} 件実行中", "vi": "{n} đang chạy"},
"monitoring.idle": {"en": "Idle", "ja": "アイドル", "vi": "Rảnh"},
"monitoring.agent_status_title": {
"en": "Agent Status", "ja": "エージェント状態", "vi": "Trạng thái Agent"},
"monitoring.source_cowork": {
"en": "Cowork tab's active turns", "ja": "Cowork タブの実行中ターン",
"vi": "Lượt đang chạy của tab Cowork"},
"monitoring.source_task": {
"en": "Schedule Task's running tasks", "ja": "Schedule Task の実行中タスク",
"vi": "Task đang chạy trong Schedule Task"},
"monitoring.source_knowledge": {
"en": "GraphRAG's Ask box", "ja": "GraphRAG の Ask ボックス", "vi": "Ô hỏi của GraphRAG"},
"monitoring.source_code": {
"en": "Runs inside a Task Agent run when the task type is Code",
"ja": "タスクタイプが Code の場合、Task Agent の実行内で動作します",
"vi": "Chạy bên trong một lượt Task Agent khi loại task là Code"},
"monitoring.source_planner": {
"en": "A phase inside a running Cowork/Task turn (update_plan) — not tracked separately",
"ja": "実行中の Cowork/Task ターン内の一段階(update_plan)— 個別には追跡されません",
"vi": "Một giai đoạn trong lượt Cowork/Task đang chạy (update_plan) — không theo dõi riêng"},
"monitoring.source_reasoning": {
"en": "The model's streamed reasoning within a running turn — not tracked separately",
"ja": "実行中のターン内でモデルがストリーミングする推論 — 個別には追跡されません",
"vi": "Luồng suy luận (reasoning) của model trong lượt đang chạy — không theo dõi riêng"},
"monitoring.source_security": {
"en": "Agent Security's prompt/attachment/command validation — runs inline on the active turn",
"ja": "エージェントセキュリティのプロンプト/添付/コマンド検証 — 実行中のターン内でインライン実行",
"vi": "Kiểm duyệt prompt/đính kèm/lệnh của Agent Security — chạy inline trong lượt đang chạy"},
"monitoring.on": {"en": "On", "ja": "オン", "vi": "Bật"},
"monitoring.off": {"en": "Off", "ja": "オフ", "vi": "Tắt"},
# ---- monitoring_tab.py — Overview card dashboard ---------------------
"monitoring.tab_overview": {"en": "Overview", "ja": "概要", "vi": "Tổng quan"},
"monitoring.overview_usage_title": {
"en": "Token & Cost", "ja": "トークンとコスト", "vi": "Token & Chi phí"},
"monitoring.overview_currency": {"en": "Currency:", "ja": "通貨:", "vi": "Tiền tệ:"},
"monitoring.tab_agents_admin": {
"en": "Agents Admin", "ja": "エージェント管理", "vi": "Agents Admin"},
"monitoring.tab_tools": {"en": "Tools", "ja": "ツール", "vi": "Công cụ"},
# ---- tools_admin_tab.py — govern built-in tools + Connectors/MCP -------
"tools_admin.hint": {
"en": "Enable or disable the built-in agent tools below. A tool toggled off is removed "
"from the agent's toolset. MCP / REST-API connectors are set up in the Connector "
"sub-tab.",
"ja": "下の組み込みエージェントツールをオン/オフします。オフにしたツールはツールセットから除外"
"されます。MCP / REST-APIコネクターは「Connector」サブタブで設定します。",
"vi": "Bật/tắt các tool tích hợp bên dưới. Tool bị tắt sẽ bị loại khỏi bộ công cụ của agent. "
"Connector MCP / REST-API được thiết lập ở tab con Connector."},
"tools_admin.refresh": {"en": "Refresh", "ja": "更新", "vi": "Làm mới"},
"tools_admin.url_fetch_group": {
"en": "Web access (fetch_url)", "ja": "Webアクセス (fetch_url)",
"vi": "Truy cập web (fetch_url)"},
"tools_admin.internet_disabled": {
"en": "Web access is OFF — enable the fetch_url tool above to allow internet access.",
"ja": "Web アクセスはオフです — 上の fetch_url ツールを有効にするとインターネットに接続できます。",
"vi": "Truy cập web đang TẮT — bật tool fetch_url ở trên để cho phép truy cập internet."},
"tools_admin.subtab_tool": {"en": "Tool", "ja": "ツール", "vi": "Tool"},
"tools_admin.subtab_connector": {"en": "Connector", "ja": "コネクター", "vi": "Connector"},
"monitoring.tab_icons": {"en": "Icons", "ja": "アイコン", "vi": "Icon"},
"icons_admin.title": {"en": "Icons", "ja": "アイコン", "vi": "Icon"},
"icons_admin.hint": {
"en": "Icons you can use for agents and flows. Type a name into a step/agent's Icon field to "
"use it. Add your own SVG icons below — they become usable by name immediately.",
"ja": "エージェントやフローに使えるアイコン。ステップ/エージェントのアイコン欄に名前を入力すると使えます。"
"下から独自のSVGアイコンを追加でき、名前ですぐ使えます。",
"vi": "Các icon dùng cho agent và flow. Gõ tên vào ô Icon của step/agent để dùng. Thêm icon SVG "
"của bạn ở dưới — dùng được ngay bằng tên."},
"icons_admin.search": {"en": "Search icons by name…", "ja": "名前でアイコンを検索…", "vi": "Tìm icon theo tên…"},
"icons_admin.builtin": {"en": "Built-in icons", "ja": "組込みアイコン", "vi": "Icon tích hợp"},
"icons_admin.custom": {"en": "Custom icons", "ja": "カスタムアイコン", "vi": "Icon tùy chỉnh"},
"icons_admin.add": {"en": "Add SVG file", "ja": "SVGファイルを追加", "vi": "Thêm tệp SVG"},
"icons_admin.paste": {"en": "Paste SVG", "ja": "SVGを貼付", "vi": "Dán SVG"},
"icons_admin.paste_prompt": {"en": "Paste the SVG markup:", "ja": "SVGマークアップを貼り付け:",
"vi": "Dán mã SVG:"},
"icons_admin.delete": {"en": "Delete custom", "ja": "カスタムを削除", "vi": "Xóa tùy chỉnh"},
"icons_admin.name_prompt": {"en": "Icon name (used in the Icon field)", "ja": "アイコン名(アイコン欄で使用)",
"vi": "Tên icon (dùng ở ô Icon)"},
"icons_admin.select_custom": {"en": "Select a custom icon to delete.",
"ja": "削除するカスタムアイコンを選択してください。",
"vi": "Hãy chọn một icon tùy chỉnh để xóa."},
"tools_admin.jira_note": {
"en": "Jira connection setup moved to the Connector tab → set it up there; here you only turn "
"the jira_search / jira_get_issue tools on or off.",
"ja": "Jira接続の設定はConnectorタブに移動しました。設定はそちらで。ここでは jira_search / "
"jira_get_issue ツールの有効/無効のみ切り替えます。",
"vi": "Phần thiết lập kết nối Jira đã chuyển sang tab Connector → cài đặt ở đó; ở đây chỉ bật/tắt "
"tool jira_search / jira_get_issue."},
"connectors.jira_group": {"en": "Jira (read)", "ja": "Jira(読み取り)", "vi": "Jira (đọc)"},
"connectors.jira_hint": {
"en": "Connect once, then just paste a Jira link into Cowork or a Co4E step — the agent reads it "
"automatically (no issue key needed). Read-only. A public Jira link works with no setup; "
"a private one needs this connection. Create a token: id.atlassian.com → Security → API tokens.",
"ja": "一度接続すれば、Cowork や Co4E ステップに Jira リンクを貼るだけで自動で読み取ります(課題キー不要)。"
"読み取り専用。公開リンクは設定不要、非公開はこの接続が必要。トークン作成: id.atlassian.com → セキュリティ → APIトークン。",
"vi": "Kết nối một lần, rồi chỉ cần dán link Jira vào Cowork hoặc bước Co4E — agent tự đọc (không cần "
"issue key). Chỉ đọc. Link Jira công khai không cần cài đặt; link riêng tư cần kết nối này. "
"Tạo token: id.atlassian.com → Security → API tokens."},
"connectors.jira_paste": {"en": "Paste a link", "ja": "リンクを貼付", "vi": "Dán link"},
"connectors.jira_paste_placeholder": {
"en": "Paste any Jira link — fills the base URL for you",
"ja": "Jiraのリンクを貼ると、ベースURLが自動入力されます",
"vi": "Dán bất kỳ link Jira nào — tự điền Base URL"},
"connectors.jira_url": {"en": "Base URL", "ja": "ベースURL", "vi": "Base URL"},
"connectors.jira_email": {"en": "Email", "ja": "メール", "vi": "Email"},
"connectors.jira_token": {"en": "API token", "ja": "APIトークン", "vi": "API token"},
"connectors.jira_save": {"en": "Save", "ja": "保存", "vi": "Lưu"},
"connectors.jira_test": {"en": "Test connection", "ja": "接続テスト", "vi": "Kiểm tra kết nối"},
"connectors.jira_saved": {"en": "Saved.", "ja": "保存しました。", "vi": "Đã lưu."},
"connectors.jira_connected": {"en": "connected", "ja": "接続済み", "vi": "đã kết nối"},
"connectors.jira_not_set": {"en": "not configured", "ja": "未設定", "vi": "chưa cấu hình"},
"connectors.jira_setup_hint": {
"en": "Double-click to connect Jira (paste any Jira link — no per-request setup after that).",
"ja": "ダブルクリックで Jira に接続(Jira リンクを貼るだけ、以降は設定不要)。",
"vi": "Nhấp đúp để kết nối Jira (dán bất kỳ link Jira nào — sau đó không cần thiết lập gì thêm)."},
"connectors.builtin_auto": {
"en": "Built-in, connects automatically", "ja": "組み込み、自動接続",
"vi": "Tích hợp, tự kết nối"},
"connectors.connect_external": {
"en": "Connect to external connectors",
"ja": "外部コネクタに接続する",
"vi": "Kết nối tới connector bên ngoài"},
"connectors.connect_external_tooltip": {
"en": ("Master switch (default ON): when off, the agent connects to NO external "
"connector or MCP server — the per-connector settings below are ignored."),
"ja": "マスタースイッチ(既定オン): オフにすると、エージェントは外部コネクタ/MCPサーバーに"
"一切接続しません(下の個別設定は無視されます)。",
"vi": ("Công tắc tổng (mặc định BẬT): khi tắt, agent sẽ KHÔNG kết nối tới bất kỳ connector "
"hay MCP server bên ngoài nào — các thiết lập từng connector bên dưới bị bỏ qua.")},
"connectors.jira_testing": {"en": "Testing…", "ja": "テスト中…", "vi": "Đang kiểm tra…"},
"connectors.jira_ok": {"en": "✓ Connected to Jira.", "ja": "✓ Jiraに接続できました。", "vi": "✓ Kết nối Jira thành công."},
"connectors.jira_fail": {"en": "✗ {err}", "ja": "✗ {err}", "vi": "✗ {err}"},
"connectors.jira_need_fields": {
"en": "Enter base URL, email and API token first.",
"ja": "先にベースURL・メール・APIトークンを入力してください。",
"vi": "Hãy nhập Base URL, Email và API token trước."},
"tools_admin.jira_group": {"en": "Jira connection", "ja": "Jira 接続", "vi": "Kết nối Jira"},
"tools_admin.jira_hint": {
"en": "Connect once, then just paste a Jira issue link into Cowork or a Co4E step — the agent "
"reads it automatically (no issue key needed). Read-only. Private Jira needs this one-time "
"connection; a public Jira link works with no setup. API token: id.atlassian.com → "
"Security → API tokens. Turn the jira tools on/off in the list above.",
"ja": "一度接続すれば、あとは Cowork や Co4E ステップに Jira のリンクを貼るだけで自動的に読み取ります"
"(課題キー不要)。読み取り専用。非公開Jiraはこの一度の接続が必要、公開リンクは設定不要。"
"APIトークン: id.atlassian.com → セキュリティ → APIトークン。ツールの有効/無効は上の一覧で。",
"vi": "Kết nối một lần, sau đó chỉ cần dán link Jira vào Cowork hoặc bước Co4E — agent tự đọc "
"(không cần nhập issue key). Chỉ đọc. Jira riêng tư cần kết nối một lần này; link Jira công "
"khai thì không cần cài đặt. API token: id.atlassian.com → Security → API tokens. Bật/tắt "
"tool jira ở danh sách phía trên."},
"tools_admin.jira_url": {"en": "Base URL", "ja": "ベースURL", "vi": "Base URL"},
"tools_admin.jira_email": {"en": "Email", "ja": "メール", "vi": "Email"},
"tools_admin.jira_token": {"en": "API token", "ja": "APIトークン", "vi": "API token"},
"tools_admin.jira_save": {"en": "Save", "ja": "保存", "vi": "Lưu"},
"tools_admin.jira_test": {"en": "Test connection", "ja": "接続テスト", "vi": "Kiểm tra kết nối"},
"tools_admin.jira_saved": {"en": "Saved.", "ja": "保存しました。", "vi": "Đã lưu."},
"tools_admin.jira_testing": {"en": "Testing…", "ja": "テスト中…", "vi": "Đang kiểm tra…"},
"tools_admin.jira_ok": {"en": "✓ Connected to Jira.", "ja": "✓ Jiraに接続できました。", "vi": "✓ Kết nối Jira thành công."},
"tools_admin.jira_fail": {"en": "✗ {err}", "ja": "✗ {err}", "vi": "✗ {err}"},
"tools_admin.jira_need_fields": {
"en": "Enter base URL, email and API token first.",
"ja": "先にベースURL・メール・APIトークンを入力してください。",
"vi": "Hãy nhập Base URL, Email và API token trước."},
# ---- Co4E (node-graph workflow studio) --------------------------------
"workspace.tab_co4e": {"en": "Co4E", "ja": "Co4E", "vi": "Co4E"},
"workspace.tab_co4e_tooltip": {
"en": "Co4E — Code for Everyone, Cowork for Everyone",
"ja": "Co4E — Code for Everyone, Cowork for Everyone",
"vi": "Co4E — Code for Everyone, Cowork for Everyone",
},
"co4e.untitled": {"en": "Untitled flow", "ja": "無題のフロー", "vi": "Flow chưa đặt tên"},
"co4e.tab_workflows": {"en": "Workflows", "ja": "ワークフロー", "vi": "Workflows"},
"co4e.tab_agents": {"en": "Agents", "ja": "エージェント", "vi": "Agents"},
"co4e.tab_skills": {"en": "Skills", "ja": "スキル", "vi": "Skills"},
"co4e.new": {"en": "New", "ja": "新規", "vi": "Mới"},
"co4e.load": {"en": "Load", "ja": "読み込み", "vi": "Tải"},
"co4e.delete": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"co4e.edit": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"co4e.new_agent": {"en": "New agent", "ja": "新規エージェント", "vi": "Agent mới"},
"co4e.manage_skills": {"en": "Manage skills…", "ja": "スキル管理…", "vi": "Quản lý skill…"},
"co4e.template": {"en": "template", "ja": "テンプレート", "vi": "mẫu"},
"co4e.saved": {"en": "saved", "ja": "保存済み", "vi": "đã lưu"},
"co4e.custom": {"en": "custom", "ja": "カスタム", "vi": "tùy chỉnh"},
"co4e.parallel_node": {"en": "Parallel (fan-out)", "ja": "並列(ファンアウト)", "vi": "Song song (fan-out)"},
"co4e.add_step": {"en": "Add step", "ja": "ステップ追加", "vi": "Thêm bước"},
"co4e.fit": {"en": "Fit", "ja": "全体表示", "vi": "Vừa màn hình"},
"co4e.fit_tooltip": {
"en": "Auto-fit: zoom to show every step", "ja": "自動フィット:全ステップを表示",
"vi": "Tự canh: thu phóng để thấy tất cả bước"},
"co4e.drag_hint": {
"en": "Drag a flow or agent onto the canvas (double-click a flow to load it).",
"ja": "フローやエージェントをキャンバスにドラッグ(フローはダブルクリックで読み込み)。",
"vi": "Kéo một flow hoặc agent vào canvas (double-click flow để tải)."},
"co4e.blank_step": {"en": "Blank step", "ja": "空のステップ", "vi": "Bước trống"},
"co4e.pick_agent": {"en": "Choose an agent", "ja": "エージェントを選択", "vi": "Chọn agent"},
"co4e.ai_draft": {"en": "Draft with AI", "ja": "AIで下書き", "vi": "Soạn bằng AI"},
"co4e.ai_draft_tooltip": {
"en": "Let AI write this agent's instructions from its name and role (no skill needed).",
"ja": "エージェントの名前と役割から指示文をAIが作成(スキル不要)。",
"vi": "Để AI viết hướng dẫn cho agent từ tên và vai trò (không cần skill)."},
"co4e.ai_draft_hint_title": {"en": "Draft with AI", "ja": "AIで下書き", "vi": "Soạn bằng AI"},
"co4e.ai_draft_hint_label": {
"en": "Describe what this agent should do (optional — leave blank to draft from just "
"the name/role). More detail here → more detailed instructions.",
"ja": "このエージェントが何をすべきか説明してください(任意 — 空欄なら名前/役割のみから"
"下書き)。詳しく書くほど、生成される指示も詳細になります。",
"vi": "Mô tả agent này nên làm gì (không bắt buộc — để trống sẽ soạn chỉ từ tên/vai trò). "
"Mô tả chi tiết hơn → hướng dẫn được tạo ra chi tiết hơn."},
"co4e.tt_add_step": {"en": "Add a blank step to the canvas", "ja": "空のステップをキャンバスに追加",
"vi": "Thêm một bước trống vào canvas"},
"co4e.tt_save": {"en": "Save this flow", "ja": "このフローを保存", "vi": "Lưu flow này"},
"co4e.tt_save_template": {"en": "Save as a reusable template", "ja": "再利用テンプレートとして保存",
"vi": "Lưu thành mẫu dùng lại"},
"co4e.tt_run": {"en": "Run the flow (or Interrupt while running)", "ja": "フローを実行(実行中は中断)",
"vi": "Chạy flow (hoặc Dừng khi đang chạy)"},
"co4e.tt_mode": {
"en": "Auto = each step plans then runs · Plan = dry-run a plan (read-only) · Manual = step-by-step (advance with Next step)",
"ja": "Auto=各ステップが計画して実行 · Plan=計画のみ(読取専用)· Manual=1ステップずつ(「次へ」で進む)",
"vi": "Auto = mỗi bước tự lập kế hoạch rồi chạy · Plan = chỉ lập kế hoạch (chỉ đọc) · Manual = từng bước (bấm Bước tiếp)"},
"co4e.tt_new_wf": {"en": "Start a new empty flow", "ja": "新しい空のフロー", "vi": "Tạo flow mới trống"},
"co4e.tt_load_wf": {"en": "Load the selected flow into the canvas",
"ja": "選択したフローをキャンバスに読み込み", "vi": "Tải flow đã chọn vào canvas"},
"co4e.tt_del_wf": {"en": "Delete the selected saved flow", "ja": "選択した保存フローを削除",
"vi": "Xóa flow đã lưu đang chọn"},
"co4e.tt_edit_wf": {"en": "Edit the selected flow", "ja": "選択したフローを編集",
"vi": "Sửa flow đang chọn"},
"co4e.tt_new_agent": {"en": "Create a custom agent persona", "ja": "カスタムエージェントを作成",
"vi": "Tạo một agent tùy chỉnh"},
"co4e.tt_edit_agent": {"en": "Edit the selected custom agent", "ja": "選択したカスタムエージェントを編集",
"vi": "Sửa agent tùy chỉnh đang chọn"},
"co4e.tt_del_agent": {"en": "Delete the selected custom agent", "ja": "選択したカスタムエージェントを削除",
"vi": "Xóa agent tùy chỉnh đang chọn"},
"co4e.tt_manage_skills": {"en": "Open the Skills manager", "ja": "スキル管理を開く",
"vi": "Mở trình quản lý Skill"},
"co4e.save": {"en": "Save", "ja": "保存", "vi": "Lưu"},
"co4e.save_template": {"en": "Save as Template", "ja": "テンプレートとして保存", "vi": "Lưu làm mẫu"},
"co4e.flow_name": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
"co4e.run": {"en": "Run", "ja": "実行", "vi": "Chạy"},
"co4e.interrupt": {"en": "Interrupt", "ja": "中断", "vi": "Dừng"},
"co4e.add": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"co4e.config_title": {"en": "Step config", "ja": "ステップ設定", "vi": "Cấu hình bước"},
"co4e.tt_collapse_config": {"en": "Collapse the config panel", "ja": "設定パネルを折りたたむ",
"vi": "Thu gọn bảng cấu hình"},
"co4e.tt_expand_config": {"en": "Expand the config panel", "ja": "設定パネルを展開",
"vi": "Mở rộng bảng cấu hình"},
"co4e.messages": {"en": "Messages", "ja": "メッセージ", "vi": "Tin nhắn"},
"co4e.tt_collapse_msgs": {"en": "Collapse the messages panel", "ja": "メッセージを折りたたむ",
"vi": "Thu gọn khung tin nhắn"},
"co4e.tt_expand_msgs": {"en": "Expand the messages panel", "ja": "メッセージを展開",
"vi": "Mở rộng khung tin nhắn"},
"co4e.mode.auto": {"en": "Auto", "ja": "自動", "vi": "Auto"},
"co4e.mode.plan": {"en": "Plan", "ja": "計画", "vi": "Plan"},
"co4e.mode.manual": {"en": "Manual", "ja": "手動", "vi": "Manual"},
# --- Co4E run manager / duplicate / status / zoom (parallel flows) ---
"co4e.copy_suffix": {"en": "copy", "ja": "コピー", "vi": "bản sao"},
"co4e.tt_dup_wf": {"en": "Duplicate the selected flow (run copies in parallel)",
"ja": "選択フローを複製(コピーを並列実行)", "vi": "Nhân bản flow đã chọn (chạy bản sao song song)"},
}
+344
View File
@@ -0,0 +1,344 @@
"""Chuỗi hiển thị — phần login_dialog.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
# ---- login_dialog.py: startup login / bootstrap / offline ----
"login.title": {"en": "Sign in", "ja": "サインイン", "vi": "Đăng nhập"},
"login.header": {"en": "Cowork-Local BamBOO", "ja": "Cowork-Local BamBOO", "vi": "Cowork-Local BamBOO"},
"login.account": {"en": "Account", "ja": "アカウント", "vi": "Tài khoản"},
"login.code": {"en": "Access code", "ja": "アクセスコード", "vi": "Mã truy cập"},
"login.department": {"en": "Department (optional)", "ja": "部署(任意)", "vi": "Phòng ban (không bắt buộc)"},
"login.department_placeholder": {
"en": "e.g. FA.PDS — groups you automatically", "ja": "例: FA.PDS — 自動でグループ分けされます",
"vi": "vd: FA.PDS — sẽ tự động xếp vào nhóm tương ứng"},
"login.login_btn": {"en": "Log in", "ja": "ログイン", "vi": "Đăng nhập"},
"login.exit_btn": {"en": "Exit", "ja": "終了", "vi": "Thoát"},
"login.err_invalid": {
"en": "Invalid account or access code.", "ja": "アカウントまたはアクセスコードが無効です。",
"vi": "Tài khoản hoặc mã truy cập không đúng."},
"login.err_admin_exists": {
"en": "An Admin account already exists for this shared folder — the app has exactly one. Log in with an account issued by the Admin instead.",
"ja": "この共有フォルダには既に管理者アカウントが存在します(管理者は1人のみ)。管理者から発行されたアカウントでログインしてください。",
"vi": "Thư mục dùng chung này đã có tài khoản Admin — app chỉ có duy nhất 1 Admin. Hãy đăng nhập bằng tài khoản do Admin cấp."},
"login.err_missing_fields": {
"en": "Enter both a shared folder path and an account name.",
"ja": "共有フォルダのパスとアカウント名の両方を入力してください。",
"vi": "Nhập đường dẫn thư mục chia sẻ và tên tài khoản."},
"login.err_shared_dir": {
"en": "Could not create the shared folder: {error}",
"ja": "共有フォルダを作成できませんでした: {error}",
"vi": "Không tạo được thư mục chia sẻ: {error}"},
"login.bootstrap_hint": {
"en": "No accounts exist yet. Choose a shared folder (a network share or a "
"locally-synced OneDrive folder) and create the first Admin account.",
"ja": "アカウントがまだありません。共有フォルダ(ネットワーク共有、または同期済みの "
"OneDrive フォルダ)を選び、最初の管理者アカウントを作成してください。",
"vi": "Chưa có tài khoản nào. Chọn một thư mục chia sẻ (network share hoặc thư mục "
"OneDrive đã đồng bộ trên máy) và tạo tài khoản Admin đầu tiên."},
"login.shared_dir": {"en": "Shared folder", "ja": "共有フォルダ", "vi": "Thư mục chia sẻ"},
"login.browse": {"en": "Browse…", "ja": "参照…", "vi": "Chọn…"},
"login.create_admin": {
"en": "Create Admin account", "ja": "管理者アカウントを作成", "vi": "Tạo tài khoản Admin"},
"login.code_shown_title": {"en": "Admin account created", "ja": "管理者アカウントを作成しました",
"vi": "Đã tạo tài khoản Admin"},
"login.code_shown_body": {
"en": "Account: {username}\nAccess code: {code}\n\nSave this code now — it will "
"not be shown again. You are now logged in.",
"ja": "アカウント: {username}\nアクセスコード: {code}\n\n今すぐこのコードを保存してくださ"
"い — 二度と表示されません。ログインしました。",
"vi": "Tài khoản: {username}\nMã truy cập: {code}\n\nHãy lưu lại mã này ngay — mã sẽ "
"không hiển thị lại lần nào nữa. Bạn đã đăng nhập."},
"login.unreachable": {
"en": "Can't reach the shared folder:\n{path}", "ja": "共有フォルダに到達できません:\n{path}",
"vi": "Không truy cập được thư mục chia sẻ:\n{path}"},
"login.offline_hint": {
"en": "Last successful login on this machine: {username} ({role}).",
"ja": "このマシンでの最後の正常なログイン: {username} ({role})。",
"vi": "Lần đăng nhập thành công gần nhất trên máy này: {username} ({role})."},
"login.offline_btn": {"en": "Continue offline as {role}", "ja": "{role} としてオフラインで続行",
"vi": "Tiếp tục offline với vai trò {role}"},
"login.no_offline_cache": {
"en": "No previous successful login on this machine — contact your Admin.",
"ja": "このマシンでの過去のログイン履歴がありません — 管理者に連絡してください。",
"vi": "Chưa có lượt đăng nhập thành công nào trên máy này — liên hệ Admin."},
"login.retry_btn": {"en": "Retry", "ja": "再試行", "vi": "Thử lại"},
# ---- accounts_tab.py: Monitoring -> Accounts panel (Admin/Sub-admin) --
"accounts.edit_title": {"en": "Edit account", "ja": "アカウントを編集", "vi": "Sửa tài khoản"},
"accounts.add_title": {"en": "Add account", "ja": "アカウントを追加", "vi": "Thêm tài khoản"},
"accounts.f_username": {"en": "Account", "ja": "アカウント", "vi": "Tài khoản"},
"accounts.f_display_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"accounts.f_email": {"en": "Email", "ja": "メール", "vi": "Email"},
"accounts.f_email_placeholder": {
"en": "name@company.com (optional)", "ja": "name@company.com(任意)",
"vi": "name@company.com (không bắt buộc)"},
"accounts.f_role": {"en": "Role", "ja": "役割", "vi": "Vai trò"},
"accounts.f_department": {"en": "Department", "ja": "部門", "vi": "Bộ phận"},
"accounts.f_group": {"en": "Group", "ja": "グループ", "vi": "Nhóm"},
"accounts.f_group_name": {"en": "Group name", "ja": "グループ名", "vi": "Tên nhóm"},
"accounts.no_group": {"en": "— No group —", "ja": "— グループなし —", "vi": "— Không có nhóm —"},
"accounts.role.admin": {"en": "Admin", "ja": "管理者", "vi": "Admin"},
"accounts.role.subadmin": {"en": "Sub-admin", "ja": "サブ管理者", "vi": "Sub-admin"},
"accounts.role.user": {"en": "User", "ja": "ユーザー", "vi": "User"},
"accounts.no_shared_dir": {
"en": "No shared folder configured — set one in Settings to manage accounts.",
"ja": "共有フォルダが設定されていません — 設定でアカウント管理用のフォルダを指定してください。",
"vi": "Chưa cấu hình thư mục chia sẻ — thiết lập trong Settings để quản lý tài khoản."},
"accounts.shared_dir_hint": {"en": "Shared folder: {path}", "ja": "共有フォルダ: {path}",
"vi": "Thư mục chia sẻ: {path}"},
"accounts.ungrouped": {"en": "Ungrouped", "ja": "未分類", "vi": "Chưa có nhóm"},
"accounts.filter_all_groups": {"en": "All groups", "ja": "すべてのグループ", "vi": "Tất cả nhóm"},
"accounts.delete_title": {"en": "Delete account", "ja": "アカウントを削除", "vi": "Xóa tài khoản"},
"accounts.delete_confirm": {"en": "Delete account '{username}'?", "ja": "アカウント「{username}」を削"
"除しますか?", "vi": "Xóa tài khoản '{username}'?"},
"accounts.new_group_title": {"en": "New group", "ja": "新しいグループ", "vi": "Nhóm mới"},
"accounts.add_btn": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"accounts.edit_btn": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"accounts.delete_btn": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"accounts.generate_code_btn": {"en": "Generate code", "ja": "コード発行", "vi": "Tạo mã"},
"accounts.new_group_btn": {"en": "New group", "ja": "新しいグループ", "vi": "Nhóm mới"},
"accounts.drag_move_hint": {
"en": "Drag an account onto a group to move it there.",
"ja": "アカウントをグループにドラッグすると移動できます。",
"vi": "Kéo tài khoản thả vào một nhóm để di chuyển đến đó."},
"accounts.err_admin_exists": {
"en": "An Admin account already exists — the app has exactly one.",
"ja": "管理者アカウントは既に存在します(1人のみ)。",
"vi": "Đã có tài khoản Admin — app chỉ có duy nhất 1 Admin."},
"accounts.search_placeholder": {
"en": "Search accounts (or type a question and press )…",
"ja": "アカウント検索(質問を入力しても可)…",
"vi": "Tìm tài khoản (hoặc gõ câu hỏi rồi bấm )…"},
"accounts.ai_search_btn": {"en": "AI", "ja": "AI", "vi": "AI"},
"accounts.ai_search_tooltip": {
"en": "AI turns your question into a search keyword (e.g. \"who in CAE has no department?\").",
"ja": "質問をAIが検索キーワードに変換します。",
"vi": "AI chuyển câu hỏi của bạn thành từ khóa tìm kiếm (vd: \"ai trong CAE chưa có phòng ban?\")."},
"accounts.excel_template_btn": {
"en": "Excel template", "ja": "Excelテンプレート", "vi": "Mẫu Excel"},
"accounts.excel_import_btn": {
"en": "Import Excel", "ja": "Excel取り込み", "vi": "Nhập từ Excel"},
"accounts.excel_imported": {
"en": "Created {n} account(s).", "ja": "{n} 件のアカウントを作成しました。",
"vi": "Đã tạo {n} tài khoản."},
"accounts.excel_codes_saved": {
"en": "Access codes saved to: {path}", "ja": "アクセスコードの保存先: {path}",
"vi": "Mã truy cập đã lưu tại: {path}"},
"accounts.usage_title": {"en": "Usage & Cost by account", "ja": "アカウント別の使用量とコスト",
"vi": "Sử dụng & Chi phí theo tài khoản"},
"accounts.period.day": {"en": "Day", "ja": "日", "vi": "Ngày"},
"accounts.period.week": {"en": "Week", "ja": "週", "vi": "Tuần"},
"accounts.period.month": {"en": "Month", "ja": "月", "vi": "Tháng"},
"accounts.period.year": {"en": "Year", "ja": "年", "vi": "Năm"},
"accounts.col_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"accounts.col_account": {"en": "Account", "ja": "アカウント", "vi": "Tài khoản"},
"accounts.col_machine": {"en": "Machine", "ja": "マシン", "vi": "Máy"},
"accounts.col_department": {"en": "Department", "ja": "部門", "vi": "Bộ phận"},
"accounts.col_tokens": {"en": "Tokens", "ja": "トークン", "vi": "Token"},
"accounts.col_cost": {"en": "Cost", "ja": "コスト", "vi": "Chi phí"},
# ---- app.py: top bar, tabs, toasts, tray ------------------------
"app.logo": {"en": "Cowork-Local BamBOO", "ja": "Cowork-Local BamBOO", "vi": "Cowork-Local BamBOO"},
"app.provider": {"en": "Provider:", "ja": "プロバイダー:", "vi": "Nhà cung cấp:"},
"app.language": {"en": "Language:", "ja": "言語:", "vi": "Ngôn ngữ:"},
"app.settings": {"en": "Settings", "ja": "設定", "vi": "Cài đặt"},
"app.tab.dashboard": {"en": "Dashboard", "ja": "Dashboard", "vi": "Dashboard"},
"app.tab.schedule": {"en": "Schedule Task", "ja": "Schedule Task", "vi": "Schedule Task"},
"app.tab.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"app.tab.code": {"en": "Code", "ja": "Code", "vi": "Code"},
"app.tab.structure": {"en": "GraphRAG", "ja": "GraphRAG", "vi": "GraphRAG"},
"app.tab.workspace": {"en": "Workspace", "ja": "ワークスペース", "vi": "Workspace"},
"app.tab.monitoring": {"en": "Monitoring", "ja": "モニタリング", "vi": "Giám sát"},
"app.nav.collapse_tooltip": {"en": "Collapse menu to icons only", "ja": "メニューをアイコンのみに折りたたむ", "vi": "Thu gọn menu về icon"},
"app.nav.expand_tooltip": {"en": "Expand menu", "ja": "メニューを展開", "vi": "Mở rộng menu"},
"app.nav.menu_label": {"en": "MENU", "ja": "MENU", "vi": "MENU"},
# Shown on the rail rows the project gate disables (Cowork, GraphRAG) —
# they stay listed and greyed instead of disappearing from the menu.
"app.nav.needs_project": {
"en": "Select a project first", "ja": "先にプロジェクトを選択してください",
"vi": "Chọn project trước"},
# Rail header: the project a new chat will be created in, and what to do
# when there is no project yet.
"app.nav.project_pick": {
"en": "Project for new chats", "ja": "新しいチャットのプロジェクト",
"vi": "Project cho đoạn chat mới"},
"app.nav.no_project": {
"en": "No project yet", "ja": "プロジェクトなし", "vi": "Chưa có project"},
"app.nav.recents": {"en": "RECENTS", "ja": "最近", "vi": "GẦN ĐÂY"},
"app.nav.all_projects": {
"en": "All projects…", "ja": "すべてのプロジェクト…", "vi": "Tất cả project…"},
"app.nav.create_project_first": {
"en": "Create a project first", "ja": "先にプロジェクトを作成してください",
"vi": "Tạo project trước"},
# ---- workspace_tab.py (Projects — Claude-Projects style) -----------
"workspace.header": {"en": "Manage projects", "ja": "プロジェクト管理", "vi": "Quản lý project"},
"workspace.tab_cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"workspace.tab_graphrag": {"en": "GraphRAG", "ja": "GraphRAG", "vi": "GraphRAG"},
"workspace.tab_project": {"en": "Project", "ja": "プロジェクト", "vi": "Project"},
"workspace.tab_folder": {"en": "Folder", "ja": "フォルダ", "vi": "Thư mục"},
"folder.path_placeholder": {
"en": "Folder path", "ja": "フォルダのパス", "vi": "Đường dẫn thư mục"},
"folder.open_folder": {"en": "Open folder", "ja": "フォルダを開く", "vi": "Mở thư mục"},
"folder.save": {"en": "Save", "ja": "保存", "vi": "Lưu"},
"folder.open_external": {
"en": "Open externally", "ja": "外部で開く", "vi": "Mở bằng app ngoài"},
"folder.preview": {"en": "Preview", "ja": "プレビュー", "vi": "Xem trước"},
"folder.edit": {"en": "Edit", "ja": "編集", "vi": "Chỉnh sửa"},
"folder.select_file": {
"en": "Select a file in the tree to view or edit it.",
"ja": "ツリーでファイルを選択して表示・編集します。",
"vi": "Chọn một tệp trong cây thư mục để xem hoặc chỉnh sửa."},
"folder.binary_file": {
"en": "Binary or very large file — open it externally to view.",
"ja": "バイナリまたは非常に大きいファイルです — 外部で開いて表示してください。",
"vi": "Tệp nhị phân hoặc quá lớn — mở bằng app ngoài để xem."},
"folder.converting": {
"en": "Rendering document… (converting to PDF via LibreOffice)",
"ja": "ドキュメントを表示中…(LibreOffice で PDF に変換しています)",
"vi": "Đang hiển thị tài liệu… (chuyển sang PDF bằng LibreOffice)"},
"folder.doc_unreadable": {
"en": "Could not extract text ({note}). Open it externally for the full document.",
"ja": "テキストを抽出できませんでした ({note})。完全な文書は外部で開いてください。",
"vi": "Không trích xuất được nội dung ({note}). Mở bằng app ngoài để xem đầy đủ."},
"folder.saved": {"en": "Saved {name}", "ja": "{name} を保存しました", "vi": "Đã lưu {name}"},
"folder.ai_edit": {"en": "AI Edit", "ja": "AI 編集", "vi": "AI Edit"},
"folder.ai_edit_tooltip": {
"en": "Edit the open file with AI (uses the Cowork conversation context)",
"ja": "AI で開いているファイルを編集(Cowork の会話コンテキストを利用)",
"vi": "Dùng AI chỉnh sửa file đang mở (dùng ngữ cảnh hội thoại Cowork)"},
"folder.ai_placeholder": {
"en": "Describe the edit… (e.g. add error handling)",
"ja": "編集内容を入力…(例: エラー処理を追加)",
"vi": "Mô tả chỉnh sửa… (vd: thêm xử lý lỗi)"},
"folder.ai_send": {"en": "Send", "ja": "送信", "vi": "Gửi"},
"folder.ai_no_file": {
"en": "Open a text/code file in Edit mode first.",
"ja": "先にテキスト/コードファイルを編集モードで開いてください。",
"vi": "Hãy mở một file text/code ở chế độ Edit trước."},
"folder.ai_applied": {
"en": "✓ Applied the edit — review it and Save.",
"ja": "✓ 編集を適用しました — 確認して保存してください。",
"vi": "✓ Đã áp dụng chỉnh sửa — kiểm tra rồi Lưu."},
"folder.ai_empty": {
"en": "(the model didn't return an edited file)",
"ja": "(モデルは編集後のファイルを返しませんでした)",
"vi": "(model không trả về file đã chỉnh sửa)"},
"folder.ai_error": {
"en": "AI edit failed: {err}", "ja": "AI 編集に失敗しました: {err}",
"vi": "AI edit thất bại: {err}"},
"folder.ai_running": {
"en": "AI is editing {name}… (keeps running while you do other things)",
"ja": "AI が {name} を編集中…(他の作業をしていても継続します)",
"vi": "AI đang chỉnh sửa {name}… (vẫn chạy tiếp khi bạn làm việc khác)"},
"folder.ai_done": {
"en": "AI edit finished for {name} — review it in the Folder tab.",
"ja": "{name} の AI 編集が完了しました — Folder タブで確認してください。",
"vi": "AI edit xong cho {name} — kiểm tra ở tab Folder."},
"folder.ai_status_running": {
"en": "processing…", "ja": "処理中…", "vi": "đang xử lí…"},
"folder.ai_status_done": {
"en": "done", "ja": "完了", "vi": "xong"},
"folder.ai_planning": {
"en": "Planning…", "ja": "計画中…", "vi": "Đang lập kế hoạch…"},
"folder.ai_apply": {"en": "Apply", "ja": "適用", "vi": "Áp dụng"},
"folder.ai_discard": {"en": "Discard", "ja": "破棄", "vi": "Hủy"},
"folder.ai_proposed": {
"en": "Proposed changes (review)", "ja": "変更案(確認)",
"vi": "Thay đổi đề xuất (xem lại)"},
"folder.ai_review_hint": {
"en": "Review the diff, then Apply or Discard.",
"ja": "差分を確認してから、適用または破棄してください。",
"vi": "Xem lại diff rồi bấm Áp dụng hoặc Hủy."},
"folder.ai_proposed_status": {
"en": "AI proposed an edit for {name} — review & Apply.",
"ja": "{name} の編集案が出ました — 確認して適用してください。",
"vi": "AI đề xuất chỉnh sửa {name} — xem lại & Áp dụng."},
"folder.ai_discarded": {
"en": "Discarded — the file was not changed.",
"ja": "破棄しました — ファイルは変更されていません。",
"vi": "Đã hủy — file không bị thay đổi."},
"folder.ai_new_file": {"en": "a new file", "ja": "新規ファイル", "vi": "file mới"},
"folder.ai_proposed_new": {
"en": "Proposed NEW file: {name} (review)",
"ja": "新規ファイルの提案: {name}(確認)",
"vi": "Đề xuất tạo file MỚI: {name} (xem lại)"},
"folder.ai_created": {
"en": "Created {name}", "ja": "{name} を作成しました", "vi": "Đã tạo {name}"},
"folder.ai_image_confirm_title": {
"en": "Confirm image change", "ja": "画像変更の確認", "vi": "Xác nhận sửa ảnh"},
"folder.ai_image_confirm": {
"en": "This edit replaces one or more images in the slide. Proceed?",
"ja": "この編集はスライド内の画像を置き換えます。実行しますか?",
"vi": "Chỉnh sửa này sẽ thay ảnh trong slide. Tiếp tục?"},
"folder.ai_image_declined": {
"en": "Image change cancelled.", "ja": "画像の変更をキャンセルしました。",
"vi": "Đã hủy thay đổi ảnh."},
"folder.ai_image_confirm_gen": {
"en": "This will GENERATE image(s) with the AI model and save them into the folder. Proceed?",
"ja": "AI モデルで画像を生成してフォルダに保存します。実行しますか?",
"vi": "Sẽ TẠO ảnh bằng model AI và lưu vào thư mục. Tiếp tục?"},
"folder.ai_image_plan": {
"en": "Will generate these illustration image(s):",
"ja": "以下のイラスト画像を生成します:",
"vi": "Sẽ tạo các ảnh minh họa sau:"},
"folder.ai_generating": {
"en": "Generating image(s)…", "ja": "画像を生成中…", "vi": "Đang tạo ảnh…"},
"folder.ai_image_created": {
"en": "Generated image {name}", "ja": "画像 {name} を生成しました",
"vi": "Đã tạo ảnh {name}"},
"folder.ai_image_failed": {
"en": "Image generation failed: {err}", "ja": "画像生成に失敗しました: {err}",
"vi": "Tạo ảnh thất bại: {err}"},
"folder.ai_model_label": {"en": "Model:", "ja": "モデル:", "vi": "Model:"},
"folder.ai_model_auto": {
"en": "(auto — provider default)", "ja": "(自動 — 既定モデル)",
"vi": "(tự động — model mặc định)"},
"folder.ai_image_suggest": {
"en": "💡 Tip: pick model '{model}' above for image generation.",
"ja": "💡 画像生成には上のモデル '{model}' を選ぶのがおすすめです。",
"vi": "💡 Gợi ý: chọn model '{model}' ở trên để tạo ảnh."},
"folder.ai_image_suggest_all": {
"en": "💡 This request involves images. Image-capable models found on other providers:",
"ja": "💡 このリクエストは画像を含みます。他プロバイダーで見つかった画像対応モデル:",
"vi": "💡 Yêu cầu này liên quan đến ảnh. Model tạo ảnh tìm thấy ở các provider khác:"},
"folder.ai_image_none": {
"en": "💡 This request involves images, but no image-capable model was found on any configured provider.",
"ja": "💡 このリクエストは画像を含みますが、設定済みのどのプロバイダーにも画像対応モデルが見つかりませんでした。",
"vi": "💡 Yêu cầu này liên quan đến ảnh, nhưng không tìm thấy model tạo ảnh ở provider nào đã cấu hình."},
"folder.ai_image_use_selected": {
"en": "💡 No dedicated image model found — will use your selected model '{model}' to generate images.",
"ja": "💡 専用の画像モデルが見つかりません — 選択中のモデル '{model}' で画像を生成します。",
"vi": "💡 Không tìm thấy model tạo ảnh chuyên biệt — sẽ dùng model bạn đã chọn '{model}' để tạo ảnh."},
"folder.ai_queued": {
"en": "⏳ Queued (#{n}) — runs after the current edit.",
"ja": "⏳ キューに追加 (#{n}) — 現在の編集の後に実行します。",
"vi": "⏳ Đã thêm vào hàng đợi (#{n}) — chạy sau lệnh hiện tại."},
"folder.ai_queue_count": {
"en": "{n} queued", "ja": "{n} 件待機中", "vi": "{n} đang chờ"},
"terminal.title": {"en": "Terminal", "ja": "ターミナル", "vi": "Terminal"},
"terminal.run": {"en": "Run", "ja": "実行", "vi": "Chạy"},
"terminal.placeholder": {
"en": "Type a command and press Enter…", "ja": "コマンドを入力して Enter…",
"vi": "Nhập lệnh rồi nhấn Enter…"},
"terminal.expand_tooltip": {
"en": "Expand terminal", "ja": "ターミナルを開く", "vi": "Mở terminal"},
"terminal.collapse_tooltip": {
"en": "Collapse terminal", "ja": "ターミナルを閉じる", "vi": "Thu gọn terminal"},
"terminal.busy": {
"en": "[a command is still running]", "ja": "[コマンドがまだ実行中です]",
"vi": "[đang chạy một lệnh khác]"},
"terminal.cd_error": {
"en": "cd: no such directory: {path}", "ja": "cd: ディレクトリがありません: {path}",
"vi": "cd: không có thư mục: {path}"},
"terminal.launch_error": {
"en": "[failed to launch the shell]", "ja": "[シェルの起動に失敗しました]",
"vi": "[không khởi chạy được shell]"},
}
+40
View File
@@ -0,0 +1,40 @@
"""Chuỗi hiển thị — phần monitoring_overview.
Cắt ra từ ``i18n.py``: một dict 3.000 dòng không mở nổi để sửa một chữ.
Cắt theo mốc phân đoạn có sẵn, nên mỗi cụm vẫn là các màn đi liền nhau.
``i18n.py`` gộp tất cả lại thành ``STRINGS``.
"""
from __future__ import annotations
from typing import Dict
STRINGS: Dict[str, Dict[str, str]] = {
"monitoring.overview_sandbox_id": {"en": "Sandbox ID", "ja": "サンドボックス ID", "vi": "Sandbox ID"},
"monitoring.overview_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"monitoring.overview_status_running": {"en": "Running", "ja": "実行中", "vi": "Đang chạy"},
"monitoring.overview_created": {"en": "Created", "ja": "作成日時", "vi": "Tạo lúc"},
"monitoring.overview_uptime": {"en": "Uptime", "ja": "稼働時間", "vi": "Thời gian hoạt động"},
"monitoring.overview_resource_limits": {
"en": "Resource Limits", "ja": "リソース制限", "vi": "Giới hạn tài nguyên"},
"monitoring.overview_edit": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"monitoring.overview_network_label": {"en": "Network", "ja": "ネットワーク", "vi": "Mạng"},
"monitoring.overview_network_disabled": {"en": "Disabled", "ja": "無効", "vi": "Đã tắt"},
"monitoring.overview_network_enabled": {"en": "Enabled", "ja": "有効", "vi": "Đang mở"},
"monitoring.overview_permissions_title": {"en": "Permissions", "ja": "権限", "vi": "Quyền"},
"monitoring.overview_perm_fs": {"en": "File System", "ja": "ファイルシステム", "vi": "Hệ thống file"},
"monitoring.overview_perm_fs_value": {"en": "Read/Write", "ja": "読み書き", "vi": "Đọc/Ghi"},
"monitoring.overview_perm_network": {"en": "Network", "ja": "ネットワーク", "vi": "Mạng"},
"monitoring.overview_perm_network_blocked": {"en": "Blocked", "ja": "ブロック", "vi": "Bị chặn"},
"monitoring.overview_perm_network_allowed": {"en": "Allowed", "ja": "許可", "vi": "Cho phép"},
"monitoring.overview_perm_process": {"en": "Process", "ja": "プロセス", "vi": "Tiến trình"},
"monitoring.overview_perm_process_value": {"en": "Limited", "ja": "制限あり", "vi": "Bị hạn chế"},
"monitoring.overview_perm_env": {"en": "Environment", "ja": "実行環境", "vi": "Môi trường"},
"monitoring.overview_perm_env_value": {"en": "Restricted", "ja": "制限あり", "vi": "Bị giới hạn"},
"monitoring.overview_audit_title": {"en": "Audit Log", "ja": "監査ログ", "vi": "Audit Log"},
"monitoring.overview_view_all": {"en": "View all", "ja": "すべて表示", "vi": "Xem tất cả"},
"monitoring.time_just_now": {"en": "just now", "ja": "たった今", "vi": "vừa xong"},
"monitoring.time_minutes_ago": {"en": "{n}m ago", "ja": "{n}分前", "vi": "{n} phút trước"},
"monitoring.time_hours_ago": {"en": "{n}h ago", "ja": "{n}時間前", "vi": "{n} giờ trước"},
"monitoring.time_days_ago": {"en": "{n}d ago", "ja": "{n}日前", "vi": "{n} ngày trước"},
"monitoring.na": {"en": "—", "ja": "—", "vi": "—"},
}

Some files were not shown because too many files have changed in this diff Show More