Compare commits

..
Author SHA1 Message Date
anhtnm1andClaude Opus 5 ab04d68a22 fix(i18n): dịch nốt chữ do Qt tự vẽ, và thêm dòng phiên bản ở góc phải
CI / test (pull_request) Canceled after 0s
Người dùng báo: chọn tiếng Nhật mà nhóm Sandbox Security, nút Save/Cancel và
nhiều chỗ khác vẫn tiếng Anh. Bộ test i18n cũ vẫn xanh vì nó chỉ bắt lỗi "có
dịch nhưng không ai áp lại" — hai lỗ thật nằm chỗ khác:

* Chuỗi HARDCODE không đi qua ``tr()`` bao giờ (``QPushButton("Unlock")``), nên
  phép đo "đổi ngôn ngữ rồi tìm chỗ không mang mốc" thấy nó đứng yên ở cả hai
  lần chụp và coi là bình thường.
* Nhãn nút do CHÍNH Qt vẽ. ``QDialogButtonBox``, ``QMessageBox.question`` và
  ``QInputDialog.get*`` lấy chữ từ bảng dịch riêng của Qt; ứng dụng không cài
  ``QTranslator`` nào và bản PySide6 đang dùng cũng không đóng gói file
  ``qtbase_*.qm`` nào để cài — nên chúng luôn rơi về tiếng Anh.

``ui/dialog_buttons.py`` gán nhãn của dự án đè lên nhãn Qt: ``dialog_buttons``
(10 hộp thoại), ``confirm`` (13 hộp Có/Không), ``ask_text``/``ask_multiline``/
``ask_item`` (16 hộp nhập liệu). Cùng với 17 chuỗi hardcode và 5 câu lỗi mà
``core/tasks.py`` trả thẳng ra hộp thoại — nay trả KHOÁ i18n, nơi hiển thị mới
gọi ``tr()`` — là 61 chỗ.

Ba chỗ nữa cùng lớp lỗi, phát hiện khi rà lại:

* ``_add_section`` nhận chuỗi ĐÃ dịch nên bốn tiêu đề mục của Step config đứng
  nguyên ở ngôn ngữ lúc dựng panel. Nay nhận khoá + ``bind_dynamic`` để không
  mất trạng thái gập/mở khi đổi ngôn ngữ.
* Thẻ tool ở Giám sát ▸ Công cụ hiện thẳng ``spec.description`` — chuỗi gửi cho
  MÔ HÌNH trong schema function-calling, phải giữ tiếng Anh. Thêm bộ mô tả hiển
  thị riêng cho 9 tool.
* Tên nhóm catalog ở tab Connector ("Other (any generic MCP server)").

Kèm theo, phần giao diện người dùng yêu cầu:

* ``__version__`` 2.26.0 -> 0.0.1, một nguồn cho tiêu đề cửa sổ, tab Giới thiệu
  và dòng mới ở góc phải thanh trạng thái (thay dòng ghi công tác giả).
* Tắt size grip: nó vẽ một vệt ngay bên phải dòng phiên bản. Cửa sổ vẫn kéo
  giãn được từ các cạnh.
* ``_NAV_SETTINGS_GAP`` 10 -> 4: hàng Cài đặt bớt xa nhóm Dashboard/Giám sát.

Hai test SẼ TREO nếu không sửa kèm: chúng patch ``QInputDialog.getText/getItem``
để tự trả lời, mà code nay gọi ``ask_text``/``ask_item`` — patch không còn chặn
được và hộp thoại thật sẽ mở ra chờ người bấm.

Ba cổng mới trong ``tests/ui/test_i18n_khong_hardcode_chu.py`` canh ở mức cấu
trúc (không ai được dựng lại kiểu cũ); đã kiểm chúng CẮN trên bản trước khi sửa:
10 + 13 + 17 vi phạm.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:09:42 +09:00
anhtnm1andClaude Opus 5 c05de8054a fix(ui): tách hàng Cài đặt khỏi nhóm menu ngay trên nó
CI / test (pull_request) Canceled after 0s
Thanh rail đặt setSpacing(0) nên nút Cài đặt dán sát Dashboard/Giám sát, ba
dòng đọc thành một khối. Thêm hằng _NAV_SETTINGS_GAP trong rail_metrics và
xin khe bằng nvl.addSpacing() — margin trong QSS vẽ BÊN TRONG hộp widget, mà
nút này bị _rebuild_nav ghim đúng chiều cao một dòng menu nên margin không
mua được pixel nào.

Rút gọn lại comment ở _rebuild_nav cho khớp.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:27:28 +09:00
anhtnm1andClaude Opus 5 0efc4bbf0e docs(agent): bổ sung role fix-dispatcher và siết lại bộ tài liệu agent
- Thêm agent/roles/0_fix_dispatcher.md: phân tier/lane cho từng defect trước
  khi các agent khác chạy, kèm agent/commands/fix.md và hợp đồng đầu ra
  agent/output/dispatch_plan.md.
- Cập nhật system/guardrail, response_policy, security và các checklist
  ui/ux/pr_readiness cho khớp luồng mới.
- Mở rộng knowledge: i18n_rules, screen_map, theme_tokens,
  secrets_and_config; cập nhật workflow intake_to_fix và handoff_contract.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:23:21 +09:00
anhtnm1andClaude Opus 5 fe99bc8727 fix(i18n): đổi ngôn ngữ áp lại toàn bộ chữ trên màn hình
Trước đây rất nhiều widget gọi setText(tr(...)) một lần lúc dựng, nên sau khi
đổi ngôn ngữ một nửa màn hình vẫn giữ tiếng cũ. Thêm họ bind_text/bind_tip/
bind_placeholder/bind_items/bind_dynamic trong i18n: khoá dịch được gắn thẳng
vào widget (giữ tham chiếu yếu) và tự áp lại mỗi lần set_language.

- co4e sidebar, node property panel, run control, routing toggle, nav rail,
  top bar, filter scaffold, usage chart: chuyển sang binding hoặc tự đăng ký
  on_language_changed thay vì trông chờ nơi nhúng.
- RoutingToggle/AutoRunToggle tự đăng ký retranslate và dùng
  AdjustToContents để bản dịch dài không bị cắt.
- BusyOverlay mới: che cửa sổ trong lúc set_language chạy đồng bộ trên GUI
  thread, tránh cảm giác treo app.
- co4e sidebar chỉ đọc thư viện skill một lần (_skill_prefix_lookup) thay vì
  quét đĩa cho từng skill — trước đó mỗi lần reload tốn ~3.8s đứng GUI.
- Bổ sung bản dịch ja/vi còn để nguyên tiếng Anh; sửa chiều cao hàng
  Settings ở nav rail.
- Thêm 4 bộ test UI cho các thay đổi trên.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:23:12 +09:00
anhtnm1 2f3cd100f8 fix: fix UI bug and agent roles 2026-09-07 22:27:36 +09:00
anhtnm1andClaude Opus 5 4eb0ae660e fix(graph): vào màn GraphRAG tự điền đường dẫn quét từ project đang chọn
GraphRenderer.auto_scan_and_fit() thoát sớm khi ô đường dẫn rỗng, trong khi
chính nút Scan lại có đường lùi (path_edit.text() or Path.cwd()). Bất đối xứng
đó nghĩa là vào màn thì không làm gì, bấm Scan thì chạy.

Cố ý KHÔNG lấy cwd() làm đường lùi như nút Scan — quét thư mục làm việc của
tiến trình là quét một cây không liên quan gì tới project và có thể rất lớn.
Điền từ project đang hoạt động, không có project thì vẫn không quét.

LƯU Ý: chưa tái hiện được ca "lần đầu khởi động không tự nạp" mà người dùng báo.
Probe với project và thư mục thật cho thấy cả hai đường (gọi thẳng
auto_scan_and_fit và bấm GraphRAG trên thanh menu) đều khởi động lượt quét. Đây
là bất đối xứng duy nhất tìm được; cần biết ô đường dẫn và combo project đang
hiện gì lúc lỗi xảy ra để đi tiếp.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:43 +09:00
anhtnm1andClaude Opus 5 45cb5cbb6c fix(ui): nới bề rộng tối thiểu của thanh menu trái lên 232px
Ở 132px nhãn "Cuộc trò chuyện mới" bị cắt mất chữ. Sàn phải đủ rộng cho nhãn
DÀI NHẤT trên thanh, không phải cho nhãn trung bình. Bề rộng mở mặc định cũng
lên 232 để nhãn hiện đủ ngay từ lần mở đầu.

Ở cửa sổ nhỏ nhất mà app cho phép (1180px) trần vẫn là 259px nên thanh vẫn kéo
được; chỉ dưới ~1055px nó mới thành cố định.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:43 +09:00
anhtnm1andClaude Opus 5 64900a2504 feat(chat): màn giới thiệu khi hội thoại còn rỗng
Bấm "Cuộc trò chuyện mới" trước đây để lại một khung trắng: không có gì nói
người dùng đang làm trong project nào, thư mục có bao nhiêu tệp, hay bắt đầu từ
đâu. Đây là trạng thái RỖNG — một trong bốn trạng thái mà mọi khung dữ liệu phải
có, và là trạng thái duy nhất người dùng nhìn thấy trước khi gõ chữ đầu tiên.

Gồm lời chào theo tên, dòng bối cảnh (project · số tệp · số skill đang bật), và
bốn thẻ gợi ý.

Hai quyết định:
- Thẻ ĐIỀN câu gợi ý vào ô nhập chứ không gửi luôn. Câu gợi ý là điểm bắt đầu;
  người dùng gần như luôn cần thêm chi tiết của riêng họ, và gửi ngay sẽ tiêu
  một lượt gọi model cho một câu hỏi chung chung.
- Dấu phía trên lời chào không bấm được — nó là dấu hiệu thị giác. Một nút không
  làm gì tệ hơn không có nút.

Dòng bối cảnh phân biệt KHÔNG BIẾT với 0: đếm được 0 tệp thì hiện "0 tệp", còn
không đọc được thư mục thì bỏ hẳn mảnh đó — hiện "0 tệp" khi người dùng vừa thấy
có tệp trong thư mục còn tệ hơn là thiếu một mảnh.

show_welcome() được móc ở ba chỗ: new_session(), load_conversation() (theo số
tin nhắn đã lưu), và TRƯỚC mọi nhánh add_user trong turn runner — đặt sau từng
add_user() thì dễ sót đúng một nhánh, và nhánh đó sẽ hiện cả hai thứ cùng lúc.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:43 +09:00
anhtnm1andClaude Opus 5 b2e2791ff6 fix(chat): tệp đính kèm không bị bản sao trong thư mục lấn chỗ
Người dùng phản ánh dán nội dung vào chat cho câu trả lời tốt hơn đính kèm cùng
nội dung đó. Nội dung KHÔNG bị cắt (giới hạn 2 triệu ký tự) — nguyên nhân là
loãng và trùng: _augment luôn quét thêm [Workspace files] và [Project files],
và tệp đính kèm nếu nằm trong thư mục workspace sẽ đi vào prompt HAI lần. Với
tài liệu dài, bản thứ hai vừa nhân đôi ngữ cảnh vừa khiến model không biết bản
nào là bản được hỏi.

Lọc trùng theo đường dẫn đã giải quyết, và đổi nhãn để nói rõ tệp đính kèm là
CHỦ THỂ CHÍNH còn tệp thư mục chỉ là ngữ cảnh phụ. Dòng cảnh báo "N tệp không
nạp được" đếm TRƯỚC khi lọc trùng, nếu không nó báo sai.

Cùng lượt, hai chỗ bỏ thông tin không cần thiết:
- gỡ dòng "provider · model" ngay sau chữ "Cowork" — nó lặp lại thứ bộ chọn
  provider ở thanh trên đang hiển thị, mà chiếm chỗ đắt nhất trên thanh công cụ;
- không báo "đang dùng <provider>" ở thanh trạng thái khi đổi provider — bộ
  chọn nằm ngay trên màn hình và đã hiện thứ người dùng vừa tự chọn.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:03 +09:00
anhtnm1andClaude Opus 5 84939eeccc feat(help): Trợ lý Hỗ trợ trả lời từ sổ tay và UI đang chạy, không từ phỏng đoán
Prompt cũ chỉ liệt kê TÊN các màn hình, nên model không có cách nào biết trên
mỗi màn có gì và nó lấp khoảng trống bằng thứ nghe hợp lý: người dùng thật đã
được hướng dẫn vào "Dashboard → Add Project" và "Settings → Project Settings →
New Project". Không một thứ nào trong đó tồn tại. Người dùng đi tìm rồi mới
phát hiện ra — câu trả lời trôi chảy mà sai còn tệ hơn câu "tôi không biết".

Ba thứ ghép thêm vào prompt:
- docs/help/app_guide.md — sổ tay viết tay, bám mã nguồn thật, có test chốt
  rằng nó nhắc đủ mọi màn trong docs/screens/manifest.json;
- luật chống bịa, kèm ví dụ few-shot nêu đúng câu trả lời sai đã xảy ra cạnh
  câu đúng, và một ví dụ dạy nó NÓI KHÔNG BIẾT;
- ngữ cảnh sống: màn hình đang mở và nhãn các nút/tab ĐANG hiện.

Ngữ cảnh sống đọc từ cây widget thật, KHÔNG từ docs/screens/controls.json: file
đó trích tự động nhưng đã cũ — 5/41 file trong đó không còn tồn tại và nó không
có file nào trong presentation/ (chưa sinh lại sau refactor R08). Nạp nó vào
prompt là dạy trợ lý về nút của những file đã bị xoá.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:03 +09:00
anhtnm1andClaude Opus 5 fc036d89e3 feat(ui): GraphRAG giữ project đã chọn, tự quét, và báo khi đang tải
Cùng lớp lỗi với tab Thư mục: _bind_project gọi _structure.set_project(pid) vô
điều kiện, và chuỗi _goto -> refresh -> _load_current -> _bind_project chạy lại
mỗi lần vào lại màn Workspace, nên bộ chọn project của chính màn GraphRAG bị
kéo về giá trị của Workspace ở mỗi cú chuyển tab. set_workspace_project() bỏ
qua khi project không đổi (dùng None làm giá trị khởi tạo, không phải "", để
lần gọi đầu không bị bỏ qua khi chưa chọn project nào).

Chọn project xong phải tự quét: _on_project_changed cố ý hoãn lượt quét sang
"lần ghé tiếp", nhưng combo nằm ngay trên màn đó nên người dùng đang đứng ở đấy
và không có lần ghé tiếp nào — họ phải tự bấm Scan. Giờ quét ngay khi màn đang
mở; hoãn vẫn giữ cho trường hợp đổi project từ màn Workspace khi GraphRAG ẩn.

Panel "đang tải": prewarm() chỉ chạy 3 giây sau khi cửa sổ hiện, nên bấm
GraphRAG trong 3 giây đầu gặp _ensure_web() dựng QWebEngineView ĐỒNG BỘ trên
GUI thread — đóng băng 1-2 giây mà không có gì báo. Vì GUI thread bị chặn, panel
phải repaint() ngay chứ không update(): update() chỉ xếp hàng một lượt vẽ cho
vòng lặp sự kiện, mà vòng lặp đó sắp bị chặn, nên panel sẽ chỉ hiện ra sau khi
hết đóng băng — đúng lúc không còn cần tới nó nữa.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:03 +09:00
anhtnm1andClaude Opus 5 2ac43a97c1 fix(ui): tab Thư mục giữ đúng thư mục người dùng tự chọn
Hai lỗi riêng biệt cùng gây ra "chọn folder khác, sang tab khác rồi quay lại
thì về folder cũ":

1. WorkspaceFileTree.root_changed KHÔNG có ai lắng nghe trong toàn bộ repo.
   Người dùng chọn thư mục trong cây thì chỉ cái cây đổi gốc; _root, khung xem
   và terminal ở lại thư mục cũ — ba widget con lệch nhau ngay từ lúc bấm chọn.
2. _load_current gọi set_root(project.workspace_dir()) vô điều kiện, và _goto
   gọi workspace.refresh() mỗi lần vào lại màn Workspace, nên mỗi cú chuyển tab
   kéo thư mục về workspace của project.

set_project_root() bỏ qua khi project KHÔNG đổi. Đổi sang project khác thì vẫn
re-root — thư mục của màn này thuộc về project; chỉ lần refresh trong CÙNG một
project là không được đụng.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:03 +09:00
anhtnm1andClaude Opus 5 d656c5c834 fix(history): "Tất cả project" và số liệu mỗi project đọc đủ mọi thư mục
Lịch sử hội thoại KHÔNG nằm chung một chỗ: _bind_project đặt
config._project_history_dir thành <workspace của project>/.cowork_history mỗi
lần chọn project khác — cố ý, để chia sẻ thư mục project là chia sẻ cả lịch sử.

Nhưng hai chỗ đọc lại chỉ đọc MỘT thư mục, gây hai triệu chứng cùng gốc:
- ui/sidebar.py đọc history_dir() (thư mục của project ĐANG mở), nên khung
  "Tất cả project…" dựng đủ tiêu đề nhóm mà mọi nhóm trừ một đều rỗng;
- _project_counts gọi list_conversations() KHÔNG tham số, tức đọc HISTORY_DIR
  toàn cục nơi không có hội thoại nào của project, nên mọi dòng project đều
  đếm "0 đoạn chat".

Thêm history_dirs() + list_conversations_by_project(), giữ đúng thứ tự cũ (ghim
trước, mới nhất trước) và chống trùng. Thư mục là chủ sở hữu có thẩm quyền: hội
thoại nằm trong workspace của project nào thì thuộc project đó, kể cả khi trường
project_id trong file đã cũ vì project bị đổi thư mục.

HISTORY_SUBDIR + project_history_dir() gom đường dẫn về một định nghĩa duy nhất
— chuỗi ".cowork_history" từng nằm rải trong ui/workspace_tab.py.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 971d39203b fix(ui): app mở lên ở màn "Tất cả project", vệt sáng khớp nội dung
Landing được chốt SAU _restore_sessions(): hội thoại lần trước vẫn được nạp
lại (phục hồi sau khi thoát đột ngột là mục đích của nó), nhưng khung nhìn đầu
tiên là danh sách chứ không phải cuộc trò chuyện vừa đóng.

Phải đi qua _goto, không gọi thẳng show_history_pane(): _goto là chỗ duy nhất
dời vệt sáng trên thanh menu theo nội dung. Gọi tắt thì nội dung sang Cowork
còn vệt sáng ở lại Project — và vì QTreeWidget không phát currentItemChanged
khi bấm lại đúng dòng đang chọn, bấm "Project" sẽ KHÔNG có tác dụng gì cho tới
khi người dùng bấm sang mục khác rồi bấm về. Gom hai đường vào (link "Tất cả
project…" và màn mặc định) về một hàm để chúng không lệch nhau nữa.

Chưa chọn project thì cổng project đang giữ sub-tab Cowork đóng; ép mở bằng cửa
sau sẽ để nội dung ở Cowork trong khi cả cổng lẫn vệt sáng đều nói là Project.
Màn đúng cho người chưa có project chính là màn quản lý project.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 5fb0f3a82d feat(ui): màn quản lý project — chế độ chỉ-xem, chặn trùng tên, menu chuột phải
Bốn thay đổi trên cùng một khối, gom vào presentation/workspace/project_editing.py:

- Project đã có mở ra ở dạng CHỈ ĐỌC; phải bấm "Sửa project" (nút vàng) mới gõ
  được, và nút Lưu chuyển xanh lá. Trước đây form luôn mở nên chỉ cần lỡ tay là
  sửa mất nội dung của một project đang dùng mà không có gì cảnh báo.
- Chặn TRÙNG TÊN khi tạo và khi lưu (không phân biệt hoa thường, bỏ khoảng
  trắng hai đầu). Danh sách bên trái chỉ hiện tên, nên trùng tên là không phân
  biệt được nữa. Chặn TRƯỚC khi ghi đĩa.
- Chuột phải một project: Mở / Sửa / Xoá. Trước đây bấm phải không làm gì cả.
- workspace.counts được format một lần lúc dựng dòng nên đổi ngôn ngữ xong nó
  vẫn nằm ở ngôn ngữ cũ, kể cả khi chọn tiếng Anh. ProjectRow giờ giữ SỐ và tự
  format lại — KHÔNG gọi refresh(), vì refresh() kết thúc bằng _load_current()
  và sẽ xoá mất nội dung người dùng đang gõ dở.

Ba nút về chung một hàng với "Project mới", và cùng theo một luật hiện/ẩn: chỉ
hiện trên sub-tab Project và khi có project đang mở. Hàng tiêu đề vắt ngang cả
màn Workspace nên thứ gì đặt lên đó cũng lọt sang Cowork/Co4E/Thư mục/GraphRAG
nếu không tự ẩn.

Màu vàng/xanh lá đi qua token warning/success. Hai nút dùng nền *_soft với chữ
và viền là token, KHÔNG phải nền đặc: hai token đó được chỉnh làm màu CHỮ (cùng
lý do accent và accent_solid là hai token riêng) — chữ trắng trên warning dark
#CCA700 chỉ đạt ~2.3:1, trượt AA.

ui/workspace_tab.py đang ở đúng trần bánh cóc nên phần mã mới bắt buộc ra module
riêng; chuyển _ProjectRow và CRUD sang đó làm file co từ 566 xuống 523 dòng mã,
và bánh cóc được siết theo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 aecdb15ed3 fix(ui): thanh menu trái không kéo mất được nữa
Kéo thanh chia sang trái hết cỡ thì thanh menu biến mất hẳn, và khi đã mất
thì không còn gì đủ rộng để nhận ra, nói gì tới bắt lại mà kéo ra.

_nav_wrap.setMinimumWidth(132) chỉ chi phối việc BỐ TRÍ, không chi phối thao
tác kéo: QSplitter mặc định cho phép người dùng kéo một ngăn vượt qua chính
minimum của nó rồi đóng sập về 0. Tắt bằng setChildrenCollapsible(False).

Thu gọn vẫn là việc của nút MENU, và nó dừng ở 54px chứ không về 0.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 482fa41d2d feat(ui): Cài đặt ▸ Giới thiệu, gỡ dòng ghi công khỏi thanh trạng thái
Dòng "Made by QuanDH14" là widget thường trực ở góc dưới phải: chiếm một góc
màn hình trên MỌI màn, suốt cả phiên, cho một thông tin chỉ cần đọc một lần.
Chuyển vào Cài đặt ▸ Giới thiệu — vẫn tra được, không còn đứng thường trực.

Mục Giới thiệu đứng CUỐI danh sách: nó không có thiết lập nào để đổi, nên đặt
trước các mục thao tác được sẽ đẩy chúng xuống mà không được gì.

Đặc tả SettingsDialog đổi từ 5 lên 6 mục — thay đổi CÓ CHỦ Ý, không phải tách nhầm.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 257cc91a3c fix(launcher): junction riêng cho từng thư mục mã nguồn
run.bat chỉ hỏi junction "có tồn tại không", không hỏi nó trỏ vào đâu. Một
junction còn lại từ checkout KHÁC vẫn được dùng lại im lặng: run.bat nằm
trong thư mục này nhưng ứng dụng chạy từ thư mục kia. Triệu chứng là "sửa
code xong chạy vẫn y nguyên", và không có gì báo lỗi.

- junction được tạo lại mỗi lần chạy, không chỉ khi thiếu;
- mỗi thư mục mã nguồn có junction RIÊNG (khoá SHA1 từ đường dẫn tuyệt đối).
  Bản trước dùng chung một đường dẫn cho cả máy, nên hai checkout tranh nhau:
  cái chạy sau trỏ junction về mình, và tiến trình con của cái chạy trước
  (máy chủ MCP MS365, sinh ra sau khi app đã mở) import mã nguồn của cái kia;
- install.bat dọn junction dùng chung của bản cũ — để lại là một cái bẫy;
- venv cũ phải CHẠY ĐƯỢC, không chỉ tồn tại file python.exe: venv dựng bằng
  bản Python đã bị nâng cấp hoặc xoá vẫn còn nguyên file đó;
- smoke test kiểm DANH TÍNH, không chỉ kiểm import được — có một "cowork_local"
  khác chen trên sys.path thì lệnh import vẫn chạy tốt và bước kiểm vẫn xanh
  trong khi ứng dụng đọc mã nguồn khác;
- run.bat chốt cowork_local/__main__.py thật sự nhìn thấy được trước khi khởi
  động, thay cho lỗi Python khó hiểu "'cowork_local' is a package and cannot
  be directly executed";
- thông báo lỗi rõ cho ổ mạng và ổ không phải NTFS — junction không trỏ sang
  được, ca hay gặp nhất khi mang sang máy khác.

Đã kiểm bằng cách chạy thật cả hai script.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 39df2c6ed1 fix(security): chặn mở khoá Sandbox Security bằng ô trống
DEFAULT_CONFIG ship agent_security.sandbox_pw = "" kể từ commit 3827552, và
cấu hình đưa tới dialog luôn được deep-merge với defaults đó. Nghĩa là trên
mọi bản cài không đặt COWORK_SANDBOX_PASSWORD, mật khẩu đã lưu là chuỗi rỗng
— và phép so `pw == self._sandbox_pw` nhận luôn ô nhập trống. Bấm Unlock với
ô trống là mở được toàn bộ nhóm Sandbox Security.

Commit 3827552 chỉ sửa config.py nên bỏ sót bản sao thứ hai của literal nằm
trong ui/settings_dialog.py, và chính nó tạo ra lỗ hổng rỗng này.

Sửa:
- gỡ literal credential khỏi mã nguồn (nó vốn là code chết: deep-merge làm
  tham số mặc định của .get() không bao giờ chạy);
- chặn rỗng trước khi so, theo đúng mẫu mà MS365 unlock đã dùng;
- so sánh timing-safe trên BYTES, không trên str — secrets.compare_digest
  ném TypeError với str ngoài ASCII, mà app mặc định tiếng Việt và phục vụ
  khách Nhật nên mật khẩu có dấu là input bình thường;
- chưa đặt mật khẩu thì báo đúng trạng thái đó, không báo "sai mật khẩu" —
  người dùng sẽ gõ lại mãi một thứ không tồn tại.

Root cause: ui/settings_dialog.py:104 (bản cũ)
Test: tests/ui/test_sandbox_unlock_security.py

LƯU Ý CHO REVIEWER: literal cũ vẫn nằm trong 6 commit của Git history. Gỡ ở
đây không gỡ khỏi lịch sử — cần xoay credential trên các máy còn giá trị đó
trong config.json. Không rewrite history (SECURITY.md).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
anhtnm1andClaude Opus 5 7bd2b95a57 docs(agent): thư viện instruction cho việc sửa bug UI/UX
Bộ 7 role chuyên biệt (triage → specialist → implementer → reviewer) cùng
lớp dùng chung: guardrail, tri thức về repo, checklist, và contract đầu ra.

Vì sao có: bug UI/UX được báo bằng lời kể triệu chứng, và người sửa hay bỏ
qua ba thứ mà repo này rất dễ vi phạm — luật "không file nào ngoài theme/
được đặt tên một màu", trần LOC theo bánh cóc, và việc ui/ với presentation/
cùng tồn tại nên sửa nhầm file là "đã fix mà vẫn thấy lỗi".

knowledge/qt_pitfalls.md chép lại 20 nguyên nhân gốc hay gặp của bug PySide6;
examples/bad_fix.md có hai ca CÓ THẬT, gồm ca chính bản vá trong nhánh này
từng mắc (compare_digest trên str ngoài ASCII) và lọt qua vòng review đầu.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 19:55:02 +09:00
duylh19andClaude Opus 5 5d23a415e1 docs: add code/layout fix agent instruction modules and skill
Add a 7-module instruction set for an agent that fixes bugs and UI/layout
defects (role, task, input contract, process, output contract, quality gate,
examples) under docs/instruction/agent/, plus a condensed skill_library entry
so the app can load it from the Skill Manager.

The modules encode the working principles this project expects: understand the
code first, fix the root cause rather than the symptom, keep the diff minimal,
change no behavior outside the requirement, follow the existing architecture
(ADR-001 4-tier layering) and patterns, and judge changes on compatibility,
security, maintainability and testability. Unresolved points must be recorded
as Assumption, Open Question or Limitation instead of being decided silently.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 17:33:24 +09:00
126 changed files with 639 additions and 5901 deletions
-82
View File
@@ -1,82 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project
Cowork Local (user-facing brand "Cowork-Local BamBOO") is a local-first PySide6 desktop app: multi-turn AI agents, per-project workspaces with GraphRAG, scheduled agent tasks (Kanban), MCP connectors, a sandbox security layer, model routing, and a monitoring dashboard. User config lives in `~/.cowork_local`. The internal name `cowork_local` / `APP_NAME` must not be rebranded. Only `DISPLAY_NAME` is the brand.
## The package-name quirk (read first)
The repository root **is** the `cowork_local` package: `__init__.py` and `__main__.py` sit at the root, and code imports itself as `cowork_local.*` or through relative imports. This checkout's folder is not named `cowork_local`, so:
- **Running the app:** `python -m cowork_local` works only from the parent of a folder literally named `cowork_local`. On Windows, `install.bat` (once; add `--dev` for test deps, `--system` to skip the venv) builds a venv under `%LOCALAPPDATA%\CoworkLocal` and creates a junction `%LOCALAPPDATA%\CoworkLocal\launcher\<key>\cowork_local` pointing at this checkout. After that, use `run.bat`. The MS365 MCP server is spawned as `python -m cowork_local.mcp_servers.ms365_server`, so the junction is needed for subprocesses too.
- **Never create a `.venv` inside the repo.** The quality gates walk the whole tree.
- **Tests:** the root `conftest.py` and `tests/conftest.py` bind `sys.modules["cowork_local"]` to this checkout, so pytest works whatever the folder is named. Tests use both import styles: top-level (`from providers.base import ...`) and qualified (`from cowork_local.core... import ...`). Characterization tests that spawn `python -c "from cowork_local..."` subprocesses still need a real `cowork_local` directory on `PYTHONPATH`. CI checks out into `cowork_local/` for this reason.
## Commands
```bash
python -m pip install -r requirements.txt # single requirements file (includes pytest)
python -m pytest tests -q # full suite (what CI runs)
python -m pytest tests/unit/test_schedule_calculator.py -q # one file
python -m pytest tests/unit/test_schedule_calculator.py -k name -q # one test
python -m pytest tests/e2e/test_smoke.py -v # release smoke test
python scripts/run_quality_gate.py # all CASAN gates + pytest
python scripts/run_quality_gate.py --skip-tests # static gates only
python scripts/check_imports.py # domain/ + application/ must not import PySide6/PyQt/ui/app
python scripts/audit_security.py # no plaintext credentials (CI also runs --self-test)
python scripts/check_loc.py # <= 400 lines per production file
python scripts/check_orphan_modules.py # every production module must be reachable by import
```
Widget tests run headless with `QT_QPA_PLATFORM=offscreen`. `tools/check_*.py` are standalone offscreen smoke checkers against a real `MainWindow` built on a copy of `~/.cowork_local` (for example `python tools/check_nav.py`). Some of them still import private names re-exported from `app.py`, so keep those re-exports. Set `COWORK_PERF_TRACE=1` to log timing spans from `performance.py`.
## Architecture
Target design is 4-tier Clean Architecture (`docs/architecture/ADR-001-layered-architecture.md`):
- `domain/`: pure stdlib entities, frozen request snapshots (`ConversationExecutionRequest`), `AgentEvent`, tool/provider descriptors, `ScheduleCalculator`.
- `application/`: pure-Python use-case services (conversations, model_routing, scheduling, workspaces, monitoring, workflows). **No Qt.** Must run headless.
- `infrastructure/`: adapters: config (`JsonConfigRepository` over `AtomicJsonFile`), OS-keyring `SecretStore`, providers, MCP (`McpToolSourceManager`), sandbox, filesystem, telemetry, and Qt bridges (`infrastructure/qt`).
- `presentation/`: PySide6 widgets by feature (`shell`, `chat`, `co4e`, `dashboard`, `scheduling`, `workspace`, `monitoring`, `graph`, `settings`, ...). Widgets call `application/` services. They don't touch persistence or run LLM calls on the GUI thread. Agent work runs in worker threads and reaches the UI as `AgentEvent`s through Qt signal bridges.
The refactor is **incomplete**. Legacy top-level packages are still live and imported by the app:
- `ui/`: older tabs such as `cowork_tab`, `workspace_tab`, `monitoring_tab`, `settings_dialog`, `chat_panel`, and `co4e_*`.
- `core/`: agents, the Co4E flow runner, task scheduler, skills, tools, audit/usage tracking, routing.
- `providers/`: `base`, `anthropic`, `openai_compat`, `factory`.
- `security/`: validators, command risk classifier.
- Root modules: `config.py`, `state.py`.
`docs/architecture/dormant-code.md` lists deprecated pieces, such as `state.py::active_project_id` and the monolithic `core/tools.py`. New layers must not import dormant code.
Wiring:
- `__main__.py` → `app.run()`.
- `presentation/shell/bootstrap.py` is the **Composition Root**. It builds `AppContext` (`state.py`) around `JsonConfigRepository` plus `KeyringAdapter`, falling back to the config file when no keyring exists.
- `run()` then seeds the built-in skills (`skill_library/*.skill`) and the Co4E flows, applies the theme, and opens `presentation/shell/main_window.MainWindow`.
- Pages are registered in `presentation/shell/page_registry.py`.
Other cross-cutting pieces:
- `i18n/`: `tr(key, **kw)` with en/ja/vi (default `vi`). Long-lived widgets must use `bind_text(...)` or `on_language_changed(...)` so a language switch re-applies their text. Transient dialogs just call `tr()` at construction.
- `theme/`: palettes and QSS. Use theme tokens, not hard-coded colors.
- `mcp_servers/`: bundled MCP servers (MS365, project_context).
- `agent/`: a markdown instruction library for UI/UX bug-fix agents, not runtime code.
Step-by-step recipes for adding a provider, a tool or MCP server, or a screen are in `docs/governance/contributor-recipes.md`.
## Rules enforced by gates and review
- **400-line limit** for every production file. This covers `domain`, `application`, `infrastructure`, `presentation`, `ui`, `core`, `providers`, `security`, `mcp_servers`, `i18n`, `theme`, and root `.py` files. Legacy oversized files have per-file caps in `scripts/check_loc.py` that may only go down. Split files; never raise a cap.
- **No orphan modules.** `check_orphan_modules.py` has an `ALLOWLIST` that may only shrink. Wire up or delete a module instead of allowlisting it.
- **Secrets** belong in the OS keyring, never in `config.json` or the code. `.env.example` is not auto-loaded. Tests never use live provider credentials (use `tests/fakes/`: `FakeProvider`, `FakeToolExecutor`, `FakeToolPolicyGateway`, `FakeConfigRepository`/`FakeSecretStore`, `FakeClock`, ...).
- **Test layout:** `tests/unit` (fast, no I/O), `tests/contracts`, `tests/integration` (Qt offscreen), `tests/characterization` (pinned legacy behavior during refactors), `tests/e2e`, `tests/ui`, plus flat `tests/test_*.py`.
- **Startup housekeeping** (seeding, pruning) is wrapped in `try/except` and must never block app launch.
- **Comments:** the ADR asks for English comments. Existing code mixes English and Vietnamese docstrings and comments, so match the surrounding file.
## Git workflow
- Branches: `feat/`, `fix/`, `test/`, `docs/`, `perf/`, `refactor/<short-desc>`. Core AI work uses `core-ai/<task-id>-<name>`.
- Commits use Conventional Commit prefixes (`feat:`, `fix:`, `test:`, `docs:`, `refactor:`, `perf:`, `chore:`).
- One logical change per PR, using `.gitea/PULL_REQUEST_TEMPLATE.md`. The remote is a Gitea instance, and CI (`.gitea/workflows/ci.yaml`, Python 3.11) runs on PRs to `main`.
- Critical areas listed in `SECURITY.md` get extra review.
Binary file not shown.
-12
View File
@@ -72,12 +72,6 @@ def run(argv: List[str] | None = None) -> int:
app = QApplication.instance() or QApplication(argv)
app.setApplicationName(APP_NAME)
app.setWindowIcon(app_icon())
try:
from .config import CONFIG_DIR
from .presentation.shell import crash_guard
crash_guard.install(Path(CONFIG_DIR) / "logs")
except Exception: # noqa: BLE001 - crash logging must never block startup
crash_guard = None
# Composition Root: presentation/shell/bootstrap.py quyết định app chạy
# bằng mảnh nào. Từ R02, đó là JsonConfigRepository + kho bí mật của hệ
# điều hành, không còn config.py::AppConfig.
@@ -138,10 +132,4 @@ def run(argv: List[str] | None = None) -> int:
pass
win.show()
if crash_guard is not None:
try:
watchdog = crash_guard.HangWatchdog(DISPLAY_NAME, win)
app.aboutToQuit.connect(watchdog.stop)
except Exception: # noqa: BLE001
pass
return app.exec()
@@ -74,14 +74,6 @@ class CoreToolRuntime:
đều phải tra tên, tra trên danh sách sẽ chậm dần theo số tool.
"""
self._output_dir = Path(output_dir)
# Every sandboxed tool (run_command included) gets this as its cwd —
# it must exist BEFORE the first tool call, same as the older
# run_cowork() (core/chat_agent.py) already does at its output_dir.
# Without this, a per-turn ".turns/<id>" folder that was never created
# makes run_command's subprocess.Popen(cwd=...) fail immediately with
# WinError 267 ("directory name is invalid") before the command even
# starts — no network, no output, just an opaque OS error.
self._output_dir.mkdir(parents=True, exist_ok=True)
self._title = title
self._extra_tools = list(extra_tools or ())
self._extra_names = {getattr(t, "name", "") for t in self._extra_tools}
-5
View File
@@ -1,5 +0,0 @@
"""Application services for the "Block network" switch (Sandbox Security Layer)."""
from .network_guard import NetworkBlockedError, bind, ensure_allowed, is_blocked, refusal
__all__ = ["NetworkBlockedError", "bind", "ensure_allowed", "is_blocked", "refusal"]
-61
View File
@@ -1,61 +0,0 @@
"""One gate for every outbound connection the app makes on its own.
The "Block network" switch (``agent_security.block_network``) used to be read
only where agent tools run, so Microsoft 365, Teams, connector test buttons,
scheduled task scripts, pip auto-installs and HTML previews still reached the
internet while Monitoring said "Network: blocked". Each of those now asks
this module first.
The AI provider path (chat, model list, model test) deliberately does NOT go
through here: with the switch on the user still talks to the model, but the
app fetches nothing else on the model's or its own behalf.
The module holds a *reader*, not a copy of the flag: the Composition Root
binds it to the live config once (``presentation/shell/bootstrap.py``), so a
change saved in Settings takes effect on the very next call. Nothing bound
(unit tests, helper subprocesses) means "not blocked", the pre-switch default.
"""
from __future__ import annotations
import threading
from typing import Callable, Optional
_lock = threading.Lock()
_reader: Optional[Callable[[], bool]] = None
class NetworkBlockedError(PermissionError):
"""Raised by :func:`ensure_allowed` while the switch is on."""
def bind(reader: Optional[Callable[[], bool]]) -> None:
"""Install the callable that says whether the network is blocked right now."""
global _reader
with _lock:
_reader = reader
def is_blocked() -> bool:
"""True while "Block network" is on. A failing reader counts as blocked."""
reader = _reader
if reader is None:
return False
try:
return bool(reader())
except Exception: # noqa: BLE001 - fail closed: an unreadable switch must not open the network
return True
def refusal(purpose: str) -> str:
"""The message shown (to the user or the model) when ``purpose`` is refused."""
return (f"{purpose}: network access is blocked by the Sandbox Security Layer "
"(\"Block network\" is on in Settings). Only the AI provider may be reached.")
def ensure_allowed(purpose: str) -> None:
"""Raise :class:`NetworkBlockedError` if ``purpose`` may not go online now."""
if is_blocked():
raise NetworkBlockedError(refusal(purpose))
__all__ = ["NetworkBlockedError", "bind", "ensure_allowed", "is_blocked", "refusal"]
@@ -21,14 +21,9 @@ def pptx_available() -> bool:
try:
from cowork_local.core.deps import ensure_module
ready = ensure_module("pptx", "python-pptx") is not None
_PPTX_READY = ensure_module("pptx", "python-pptx") is not None
except Exception: # noqa: BLE001
ready = False
from ..network import network_guard
if ready or not network_guard.is_blocked():
_PPTX_READY = ready # a refusal under "Block network" is retried later
return ready
_PPTX_READY = False
return _PPTX_READY
+6 -10
View File
@@ -100,15 +100,11 @@ DEFAULT_CONFIG: Dict[str, Any] = {
"resource_limit_cpu_percent": 80, # 0 = unlimited; caps a run_command/install_package process TREE's total CPU%
"resource_limit_memory_mb": 2048, # 0 = unlimited; caps total RSS memory (MB)
"resource_limit_disk_mb": 512, # 0 = unlimited; caps total disk read+write (MB)
# "Block network": every outbound connection except the AI provider is
# refused (application/network/network_guard.py), and agent shell
# commands / task scripts run in a network-less AppContainer.
# OFF on first launch — the user turns it on in Settings.
"block_network": False,
"block_network": True, # strip proxy env / point at a black-hole address for agent-run commands
# Allow the agent's fetch_url tool to read web pages / online documents /
# SharePoint-OneDrive share links. Its own toggle — reading a URL for info
# is safe and useful, so this defaults ON — but block_network outranks it:
# with the network blocked the tool is refused either way.
# SharePoint-OneDrive share links. SEPARATE from block_network (that only
# sandboxes agent-run shell commands) — reading a URL for info is safe and
# useful, so this defaults ON. Toggle in Settings → Security.
"allow_url_fetch": True,
"sandbox_pw": "", # set through COWORK_SANDBOX_PASSWORD
"rulebase_path": "", # custom RULEBASE.md — attached to every agent execution
@@ -236,7 +232,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
# file (~/.cowork_local/assessments.json + assessments_history/), not here —
# this section is only the behaviour config the user edits.
"routing": {
"switch_mode": "auto", # global default: "auto" | "manual"
"switch_mode": "off", # global default: "off" | "auto" | "manual"
"policy": "balanced", # "quality" | "cost" | "latency" | "balanced"
"min_score_gain": 0.05, # only switch if the new model beats current by ≥ this
"confirm_timeout_sec": 60, # (manual) auto-keep current if the user doesn't confirm in time
@@ -246,7 +242,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
"judge_model": "", # fixed cheap judge model ("" → a per-provider default)
"candidates": [], # explicit [{provider, model_id, tier}]; empty → discover from providers
"auto_reassess_on_add": True, # reassess a newly-added model as soon as it's added
# Per-surface Auto/Manual toggle state (the chat-screen toggle). An
# Per-surface Off/Auto/Manual toggle state (the chat-screen toggle). An
# empty string means "follow the global switch_mode above".
"surface_modes": {
"cowork": "",
-9
View File
@@ -527,15 +527,6 @@ def run_cowork(
preview = {"kind": "info", "title": name, "text": str(args)}
emit({"type": "tool_proposed", "id": tc_id, "name": name, "args": args,
"preview": preview})
if ctx.block_network and not name.startswith("ms365_local__"):
result = {"ok": False, "output": (
f"{name}: network access is blocked by the Sandbox Security Layer "
'("Block network for agent-run commands" is on in Settings).')}
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
# 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.
-114
View File
@@ -1,114 +0,0 @@
"""Mirror a OneDrive/SharePoint folder to/from a local directory (DF-007).
This is deliberately NOT a general sync engine: every existing tool
(``run_command``, ``read_file``, ``write_file``...) operates on a real local
``Path`` (``Project.output_dir`` — see ``core/projects.py::Project.workspace_dir``),
and that contract does not change here. A cloud-backed project's
``output_dir`` still points at a real local folder; this module only knows how
to pull that folder's content down from Graph once, and push it back up once,
both on explicit user action (a button click) — there is no background
watcher, no continuous sync, no delete propagation, and no conflict
resolution beyond "whichever side ran last wins" for a given file. See the
DF-007 plan for why: OneDrive/SharePoint sync-client detection is unreliable,
so a local mirror + manual sync is the only predictable option that does not
touch the sandboxed command/file tools.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List
from . import ms365_graph as graph
@dataclass
class SyncReport:
"""Kết quả một lượt tải xuống/đẩy lên — hiển thị cho người dùng sau khi chạy."""
transferred: int = 0
skipped_too_large: List[str] = field(default_factory=list)
errors: List[str] = field(default_factory=list)
def _list_children(token: str, cloud_source: Dict[str, str], remote_path: str) -> List[dict]:
provider = cloud_source.get("provider")
if provider == "sharepoint":
return graph.list_sharepoint_files(token, cloud_source["site_id"], remote_path)
return graph.list_onedrive_files(token, remote_path)
def _download_file(token: str, cloud_source: Dict[str, str], remote_path: str) -> bytes:
if cloud_source.get("provider") == "sharepoint":
return graph.download_sharepoint_file_bytes(token, cloud_source["site_id"], remote_path)
return graph.download_onedrive_file_bytes(token, remote_path)
def _upload_file(token: str, cloud_source: Dict[str, str], remote_path: str, data: bytes) -> None:
if cloud_source.get("provider") == "sharepoint":
graph.upload_sharepoint_file_bytes(token, cloud_source["site_id"], remote_path, data)
else:
graph.upload_onedrive_file_bytes(token, remote_path, data)
def download_folder(token: str, cloud_source: Dict[str, str], local_dir: Path) -> SyncReport:
"""Tải toàn bộ cây thư mục ``cloud_source['remote_path']`` xuống ``local_dir``,
giữ nguyên cấu trúc thư mục con. Ghi đè file local nếu đã tồn tại (một
chiều: cloud thắng). Không xoá file local nào không còn ở phía cloud."""
report = SyncReport()
root_remote = cloud_source.get("remote_path", "")
local_dir.mkdir(parents=True, exist_ok=True)
def _walk(remote_path: str, local_sub: Path) -> None:
try:
children = _list_children(token, cloud_source, remote_path)
except graph.Ms365GraphError as exc:
report.errors.append(f"{remote_path or '/'}: {exc}")
return
for item in children:
name = item.get("name", "")
if not name:
continue
child_remote = f"{remote_path}/{name}" if remote_path else name
child_local = local_sub / name
if "folder" in item:
child_local.mkdir(parents=True, exist_ok=True)
_walk(child_remote, child_local)
else:
try:
data = _download_file(token, cloud_source, child_remote)
child_local.write_bytes(data)
report.transferred += 1
except graph.Ms365GraphError as exc:
report.errors.append(f"{child_remote}: {exc}")
_walk(root_remote, local_dir)
return report
def upload_folder(token: str, cloud_source: Dict[str, str], local_dir: Path) -> SyncReport:
"""Đẩy mọi file dưới ``local_dir`` lên đúng đường dẫn tương ứng phía cloud
(tạo mới hoặc ghi đè). Một chiều: local thắng cho từng file được duyệt qua.
Không xoá file cloud nào đã bị xoá ở local, không phát hiện xung đột."""
report = SyncReport()
root_remote = cloud_source.get("remote_path", "")
local_dir = Path(local_dir)
for dirpath, _dirnames, filenames in os.walk(local_dir):
rel_dir = Path(dirpath).relative_to(local_dir)
for fname in filenames:
local_file = Path(dirpath) / fname
rel_parts = [] if str(rel_dir) == "." else list(rel_dir.parts)
rel_parts.append(fname)
child_remote = "/".join(([root_remote] if root_remote else []) + rel_parts)
try:
data = local_file.read_bytes()
_upload_file(token, cloud_source, child_remote, data)
report.transferred += 1
except graph.Ms365GraphError as exc:
if "too large" in str(exc):
report.skipped_too_large.append(child_remote)
else:
report.errors.append(f"{child_remote}: {exc}")
except OSError as exc:
report.errors.append(f"{child_remote}: {exc}")
return report
+1 -6
View File
@@ -327,12 +327,7 @@ def run_code(
else:
emit({"type": "tool_start", "id": tc_id, "name": name})
if is_extra and extra_executor is not None:
if ctx.block_network and not name.startswith("ms365_local__"):
result = {"ok": False, "output": (
f"{name}: network access is blocked by the Sandbox Security Layer "
'("Block network for agent-run commands" is on in Settings).')}
else:
result = extra_executor(name, args)
result = extra_executor(name, args)
else:
def on_output(line: str, _id=tc_id, _name=name) -> None:
emit({"type": "tool_output", "id": _id, "name": _name, "delta": line})
+5 -24
View File
@@ -91,7 +91,6 @@ def run_cancellable(
on_output: Optional[Callable[[str], None]] = None,
env: Optional[Dict[str, str]] = None,
limits: Optional[Dict[str, float]] = None,
isolate_network: bool = False,
) -> Tuple[Optional[int], str, bool, bool, bool]:
"""Run a subprocess so the Stop button can actually interrupt it.
@@ -118,27 +117,17 @@ def run_cancellable(
a failure to create/assign the job just means the existing taskkill
fallback is used, same as before this was added.
``isolate_network`` runs ``args`` as a shell command that the OS keeps
off the network (see ``infrastructure/sandbox/network_isolation.py``);
if that isolation cannot be set up the command is NOT run.
Returns ``(returncode, combined_output, cancelled, timed_out,
resource_exceeded)``; on a failure to even launch the process,
``returncode`` is ``None`` and the output holds the launch error."""
cancel = cancel or (lambda: False)
popen_kwargs = {} if sys.platform == "win32" else {"start_new_session": True}
try:
if isolate_network:
from ..infrastructure.sandbox.network_isolation import spawn_without_network
command = args if isinstance(args, str) else subprocess.list2cmdline(args)
proc = spawn_without_network(command, cwd, env)
else:
proc = subprocess.Popen(
args, shell=shell, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1, env=env, **popen_kwargs,
)
except (OSError, RuntimeError) as exc: # RuntimeError: NetworkIsolationUnavailable
proc = subprocess.Popen(
args, shell=shell, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1, env=env, **popen_kwargs,
)
except OSError as exc:
return None, str(exc), False, False, False
with _active_pids_lock:
@@ -277,10 +266,6 @@ def ensure_module(module: str, package: str | None = None):
pkg = package or module
if pkg in _FAILED or not _can_pip():
return None
from ..application.network import network_guard
if network_guard.is_blocked():
return None # not cached in _FAILED: retried once the network is back
ok, _ = pip_install(pkg)
if not ok:
_FAILED.add(pkg)
@@ -354,10 +339,6 @@ def pip_install(package: str, cancel: Optional[CancelFn] = None,
name) is NOT retried, since repeating it would just waste time."""
if not _can_pip():
return False, "This packaged build can't install packages at runtime."
from ..application.network import network_guard
if network_guard.is_blocked():
return False, network_guard.refusal(f"pip install {package}")
exe = python or sys.executable
attempt = 0
while True:
+8 -19
View File
@@ -94,28 +94,17 @@ def find_input_files(folder: Path, exts: set[str] | None = None,
capped at ``max_files`` (0 = unlimited), ``total_matched`` is the count
before that cap, so a caller can report how many were skipped."""
exts = exts or INPUT_EXTS
# Do not sort an unbounded recursive tree merely to return a small prefix.
# The caller receives a stable lexical order for the bounded result, while
# traversal stops as soon as the configured file budget is reached.
files: list[Path] = []
total = 0
try:
for f in folder.rglob("*"):
if not f.is_file():
continue
try:
relative = f.relative_to(folder)
except ValueError:
continue
if any(part.startswith(".") for part in relative.parts) or f.suffix.lower() not in exts:
continue
total += 1
if max_files <= 0 or len(files) < max_files:
files.append(f)
matched = sorted(
f for f in folder.rglob("*")
if f.is_file()
and not any(part.startswith(".") for part in f.relative_to(folder).parts)
and f.suffix.lower() in exts
)
except OSError:
return [], 0
files.sort(key=lambda p: str(p).lower())
return files, total
files = matched if max_files <= 0 else matched[:max_files]
return files, len(matched)
def find_soffice() -> str | None:
-6
View File
@@ -132,11 +132,8 @@ class RestApiConnector:
def call(self, args: Dict[str, Any]) -> Dict[str, Any]:
"""Gọi API theo tham số model đưa ra, đi qua lớp TLS có ghim chứng chỉ nội bộ."""
from ..application.network import network_guard
from .tls_trust import request_any_method as tls_request
if network_guard.is_blocked():
return {"ok": False, "output": network_guard.refusal(self.display_name)}
method = str(args.get("method", "GET")).upper()
path = str(args.get("path", "")).lstrip("/")
url = urljoin(self.base_url, path)
@@ -167,13 +164,10 @@ class RestApiConnector:
def test_connection(self) -> Tuple[bool, str]:
"""Thử kết nối tới endpoint; trả về (thành công, thông điệp)."""
from ..application.network import network_guard
from .tls_trust import request as tls_request
if not self.base_url.strip("/"):
return False, "No base URL configured."
if network_guard.is_blocked():
return False, network_guard.refusal(self.display_name)
headers = {}
if self.api_key:
headers[self.auth_header] = (
+3 -71
View File
@@ -12,67 +12,16 @@ sort by recency. History can live locally or in a OneDrive folder (resolved by
from __future__ import annotations
import json
import re
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List
from ..performance import span
_LIST_CACHE: dict[tuple[str, str, int], List[Dict[str, Any]]] = {}
def _invalidate_history_cache(directory: Path) -> None:
prefix = str(Path(directory).resolve())
for key in list(_LIST_CACHE):
if key[0] == prefix:
_LIST_CACHE.pop(key, None)
def new_session_id() -> str:
"""Id phiên mới theo mốc thời gian, chính xác tới mili giây."""
return datetime.now().strftime("%Y%m%d-%H%M%S-%f")[:-3]
#: Độ dài mong muốn của một tiêu đề hội thoại, tính bằng ký tự.
TITLE_MAX_CHARS = 60
#: Số ký tự được phép vượt ``TITLE_MAX_CHARS`` để viết nốt từ đang bị cắt dở.
#: Cỡ một từ tiếng Việt — đủ để cứu chữ cuối, không đủ để kéo dài tiêu đề.
_TITLE_SLACK = 12
_KHOANG_TRANG = re.compile(r"\s")
def shorten_title(text: str, limit: int = TITLE_MAX_CHARS) -> str:
"""Rút gọn tiêu đề mà KHÔNG cắt vào giữa một từ.
Cắt cứng ở ký tự thứ ``limit`` đọc rất khó chịu khi mốc đó rơi vào giữa từ:
"…tóm tắt từng tệp" thành "…tóm tắt từng tệ…" — trông như lỗi gõ chứ không
như một câu bị rút gọn. Nên khi mốc cắt rơi vào giữa từ thì viết nốt từ đó.
Ba lối ra, theo thứ tự ưu tiên:
* Viết nốt từ đang dở, nếu chỉ phải vượt thêm tối đa ``_TITLE_SLACK`` ký tự.
Viết nốt mà vừa hết chuỗi thì **không** thêm dấu ba chấm — không còn chữ
nào bị bỏ thì dấu ba chấm là nói dối.
* Từ dài bất thường (đường dẫn, URL) thì lùi về ranh giới từ ngay trước mốc,
để một token dài không kéo tiêu đề dài ra tuỳ ý.
* Cả tiêu đề chỉ là một từ dài thì đành cắt cứng — không còn ranh giới nào.
"""
if len(text) <= limit:
return text
if text[limit].isspace(): # mốc cắt vốn đã nằm giữa hai từ
return text[:limit].rstrip() + "…"
sau = _KHOANG_TRANG.search(text, limit)
het_tu = sau.start() if sau is not None else len(text)
if het_tu - limit <= _TITLE_SLACK:
return text if het_tu == len(text) else text[:het_tu] + "…"
truoc = [m.start() for m in _KHOANG_TRANG.finditer(text, 0, limit)]
if truoc:
return text[:truoc[-1]] + "…"
return text[:limit] + "…"
def derive_title(messages: List[Dict[str, Any]]) -> str:
"""Suy tiêu đề hội thoại từ tin nhắn đầu tiên của người dùng.
@@ -80,7 +29,8 @@ def derive_title(messages: List[Dict[str, Any]]) -> str:
"""
for m in messages:
if m.get("role") == "user" and m.get("content"):
return shorten_title(" ".join(m["content"].split()))
text = " ".join(m["content"].split())
return text[:60] + ("…" if len(text) > 60 else "")
return "(empty)"
@@ -128,7 +78,6 @@ def save_conversation(
# R06-T02: atomic write - see infrastructure/persistence/json/atomic_write.py.
from ..infrastructure.persistence.json.atomic_write import write_json
write_json(path, payload)
_invalidate_history_cache(directory)
return path
@@ -136,7 +85,6 @@ def delete_conversation(path) -> None:
"""Xoá file hội thoại; không có thì bỏ qua."""
try:
Path(path).unlink()
_invalidate_history_cache(Path(path).parent)
except OSError:
pass
@@ -148,7 +96,6 @@ def rename_conversation(path, new_title: str) -> None:
data = load_conversation(path)
data["title"] = new_title
write_json(Path(path), data)
_invalidate_history_cache(Path(path).parent)
def set_pinned(path, pinned: bool) -> None:
@@ -158,7 +105,6 @@ def set_pinned(path, pinned: bool) -> None:
data = load_conversation(path)
data["pinned"] = bool(pinned)
write_json(Path(path), data)
_invalidate_history_cache(Path(path).parent)
def load_conversation(path: Path) -> Dict[str, Any]:
@@ -251,16 +197,8 @@ def list_conversations(directory: Optional[Path] = None, query: str = "") -> Lis
if not directory or not directory.exists():
return []
q = (query or "").strip().lower()
try:
cache_key = (str(directory.resolve()), q, directory.stat().st_mtime_ns)
except OSError:
return []
cached = _LIST_CACHE.get(cache_key)
if cached is not None:
return [dict(item) for item in cached]
items: List[Dict[str, Any]] = []
with span("history.list", query=bool(q)):
for path in directory.glob("*.json"):
for path in directory.glob("*.json"):
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
@@ -283,10 +221,4 @@ def list_conversations(directory: Optional[Path] = None, query: str = "") -> Lis
})
# pinned first, then most recent
items.sort(key=lambda d: (not d["pinned"], -d["mtime"]))
_LIST_CACHE[cache_key] = [dict(item) for item in items]
# Keep this bounded; old directory signatures become unreachable after a
# write and should not grow process memory forever.
if len(_LIST_CACHE) > 256:
for old in list(_LIST_CACHE)[:64]:
_LIST_CACHE.pop(old, None)
return items
-2
View File
@@ -85,10 +85,8 @@ def get_issue_by_url(config: Dict[str, Any] | None, url: str) -> str:
def _get(config: Dict[str, Any], path: str, params: dict = None):
"""Gọi Jira REST API bằng xác thực cơ bản, qua lớp TLS có ghim chứng chỉ nội bộ."""
from ..application.network import network_guard
from . import tls_trust
network_guard.ensure_allowed("Jira")
c = _conf(config)
url = c["base_url"].rstrip("/") + path
# Same TLS auto-recovery the LLM provider calls get (core/tls_trust.py) —
-6
View File
@@ -147,12 +147,6 @@ def fetch_link_preview(url: str) -> str:
return ""
if not re.match(r"^https?://", url, re.IGNORECASE):
return f"[Link: {url}] (not a fetchable http(s) URL — referenced by address only)"
# Every caller (fetch_url, task link attachments, ...) passes through here,
# so this one check covers the paths that never saw a ToolContext.
from ..application.network import network_guard
if network_guard.is_blocked():
return f"[Link: {url}] (not fetched — {network_guard.refusal('link fetch')})"
# SharePoint / OneDrive share links are rewritten to their direct-download
# form so the shared FILE itself is fetched and parsed (like an attachment),
# not the share page's HTML shell.
+1 -12
View File
@@ -88,14 +88,7 @@ class McpServerConnection:
def start(self, timeout: float = 15.0) -> None:
"""Spawn the server subprocess and complete the MCP handshake.
Raises :class:`McpServerError` on failure (bad command, the server
crashed on startup, the handshake timed out, ...).
Refused while "Block network" is on: a server process is free to open
any socket it likes, so the only safe server is one never started."""
from ..application.network import network_guard
if network_guard.is_blocked():
raise McpServerError(network_guard.refusal(f"MCP server '{self.name}'"))
crashed on startup, the handshake timed out, ...)."""
self._thread = threading.Thread(target=self._run_loop, daemon=True)
self._thread.start()
if not self._ready.wait(timeout):
@@ -181,10 +174,6 @@ class McpServerConnection:
def call_tool(self, qualified_name: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""``extra_executor``-shaped result: ``{"ok": bool, "output": str}``."""
from ..application.network import network_guard
if network_guard.is_blocked():
return {"ok": False, "output": network_guard.refusal(f"MCP server '{self.name}'")}
tool_name = qualified_name.split(_SEP, 1)[1] if _SEP in qualified_name else qualified_name
try:
result = self._run_coro(self._session.call_tool(tool_name, args or {}))
-29
View File
@@ -137,34 +137,8 @@ def _app(tenant_id: str, client_id: str):
return app, cache
def _cached_account_offline() -> Optional[dict]:
"""First account in the saved token cache, read without any MSAL network setup."""
try:
import msal
accounts = _load_cache().find(msal.TokenCache.CredentialType.ACCOUNT)
except Exception: # noqa: BLE001 - no msal / unreadable cache = not signed in
return None
return accounts[0] if accounts else None
def _ensure_network(action: str) -> None:
"""Turn a "Block network" refusal into the error type callers already handle."""
from ..application.network import network_guard
if network_guard.is_blocked():
raise Ms365AuthError(network_guard.refusal(action))
def signed_in_account(tenant_id: str, client_id: str) -> Optional[dict]:
"""The cached account, if any — a local cache lookup, no network call."""
from ..application.network import network_guard
if network_guard.is_blocked():
# Building the MSAL app fetches the tenant's OpenID configuration, so
# read the token cache directly instead: the UI still sees who is
# signed in without the app reaching login.microsoftonline.com.
return _cached_account_offline()
try:
app, _cache = _app(tenant_id, client_id)
except Ms365AuthError:
@@ -182,7 +156,6 @@ def sign_in_device_code(tenant_id: str, client_id: str, on_code: Callable[[dict]
``verification_uri_complete`` (URL with the code pre-filled, when the tenant
returns it) and ``message`` (the full human-readable instruction). Returns
the MSAL token result dict; raises Ms365AuthError on failure/timeout."""
_ensure_network("Microsoft 365 sign-in")
app, cache = _app(tenant_id, client_id)
flow = app.initiate_device_flow(scopes=SCOPES)
if "user_code" not in flow:
@@ -210,7 +183,6 @@ def get_access_token(tenant_id: str, client_id: str) -> str:
"""Silently reuse the cached sign-in. Raises Ms365AuthError when there is
no valid session — the caller (a Graph call) should surface that as a
normal tool failure telling the user to sign in again from Settings."""
_ensure_network("Microsoft 365")
app, cache = _app(tenant_id, client_id)
accounts = app.get_accounts()
if not accounts:
@@ -256,7 +228,6 @@ def sign_out_default(config=None) -> None:
def sign_out(tenant_id: str, client_id: str) -> None:
"""Đăng xuất và xoá token của một tenant/client khỏi kho."""
try:
_ensure_network("Microsoft 365 sign-out") # chặn mạng: chỉ xoá kho token bên dưới
app, cache = _app(tenant_id, client_id)
for acc in app.get_accounts():
app.remove_account(acc)
-56
View File
@@ -43,10 +43,6 @@ def _request(method: str, url: str, token: str, **kwargs) -> requests.Response:
"""Gọi Graph API, tự ghép ``GRAPH_BASE`` cho đường dẫn tương đối và đổi lỗi HTTP
thành :class:`Ms365GraphError` kèm thông điệp đọc được.
"""
from ..application.network import network_guard
if network_guard.is_blocked():
raise Ms365GraphError(network_guard.refusal("Microsoft 365 (Graph)"))
if not url.startswith("http"):
url = f"{GRAPH_BASE}{url}"
headers = _headers(token, kwargs.pop("headers", None))
@@ -200,40 +196,6 @@ def write_onedrive_file(token: str, path: str, content: str) -> dict:
return resp.json()
# Graph's "simple upload" (a single PUT to .../content) is documented to only
# support items up to 4 MiB; anything larger needs a chunked "upload session"
# (createUploadSession + PUT-per-range), which this module does not implement
# (see DF-007 cloud workspace picker — v1 explicitly skips large files rather
# than silently truncating or corrupting them).
MAX_SIMPLE_UPLOAD_BYTES = 4 * 1024 * 1024
def _check_upload_size(data: bytes) -> None:
if len(data) > MAX_SIMPLE_UPLOAD_BYTES:
raise Ms365GraphError(
f"File too large for simple upload ({len(data)} bytes > "
f"{MAX_SIMPLE_UPLOAD_BYTES} bytes) — chunked upload sessions are not "
"implemented yet."
)
def download_onedrive_file_bytes(token: str, path: str) -> bytes:
"""Đọc RAW BYTES một tệp OneDrive (không ép UTF-8/không cắt) — dùng cho
mirror thư mục cloud xuống local, khác với :func:`read_onedrive_file` vốn
chỉ dành cho việc đọc nội dung văn bản vào ngữ cảnh chat."""
resp = _request("GET", f"/me/drive/root:/{_path_segment(path)}:/content", token)
return resp.content
def upload_onedrive_file_bytes(token: str, path: str, data: bytes) -> dict:
"""Ghi RAW BYTES vào một tệp OneDrive (tạo mới hoặc ghi đè). Xem
:data:`MAX_SIMPLE_UPLOAD_BYTES`."""
_check_upload_size(data)
resp = _request("PUT", f"/me/drive/root:/{_path_segment(path)}:/content", token,
data=data, headers={"Content-Type": "application/octet-stream"})
return resp.json()
def _encode_share_url(url: str) -> str:
"""Encode a OneDrive/SharePoint sharing URL into Graph's ``u!<base64url>``
share-id form (see Microsoft's 'Get access to shared items' docs)."""
@@ -267,24 +229,6 @@ def list_sharepoint_files(token: str, site_id: str, path: str = "") -> List[dict
return resp.json().get("value", [])
def download_sharepoint_file_bytes(token: str, site_id: str, path: str) -> bytes:
"""Đọc RAW BYTES một tệp trong thư viện tài liệu SharePoint — xem
:func:`download_onedrive_file_bytes`."""
resp = _request(
"GET", f"/sites/{quote(site_id)}/drive/root:/{_path_segment(path)}:/content", token)
return resp.content
def upload_sharepoint_file_bytes(token: str, site_id: str, path: str, data: bytes) -> dict:
"""Ghi RAW BYTES vào một tệp trong thư viện tài liệu SharePoint. Xem
:data:`MAX_SIMPLE_UPLOAD_BYTES`."""
_check_upload_size(data)
resp = _request(
"PUT", f"/sites/{quote(site_id)}/drive/root:/{_path_segment(path)}:/content", token,
data=data, headers={"Content-Type": "application/octet-stream"})
return resp.json()
# ---- Teams meeting transcripts ------------------------------------------
def find_online_meeting(token: str, join_url: str) -> List[dict]:
"""Tìm cuộc họp online theo link tham gia."""
-55
View File
@@ -24,7 +24,6 @@ project — nothing about it is special-cased in the UI.
from __future__ import annotations
import json
import os
import re
from dataclasses import asdict, dataclass, field
from datetime import datetime
@@ -66,13 +65,6 @@ class Project:
# auto_run: None → follow the global agent_security.cowork_confirm_commands;
# True → auto-approve commands (no confirm); False → always confirm.
auto_run: Optional[bool] = None
# {} = an ordinary local/managed workspace. Non-empty when ``output_dir``
# is a LOCAL MIRROR of a OneDrive/SharePoint folder (see
# core/cloud_workspace_sync.py) — {"provider": "onedrive"|"sharepoint",
# "site_id": "", "site_name": "", "remote_path": ""}. ``output_dir`` itself
# always stays a real local path; nothing that reads ``workspace_dir()``
# needs to change because of this field.
cloud_source: Dict[str, str] = field(default_factory=dict)
def workspace_dir(self, base: Path = None) -> Path:
"""The project's sandbox root. Every chat of the project writes inside
@@ -83,53 +75,6 @@ class Project:
return (base or WORKSPACES_DIR) / self.project_id
def _norm_dir(path) -> str:
"""Đường dẫn đã chuẩn hoá để đem ra so sánh.
Bung ``~``, đưa về tuyệt đối, rồi ``normcase`` — trên Windows thì
``D:/Work`` và ``d:/work`` là cùng một thư mục, nên so chuỗi thô sẽ
cho hai project chiếm chung một chỗ mà không ai biết.
"""
return os.path.normcase(os.path.abspath(os.path.expanduser(str(path))))
def _cham_nhau(a: str, b: str) -> bool:
"""Hai thư mục đã chuẩn hoá có chạm nhau không: trùng, hoặc lồng nhau.
Lồng nhau cũng tính, vì lý do tồn tại của sandbox là "agent của project này
không bao giờ chạm được file của project kia" (xem docstring đầu module).
Đứng ở thư mục cha thì đọc/ghi được toàn bộ thư mục con, nên cha-con vẫn là
chạm nhau dù hai đường dẫn không giống nhau.
"""
return a == b or a.startswith(b + os.sep) or b.startswith(a + os.sep)
def folder_conflict(path, *, ignore_id: str = "",
directory: Path = None) -> Optional[Project]:
"""Project khác đang chiếm ``path``, hoặc ``None`` nếu chưa ai chiếm.
Mỗi thư mục chỉ được thuộc về một project: thư mục làm việc vừa là sandbox
vừa là kho kiến thức dùng chung của project, nên hai project dùng chung một
thư mục là đọc lẫn dữ liệu của nhau.
So theo thư mục THỰC SỰ đang dùng (``workspace_dir()``), không phải theo
``output_dir``: project chưa đặt thư mục riêng vẫn đang chiếm thư mục quản
lý sẵn của nó, và chính thư mục đó là thứ hay bị chọn nhầm.
``ignore_id`` là project đang sửa — giữ nguyên thư mục của chính nó thì
không phải là trùng.
"""
if not str(path).strip():
return None
muon = _norm_dir(path)
for project in list_projects(directory):
if project.project_id == ignore_id:
continue
if _cham_nhau(muon, _norm_dir(project.workspace_dir())):
return project
return None
def _starter_project() -> Project:
"""An ordinary (deletable, renamable) project seeded when the projects
folder is empty, so the app always opens with somewhere to chat."""
+16 -6
View File
@@ -75,16 +75,26 @@ class RoutingScheduler(QObject):
return None
def _routing_enabled_anywhere(self) -> bool:
"""Is routing actually in use? Always, now: the Off mode was removed and
every stored value resolves to Auto or Manual (see
``config.user_routing_mode``). Paid probing is switched off through
``reassess_interval_hours = 0`` instead."""
return True
"""Is routing actually in use? True if the global mode is auto/manual OR
any chat surface overrides to auto/manual. When everything is Off, the
assessment scores would never be consulted — so we don't spend tokens
probing for them (no surprise cost on a fresh install)."""
try:
routing = self.ctx.config.routing
if (routing.get("switch_mode") or "off") in ("auto", "manual"):
return True
for m in (routing.get("surface_modes") or {}).values():
if m in ("auto", "manual"):
return True
except Exception: # noqa: BLE001
pass
return False
def is_due(self) -> bool:
"""Đã đến lúc chấm điểm lại chưa.
Dò model là lượt gọi có tính phí: đặt chu kỳ chấm lại = 0 thì không dò.
Tắt định tuyến ở mọi bề mặt thì KHÔNG dò — dò model là lượt gọi có tính phí,
không được tiêu tiền cho một tính năng người dùng đã tắt.
"""
if not self._routing_enabled_anywhere():
return False # routing off everywhere → don't probe (would be wasted cost)
+4 -48
View File
@@ -218,13 +218,8 @@ class SandboxManager:
timeout_sec: int,
cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
"""Dispatch execution to the selected backend.
With the network blocked every backend is replaced by the same OS-level
isolation: the backends below only ever set proxy env vars, which
anything that ignores proxies (raw sockets, ping, .NET WebClient...)
walked straight past."""
if block_network or backend == "direct":
"""Dispatch execution to the selected backend."""
if backend == "direct":
return self._run_direct(command, workdir, block_network, timeout_sec, cancel)
if backend == "integrity_job_wfp":
@@ -279,8 +274,7 @@ class SandboxManager:
env = os.environ.copy()
if block_network:
from .deps import network_blocked_env
env = network_blocked_env(env) # belt and braces on top of the OS block
return self._run_network_isolated(command, workdir, env, timeout_sec, cancel)
env = network_blocked_env(env)
if cancel is not None:
from .deps import run_cancellable
@@ -340,42 +334,4 @@ class SandboxManager:
"stderr": str(exc),
"returncode": -1,
"sandbox": "direct",
}
@staticmethod
def _run_network_isolated(
command: str,
workdir: str,
env: Dict[str, str],
timeout_sec: int,
cancel: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
"""Run ``command`` in a process the OS keeps off the network.
Fail-closed: when the isolation cannot be set up the command is
refused (``sandbox == "blocked"``), never run with the network open."""
from .deps import run_cancellable
rc, output, cancelled, timed_out, exceeded = run_cancellable(
command, cwd=workdir or None, timeout=timeout_sec, cancel=cancel,
shell=True, env=env, isolate_network=True,
)
if rc is None and not (cancelled or timed_out or exceeded):
return {"ok": False, "stdout": "", "returncode": -1, "sandbox": "blocked",
"stderr": ("Command refused: network is blocked and the command could "
f"not be isolated from the network ({output.strip()}).")}
if cancelled:
stderr = "Cancelled by user."
elif timed_out:
stderr = f"Timeout after {timeout_sec}s"
elif exceeded:
stderr = "Resource limit exceeded."
else:
stderr = ""
return {
"ok": rc == 0 and not (cancelled or timed_out or exceeded),
"stdout": output,
"stderr": stderr,
"returncode": rc if rc is not None else -1,
"sandbox": "network_isolated",
}
}
+13 -1
View File
@@ -19,6 +19,7 @@ in Waiting Input), so executors here run with an auto gate.
"""
from __future__ import annotations
import subprocess
import time
import uuid
from datetime import datetime
@@ -29,7 +30,6 @@ from . import agent_roles
from . import agent_security
from . import projects
from .permissions import PermissionGate
from .task_script import run_script as _run_script
from .tasks import ARTIFACTS_DIR, resolve_input_text
from .tools import ToolContext
@@ -358,6 +358,18 @@ def _run_agent(ctx, task_type: str, prompt: str, out_dir: Path,
return _last_assistant_text(messages), timed_out(), incomplete
def _run_script(command: str, out_dir: Path, timeout_sec: int) -> str:
"""Chạy một task kiểu script bằng shell trong thư mục kết quả, có hạn giờ."""
if not command.strip():
raise RuntimeError("Script task has no command configured.")
proc = subprocess.run(command, shell=True, cwd=str(out_dir),
capture_output=True, text=True, timeout=max(1, timeout_sec))
output = (proc.stdout or "") + (("\n[stderr]\n" + proc.stderr) if proc.stderr else "")
if proc.returncode != 0:
raise RuntimeError(f"Script exited with code {proc.returncode}:\n{output[-2000:]}")
return output
def execute_task(ctx, task: Dict[str, Any], run_id: str,
emit: Optional[EmitFn] = None, cancel: Optional[CancelFn] = None,
tasks_dir: Path = None) -> Dict[str, Any]:
-47
View File
@@ -1,47 +0,0 @@
"""Run a scheduled task of type ``script`` (tách khỏi ``task_executors.py``).
Khi công tắc "Chặn mạng" đang bật, lệnh của task chạy trong tiến trình bị hệ
điều hành cắt mạng — giống ``run_command`` của agent. Trước đây task script
chạy thẳng bằng ``subprocess.run``, không sandbox, nên lên mạng tự do.
"""
from __future__ import annotations
import subprocess
from pathlib import Path
def run_script(command: str, out_dir: Path, timeout_sec: int) -> str:
"""Chạy một task kiểu script bằng shell trong thư mục kết quả, có hạn giờ."""
if not command.strip():
raise RuntimeError("Script task has no command configured.")
from ..application.network import network_guard
if network_guard.is_blocked():
return _run_script_without_network(command, out_dir, timeout_sec)
proc = subprocess.run(command, shell=True, cwd=str(out_dir),
capture_output=True, text=True, timeout=max(1, timeout_sec))
output = (proc.stdout or "") + (("\n[stderr]\n" + proc.stderr) if proc.stderr else "")
if proc.returncode != 0:
raise RuntimeError(f"Script exited with code {proc.returncode}:\n{output[-2000:]}")
return output
def _run_script_without_network(command: str, out_dir: Path, timeout_sec: int) -> str:
"""Như :func:`run_script`, nhưng tiến trình không có mạng; không cô lập được thì không chạy."""
from .deps import network_blocked_env, run_cancellable
rc, output, _cancelled, timed_out, _exceeded = run_cancellable(
command, cwd=str(out_dir), timeout=max(1, timeout_sec), shell=True,
env=network_blocked_env(), isolate_network=True,
)
if timed_out:
raise subprocess.TimeoutExpired(command, timeout_sec)
if rc is None:
raise RuntimeError("Script not run: network is blocked and the script could not be "
f"isolated from the network ({output.strip()}).")
if rc != 0:
raise RuntimeError(f"Script exited with code {rc} (network blocked):\n{output[-2000:]}")
return output
__all__ = ["run_script"]
-4
View File
@@ -43,10 +43,6 @@ class TeamsNotifier:
"""Post a notification. Returns ``(ok, detail)``."""
if not self.configured:
return False, "Teams webhook URL is not configured."
from ..application.network import network_guard
if network_guard.is_blocked():
return False, network_guard.refusal("Teams notification")
# Workflows webhooks expect an Adaptive Card; classic connectors expect a
# MessageCard. Try both, then a plain-text fallback.
-23
View File
@@ -1,23 +0,0 @@
Source HEAD: db80289 (preserved)
Branch: perf/fsg-performance
Baseline: app import 1517ms; config 934ms; MainWindow 1742ms (offscreen, local machine).
Packets completed:
- P0: measured constructor with cProfile; dominant cost was provider model discovery (~0.7s network worker) and eager Workspace composition.
- P2: cache history listing by directory mtime/query and coalesce sidebar refresh bursts.
- P3: batch streaming Markdown/layout renders at 40ms; final content remains intact.
- P4: bounded attachment discovery avoids sorting a full recursive tree when a cap is set.
- P5: instrument monitoring log refresh; existing 30-day bounded window retained.
- P6: defer provider model discovery to the first Qt event-loop turn.
After: config 452ms; MainWindow 599ms in the same offscreen smoke benchmark (discovery no longer blocks construction).
Streaming render count is now bounded by batch cadence rather than token count.
Representative history benchmark: 1,000 files 383.6ms cold / 0.8ms cached on this machine.
Relevant commits: c5cb258 (perf: defer discovery and reduce UI refresh work).
Remaining bottleneck: eager Workspace/Co4E/Folder widget construction and import-time PySide6 overhead.
Closure pass (starting HEAD 58b5220): Workspace now keeps Co4E, Folder, and GraphRAG as tab placeholders and creates each once on first selection. MainWindow benchmark: 357.6ms; first opens Co4E 143.1ms, Folder 148.0ms, GraphRAG 270.6ms; repeat opens 0.0–2.4ms. Focused lazy navigation/project tests: 15 passed. Pytest temp failures were ACL/path setup issues, not production assertions; a pre-created writable repository-local temp base allowed the focused gates to pass.
Remaining startup cost is base PySide6/application import and eager Cowork shell; further lazy work is not justified without broader architectural risk.
Performance initiative status: closed for this pass.
-2
View File
@@ -48,7 +48,6 @@ from . import skills_dialog as _skills_dialog
from . import libreoffice_view as _libreoffice_view
from . import agents_admin_tab as _agents_admin_tab
from . import monitoring_overview as _monitoring_overview
from . import cloud_workspace as _cloud_workspace
from . import dialog_buttons as _dialog_buttons
from . import connectors as _connectors
@@ -65,7 +64,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
**_libreoffice_view.STRINGS,
**_agents_admin_tab.STRINGS,
**_monitoring_overview.STRINGS,
**_cloud_workspace.STRINGS,
**_dialog_buttons.STRINGS,
**_connectors.STRINGS,
}
-8
View File
@@ -232,14 +232,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"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.page_size_label": {
"en": "Rows/page:", "ja": "1ページの行数:", "vi": "Số dòng/trang:"},
"monitoring.page_indicator": {
"en": "Page {page}/{total}", "ja": "{page}/{total} ページ", "vi": "Trang {page}/{total}"},
"monitoring.page_prev": {
"en": "Previous page", "ja": "前のページ", "vi": "Trang trước"},
"monitoring.page_next": {
"en": "Next page", "ja": "次のページ", "vi": "Trang sau"},
"monitoring.pricing_title": {
"en": "Model pricing (USD / 1M tokens)", "ja": "モデル価格表 (USD / 100万トークン)",
"vi": "Bảng giá model (USD / 1 triệu token)"},
-116
View File
@@ -1,116 +0,0 @@
"""DF-007 — Microsoft 365 sign-in dialog + cloud (OneDrive/SharePoint)
folder picker. Deliberately its own module rather than reusing the
similarly-named orphaned keys under ``settings.ms365_*`` in ``cowork_tab.py``/
``settings_dialog.py`` — those are leftovers from a MS365 sign-in UI that was
removed (see ``ui/settings_dialog.py`` module docstring) and the two files
disagree with each other on wording for several duplicate keys, so reusing
them risked resurrecting an inconsistency rather than a clean, tested string
set."""
from __future__ import annotations
STRINGS = {
# ---- ui/ms365_signin_dialog.py ----
"ms365_signin.title": {
"en": "Sign in to Microsoft 365", "ja": "Microsoft 365 にサインイン",
"vi": "Đăng nhập Microsoft 365",
},
"ms365_signin.already": {
"en": "Signed in as {who}.", "ja": "{who} としてサインイン済みです。",
"vi": "Đã đăng nhập với {who}.",
},
"ms365_signin.intro": {
"en": "Sign in with your Microsoft work/school (or personal) account to "
"browse OneDrive/SharePoint folders.",
"ja": "OneDrive/SharePoint のフォルダーを参照するには、Microsoft の職場/学校\n"
"(または個人) アカウントでサインインしてください。",
"vi": "Đăng nhập bằng tài khoản Microsoft (công ty/trường học hoặc cá nhân) "
"để duyệt thư mục OneDrive/SharePoint.",
},
"ms365_signin.button": {
"en": "Sign in", "ja": "サインイン", "vi": "Đăng nhập",
},
"ms365_signin.signing_in": {
"en": "Signing in…", "ja": "サインイン中…", "vi": "Đang đăng nhập…",
},
"ms365_signin.code_hint": {
"en": "Open {url} and enter this code:", "ja": "{url} を開いてこのコードを入力してください:",
"vi": "Mở {url} và nhập mã sau:",
},
"ms365_signin.open_link": {
"en": "Open link", "ja": "リンクを開く", "vi": "Mở link",
},
"ms365_signin.failed": {
"en": "Sign-in failed: {err}", "ja": "サインインに失敗しました: {err}",
"vi": "Đăng nhập thất bại: {err}",
},
"ms365_signin.cancel": {
"en": "Cancel", "ja": "キャンセル", "vi": "Hủy",
},
# ---- ui/cloud_folder_picker_dialog.py ----
"cloud_picker.title": {
"en": "Choose a OneDrive/SharePoint folder", "ja": "OneDrive/SharePoint フォルダーを選択",
"vi": "Chọn thư mục OneDrive/SharePoint",
},
"cloud_picker.source_onedrive": {
"en": "My OneDrive", "ja": "自分の OneDrive", "vi": "OneDrive của tôi",
},
"cloud_picker.source_sharepoint": {
"en": "SharePoint site", "ja": "SharePoint サイト", "vi": "Site SharePoint",
},
"cloud_picker.search_sites_placeholder": {
"en": "Search SharePoint sites…", "ja": "SharePoint サイトを検索…",
"vi": "Tìm site SharePoint…",
},
"cloud_picker.search_btn": {
"en": "Search", "ja": "検索", "vi": "Tìm",
},
"cloud_picker.up": {
"en": ".. (up)", "ja": ".. (上へ)", "vi": ".. (lùi lại)",
},
"cloud_picker.choose_here": {
"en": "Choose this folder", "ja": "このフォルダーを選択", "vi": "Chọn thư mục này",
},
"cloud_picker.cancel": {
"en": "Cancel", "ja": "キャンセル", "vi": "Hủy",
},
"cloud_picker.load_failed": {
"en": "Could not load this folder: {err}", "ja": "フォルダーを読み込めませんでした: {err}",
"vi": "Không tải được thư mục này: {err}",
},
"cloud_picker.no_sites": {
"en": "No matching SharePoint sites.", "ja": "一致する SharePoint サイトがありません。",
"vi": "Không tìm thấy site SharePoint phù hợp.",
},
# ---- ui/workspace_tab.py additions ----
"workspace.cloud_pick": {
"en": "Choose from OneDrive/SharePoint…", "ja": "OneDrive/SharePoint から選択…",
"vi": "Chọn từ OneDrive/SharePoint…",
},
"workspace.cloud_sync": {
"en": "Sync with cloud", "ja": "クラウドと同期", "vi": "Đồng bộ với cloud",
},
"workspace.cloud_badge_onedrive": {
"en": "☁ Local mirror of OneDrive: {path}", "ja": "☁ OneDrive のローカルミラー: {path}",
"vi": "☁ Bản sao cục bộ của OneDrive: {path}",
},
"workspace.cloud_badge_sharepoint": {
"en": "☁ Local mirror of SharePoint ({site}): {path}",
"ja": "☁ SharePoint ({site}) のローカルミラー: {path}",
"vi": "☁ Bản sao cục bộ của SharePoint ({site}): {path}",
},
"workspace.cloud_sync_result": {
"en": "Sync done — {up} uploaded, {down} downloaded.",
"ja": "同期完了 — アップロード {up} 件、ダウンロード {down} 件。",
"vi": "Đồng bộ xong — {up} tệp đẩy lên, {down} tệp tải về.",
},
"workspace.cloud_sync_errors": {
"en": "{n} item(s) had errors — see details below.",
"ja": "{n} 件のエラーがありました — 詳細は下記のとおりです。",
"vi": "{n} mục bị lỗi — chi tiết bên dưới.",
},
"workspace.cloud_sync_skipped": {
"en": "{n} file(s) skipped (over 4 MB, not supported yet).",
"ja": "{n} 件のファイルはスキップされました (4 MB 超、未対応)。",
"vi": "{n} tệp bị bỏ qua (quá 4 MB, chưa hỗ trợ).",
},
}
-2
View File
@@ -114,8 +114,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"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.stopped": {"en": "{name}: stopped.", "ja": "{name}: 停止しました。",
"vi": "{name}: đã dừng."},
"chatpanel.stopping": {"en": "{name}: stopping…", "ja": "{name}: 停止中…", "vi": "{name}: đang dừng…"},
"chatpanel.attach_limit": {
"en": "Max {n} attachments — extra files were skipped.",
+6
View File
@@ -344,6 +344,12 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Let the control agent review a command with AI before it runs.",
"ja": "実行前に制御エージェントがAIでコマンドを確認します。",
"vi": "Cho control-agent dùng AI xét lệnh trước khi chạy."},
"settings.sandbox_pw_unset_title": {
"en": "Sandbox Security", "ja": "サンドボックスセキュリティ", "vi": "Bảo mật Sandbox"},
"settings.sandbox_pw_unset_body": {
"en": "No sandbox password is set yet, so these settings stay locked. Set COWORK_SANDBOX_PASSWORD, or ask your administrator.",
"ja": "サンドボックスのパスワードが未設定のため、この設定はロックされたままです。COWORK_SANDBOX_PASSWORD を設定するか、管理者にお問い合わせください。",
"vi": "Chưa đặt mật khẩu sandbox nên nhóm thiết lập này vẫn khóa. Hãy đặt COWORK_SANDBOX_PASSWORD, hoặc liên hệ quản trị viên."},
"settings.sandbox_confirm_commands": {
"en": "Confirm before Cowork runs a command",
"ja": "Cowork がコマンドを実行する前に確認する",
-9
View File
@@ -155,12 +155,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"app.lang.switching": {
"en": "Switching language…", "ja": "言語を切り替えています…",
"vi": "Đang đổi ngôn ngữ…"},
# Popup do luồng canh treo mở khi giao diện đứng quá vài giây
# (presentation/shell/crash_guard.py).
"app.hang.message": {
"en": "Processing, please wait…\n\nThis window closes by itself once the app responds again.",
"ja": "処理中です。しばらくお待ちください…\n\nアプリが応答を再開すると、このウィンドウは自動的に閉じます。",
"vi": "Đang xử lý, vui lòng đợi…\n\nCửa sổ này tự đóng khi app phản hồi lại."},
"app.tab.dashboard": {"en": "Dashboard", "ja": "ダッシュボード", "vi": "Dashboard"},
"app.tab.schedule": {"en": "Schedule Task", "ja": "タスクスケジュール", "vi": "Schedule Task"},
"app.tab.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
@@ -183,9 +177,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Project cho đoạn chat mới"},
"app.nav.no_project": {
"en": "No project yet", "ja": "プロジェクトなし", "vi": "Chưa có project"},
# KHAC no_project: đã có project, chỉ là người dùng chưa chọn cái nào.
"app.nav.pick_project": {
"en": "Select a project…", "ja": "プロジェクトを選択…", "vi": "Chọn project…"},
"app.nav.recents": {"en": "RECENTS", "ja": "最近", "vi": "GẦN ĐÂY"},
"app.nav.all_projects": {
"en": "All projects…", "ja": "すべてのプロジェクト…", "vi": "Tất cả project…"},
+33 -17
View File
@@ -19,13 +19,13 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Cho phép agent lấy dữ liệu từ URL (trang web, link SharePoint / OneDrive)"},
"settings.allow_url_fetch_tooltip": {
"en": ("Lets the agent's fetch_url tool read web pages, online documents and "
"SharePoint/OneDrive share links to search & process them. 'Block network' "
"overrides this switch. Default: on."),
"SharePoint/OneDrive share links to search & process them. Separate from "
"'Block network' (which only sandboxes shell commands). Default: on."),
"ja": "エージェントのfetch_urlツールがWebページ・オンライン文書・SharePoint/OneDrive共有リンクを"
"読み取れるようにします。「ネットワークをブロック」がオンの場合はそちらが優先されます。既定: オン。",
"読み取れるようにします。「ネットワークをブロック」(シェルコマンド用)とは別です。既定: オン。",
"vi": ("Cho phép tool fetch_url của agent đọc trang web, tài liệu online và link chia sẻ "
"SharePoint/OneDrive để tìm kiếm & xử lý. 'Chặn mạng' được ưu tiên hơn công tắc "
"này. Mặc định: bật.")},
"SharePoint/OneDrive để tìm kiếm & xử lý. Tách biệt với 'Chặn mạng' (chỉ áp cho lệnh "
"shell). Mặc định: bật.")},
"settings.test_internet": {
"en": "Test Internet", "ja": "インターネット接続テスト", "vi": "Kiểm tra Internet"},
"settings.test_internet_tooltip": {
@@ -39,18 +39,34 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Testing internet access…", "ja": "インターネット接続をテスト中…",
"vi": "Đang kiểm tra truy cập internet…"},
"settings.sandbox_block_network_tooltip": {
"en": ("Only the AI provider (chat, model list, model test) may reach the network. "
"Agent shell commands and task scripts run in a Windows AppContainer with no "
"network access; fetch_url, Jira, connectors/MCP, Microsoft 365, Teams, "
"connector tests, pip auto-install and remote content in HTML previews are refused."),
"ja": "ネットワークに接続できるのはAIプロバイダー(チャット・モデル一覧・モデルテスト)のみです。"
"エージェントのシェルコマンドとタスクスクリプトはネットワークなしのWindows AppContainerで実行され、"
"fetch_url・Jira・コネクタ/MCP・Microsoft 365・Teams・接続テスト・pip自動インストール・"
"HTMLプレビューの外部リソースは拒否されます。",
"vi": "Chỉ nhà cung cấp AI (chat, tải danh sách model, thử model) được ra mạng. Lệnh shell "
"của agent và task script chạy trong Windows AppContainer không có mạng; fetch_url, "
"Jira, connector/MCP, Microsoft 365, Teams, nút Test, tự cài thư viện và tài nguyên "
"web trong xem trước HTML đều bị từ chối."},
"en": ("Policy-level control (proxy env vars point at a black hole) — not a kernel "
"firewall. Combine with the command whitelist above for defense in depth."),
"ja": "ポリシーレベルの制御です(プロキシ環境変数をブラックホールに向ける)— カーネルレベルの"
"ファイアウォールではありません。上のコマンドホワイトリストと併用してください。",
"vi": "Kiểm soát ở tầng chính sách (trỏ biến môi trường proxy vào hố đen) — không phải "
"firewall tầng kernel. Kết hợp với whitelist lệnh ở trên để phòng thủ nhiều lớp."},
"settings.sandbox_pw_label": {
"en": "Sandbox Security Password", "ja": "サンドボックスセキュリティのパスワード",
"vi": "Mật khẩu Bảo mật Sandbox"},
"settings.sandbox_pw_placeholder": {
"en": "Enter password to edit sandbox settings",
"ja": "サンドボックス設定を変更するにはパスワードを入力してください",
"vi": "Nhập mật khẩu để sửa thiết lập sandbox"},
"settings.sandbox_unlock_btn": {"en": "Unlock", "ja": "ロック解除", "vi": "Mở khoá"},
"settings.sandbox_locked": {
"en": "Locked (changes disabled)", "ja": "ロック中(変更できません)",
"vi": "Đang khoá (không sửa được)"},
"settings.sandbox_unlocked": {
"en": "Unlocked", "ja": "ロック解除済み", "vi": "Đã mở khoá"},
"settings.sandbox_unlocked_body": {
"en": "Sandbox settings unlocked.", "ja": "サンドボックス設定のロックを解除しました。",
"vi": "Đã mở khoá thiết lập sandbox."},
"settings.sandbox_pw_wrong_title": {
"en": "Wrong Password", "ja": "パスワードが違います", "vi": "Sai mật khẩu"},
"settings.sandbox_pw_wrong_body": {
"en": "Password incorrect. Sandbox settings remain locked.",
"ja": "パスワードが正しくありません。サンドボックス設定はロックされたままです。",
"vi": "Mật khẩu không đúng. Thiết lập sandbox vẫn bị khoá."},
"settings.sandbox_unlimited": {"en": "Unlimited", "ja": "無制限", "vi": "Không giới hạn"},
"settings.sandbox_cpu_label": {"en": "CPU limit", "ja": "CPU 制限", "vi": "Giới hạn CPU"},
"settings.sandbox_memory_label": {"en": "Memory limit", "ja": "メモリ制限", "vi": "Giới hạn bộ nhớ"},
-16
View File
@@ -57,17 +57,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Another project is already called \"{name}\". Project names must be unique — the list shows nothing but the name, so two of them cannot be told apart.",
"ja": "「{name}」という名前のプロジェクトが既にあります。一覧には名前しか出ないため、同じ名前が二つあると区別できません。",
"vi": "Đã có project khác tên \"{name}\". Tên project phải khác nhau — danh sách chỉ hiện tên, trùng tên là không phân biệt được."},
"workspace.folder_taken_title": {
"en": "Folder already used", "ja": "フォルダーが重複しています",
"vi": "Thư mục đã được dùng"},
"workspace.folder_taken_body": {
"en": "Project \"{name}\" already works in {folder}. One folder belongs to one project only — the folder is that project's sandbox and shared knowledge, so sharing it lets two projects read and overwrite each other's files. Pick another folder.",
"ja": "プロジェクト「{name}」が既に {folder} を使用しています。フォルダーは 1 つのプロジェクト専用です — フォルダーはそのプロジェクトのサンドボックス兼共有ナレッジなので、共有すると互いのファイルを読み書きしてしまいます。別のフォルダーを選んでください。",
"vi": "Project \"{name}\" đang làm việc trong {folder}. Mỗi thư mục chỉ thuộc về một project — thư mục vừa là sandbox vừa là kho kiến thức chung của project đó, dùng chung là hai project đọc và ghi đè file của nhau. Hãy chọn thư mục khác."},
"workspace.folder_shared_warning": {
"en": "⚠ This folder is also used by project \"{name}\". One folder belongs to one project only — pick another folder for one of them.",
"ja": "⚠ このフォルダーはプロジェクト「{name}」でも使われています。フォルダーは 1 つのプロジェクト専用です — どちらかに別のフォルダーを指定してください。",
"vi": "⚠ Thư mục này đang được project \"{name}\" dùng chung. Mỗi thư mục chỉ thuộc về một project — hãy đổi thư mục cho một trong hai."},
"workspace.instructions_placeholder": {
"en": "e.g. \"All answers in Vietnamese. We are building the X reporting tool; always follow the naming rules …\"",
"ja": "例:「回答はすべて日本語で。X レポートツールを開発中。命名規則に従うこと …」",
@@ -229,11 +218,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"chat.open_folder": {"en": "Open folder", "ja": "フォルダを開く", "vi": "Mở thư mục"},
"chat.open_output_folder": {"en": "Open output folder", "ja": "出力フォルダを開く", "vi": "Mở thư mục output"},
"chat.done_marker": {"en": "Done", "ja": "完了しました", "vi": "Đã hoàn thành"},
"chat.stopping": {"en": "Stopping", "ja": "停止中", "vi": "Đang dừng"},
"chat.stopped_marker": {
"en": "⏹ Stopped at your request",
"ja": "⏹ リクエストにより停止しました",
"vi": "⏹ Đã dừng theo yêu cầu"},
"chat.session_folder_marker": {
"en": "This conversation's output folder", "ja": "この会話の出力フォルダ",
"vi": "Thư mục output của hội thoại này"},
@@ -258,14 +258,6 @@ class JsonConfigRepository(ConfigSectionsMixin):
#: là bản chính; ``tests/test_config_repository.py`` có bài đối chiếu với
#: ``config.py`` để hai bên lệch nhau là đỏ ngay.
ROUTING_MODES = ("off", "auto", "manual", "fallback")
#: Chế độ người dùng còn chọn được. "off"/"fallback" đã bỏ khỏi giao diện;
#: giá trị cũ còn lưu trong config/project (hoặc giá trị lạ) đều hiểu là "auto".
USER_ROUTING_MODES = ("auto", "manual")
@classmethod
def user_routing_mode(cls, mode: str) -> str:
"""Quy một giá trị đã lưu về chế độ người dùng chọn được (mặc định "auto")."""
return mode if mode in cls.USER_ROUTING_MODES else "auto"
@classmethod
def load(cls, path: Path | None = None, *, secrets: SecretStore | None = None):
@@ -321,14 +313,16 @@ class JsonConfigRepository(ConfigSectionsMixin):
"""Chế độ có hiệu lực cho một bề mặt chat.
Đặt riêng cho bề mặt thì thắng; để trống thì lấy ``switch_mode`` chung.
Chỉ còn Auto/Manual: "off", "fallback" cũ hay giá trị lạ đều hiểu là "auto"."""
Giá trị lạ rơi về "off" — định tuyến luôn là thứ phải bật, kể cả khi
có người sửa tay file cấu hình."""
routing = self.routing
override = (routing.get("surface_modes", {}) or {}).get(surface, "")
return self.user_routing_mode(override or routing.get("switch_mode", ""))
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:
"""Đặt chế độ định tuyến riêng cho một bề mặt chat, ghi đĩa ngay."""
mode = self.user_routing_mode(mode)
mode = mode if mode in self.ROUTING_MODES else "off"
self.routing.setdefault("surface_modes", {})[surface] = mode
self.save()
+1 -27
View File
@@ -62,9 +62,7 @@ def run_command(ctx: ToolContext, args: Dict[str, Any],
"""
from cowork_local.core.deps import network_blocked_env, run_cancellable, sandbox_env
from cowork_local.core.sandbox_manager import ExecutionConfig, SandboxManager
from cowork_local.security.command_risk_classifier import (
classify_command, command_bypasses_network_proxy,
)
from cowork_local.security.command_risk_classifier import classify_command
command = str(args.get("command", "")).strip()
if not command:
@@ -76,21 +74,6 @@ def run_command(ctx: ToolContext, args: Dict[str, Any],
denial = "Command blocked by security policy: " + "; ".join(risk.reasons)
return {"ok": False, "output": denial}
# With the network blocked, SandboxManager runs the command in an OS-level
# network-less process (AppContainer on Windows — see
# infrastructure/sandbox/network_isolation.py). Tools that exist only to
# reach the network (ping, nslookup, ssh...) are still denied BY NAME
# first: the model gets a clear reason instead of a cryptic socket error.
if ctx.block_network:
bypass_tool = command_bypasses_network_proxy(command)
if bypass_tool:
return {"ok": False, "output": (
f"Command blocked: '{bypass_tool}' can reach the network without going through "
"an HTTP proxy, so the sandbox's network block (which only filters proxy-aware "
"traffic) cannot stop it by itself — blocked by name instead while "
"'Chặn mạng cho lệnh do agent chạy' is on."
)}
# Route through SandboxManager for risk-based isolation
mgr = SandboxManager(ExecutionConfig(
enabled=True,
@@ -128,15 +111,6 @@ def install_package(ctx: ToolContext, args: Dict[str, Any],
package = str(args.get("package", "")).strip()
if not package:
return {"ok": False, "output": "No package specified."}
# ``pip install`` bắt buộc phải ra internet, mà ``deps.pip_install`` chạy
# subprocess với ``os.environ`` nguyên vẹn — biến proxy hố đen của
# ``network_blocked_env`` không chạm tới nó. Từ chối thẳng ở đây (giống cách
# run_command chặn theo tên các công cụ không đi qua proxy) thay vì để pip
# thử 600 giây rồi báo một lỗi proxy khó hiểu.
if ctx.block_network:
return {"ok": False, "output": (
"install_package: network access is blocked by the Sandbox Security Layer "
"(\"Block network for agent-run commands\" is on in Settings).")}
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}."
+1 -25
View File
@@ -6,26 +6,11 @@ tag added in R05-T01/domain/tools/tool_registry.py describes.
"""
from __future__ import annotations
from typing import Any, Dict, Optional
from typing import Any, Dict
from .tool_context import ToolContext
def _network_refusal(ctx: ToolContext, tool: str) -> Optional[Dict[str, Any]]:
"""Lời từ chối khi Sandbox Security Layer đang chặn mạng; None nếu được đi.
``block_network`` trước đây chỉ được đọc ở ``command_tools.py`` (lệnh shell),
nên ba tool mang ``ToolCapability.NETWORK`` ở file này vẫn ra internet bình
thường trong khi Monitoring báo "Mạng: Bị chặn". Kiểm ở đây, TRƯỚC mọi lời
gọi mạng, để công tắc chặn đúng thứ nó nói là chặn.
"""
if not ctx.block_network:
return None
return {"ok": False, "output": (
f"{tool}: network access is blocked by the Sandbox Security Layer "
"(\"Block network for agent-run commands\" is on in Settings).")}
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
@@ -35,9 +20,6 @@ def fetch_url(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
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}"}
blocked = _network_refusal(ctx, "fetch_url")
if blocked is not None:
return blocked
if not ctx.allow_url_fetch:
return {"ok": False,
"output": ("fetch_url: URL fetching is turned off in Settings → Security "
@@ -55,9 +37,6 @@ def fetch_url(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
def jira_search(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
"""Tìm issue trên Jira bằng JQL."""
blocked = _network_refusal(ctx, "jira_search")
if blocked is not None:
return blocked
from cowork_local.core import jira_tool
out = jira_tool.search(ctx.jira, str(args.get("jql", "")),
@@ -68,9 +47,6 @@ def jira_search(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
def jira_get_issue(ctx: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
"""Lấy chi tiết một issue Jira theo mã."""
blocked = _network_refusal(ctx, "jira_get_issue")
if blocked is not None:
return blocked
from cowork_local.core import jira_tool
out = jira_tool.get_issue(ctx.jira, str(args.get("key", "")))
+4 -8
View File
@@ -37,16 +37,12 @@ class ToolContext:
# None (default) = no limits, matching pre-existing behavior.
resource_limits: Optional[Dict[str, float]] = None
# Sandbox Security Layer — Settings' "Block network for agent commands"
# — the proxy-env block for shell commands (deps.py::network_blocked_env)
# AND a flat refusal from every NETWORK-capability tool, which reaches the
# net in-process where proxy env vars mean nothing. False (default) =
# (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. Its own toggle, but NOT a way
# around block_network: with the network blocked every NETWORK-capability
# tool is refused first (fetch_tools.py::_network_refusal), so this flag only
# decides anything while the network is open. Defaults True; set from
# agent_security.allow_url_fetch.
# 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"].
@@ -1,392 +0,0 @@
"""Spawn a shell command inside a Windows AppContainer with NO network capability.
Why this exists
---------------
The old "block network" for agent shell commands only pointed the proxy env
vars at a dead port (``core/deps.py::network_blocked_env``). Anything that
ignores proxies (``Invoke-WebRequest -NoProxy``, raw sockets, ``certutil``,
.NET ``WebClient``...) still reached the internet. An AppContainer token that
is granted no ``internetClient``/``privateNetworkClientServer`` capability is
refused by the kernel firewall for every outbound connection, loopback
included, no matter which tool makes it. No admin rights are needed.
An AppContainer can only open files whose ACL admits its SID (or ALL
APPLICATION PACKAGES). System32 and Program Files already do; the workdir and
the app's own Python install do not, so :func:`spawn` grants the profile SID
access to those folders first (an extra ACE, nothing is removed).
:class:`AppContainerProcess` quacks like ``subprocess.Popen`` for the subset
``core/deps.py::_run_cancellable_body`` uses (``pid``, ``stdout``/``stderr``
text streams, ``poll``/``wait``/``kill``/``returncode``), so the Stop button,
timeouts, Job Objects and resource limits keep working unchanged.
"""
from __future__ import annotations
import io
import locale
import os
import subprocess
import sys
import threading
from typing import Dict, Iterable, Optional
PROFILE_NAME = "cowork_local.agent_netblock"
_IS_WINDOWS = sys.platform == "win32"
if _IS_WINDOWS:
import ctypes
import msvcrt
from ctypes import wintypes
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
_uenv = ctypes.WinDLL("userenv", use_last_error=True)
class _SECURITY_CAPABILITIES(ctypes.Structure):
_fields_ = [("AppContainerSid", ctypes.c_void_p), ("Capabilities", ctypes.c_void_p),
("CapabilityCount", wintypes.DWORD), ("Reserved", wintypes.DWORD)]
class _STARTUPINFOW(ctypes.Structure):
_fields_ = [("cb", wintypes.DWORD), ("lpReserved", wintypes.LPWSTR),
("lpDesktop", wintypes.LPWSTR), ("lpTitle", wintypes.LPWSTR),
("dwX", wintypes.DWORD), ("dwY", wintypes.DWORD),
("dwXSize", wintypes.DWORD), ("dwYSize", wintypes.DWORD),
("dwXCountChars", wintypes.DWORD), ("dwYCountChars", wintypes.DWORD),
("dwFillAttribute", wintypes.DWORD), ("dwFlags", wintypes.DWORD),
("wShowWindow", wintypes.WORD), ("cbReserved2", wintypes.WORD),
("lpReserved2", ctypes.c_void_p), ("hStdInput", wintypes.HANDLE),
("hStdOutput", wintypes.HANDLE), ("hStdError", wintypes.HANDLE)]
class _STARTUPINFOEXW(ctypes.Structure):
_fields_ = [("StartupInfo", _STARTUPINFOW), ("lpAttributeList", ctypes.c_void_p)]
class _PROCESS_INFORMATION(ctypes.Structure):
_fields_ = [("hProcess", wintypes.HANDLE), ("hThread", wintypes.HANDLE),
("dwProcessId", wintypes.DWORD), ("dwThreadId", wintypes.DWORD)]
class _SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = [("nLength", wintypes.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p),
("bInheritHandle", wintypes.BOOL)]
_uenv.CreateAppContainerProfile.restype = ctypes.c_long
_uenv.CreateAppContainerProfile.argtypes = [
wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.c_void_p,
wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p)]
_uenv.DeriveAppContainerSidFromAppContainerName.restype = ctypes.c_long
_uenv.DeriveAppContainerSidFromAppContainerName.argtypes = [
wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]
_uenv.GetAppContainerFolderPath.restype = ctypes.c_long
_uenv.GetAppContainerFolderPath.argtypes = [
wintypes.LPCWSTR, ctypes.POINTER(ctypes.c_wchar_p)]
_adv.ConvertSidToStringSidW.restype = wintypes.BOOL
_adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_wchar_p)]
_k32.InitializeProcThreadAttributeList.restype = wintypes.BOOL
_k32.InitializeProcThreadAttributeList.argtypes = [
ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_size_t)]
_k32.UpdateProcThreadAttribute.restype = wintypes.BOOL
_k32.UpdateProcThreadAttribute.argtypes = [
ctypes.c_void_p, wintypes.DWORD, ctypes.c_size_t, ctypes.c_void_p,
ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p]
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
_k32.CreatePipe.restype = wintypes.BOOL
_k32.CreatePipe.argtypes = [ctypes.POINTER(wintypes.HANDLE), ctypes.POINTER(wintypes.HANDLE),
ctypes.POINTER(_SECURITY_ATTRIBUTES), wintypes.DWORD]
_k32.SetHandleInformation.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD]
_k32.CreateProcessW.restype = wintypes.BOOL
_k32.CreateProcessW.argtypes = [
wintypes.LPCWSTR, wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, wintypes.BOOL,
wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(_STARTUPINFOEXW),
ctypes.POINTER(_PROCESS_INFORMATION)]
_k32.ResumeThread.argtypes = [wintypes.HANDLE]
_k32.WaitForSingleObject.restype = wintypes.DWORD
_k32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
_k32.GetExitCodeProcess.argtypes = [wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD)]
_k32.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
_k32.CloseHandle.argtypes = [wintypes.HANDLE]
_k32.GetStdHandle.restype = wintypes.HANDLE
_k32.OpenProcess.restype = wintypes.HANDLE
_ALREADY_EXISTS = ctypes.c_long(0x800700B7).value
_PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002
_PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES = 0x00020009
_EXTENDED_STARTUPINFO_PRESENT = 0x00080000
_CREATE_UNICODE_ENVIRONMENT = 0x00000400
_CREATE_NO_WINDOW = 0x08000000
_CREATE_SUSPENDED = 0x00000004
_STARTF_USESTDHANDLES = 0x00000100
_HANDLE_FLAG_INHERIT = 0x00000001
_STILL_ACTIVE = 259
_profile_lock = threading.Lock()
_profile: Dict[str, object] = {}
_granted: set = set()
class NetworkIsolationUnavailable(RuntimeError):
"""This machine cannot start a network-less process — callers must refuse to run."""
def is_supported() -> bool:
"""True on Windows builds that ship the AppContainer API (Windows 8+)."""
if not _IS_WINDOWS:
return False
try:
return bool(_uenv.CreateAppContainerProfile)
except AttributeError:
return False
def _profile_sid():
"""``(sid pointer, sid string, temp folder)`` of the shared no-network profile."""
with _profile_lock:
if _profile:
return _profile["sid"], _profile["sid_str"], _profile["temp"]
sid = ctypes.c_void_p()
hr = _uenv.CreateAppContainerProfile(PROFILE_NAME, "Cowork Local agent (no network)",
"Agent shell commands with the network blocked",
None, 0, ctypes.byref(sid))
if hr == _ALREADY_EXISTS:
hr = _uenv.DeriveAppContainerSidFromAppContainerName(PROFILE_NAME, ctypes.byref(sid))
if hr != 0 or not sid.value:
raise NetworkIsolationUnavailable(f"AppContainer profile error 0x{hr & 0xFFFFFFFF:08X}")
text = ctypes.c_wchar_p()
if not _adv.ConvertSidToStringSidW(sid, ctypes.byref(text)):
raise NetworkIsolationUnavailable("Could not read the AppContainer SID")
sid_str = text.value
folder = ctypes.c_wchar_p()
temp = ""
if _uenv.GetAppContainerFolderPath(sid_str, ctypes.byref(folder)) == 0 and folder.value:
temp = os.path.join(folder.value, "Temp")
os.makedirs(temp, exist_ok=True)
_profile.update(sid=sid, sid_str=sid_str, temp=temp)
return sid, sid_str, temp
_PERMS = {"write": "(OI)(CI)(M)", "read": "(OI)(CI)(RX)", "read_here": "(OI)(NP)(RX)"}
def _qt_package_dir() -> str:
"""Folder of the installed PySide6/Qt binaries ('' if PySide6 is absent)."""
try:
import importlib.util
spec = importlib.util.find_spec("PySide6")
except (ImportError, ValueError):
return ""
return os.path.dirname(spec.origin) if spec and spec.origin else ""
def _covers(folder: str, target: str) -> bool:
"""True if ``target`` is ``folder`` itself or lies somewhere below it."""
if not folder or not target:
return False
folder, target = os.path.normcase(folder), os.path.normcase(target)
return target == folder or target.startswith(folder.rstrip("\\/") + os.sep)
def _icacls(*args: str) -> subprocess.CompletedProcess:
return subprocess.run(["icacls", *args], capture_output=True, text=True,
creationflags=_CREATE_NO_WINDOW)
def grant_access(path: str, sid_str: str, mode: str) -> None:
"""Let the AppContainer SID open ``path``.
``mode`` is ``"write"``/``"read"`` (inherited by everything below) or
``"read_here"`` (this folder and the files directly in it, no deeper).
An inherited ACE must never reach the Qt WebEngine binaries: Chromium's
sandboxed render process then fails to load Qt6WebEngineCore.dll
(STATUS_DLL_NOT_FOUND) and every web view in the app goes blank. A folder
that contains the PySide6 install is therefore refused.
"""
path = os.path.abspath(path)
key = (os.path.normcase(path), mode)
if key in _granted or not os.path.exists(path):
return
if mode != "read_here" and _covers(path, _qt_package_dir()):
raise NetworkIsolationUnavailable(
f"Refusing to sandbox a folder that contains the app's Qt runtime: {path}")
perm = _PERMS[mode]
listing = (_icacls(path).stdout or "").lower()
if f"{sid_str}:{perm}".lower() not in listing:
done = _icacls(path, "/grant", f"*{sid_str}:{perm}", "/Q", "/C")
if done.returncode != 0:
raise NetworkIsolationUnavailable(
f"Could not grant the sandbox access to {path}: {(done.stderr or done.stdout).strip()}")
_granted.add(key)
def _repair_inherited_grant(path: str, sid_str: str) -> None:
"""Drop an inherited grant that an earlier build put on the app's venv."""
key = (os.path.normcase(os.path.abspath(path)), "repaired")
if key in _granted or not os.path.isdir(path):
return
listing = (_icacls(path).stdout or "").lower()
if f"{sid_str}:(oi)(ci)".lower() in listing:
_icacls(path, "/remove:g", f"*{sid_str}", "/Q", "/C")
_granted.add(key)
def _interpreter_grants():
"""``(folder, mode)`` pairs that let the sandbox run the app's Python.
The base install is read-only and holds no Qt; a venv only needs its root
(``pyvenv.cfg``) and ``Scripts`` — never ``Lib/site-packages``.
"""
qt_dir = _qt_package_dir()
if _covers(sys.base_prefix, qt_dir):
# PySide6 lives in the base install itself: expose only the executable
# and the compiled stdlib modules, never the tree holding Qt.
grants = [(sys.base_prefix, "read_here"), (os.path.join(sys.base_prefix, "DLLs"), "read")]
else:
grants = [(sys.base_prefix, "read")]
if os.path.normcase(sys.prefix) != os.path.normcase(sys.base_prefix):
grants += [(sys.prefix, "read_here"), (os.path.join(sys.prefix, "Scripts"), "read")]
return [(folder, mode) for folder, mode in grants
if mode == "read_here" or not _covers(folder, qt_dir)]
def _env_block(env: Dict[str, str]) -> ctypes.Array:
"""Sorted, double-NUL-terminated UTF-16 environment block for CreateProcessW."""
items = sorted(env.items(), key=lambda kv: kv[0].upper())
text = "".join(f"{k}={v}\0" for k, v in items if k and "=" not in k) + "\0"
return ctypes.create_unicode_buffer(text, len(text))
def _pipe():
"""Anonymous pipe; only the child's (write) end is inheritable."""
sa = _SECURITY_ATTRIBUTES(ctypes.sizeof(_SECURITY_ATTRIBUTES), None, True)
read, write = wintypes.HANDLE(), wintypes.HANDLE()
if not _k32.CreatePipe(ctypes.byref(read), ctypes.byref(write), ctypes.byref(sa), 0):
raise ctypes.WinError(ctypes.get_last_error())
_k32.SetHandleInformation(read, _HANDLE_FLAG_INHERIT, 0)
return read, write
class AppContainerProcess:
"""The ``subprocess.Popen`` subset that ``deps._run_cancellable_body`` relies on."""
def __init__(self, handle, pid: int, stdout: io.TextIOBase, stderr: io.TextIOBase):
"""Wrap an already-started process handle and its two output streams."""
self._handle = handle
self.pid = pid
self.stdout = stdout
self.stderr = stderr
self.returncode: Optional[int] = None
def poll(self) -> Optional[int]:
"""Exit code if the process has finished, else None."""
if self.returncode is None and self._handle:
code = wintypes.DWORD()
if _k32.GetExitCodeProcess(self._handle, ctypes.byref(code)) and code.value != _STILL_ACTIVE:
self.returncode = ctypes.c_int32(code.value).value
_k32.CloseHandle(self._handle)
self._handle = None
return self.returncode
def wait(self, timeout: Optional[float] = None) -> int:
"""Block until exit; raise ``subprocess.TimeoutExpired`` like Popen does."""
if self.returncode is None and self._handle:
ms = 0xFFFFFFFF if timeout is None else int(timeout * 1000)
if _k32.WaitForSingleObject(self._handle, ms) != 0:
raise subprocess.TimeoutExpired("appcontainer", timeout)
return self.poll()
def kill(self) -> None:
"""Terminate the process (the Job Object in deps kills its children)."""
if self.returncode is None and self._handle:
_k32.TerminateProcess(self._handle, 1)
def communicate(self, timeout: Optional[float] = None):
"""Read both streams to the end and wait; returns ``(stdout, stderr)``."""
chunks: Dict[str, str] = {}
def _drain(name, stream):
chunks[name] = stream.read()
readers = [threading.Thread(target=_drain, args=(n, s), daemon=True)
for n, s in (("out", self.stdout), ("err", self.stderr))]
for t in readers:
t.start()
for t in readers:
t.join(timeout)
self.wait(timeout)
return chunks.get("out", ""), chunks.get("err", "")
def spawn(command: str, cwd: Optional[str], env: Optional[Dict[str, str]],
readable_dirs: Iterable[str] = ()) -> AppContainerProcess:
"""Start ``cmd.exe /c command`` in the no-network AppContainer.
Raises :class:`NetworkIsolationUnavailable` when that cannot be done —
callers must then refuse the command rather than run it with the network on.
"""
if not is_supported():
raise NetworkIsolationUnavailable("AppContainer is only available on Windows")
sid, sid_str, temp = _profile_sid()
cwd = os.path.abspath(cwd or os.getcwd())
_repair_inherited_grant(sys.prefix, sid_str)
grant_access(cwd, sid_str, "write")
for folder, mode in [*_interpreter_grants(), *((d, "read") for d in readable_dirs if d)]:
grant_access(folder, sid_str, mode)
child_env = dict(os.environ if env is None else env)
if temp:
child_env["TEMP"] = child_env["TMP"] = temp
child_env.setdefault("PYTHONIOENCODING", "utf-8")
env_block = _env_block(child_env)
out_r, out_w = _pipe()
err_r, err_w = _pipe()
handles = (wintypes.HANDLE * 2)(out_w, err_w)
caps = _SECURITY_CAPABILITIES(sid, None, 0, 0)
size = ctypes.c_size_t()
_k32.InitializeProcThreadAttributeList(None, 2, 0, ctypes.byref(size))
attr = ctypes.create_string_buffer(size.value)
pi = _PROCESS_INFORMATION()
try:
if not (_k32.InitializeProcThreadAttributeList(attr, 2, 0, ctypes.byref(size))
and _k32.UpdateProcThreadAttribute(
attr, 0, _PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, ctypes.byref(caps),
ctypes.sizeof(caps), None, None)
and _k32.UpdateProcThreadAttribute(
attr, 0, _PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
ctypes.sizeof(handles), None, None)):
raise NetworkIsolationUnavailable(str(ctypes.WinError(ctypes.get_last_error())))
si = _STARTUPINFOEXW()
si.StartupInfo.cb = ctypes.sizeof(si)
si.StartupInfo.dwFlags = _STARTF_USESTDHANDLES
si.StartupInfo.hStdOutput = out_w
si.StartupInfo.hStdError = err_w
si.lpAttributeList = ctypes.addressof(attr)
comspec = os.environ.get("COMSPEC") or r"C:\Windows\System32\cmd.exe"
cmdline = ctypes.create_unicode_buffer(f'"{comspec}" /d /s /c "{command}"')
flags = (_EXTENDED_STARTUPINFO_PRESENT | _CREATE_UNICODE_ENVIRONMENT
| _CREATE_NO_WINDOW | _CREATE_SUSPENDED)
if not _k32.CreateProcessW(None, cmdline, None, None, True, flags,
ctypes.addressof(env_block), cwd,
ctypes.byref(si), ctypes.byref(pi)):
raise NetworkIsolationUnavailable(
f"Could not start the sandboxed command: {ctypes.WinError(ctypes.get_last_error())}")
_k32.ResumeThread(pi.hThread)
_k32.CloseHandle(pi.hThread)
except BaseException:
for h in (out_r, err_r):
_k32.CloseHandle(h)
raise
finally:
_k32.DeleteProcThreadAttributeList(attr)
_k32.CloseHandle(out_w)
_k32.CloseHandle(err_w)
def _stream(handle) -> io.TextIOBase:
fd = msvcrt.open_osfhandle(handle.value, os.O_RDONLY)
return io.TextIOWrapper(io.FileIO(fd, "rb"), encoding=locale.getpreferredencoding(False),
errors="replace")
return AppContainerProcess(pi.hProcess, pi.dwProcessId, _stream(out_r), _stream(err_r))
__all__ = ["AppContainerProcess", "NetworkIsolationUnavailable", "PROFILE_NAME",
"grant_access", "is_supported", "spawn"]
@@ -1,46 +0,0 @@
"""Start a shell command that the operating system keeps off the network.
Used whenever "Block network" is on for agent ``run_command`` calls and for
scheduled script tasks. The contract is fail-closed: if isolation cannot be
set up, :class:`NetworkIsolationUnavailable` is raised and the caller refuses
the command instead of running it with the network open.
* Windows: an AppContainer with no network capability
(:mod:`.appcontainer_process`).
* macOS: ``sandbox-exec`` with a profile that denies every network operation.
* Linux: ``unshare --net`` in a new user namespace (an empty network namespace
has only a downed loopback). If unprivileged namespaces are disabled,
``unshare`` itself fails and the command never runs.
"""
from __future__ import annotations
import shutil
import subprocess
import sys
from typing import Dict, Optional
from .appcontainer_process import NetworkIsolationUnavailable
_MACOS_PROFILE = "(version 1)(allow default)(deny network*)"
def spawn_without_network(command: str, cwd: Optional[str], env: Optional[Dict[str, str]]):
"""A ``Popen``-like process running ``command`` through the shell, with no network."""
if sys.platform == "win32":
from . import appcontainer_process
return appcontainer_process.spawn(command, cwd, env)
if sys.platform == "darwin" and shutil.which("sandbox-exec"):
argv = ["sandbox-exec", "-p", _MACOS_PROFILE, "/bin/sh", "-c", command]
elif sys.platform.startswith("linux") and shutil.which("unshare"):
argv = ["unshare", "--user", "--map-root-user", "--net", "/bin/sh", "-c", command]
else:
raise NetworkIsolationUnavailable(
"No network isolation is available on this system (needs AppContainer, "
"sandbox-exec or unshare).")
return subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, bufsize=1,
start_new_session=True)
__all__ = ["NetworkIsolationUnavailable", "spawn_without_network"]
-31
View File
@@ -1,31 +0,0 @@
"""Tiny opt-in performance tracing helpers.
Tracing is disabled by default and emits only timings/counts, never prompts,
credentials, file contents, or provider payloads.
"""
from __future__ import annotations
import logging
import os
import time
from contextlib import contextmanager
_LOG = logging.getLogger("cowork.performance")
def enabled() -> bool:
return os.environ.get("COWORK_PERF_TRACE", "").strip().lower() in {"1", "true", "yes"}
@contextmanager
def span(name: str, **fields):
if not enabled():
yield
return
started = time.perf_counter()
try:
yield
finally:
elapsed = (time.perf_counter() - started) * 1000.0
safe = " ".join(f"{k}={v}" for k, v in fields.items())
_LOG.info("perf %s %.1fms%s", name, elapsed, f" {safe}" if safe else "")
+4 -17
View File
@@ -115,23 +115,10 @@ class ChatAgentsMixin:
if err:
self.status_message.emit(tr("chatpanel.agent_list_error", err=err))
# Model discovery can involve a provider/network request. Constructing
# the chat panel during startup must not wait for it; schedule it after
# the first event-loop turn so the initial shell can paint immediately.
from PySide6.QtCore import QTimer
if getattr(self, "_agent_refresh_pending", False):
return
self._agent_refresh_pending = True
def start_worker() -> None:
self._agent_refresh_pending = False
w = AgentWorker(job)
w.finished_ok.connect(done)
self._agent_worker = w
w.start()
QTimer.singleShot(0, start_worker)
w = AgentWorker(job)
w.finished_ok.connect(done)
self._agent_worker = w
w.start()
def _populate_agents(self, models, keep: str) -> None:
"""Đổ danh sách vào bộ chọn Agent.
-7
View File
@@ -9,13 +9,6 @@ from typing import Any, Dict, List, Optional
_PLAN_ICONS = {"pending": "○", "running": "▶", "done": "✓", "error": "✗"}
HEADER_TITLE_MAX_CHARS = 10 # thanh tiêu đề khung chat chỉ hiện tối đa ngần này ký tự
def clip_chars(text: str, limit: int = HEADER_TITLE_MAX_CHARS) -> str:
"""Giữ tối đa ``limit`` ký tự, dư thì cắt và thêm "…"."""
return text if len(text) <= limit else text[:limit].rstrip() + "…"
def _format_plan_steps(steps) -> str:
+2 -11
View File
@@ -51,8 +51,6 @@ class MessageBubble(QFrame):
super().__init__()
self.role = role
self._text = ""
self._stream_pending = False
self._render_count = 0
self._collapsible = collapsible
self._title = title
self._head = None
@@ -166,20 +164,12 @@ class MessageBubble(QFrame):
def append_delta(self, delta: str) -> None:
"""Nối thêm một mẩu văn bản đang phát dần từ model rồi vẽ lại dạng markdown."""
self._text += delta
if not self._stream_pending:
self._stream_pending = True
QTimer.singleShot(40, self.flush_stream)
def flush_stream(self) -> None:
if self._stream_pending:
self._stream_pending = False
self.set_markdown(self._text)
self.set_markdown(self._text)
def set_markdown(self, text: str) -> None:
"""Đặt toàn bộ nội dung, hiển thị dạng markdown, rồi co giãn lại chiều cao."""
self._text = text
self.body.setMarkdown(text)
self._render_count += 1
self._autosize()
if self._collapsible:
self._update_head()
@@ -403,3 +393,4 @@ class ChatView(QScrollArea):
ChatHistoryWidget = ChatView
__all__ = ["ChatView", "ChatHistoryWidget", "MessageBubble"]
+1 -7
View File
@@ -99,9 +99,6 @@ class ChatPanel(ChatLiveTurnsMixin, ChatPanelLayoutMixin, ChatEventStreamMixin,
# can run concurrently. Each value is a turn-context dict — see _start_turn.
self.worker: AgentWorker | None = None
self._active: Dict[AgentWorker, Dict[str, Any]] = {}
# Người dùng đã bấm Dừng cho lượt đang chạy chưa. Cờ này chỉ đổi thứ
# MÀN HÌNH nói, không đổi việc huỷ: huỷ vẫn là cờ trên worker.
self._stop_requested = False
self._turn_seq: int = 0
# session_id -> its live messages list, for every conversation that still has
# a turn running. Lets you start a new chat / reopen an old one WHILE work
@@ -340,10 +337,7 @@ class ChatPanel(ChatLiveTurnsMixin, ChatPanelLayoutMixin, ChatEventStreamMixin,
Switching chats, or hitting History → Refresh, shows whether THIS chat is
still processing (a background turn) or idle."""
if self._view_busy():
# Đã bấm Dừng mà lượt chưa kết thúc: giữ nhãn "đang dừng", đừng kéo
# ngược về "đang chạy" — người dùng vừa bấm xong mà thấy chữ cũ thì
# đọc ra là nút không ăn.
self.thinking.start("chat.stopping" if self._stop_requested else "chat.running")
self.thinking.start("chat.running") # this conversation is still working
else:
self.thinking.stop()
self.composer.set_running(bool(self._active)) # Stop shows while anything runs
-17
View File
@@ -224,23 +224,6 @@ class ChatSessionMixin:
if getattr(self, "_usage_total_lbl", None) is not None:
self.refresh_usage()
def set_title_label(self, lbl, fallback: str) -> None:
"""Đặt tiêu đề hội thoại lên nhãn: tối đa 10 ký tự, bản đầy đủ ở tooltip."""
from .chat_helpers import clip_chars
full = self.title or fallback
lbl.setText(clip_chars(full))
lbl.setToolTip(full)
def apply_renamed_title(self, session_id: str, title: str) -> None:
"""Hội thoại đang mở vừa được đổi tên ở cột lịch sử: đổi luôn ``self.title``.
Không chỉ để thanh tiêu đề cập nhật ngay — lượt chat kế tiếp lưu bằng
``self.title``, giữ tên cũ sẽ ghi đè mất tên người dùng vừa đặt."""
if session_id and session_id == self.session_id:
self.title = title
self._notify_title()
def load_conversation(self, conv: Dict[str, Any]) -> None:
"""Switch the view to a stored conversation. Allowed while work is running —
the current turns keep going in the background."""
+4 -38
View File
@@ -13,7 +13,6 @@ from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Optional
from PySide6.QtCore import Qt, Signal
from ...core.history import shorten_title
from ...core.worker import AgentWorker
from ...i18n import tr
from ...state import AppContext
@@ -89,11 +88,7 @@ class ChatTurnRunnerMixin:
prefix = f"{prefix}\n\n{agent_prefix}" if prefix else agent_prefix
if not self.title:
base = text or (Path(attachments[0]).name if attachments else "(attachment)")
# Rút gọn mà không cắt vào giữa từ: xem shorten_title trong
# core/history.py. Dùng chung với derive_title để tiêu đề trên
# thanh tiêu đề và tiêu đề lưu vào lịch sử không rút gọn theo
# hai kiểu khác nhau.
self.title = shorten_title(base)
self.title = (base[:60] + "…") if len(base) > 60 else base
self._notify_title()
# Reset the Plan panel so each message starts from a clean checklist (the
@@ -217,7 +212,6 @@ class ChatTurnRunnerMixin:
if self._view_busy() or len(self._active) >= self._max_parallel():
self.composer.set_busy(True)
self.status_message.emit(tr("chatpanel.working", name=tr(f"app.tab.{self.kind}")))
self._stop_requested = False # lượt mới: xoá dấu vết lần Dừng trước
self.thinking.start("chat.running")
worker.start()
@@ -260,7 +254,7 @@ class ChatTurnRunnerMixin:
self._show_usage(ctx) # per-turn + conversation token/cost
except Exception: # noqa: BLE001 — usage display must never break a turn
pass
done = self._dau_ket_thuc()
done = self.chat_view.add_success(tr("chat.done_marker")) # green done marker in the chat box
folder = self.workspace_dir()
if folder:
done.add_folder_link(str(folder), tr("chat.open_output_folder"))
@@ -274,32 +268,12 @@ class ChatTurnRunnerMixin:
self._maybe_notify_teams(result)
self._drain_queue()
def _dau_ket_thuc(self):
"""Dấu kết thúc đặt vào khung chat khi một lượt vừa xong.
Dừng theo yêu cầu KHÔNG phải là hoàn thành: dấu xanh "Đã hoàn thành" ở
đó nói ngược hẳn với thứ người dùng vừa làm, và là lý do người dùng báo
"bấm Dừng mà không biết nó đã dừng hay chưa".
Tách khỏi ``_on_finished`` để nhánh này kiểm được bằng test mà không
phải dựng cả một ``ChatPanel``.
"""
if self._stop_requested:
return self.chat_view.add_status(tr("chat.stopped_marker"))
return self.chat_view.add_success(tr("chat.done_marker"))
def _on_failed(self, ctx: Dict[str, Any], err: str) -> None:
"""Lượt chạy lỗi: huỷ thư mục kết quả tạm và hiện lỗi (nếu hội thoại còn đang mở)."""
live = self._turn_is_live(ctx)
self._end_turn(ctx)
self._cleanup_turn(ctx, False) # discard this turn's output sandbox
if live and self._stop_requested:
# Người dùng vừa bấm Dừng: mọi lỗi phát sinh trong lúc huỷ là hệ quả
# của chính việc huỷ (đóng socket giữa stream, tool bị cắt ngang).
# Dội một traceback đỏ vào mặt họ là trả lời sai câu hỏi "nó dừng
# chưa?" — thứ họ cần là một dòng nói rõ là đã dừng.
self._dau_ket_thuc()
elif live:
if live:
self.chat_view.add_error(err)
self.graph_event.emit(self.session_name, {"type": "error", "content": err})
from ...providers.base import is_model_not_found_error
@@ -312,10 +286,7 @@ class ChatTurnRunnerMixin:
self.composer.set_text(ctx["display_text"])
else:
self._persist_session(ctx)
# Thanh trạng thái phải nói cùng một chuyện với khung chat: dừng theo
# yêu cầu thì không phải "lỗi".
key = "chatpanel.stopped" if self._stop_requested else "chatpanel.failed"
self.status_message.emit(tr(key, name=tr(f"app.tab.{self.kind}")))
self.status_message.emit(tr("chatpanel.failed", name=tr(f"app.tab.{self.kind}")))
self.turn_finished.emit({"error": err})
self._drain_queue()
@@ -340,11 +311,6 @@ class ChatTurnRunnerMixin:
"""Dừng mọi lượt đang chạy của hội thoại này và xoá sạch hàng đợi."""
if not self._active:
return
# Báo NGAY trên màn: huỷ thật có thể mất vài giây (đang chờ gateway trả
# lời, đang chạy dở một tool), mà trong lúc đó chỉ báo vẫn đếm "Đang
# chạy · 160s" — người dùng đọc ra là nút Dừng không ăn.
self._stop_requested = True
self.thinking.set_label("chat.stopping")
for w in list(self._active):
if w.isRunning():
w.request_stop()
-8
View File
@@ -200,14 +200,6 @@ class _NodeItem(QGraphicsObject):
e.accept()
return
super().mousePressEvent(e)
if self.isSelected():
# itemChange() only emits node_selected when the SELECTION STATE
# actually flips (ItemSelectedHasChanged) — clicking a node that
# was already selected (e.g. left selected when a run started)
# never re-fires it, so the property panel silently kept showing
# stale data and looked "locked" while the node ran. Emit
# explicitly on every click so the panel always reloads.
self.canvas.node_selected.emit(self.node.id)
def mouseMoveEvent(self, e):
"""Rê chuột trong lúc kéo nối: vẽ lại đường nét đứt theo con trỏ."""
-9
View File
@@ -273,15 +273,6 @@ class Co4ECanvas(_CanvasInteractionMixin, QGraphicsView):
item.status = status
item.update()
def node_status(self, node_id: str) -> str:
"""Trạng thái chạy hiện tại của một node — "idle" nếu không tìm thấy.
Dùng để quyết định có khóa bảng thuộc tính bên phải hay không khi
người dùng chọn node (xem ``StepConfigPanel.set_locked``).
"""
item = self._nodes.get(node_id)
return item.status if item is not None else "idle"
def reset_statuses(self) -> None:
"""Đưa mọi node về trạng thái chờ — gọi trước mỗi lần chạy lại luồng."""
for it in self._nodes.values():
-5
View File
@@ -101,11 +101,6 @@ class Co4EFlowTabsMixin:
self.center_stack.setCurrentIndex(1)
self._sync_runs_toggle(False)
self._apply_workflow(self._flows[flow_idx])
# _apply_workflow() rebuilds the canvas from wf.nodes/edges, which
# resets every node's live status to "idle" — without this, coming
# back to a flow that's still running (e.g. from the Runs page)
# shows every node as idle even though it's actually mid-run.
self._reflect_active_run(self._flows[flow_idx].id)
def _sync_runs_toggle(self, on: bool) -> None:
"""Keep the Runs toggle showing which page is up, however it got there
(a double-click in the runs table also switches pages)."""
+1 -9
View File
@@ -17,7 +17,6 @@ from PySide6.QtWidgets import QMenu, QMessageBox, QTableWidget, QTableWidgetItem
from ...core import co4e
from ...i18n import tr
from ...theme import current_palette
from .co4e_workflow_crud import _LOCKED_NODE_STATUSES
class Co4ERunsMixin:
@@ -156,14 +155,7 @@ class Co4ERunsMixin:
t = ev.get("type")
if t == "node_status":
if shown:
nid = ev.get("node_id")
self.canvas.update_node_status(nid, ev.get("status"))
# If the panel is showing THIS node right now (e.g. it was
# idle and the user had it open when the run started), keep
# the lock in sync instead of waiting for the next click.
if nid == getattr(self.config, "_node_id", None):
self.config.set_locked(
self.canvas.node_status(nid) in _LOCKED_NODE_STATUSES)
self.canvas.update_node_status(ev.get("node_id"), ev.get("status"))
elif t == "node_output":
if run_wf is not None:
self._outputs_for(run_wf)[ev["node_id"]] = ev.get("output", "")
+1 -9
View File
@@ -10,14 +10,11 @@ from typing import List, Optional
from PySide6.QtCore import QSize, Qt
from PySide6.QtWidgets import QMenu
from ...core import co4e
from ...core.co4e import STEP_RUNNING
from ...i18n import tr
from ...ui.dialog_buttons import ask_text
from ...ui.icons import icon
from ...presentation.co4e.co4e_chat_view import _skill_names
_LOCKED_NODE_STATUSES = (STEP_RUNNING,)
class Co4EWorkflowCrudMixin:
"""Phần tạo/mở/lưu/xoá luồng của Co4E Studio.
@@ -167,15 +164,10 @@ class Co4EWorkflowCrudMixin:
self.canvas.add_palette_step(co4e.Step(label="New Step"),
self.canvas.mapToScene(self.canvas.rect().center()))
def _on_node_selected(self, node_id: str) -> None:
"""Chọn một node thì nạp bước đó vào bảng thuộc tính, tự mở bảng nếu đang gập.
Chỉ khoá ô nhập liệu khi bước ĐANG chạy (DF-002) — chạy xong rồi thì
vẫn sửa lại được bình thường.
"""
"""Chọn một node thì nạp bước đó vào bảng thuộc tính, tự mở bảng nếu đang gập."""
for n in self.canvas.nodes():
if n.id == node_id:
self.config.load_step(node_id, n.data, _skill_names())
self.config.set_locked(self.canvas.node_status(node_id) in _LOCKED_NODE_STATUSES)
if self._config_collapsed:
self._toggle_config()
return
+1 -24
View File
@@ -38,7 +38,7 @@ from PySide6.QtWidgets import (
)
from ...config import PROVIDER_LABELS
from ...core.co4e import PERMISSION_PRESETS, STEP_DONE, STEP_RUNNING, Step
from ...core.co4e import PERMISSION_PRESETS, Step
from ...i18n import bind_items, bind_placeholder, bind_text, bind_tip, tr
from ...ui.icons import icon, icon_picker_combo
from .node_property_actions_mixin import _StepConfigActionsMixin
@@ -65,8 +65,6 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
self._step: Optional[Step] = None
self._node_id = ""
self._loading = False
self._ctx_available = ctx is not None
self._locked = False
self.setWidgetResizable(True)
host = QWidget()
self.setWidget(host)
@@ -291,27 +289,6 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
self.sub_list.addItem(sub.agent)
self._loading = False
def set_locked(self, locked: bool) -> None:
"""Khoá/mở khoá các trường chỉnh sửa theo trạng thái chạy của bước.
Chỉ khoá khi bước ĐANG chạy — tránh sửa nhầm cấu hình trong lúc chưa
biết kết quả (DF-002: trước đây còn khoá cả bước đã chạy xong, khiến
không sửa lại được sau khi run xong). Nút Chạy/Chạy từ đây/Xoá bước
vẫn hoạt động bình thường khi khoá — chỉ ô nhập liệu bị khoá, không
phải cả panel.
"""
self._locked = locked
editable = not locked
for w in (self.label_edit, self.role_edit, self.icon_edit,
self.instructions_edit, self.context_edit,
self.model_combo, self.perm_combo, self.verify_chk,
self.rounds_spin, self.skills_list,
self.attach_add_btn, self.attach_del_btn,
self.sub_add_btn, self.sub_del_btn, self.sub_list):
w.setEnabled(editable)
self.gen_btn.setEnabled(editable and self._ctx_available)
self.load_models_btn.setEnabled(editable and self._ctx_available)
def clear_step(self) -> None:
"""Xoá bảng khi không có bước nào được chọn."""
self._step = None
+5 -44
View File
@@ -21,9 +21,9 @@ from __future__ import annotations
from typing import List, Optional
from PySide6.QtWidgets import (
QComboBox, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget,
QComboBox, QHBoxLayout, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget,
)
from PySide6.QtCore import Qt, Signal
from PySide6.QtCore import Signal
from cowork_local.i18n import on_language_changed, tr
from cowork_local.presentation.folder.ai_edit_model_resolver import AiEditModelResolver
@@ -32,45 +32,6 @@ from cowork_local.theme import current_palette
from cowork_local.ui.chat_view import ChatView
class _AutoExpandInput(QPlainTextEdit):
"""Instruction box: grows with content (1..~6 lines, then scrolls), Enter
submits, Shift+Enter inserts a newline — same convention as the Cowork
composer (``presentation/chat/chat_input_box.py::_Input``), minus its
``/skill``/``/agent`` popups and drag-drop attachment handling, which
don't apply to a single AI-edit instruction. DF-008: a fixed-height
single-line ``QLineEdit`` read as cramped for a full instruction; this
replaces it instead of just nudging the height up further."""
submit = Signal()
MIN_HEIGHT = 36 # matches the old QLineEdit's bumped-up height
MAX_HEIGHT = 140 # ~6 lines, then it scrolls instead of growing further
def __init__(self, parent=None):
super().__init__(parent)
self.setTabChangesFocus(True) # Tab moves focus, doesn't insert a tab
self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.textChanged.connect(self._adjust_height)
self._adjust_height()
def _adjust_height(self) -> None:
# QPlainTextEdit reports the document height in LINES, not pixels —
# convert via line spacing (same approach as chat_input_box.py).
lines = self.document().size().height() or 1
line_px = self.fontMetrics().lineSpacing()
h = int(lines * line_px + 2 * self.frameWidth() + 12)
h = max(self.MIN_HEIGHT, min(self.MAX_HEIGHT, h))
if h != self.height():
self.setFixedHeight(h)
def keyPressEvent(self, e) -> None: # noqa: N802
if e.key() in (Qt.Key_Return, Qt.Key_Enter) and not (e.modifiers() & Qt.ShiftModifier):
self.submit.emit()
return
super().keyPressEvent(e)
class AiFileEditorDialog(QWidget):
"""Collapsible panel: a Cowork-style inline chat timeline, this panel's
OWN model picker + routing toggle, an instruction box, and an Apply/
@@ -133,9 +94,9 @@ class AiFileEditorDialog(QWidget):
ctx, self.ai_model_combo, self.ai_chat.add_status, self._confirm_routing_switch)
row = QHBoxLayout()
self.ai_input = _AutoExpandInput()
self.ai_input = QLineEdit()
self.ai_input.setPlaceholderText(tr("folder.ai_placeholder"))
self.ai_input.submit.connect(self._ai_send)
self.ai_input.returnPressed.connect(self._ai_send)
row.addWidget(self.ai_input, 1)
self.ai_send_btn = QPushButton(tr("folder.ai_send"))
self.ai_send_btn.setObjectName("primary")
@@ -209,7 +170,7 @@ class AiFileEditorDialog(QWidget):
if not self.preview.root:
self.ai_chat.add_error(tr("folder.ai_no_file"))
return
instruction = self.ai_input.toPlainText().strip()
instruction = self.ai_input.text().strip()
if not instruction:
return
self.ai_input.clear()
@@ -110,10 +110,7 @@ class OfficeDocumentRenderer:
if self._engine is None:
try:
from PySide6.QtWebEngineWidgets import QWebEngineView
from .offline_web_page import install_offline_page
self._engine = QWebEngineView()
install_offline_page(self._engine)
self._owner.stack.addWidget(self._engine)
except Exception: # noqa: BLE001
self._engine = None
-66
View File
@@ -1,66 +0,0 @@
"""HTML preview page that loads nothing from the web while "Block network" is on.
``QWebEngineView.setHtml`` happily fetches every ``<img src="https://...">``,
``<script src>`` and stylesheet the previewed file references — an outbound
connection the user never asked for, made by the app itself. The preview gets
its own off-the-record profile (so the interceptor below touches no other web
view, e.g. the GraphRAG renderer) and every remote request is refused while
the switch is on. Local files, ``data:`` and ``qrc:`` URLs still load.
Lifetime rule: a ``QWebEngineProfile`` must outlive every page that uses it.
A profile owned by the view is destroyed *before* the page (children die in
creation order) — Qt then warns "Release of profile requested but
WebEnginePage still not deleted" and the app can abort later (0xc0000409 in
Qt6Core.dll, seen when switching tabs). So there is ONE profile for the whole
app, owned by the QApplication, and each page is owned by its view.
"""
from __future__ import annotations
from typing import Optional
from PySide6.QtWebEngineCore import (
QWebEnginePage, QWebEngineProfile, QWebEngineSettings, QWebEngineUrlRequestInterceptor,
)
from PySide6.QtWidgets import QApplication
from cowork_local.application.network import network_guard
_REMOTE_SCHEMES = frozenset({"http", "https", "ws", "wss", "ftp"})
_profile: Optional[QWebEngineProfile] = None
_blocker: Optional["RemoteRequestBlocker"] = None # Python must hold it, or it is collected
class RemoteRequestBlocker(QWebEngineUrlRequestInterceptor):
"""Refuses remote URLs whenever the network guard says the network is blocked."""
def interceptRequest(self, info) -> None: # noqa: N802 - Qt override
"""Called by WebEngine for every request the page makes."""
if info.requestUrl().scheme().lower() in _REMOTE_SCHEMES and network_guard.is_blocked():
info.block(True)
def preview_profile() -> QWebEngineProfile:
"""The app-wide off-the-record profile shared by every HTML preview."""
global _profile, _blocker
if _profile is None:
_profile = QWebEngineProfile(QApplication.instance()) # no storage name = off the record
_blocker = RemoteRequestBlocker(_profile)
_profile.setUrlRequestInterceptor(_blocker)
_profile.settings().setAttribute(
QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
return _profile
def install_offline_page(view) -> None:
"""Give ``view`` a page on the shared preview profile.
The previewed file is loaded with a ``file://`` base URL, and Qt refuses
every remote resource of such a page unless
``LocalContentCanAccessRemoteUrls`` is on — so web images never showed,
even with the network open. The switch is turned on for the profile; the
interceptor is what keeps remote content out while "Block network" is on.
"""
view.setPage(QWebEnginePage(preview_profile(), view))
__all__ = ["RemoteRequestBlocker", "install_offline_page", "preview_profile"]
-83
View File
@@ -1,83 +0,0 @@
"""Khoá phạm vi quét của màn GraphRAG vào một project.
Tách khỏi ``graph_renderer.py``: file đó đã ở 399/400 dòng — đúng một dòng
trước trần của ``scripts/check_loc.py``, và cổng ấy nói rõ cách duy nhất đúng
khi chạm trần là tách file, không phải nới con số. Khối này là chỗ tự nhiên
để cắt: ba phương thức dưới đây chỉ nói về một việc — project nào đang khoá,
và thư mục nào đi theo nó — còn phần còn lại của renderer lo việc vẽ.
Là mixin chứ không phải đối tượng rời, cùng lý do như ``NavRailMixin``: ba
phương thức này đọc/ghi state của chính renderer (``project_combo``,
``path_edit``, ``_needs_scan``…). 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.renderer.X`` mà không đổi hành vi gì.
"""
from __future__ import annotations
from cowork_local.i18n import tr
class GraphProjectLockMixin:
"""Ba phương thức khoá-theo-project. Trộn vào ``GraphRenderer``."""
def _refresh_project_combo(self) -> None:
"""Nạp lại danh sách project vào bộ chọn, giữ nguyên project đang chọn."""
from cowork_local.core.projects import list_projects
keep = self._active_project_id
self.project_combo.blockSignals(True)
self.project_combo.clear()
self.project_combo.addItem(tr("structure.project_none"), "")
row_to_select = 0
for i, p in enumerate(list_projects(), start=1):
self.project_combo.addItem(p.name, p.project_id)
if p.project_id == keep:
row_to_select = i
self.project_combo.setCurrentIndex(row_to_select)
self.project_combo.blockSignals(False)
def set_project(self, project_id: str) -> None:
"""Khoá phạm vi quét vào một project (chuỗi rỗng là bỏ khoá)."""
pid = project_id or ""
self._refresh_project_combo()
target = self.project_combo.findData(pid)
if target < 0:
target = 0
if self.project_combo.currentIndex() == target:
self._on_project_changed(target)
else:
self.project_combo.setCurrentIndex(target)
def _on_project_changed(self, _idx: int) -> None:
"""Áp trạng thái khoá: đường dẫn chuyển sang chỉ đọc và trỏ vào thư mục"""
from cowork_local.core.projects import load_project
pid = self.project_combo.currentData() or ""
project_changed = pid != self._active_project_id
self._active_project_id = pid
locked = bool(pid)
self.path_edit.setReadOnly(locked)
self._pick_btn.setEnabled(not locked)
if locked:
project = load_project(pid)
if project is not None:
self.path_edit.setText(str(project.workspace_dir()))
# Changing the FOLDER changes what we scan just as much as changing the
# project does. Keying this off the id alone left the path in the bar
# updated while the graph in the middle still showed the old folder's
# nodes: "Đổi" in the Project screen moves the folder, never the id.
duong_dan = self.path_edit.text().strip()
doi_muc_tieu = project_changed or duong_dan != self._active_path
self._active_path = duong_dan
if doi_muc_tieu:
self.project_changed.emit() # GraphQaWidget drops its temp extraction cache
# Mark it and scan on the next visit rather than now — see
# auto_scan_and_fit()'s docstring for why.
self._needs_scan = True
# ...except when this screen is the one on show. The picker lives HERE,
# so a user changing project is already looking at the graph: there is
# no "next visit" to defer to, and they had to press Scan by hand.
# Deferring still applies when the change came from the Workspace
# screen while this one is hidden, which is what it was for.
if self.isVisible() and duong_dan:
self._needs_scan = False
self._scan()
+59 -5
View File
@@ -27,7 +27,6 @@ from cowork_local.core.worker import AgentWorker
from cowork_local.i18n import on_language_changed, tr
from cowork_local.presentation.graph import graph_export
from cowork_local.presentation.graph.graph_messages_view import GraphMessagesView
from cowork_local.presentation.graph.graph_project_lock import GraphProjectLockMixin
from cowork_local.presentation.graph.graph_scene_builder import build_scene
from cowork_local.presentation.graph.graph_scene_items import _Bridge, _Edge, _GraphView, _Node
from cowork_local.presentation.shared import HAS_WEB_ENGINE
@@ -36,7 +35,7 @@ from cowork_local.theme import current_palette
from cowork_local.ui.icons import icon
class GraphRenderer(GraphProjectLockMixin, QWidget):
class GraphRenderer(QWidget):
"""Nửa "đồ thị" của màn GraphRAG: thanh công cụ, khung xem và vòng đời quét."""
status_message = Signal(str)
node_selected = Signal(object) # a node's .data, whenever the scene selection changes
@@ -61,8 +60,6 @@ class GraphRenderer(GraphProjectLockMixin, QWidget):
self._needs_scan = False
self._scan_seq = 0 # only the latest scan's result is rendered (no stale overwrite)
self._active_project_id = "" # "" = free path; set = scan locked to that project's sandbox
# The folder last scanned — see graph_project_lock.py.
self._active_path = ""
self._rescan_timer = QTimer(self)
self._rescan_timer.setSingleShot(True)
@@ -157,6 +154,63 @@ class GraphRenderer(GraphProjectLockMixin, QWidget):
"""
return [item.data for item in self.scene.selectedItems() if isinstance(item, _Node)]
# ---- project sandbox lock ------------------------------------------------- #
def _refresh_project_combo(self) -> None:
"""Nạp lại danh sách project vào bộ chọn, giữ nguyên project đang chọn."""
from cowork_local.core.projects import list_projects
keep = self._active_project_id
self.project_combo.blockSignals(True)
self.project_combo.clear()
self.project_combo.addItem(tr("structure.project_none"), "")
row_to_select = 0
for i, p in enumerate(list_projects(), start=1):
self.project_combo.addItem(p.name, p.project_id)
if p.project_id == keep:
row_to_select = i
self.project_combo.setCurrentIndex(row_to_select)
self.project_combo.blockSignals(False)
def set_project(self, project_id: str) -> None:
"""Khoá phạm vi quét vào một project (chuỗi rỗng là bỏ khoá)."""
pid = project_id or ""
self._refresh_project_combo()
target = self.project_combo.findData(pid)
if target < 0:
target = 0
if self.project_combo.currentIndex() == target:
self._on_project_changed(target)
else:
self.project_combo.setCurrentIndex(target)
def _on_project_changed(self, _idx: int) -> None:
"""Áp trạng thái khoá: đường dẫn chuyển sang chỉ đọc và trỏ vào thư mục"""
from cowork_local.core.projects import load_project
pid = self.project_combo.currentData() or ""
project_changed = pid != self._active_project_id
self._active_project_id = pid
locked = bool(pid)
self.path_edit.setReadOnly(locked)
self._pick_btn.setEnabled(not locked)
if locked:
project = load_project(pid)
if project is not None:
self.path_edit.setText(str(project.workspace_dir()))
if project_changed:
self.project_changed.emit() # GraphQaWidget drops its temp extraction cache
# Mark it and scan on the next visit rather than now — see
# auto_scan_and_fit()'s docstring for why.
self._needs_scan = True
# ...except when this screen is the one on show. The picker lives HERE,
# so a user changing project is already looking at the graph: there is
# no "next visit" to defer to, and they had to press Scan by hand.
# Deferring still applies when the change came from the Workspace
# screen while this one is hidden, which is what it was for.
if self.isVisible() and self.path_edit.text().strip():
self._needs_scan = False
self._scan()
# ---- helpers ---------------------------------------------------------------- #
def _pick(self) -> None:
"""Mở hộp thoại chọn thư mục gốc để quét."""
@@ -183,7 +237,7 @@ class GraphRenderer(GraphProjectLockMixin, QWidget):
# ---- prewarm / scan lifecycle -------------------------------------------------- #
def prewarm(self) -> None:
"""Pay for the graph view before it is clicked on, not during."""
if self.web is not None:
if not HAS_WEB_ENGINE or self.web is not None:
return
self._ensure_web()
if self._graph is None and self.path_edit.text().strip():
+2 -21
View File
@@ -40,9 +40,6 @@ class StructureGraphView(QWidget):
# Project ma man Workspace da ap xuong lan gan nhat. None = chua ap lan
# nao, de lan goi dau tien khong bi bo qua ke ca khi pid la chuoi rong.
self._workspace_project = None
# Thư mục của project đó lúc áp gần nhất. Chốt theo CẢ đường dẫn chứ
# không chỉ theo id — xem set_workspace_project.
self._workspace_dir = None
root = QVBoxLayout(self)
self.renderer = GraphRenderer(ctx)
@@ -211,29 +208,13 @@ class StructureGraphView(QWidget):
Đổi sang project khác ở màn Workspace thì vẫn áp — cùng luật với tab Thư
mục (``FolderTab.set_project_root``). Chỉ lần refresh trong CÙNG một
project VÀ cùng một thư mục là không được đụng.
Chốt theo cả đường dẫn chứ không chỉ theo id: đổi thư mục làm việc ở
màn Project không làm id đổi, nên chốt theo mỗi id thì màn này giữ
nguyên đường dẫn cũ và quét nhầm thư mục. Tab Thư mục vốn đã chốt theo
đường dẫn — đây là đưa hai nơi về đúng cùng một luật như comment này
vẫn nói.
project là không được đụng.
"""
thu_muc = self._thu_muc_cua(project_id)
if project_id == self._workspace_project and thu_muc == self._workspace_dir:
if project_id == self._workspace_project:
return
self._workspace_project = project_id
self._workspace_dir = thu_muc
self.set_project(project_id)
@staticmethod
def _thu_muc_cua(project_id: str) -> str:
"""Thư mục làm việc hiện tại của project, chuỗi rỗng nếu không có."""
from cowork_local.core.projects import load_project
project = load_project(project_id) if project_id else None
return str(project.workspace_dir()) if project is not None else ""
def prewarm(self) -> None:
"""Dựng sẵn khung đồ thị trước khi người dùng bấm vào, để lần mở đầu không giật."""
self.renderer.prewarm()
+10 -33
View File
@@ -10,7 +10,6 @@ the ``status_message`` signal, ``select_subtab(index)``, ``nav_subtabs()``,
"""
from __future__ import annotations
from datetime import date, timedelta
from typing import List
from PySide6.QtCore import QTimer, Signal
@@ -19,7 +18,6 @@ from PySide6.QtWidgets import QHBoxLayout, QLabel, QTabWidget, QVBoxLayout, QWid
from ...core import audit_log
from ...i18n import on_language_changed, tr
from ...state import AppContext
from ...performance import span
from .tabs.action_logs_tab import ActionLogsTab
from .tabs.agent_status_tab import AgentStatusTab
from .tabs.mcp_tab import McpTab
@@ -27,25 +25,11 @@ from .tabs.overview_tab import OverviewTab
from .tabs.security_events_tab import SecurityEventsTab
_REFRESH_MS = 3000
# Comfortably larger than any realistic audit-log size for the WINDOW of
# events _load_events() now actually reads (see _LOG_WINDOW_DAYS below) — this
# is MonitoringQueryService's query-side page size, kept unbounded so it
# always returns every matching event within the window; the user-facing
# "Số dòng/trang" control (DF-006 — see shared/event_table.py::set_page_size,
# shared/filter_scaffold.py::build_filter_scaffold's with_page_size) trims
# that down for DISPLAY, client-side, per event tab.
# Comfortably larger than any realistic audit-log size — the event tables
# have never had pagination controls, so every tab still shows "all matching
# events" exactly like before; MonitoringQueryService's pagination support
# is exercised for real here, just not surfaced as UI (yet).
_UNBOUNDED_PAGE_SIZE = 100_000
# _load_events() re-reads the audit log from disk every _REFRESH_MS (3s) via
# _auto_refresh(), and audit_log.load_events()/load_shared_audit_events() are
# day-sharded JSONL — unbounded start/end means EVERY day file ever written
# gets re-read and re-parsed on EVERY tick, which is what actually made
# Monitoring "gây nặng khi log lớn" (see DF-006): the slowness was never in
# rendering (EventTable paginates client-side, 5-100 rows/page — see
# shared/event_table.py::_DEFAULT_PAGE_SIZE), it was this repeated full-history
# read.
# 30 days is a live-monitoring window, not a hard retention limit — nothing
# is deleted, older days are simply not re-read on every 3s tick.
_LOG_WINDOW_DAYS = 30
class MonitoringTab(QWidget):
@@ -275,21 +259,14 @@ class MonitoringTab(QWidget):
Có cấu hình thư mục chia sẻ VÀ đọc ra được dữ liệu thì dùng nó, để cả đội
nhìn chung một bức tranh; rỗng thì rơi về nhật ký của máy này.
Chỉ đọc ``_LOG_WINDOW_DAYS`` ngày gần nhất — cả hai nguồn đều lưu theo
file JSONL từng ngày, nên bounding ở đây tránh việc đọc lại TOÀN BỘ
lịch sử mỗi 3 giây (xem ``_auto_refresh``), là nguyên nhân thật của
DF-006 (gây nặng khi log lớn).
"""
start = date.today() - timedelta(days=_LOG_WINDOW_DAYS)
shared_dir = self.ctx.config.shared_dir
with span("monitoring.load_events", window_days=_LOG_WINDOW_DAYS):
if shared_dir:
from ...core import telemetry_shared
shared_events = telemetry_shared.load_shared_audit_events(shared_dir, start=start)
if shared_events:
return shared_events
return audit_log.load_events(start=start)
if shared_dir:
from ...core import telemetry_shared
shared_events = telemetry_shared.load_shared_audit_events(shared_dir)
if shared_events:
return shared_events
return audit_log.load_events()
def _apply_events_to_event_tabs(self, events: List[dict]) -> None:
"""Filters the ALREADY-LOADED event list (see ``_load_events`` — one
+4 -63
View File
@@ -6,7 +6,7 @@ from __future__ import annotations
from typing import List, Optional
from PySide6.QtCore import QEvent, QObject, QRect, QSize, Qt, Signal
from PySide6.QtCore import QEvent, QObject, QRect, QSize, Qt
from PySide6.QtGui import QBrush, QColor
from PySide6.QtWidgets import QHeaderView, QTableWidget, QTableWidgetItem, QWidget
@@ -17,8 +17,7 @@ from ....ui.icons import DOT_GREEN, DOT_RED, icon
from .badges import action_label
from .formatters import agent_avatar_icon, fmt_event_time
_DEFAULT_PAGE_SIZE = 20
PAGE_SIZE_OPTIONS = (5, 10, 20, 50, 100)
_MAX_ROWS = 300
class _TimeItem(QTableWidgetItem):
@@ -63,12 +62,6 @@ class EventTable(QTableWidget):
"secret_in_output": "warning",
}
# Emitted whenever the rendered page changes (new data, page-size change,
# or prev/next navigation) — args are (current_page, page_count), both
# 1-based-friendly in that current_page is 0-indexed but page_count is a
# plain count. filter_scaffold.py's pager label/buttons listen to this.
page_changed = Signal(int, int)
def __init__(self, show_result: bool = True):
# Security Events drops the result column entirely (see _ACTION_TINTS).
"""Bảng sự kiện dùng chung của các tab Giám sát.
@@ -77,10 +70,6 @@ class EventTable(QTableWidget):
là thất bại nên cột ấy chỉ tốn chỗ.
"""
self._show_result = show_result
self._page_size = _DEFAULT_PAGE_SIZE
self._current_page = 0
self._last_events: List[dict] = []
self._sorted_events: List[dict] = []
super().__init__(0, 7 if show_result else 6)
self.setEditTriggers(QTableWidget.NoEditTriggers)
self.setSelectionBehavior(QTableWidget.SelectRows)
@@ -109,60 +98,13 @@ class EventTable(QTableWidget):
cols += [tr("monitoring.col_detail_block") if not self._show_result else tr("monitoring.col_detail")]
self.setHorizontalHeaderLabels(cols)
def page_size(self) -> int:
"""Số dòng đang hiển thị mỗi trang."""
return self._page_size
def page_count(self) -> int:
"""Tổng số trang với dữ liệu và số dòng/trang hiện tại (tối thiểu 1)."""
if not self._sorted_events:
return 1
return -(-len(self._sorted_events) // self._page_size) # ceil div
def current_page(self) -> int:
"""Trang đang hiển thị, đánh số từ 0."""
return self._current_page
def go_to_page(self, page: int) -> None:
"""Nhảy tới một trang cụ thể (đánh số từ 0), tự kẹp trong khoảng hợp lệ."""
self._current_page = page
self._render_current_page()
def next_page(self) -> None:
"""Sang trang kế — không làm gì nếu đã ở trang cuối."""
self.go_to_page(self._current_page + 1)
def prev_page(self) -> None:
"""Về trang trước — không làm gì nếu đã ở trang đầu."""
self.go_to_page(self._current_page - 1)
def set_page_size(self, n: int) -> None:
"""Đổi số dòng hiển thị mỗi trang, quay về trang đầu, rồi vẽ lại với dữ
liệu đã có sẵn (không cần refresh lại từ nguồn)."""
self._page_size = n
self._current_page = 0
self._render_current_page()
def set_events(self, events: List[dict]) -> None:
"""Đổ danh sách sự kiện vào bảng: mới nhất lên đầu, chia trang theo
``self._page_size`` — xem qua trang khác bằng ``next_page``/``prev_page``
(nút tiến/lùi ở filter_scaffold.py), không còn bị cắt bỏ vĩnh viễn như
trước (DF-006)."""
self._last_events = events
self._sorted_events = sorted(events, key=lambda e: e.get("ts", ""), reverse=True)
self._current_page = 0
self._render_current_page()
def _render_current_page(self) -> None:
"""Vẽ đúng một trang (theo ``self._current_page``/``self._page_size``)
từ ``self._sorted_events`` đã sắp sẵn.
"""Đổ danh sách sự kiện vào bảng: mới nhất lên đầu, cắt ở ``_MAX_ROWS``.
Tắt sắp xếp trong lúc đổ dữ liệu — để bật, Qt sắp lại sau mỗi dòng và việc
nạp chậm đi theo bậc hai.
"""
self._current_page = max(0, min(self._current_page, self.page_count() - 1))
start = self._current_page * self._page_size
events = self._sorted_events[start:start + self._page_size]
events = sorted(events, key=lambda e: e.get("ts", ""), reverse=True)[:_MAX_ROWS]
self.setSortingEnabled(False)
self.setRowCount(len(events))
for row, ev in enumerate(events):
@@ -207,7 +149,6 @@ class EventTable(QTableWidget):
self.setItem(row, col, item)
self.setSortingEnabled(True)
self.apply_filter(getattr(self, "_filter_needle", ""))
self.page_changed.emit(self._current_page, self.page_count())
def apply_filter(self, needle: str) -> None:
"""Ẩn/hiện dòng theo từ khoá tìm kiếm (không phân biệt hoa thường)."""
@@ -16,13 +16,13 @@ from typing import Callable, Dict, Optional
from PySide6.QtCore import Qt
from PySide6.QtGui import QKeySequence, QShortcut
from PySide6.QtWidgets import (
QApplication, QComboBox, QHBoxLayout, QLabel, QLineEdit, QPushButton,
QSplitter, QTableWidget, QVBoxLayout, QWidget,
QApplication, QHBoxLayout, QLabel, QLineEdit, QPushButton, QSplitter,
QTableWidget, QVBoxLayout, QWidget,
)
from ....i18n import bind_tip, tr
from ....ui.icons import icon
from .event_table import PAGE_SIZE_OPTIONS, ClickOutsideCloser, EventTable
from .event_table import ClickOutsideCloser, EventTable
from .event_detail_panel import EventDetailPanel
@@ -47,12 +47,11 @@ def _sync_event_detail(table: EventTable, panel: EventDetailPanel) -> None:
def build_filter_scaffold(
page: QWidget, table: QTableWidget, *, on_refresh: Callable[[], None],
title_key: Optional[str] = None, with_search: bool = True,
with_detail: bool = False, with_page_size: bool = False,
with_detail: bool = False,
on_ai_filter: Optional[Callable[[QLineEdit, QPushButton], None]] = None,
) -> Dict[str, object]:
"""Dựng khung chung cho một tab sự kiện: tiêu đề, nút làm mới, ô tìm kiếm,
nút lọc bằng AI, control "Số dòng/trang" (nếu ``with_page_size``) và panel
chi tiết.
nút lọc bằng AI và panel chi tiết.
Bốn tab sự kiện của màn Giám sát chỉ khác nhau ở nguồn dữ liệu, nên phần vỏ
này được dựng một lần và dùng chung.
@@ -92,55 +91,6 @@ def build_filter_scaffold(
ai_btn.clicked.connect(lambda: on_ai_filter(search, ai_btn))
row.addWidget(search, 1)
row.addWidget(ai_btn)
if with_page_size and isinstance(table, EventTable):
# DF-006: the item-per-page count was never surfaced anywhere in
# the UI (design called for it) — EventTable already trims to a
# page size internally, this just makes that number visible AND
# user-choosable instead of a fixed constant.
page_size_lbl = QLabel(tr("monitoring.page_size_label"))
page_size_combo = QComboBox()
for n in PAGE_SIZE_OPTIONS:
page_size_combo.addItem(str(n), n)
current = table.page_size()
page_size_combo.setCurrentIndex(
PAGE_SIZE_OPTIONS.index(current) if current in PAGE_SIZE_OPTIONS else 0)
page_size_combo.currentIndexChanged.connect(
lambda i: table.set_page_size(page_size_combo.itemData(i)))
row.addWidget(page_size_lbl)
row.addWidget(page_size_combo)
# DF-006 follow-up: trimming to a page size alone silently dropped
# every row past it with no way back to see them — prev/next
# buttons plus a "trang X/Y" indicator make the rest reachable.
page_prev_btn = QPushButton()
page_prev_btn.setIcon(icon("chevron-left"))
page_prev_btn.setCursor(Qt.PointingHandCursor)
bind_tip(page_prev_btn, "monitoring.page_prev")
page_next_btn = QPushButton()
page_next_btn.setIcon(icon("chevron-right"))
page_next_btn.setCursor(Qt.PointingHandCursor)
bind_tip(page_next_btn, "monitoring.page_next")
page_indicator_lbl = QLabel()
def _refresh_pager(cur: int = None, total: int = None) -> None:
if cur is None or total is None:
cur, total = table.current_page(), table.page_count()
page_indicator_lbl.setText(tr("monitoring.page_indicator", page=cur + 1, total=total))
page_prev_btn.setEnabled(cur > 0)
page_next_btn.setEnabled(cur < total - 1)
page_prev_btn.clicked.connect(table.prev_page)
page_next_btn.clicked.connect(table.next_page)
table.page_changed.connect(_refresh_pager)
_refresh_pager()
row.addWidget(page_prev_btn)
row.addWidget(page_indicator_lbl)
row.addWidget(page_next_btn)
parts.update(
page_size_label=page_size_lbl, page_size_combo=page_size_combo,
page_prev_btn=page_prev_btn, page_next_btn=page_next_btn,
page_indicator_label=page_indicator_lbl, page_pager_refresh=_refresh_pager)
lay.addLayout(row)
parts.update(filter_edit=search, ai_filter_btn=ai_btn)
@@ -25,16 +25,13 @@ class ActionLogsTab(QWidget):
parts = build_filter_scaffold(
self, self.table, on_refresh=on_refresh_all,
title_key="monitoring.action_logs_title",
with_search=True, with_detail=True, with_page_size=True,
on_ai_filter=self._start_ai_filter)
with_search=True, with_detail=True, on_ai_filter=self._start_ai_filter)
self.title_lbl = parts["title_lbl"]
self.title_key = parts["title_key"]
self.title_refresh_btn = parts["title_refresh_btn"]
self.filter_edit = parts["filter_edit"]
self.ai_filter_btn = parts["ai_filter_btn"]
self.detail_panel = parts["detail_panel"]
self.page_size_label = parts["page_size_label"]
self.page_pager_refresh = parts["page_pager_refresh"]
def set_events(self, events: List[dict]) -> None:
"""Đổ danh sách sự kiện vào bảng."""
@@ -47,8 +44,6 @@ class ActionLogsTab(QWidget):
self.detail_panel.retranslate()
self.title_lbl.setText(tr(self.title_key))
self.title_refresh_btn.setText(tr("monitoring.refresh"))
self.page_size_label.setText(tr("monitoring.page_size_label"))
self.page_pager_refresh()
def _start_ai_filter(self, search: QLineEdit, ai_btn: QPushButton) -> None:
"""Nhờ AI dịch câu tìm kiếm tự nhiên thành từ khoá lọc."""
+1 -6
View File
@@ -25,16 +25,13 @@ class McpTab(QWidget):
parts = build_filter_scaffold(
self, self.table, on_refresh=on_refresh_all,
title_key="monitoring.mcp_history_title",
with_search=True, with_detail=True, with_page_size=True,
on_ai_filter=self._start_ai_filter)
with_search=True, with_detail=True, on_ai_filter=self._start_ai_filter)
self.title_lbl = parts["title_lbl"]
self.title_key = parts["title_key"]
self.title_refresh_btn = parts["title_refresh_btn"]
self.filter_edit = parts["filter_edit"]
self.ai_filter_btn = parts["ai_filter_btn"]
self.detail_panel = parts["detail_panel"]
self.page_size_label = parts["page_size_label"]
self.page_pager_refresh = parts["page_pager_refresh"]
def set_events(self, events: List[dict]) -> None:
"""Đổ danh sách sự kiện vào bảng."""
@@ -47,8 +44,6 @@ class McpTab(QWidget):
self.detail_panel.retranslate()
self.title_lbl.setText(tr(self.title_key))
self.title_refresh_btn.setText(tr("monitoring.refresh"))
self.page_size_label.setText(tr("monitoring.page_size_label"))
self.page_pager_refresh()
def _start_ai_filter(self, search: QLineEdit, ai_btn: QPushButton) -> None:
"""Nhờ AI dịch câu tìm kiếm tự nhiên thành từ khoá lọc."""
@@ -31,16 +31,13 @@ class SecurityEventsTab(QWidget):
parts = build_filter_scaffold(
self, self.table, on_refresh=on_refresh_all,
title_key="monitoring.security_events_title",
with_search=True, with_detail=True, with_page_size=True,
on_ai_filter=self._start_ai_filter)
with_search=True, with_detail=True, on_ai_filter=self._start_ai_filter)
self.title_lbl = parts["title_lbl"]
self.title_key = parts["title_key"]
self.title_refresh_btn = parts["title_refresh_btn"]
self.filter_edit = parts["filter_edit"]
self.ai_filter_btn = parts["ai_filter_btn"]
self.detail_panel = parts["detail_panel"]
self.page_size_label = parts["page_size_label"]
self.page_pager_refresh = parts["page_pager_refresh"]
def set_events(self, events: List[dict]) -> None:
"""Đổ danh sách sự kiện vào bảng."""
@@ -53,8 +50,6 @@ class SecurityEventsTab(QWidget):
self.detail_panel.retranslate()
self.title_lbl.setText(tr(self.title_key))
self.title_refresh_btn.setText(tr("monitoring.refresh"))
self.page_size_label.setText(tr("monitoring.page_size_label"))
self.page_pager_refresh()
def _start_ai_filter(self, search: QLineEdit, ai_btn: QPushButton) -> None:
"""Nhờ AI dịch câu tìm kiếm tự nhiên thành từ khoá lọc."""
@@ -216,8 +216,7 @@ class ToolsAdminTab(QWidget):
result. Respects the fetch_url toggle: when web access is OFF the agent
cannot reach the internet, so the test reports that instead of probing."""
disabled = ("fetch_url" in self.ctx.config.tools_disabled
or not bool(self.ctx.config.agent_security.get("allow_url_fetch", True))
or bool(self.ctx.config.agent_security.get("block_network", False)))
or not bool(self.ctx.config.agent_security.get("allow_url_fetch", True)))
if disabled:
self.test_internet_status.setText(tr("tools_admin.internet_disabled"))
self.test_internet_status.setStyleSheet("color: #c00;")
@@ -12,9 +12,11 @@ from PySide6.QtWidgets import (
from ...i18n import tr
#: Các chế độ người dùng chọn được — khớp ``AppConfig.USER_ROUTING_MODES``.
#: Off/Fallback đã bỏ; giá trị cũ còn lưu được hiểu là Auto.
MODE_KEYS = (("auto", "routing.mode_auto"), ("manual", "routing.mode_manual"))
#: Các chế độ định tuyến. Danh sách này phải khớp ``config.py::AppConfig
#: .ROUTING_MODES`` — Delta thêm "fallback" ở R03-T03 và nếu quên đồng bộ
#: chỗ này thì người dùng không chọn được chế độ đó, mà không có lỗi nào báo.
MODE_KEYS = (("off", "routing.mode_off"), ("auto", "routing.mode_auto"),
("manual", "routing.mode_manual"))
POLICY_KEYS = (("quality", "routing.policy_quality"), ("cost", "routing.policy_cost"),
("latency", "routing.policy_latency"),
@@ -35,7 +37,7 @@ class RoutingSettingsWidget(QGroupBox):
self.mode = QComboBox()
for value, key in MODE_KEYS:
self.mode.addItem(tr(key), value)
_select(self.mode, routing.get("switch_mode", "auto")) # off/fallback cũ → mục đầu (Auto)
_select(self.mode, routing.get("switch_mode", "off"))
form.addRow(tr("routing.settings_mode"), self.mode)
self.policy = QComboBox()
-27
View File
@@ -1,27 +0,0 @@
"""Width of a navigation list whose current row is drawn bold.
The theme draws the selected ``sectionIndex`` row with ``font-weight: 600``
and 10px padding each side (``theme/qss.py``). Sizing the list from the plain
font left the selected label too wide for its row, so "Sandbox Security
Layer" was cut off in Settings as soon as it was picked.
"""
from __future__ import annotations
from typing import Iterable
from PySide6.QtGui import QFont, QFontMetrics
#: Item padding (10px x 2) + item radius + list frame, with a little slack.
ROW_CHROME_PX = 48
def selected_label_width(widget, labels: Iterable[str]) -> int:
"""Pixels needed to show the widest of ``labels`` in the bold selected style."""
widget.ensurePolished()
bold = QFont(widget.font())
bold.setWeight(QFont.Weight.DemiBold)
metrics = QFontMetrics(bold)
return max((metrics.horizontalAdvance(label) for label in labels), default=0) + ROW_CHROME_PX
__all__ = ["ROW_CHROME_PX", "selected_label_width"]
@@ -27,14 +27,7 @@ def _frozen_onefile() -> bool:
return True
# QtWebEngine is noisy and unreliable on the macOS runtime we support (GPU/
# helper-process failures leave the stacked view blank). The native Qt graph is
# already available and avoids that failure path entirely.
HAS_WEB_ENGINE = False
try: # WebEngine + WebChannel are optional PySide6 add-ons
if sys.platform == "darwin":
raise ImportError("use native graph renderer on macOS")
from PySide6.QtWebEngineWidgets import QWebEngineView # noqa: F401
from PySide6.QtWebChannel import QWebChannel # noqa: F401
HAS_WEB_ENGINE = not _frozen_onefile()
+2 -11
View File
@@ -42,14 +42,5 @@ def build_config(path: Path | None = None) -> JsonConfigRepository:
def build_context(path: Path | None = None) -> AppContext:
"""Dựng AppContext hoàn chỉnh — điểm vào cho ``app.run()`` và cho checker.
Nối luôn cổng mạng chung vào cấu hình SỐNG của context: đổi công tắc
"Chặn mạng" trong Settings là có hiệu lực ngay ở lời gọi mạng kế tiếp.
"""
from ...application.network import network_guard
from ...core.agent_security import sandbox_settings
ctx = AppContext(build_config(path))
network_guard.bind(lambda: sandbox_settings(ctx.config)[1])
return ctx
"""Dựng AppContext hoàn chỉnh — điểm vào cho ``app.run()`` và cho checker."""
return AppContext(build_config(path))
-171
View File
@@ -1,171 +0,0 @@
"""Ghi lại mọi lần app chết hoặc treo, và báo "Đang xử lý…" khi giao diện đứng.
Trước đây app văng ra (mã 0xC0000409) mà không để lại dấu vết gì: lỗi ở tầng
native không in traceback Python, còn cửa sổ console thì đóng ngay theo app. Mô-đun
này ghi mọi thứ vào ``~/.cowork_local/logs/``:
* ``crash.log``: stack của mọi luồng lúc tiến trình chết (``faulthandler``), kèm
exception Python không ai bắt, ở luồng chính lẫn luồng nền. Exception Python
chỉ được ghi lại, app vẫn chạy tiếp.
* ``qt.log``: cảnh báo, lỗi và lỗi nghiêm trọng của Qt (cũng vẫn in ra console).
* ``hang.log``: stack của mọi luồng mỗi khi luồng giao diện đứng quá
``HANG_SECONDS`` giây, để biết app đang kẹt ở dòng nào.
Luồng giao diện đang đứng thì không thể tự vẽ popup, nên popup "Đang xử lý…" do một
luồng canh riêng mở bằng hộp thoại gốc của Windows. Giao diện chạy lại thì hộp
thoại tự đóng.
"""
from __future__ import annotations
import datetime
import faulthandler
import sys
import threading
import time
import traceback
from pathlib import Path
from typing import Optional
from PySide6.QtCore import QTimer, QtMsgType, qInstallMessageHandler
HANG_SECONDS = 5.0 # luồng giao diện đứng quá ngần này giây thì coi là treo
_BEAT_MS = 500 # nhịp luồng giao diện báo "vẫn sống"
_crash_file = None # giữ file mở suốt đời app: faulthandler ghi vào lúc chết
_log_dir: Optional[Path] = None
def _stamp() -> str:
"""Mốc giờ hiện tại, dùng làm tiêu đề mỗi mục trong log."""
return datetime.datetime.now().isoformat(timespec="seconds")
def _append(name: str, text: str) -> None:
"""Ghi thêm vào một file log. Ghi log hỏng thì bỏ qua, không kéo app theo."""
if _log_dir is None:
return
try:
with open(_log_dir / name, "a", encoding="utf-8") as f:
f.write(text)
except OSError:
pass
def _log_exception(where: str, exc_type, exc, tb) -> None:
"""Ghi một exception không ai bắt vào crash.log và in ra console."""
body = "".join(traceback.format_exception(exc_type, exc, tb))
_append("crash.log", f"\n=== {_stamp()} exception chưa bắt ({where}) ===\n{body}")
if sys.__stderr__:
sys.__stderr__.write(body)
def _qt_message(mode, context, message) -> None:
"""Chuyển thông báo của Qt vào qt.log, vẫn in ra console như trước."""
level = {QtMsgType.QtWarningMsg: "WARNING", QtMsgType.QtCriticalMsg: "CRITICAL",
QtMsgType.QtFatalMsg: "FATAL"}.get(mode)
if sys.__stderr__:
sys.__stderr__.write(message + "\n")
if level is None:
return # debug/info: chỉ in, không ghi file
_append("qt.log", f"{_stamp()} {level}: {message}\n")
if mode == QtMsgType.QtFatalMsg and _crash_file is not None:
faulthandler.dump_traceback(_crash_file, all_threads=True)
def install(log_dir: Path) -> None:
"""Bật ghi log crash. Gọi một lần, sớm nhất có thể sau khi có QApplication."""
global _crash_file, _log_dir
log_dir.mkdir(parents=True, exist_ok=True)
_log_dir = log_dir
_crash_file = open(log_dir / "crash.log", "a", encoding="utf-8") # noqa: SIM115
_crash_file.write(f"\n=== {_stamp()} app khởi động ===\n")
_crash_file.flush()
faulthandler.enable(file=_crash_file, all_threads=True)
sys.excepthook = lambda t, e, tb: _log_exception("luồng chính", t, e, tb)
threading.excepthook = lambda a: _log_exception(
f"luồng {a.thread.name if a.thread else '?'}", a.exc_type, a.exc_value, a.exc_traceback)
qInstallMessageHandler(_qt_message)
class HangWatchdog:
"""Canh luồng giao diện: đứng quá ``HANG_SECONDS`` giây thì ghi stack vào
hang.log và mở popup "Đang xử lý…", chạy lại thì đóng popup.
Luồng giao diện đều đặn cập nhật nhịp qua một ``QTimer``; một luồng nền kiểm tra
nhịp đó. Luồng nền không đụng vào widget Qt nào.
"""
def __init__(self, title: str, parent=None) -> None:
self._title = title
self._last_beat = time.monotonic()
self._timer = QTimer(parent)
self._timer.timeout.connect(self._beat)
self._timer.start(_BEAT_MS)
self._stop = threading.Event()
self._popup: Optional[threading.Thread] = None
self._popup_title = title
threading.Thread(target=self._watch, name="hang-watchdog", daemon=True).start()
def stop(self) -> None:
"""Dừng canh (khi app thoát)."""
self._stop.set()
self._timer.stop()
def _beat(self) -> None:
self._last_beat = time.monotonic()
def _watch(self) -> None:
stalled = False
while not self._stop.wait(0.5):
lag = time.monotonic() - self._last_beat
if lag >= HANG_SECONDS and not stalled:
stalled = True
self._dump_stacks(lag)
self._show_popup()
elif lag < HANG_SECONDS and stalled:
stalled = False
self._close_popup()
def _dump_stacks(self, lag: float) -> None:
if _log_dir is None:
return
try:
with open(_log_dir / "hang.log", "a", encoding="utf-8") as f:
f.write(f"\n=== {_stamp()} giao diện đứng {lag:.1f}s ===\n")
f.flush()
faulthandler.dump_traceback(f, all_threads=True)
except OSError:
pass
def _show_popup(self) -> None:
if sys.platform != "win32":
return
import ctypes
from ...i18n import tr
# Đọc chữ NGAY LÚC hiện popup: luôn khớp ngôn ngữ đang chọn trong app,
# kể cả khi người dùng vừa đổi ngôn ngữ.
title, message = self._title, tr("app.hang.message")
# MB_ICONINFORMATION | MB_TOPMOST | MB_SETFOREGROUND. MessageBoxW có vòng
# thông điệp riêng trên luồng này, nên hiện được dù luồng giao diện đang đứng.
flags = 0x40 | 0x40000 | 0x10000
self._popup_title = title
self._popup = threading.Thread(
target=lambda: ctypes.windll.user32.MessageBoxW(None, message, title, flags),
name="hang-popup", daemon=True)
self._popup.start()
def _close_popup(self) -> None:
if self._popup is None or sys.platform != "win32":
return
import ctypes
user32 = ctypes.windll.user32
for _ in range(10): # hộp thoại có thể chưa kịp hiện ra
hwnd = user32.FindWindowW(None, self._popup_title)
if hwnd:
user32.PostMessageW(hwnd, 0x0010, 0, 0) # WM_CLOSE
break
time.sleep(0.05)
self._popup = None
+5 -7
View File
@@ -32,7 +32,9 @@ from .rail_metrics import _NAV_MIN_WIDTH
from .tray_manager import TrayManager
from ...state import AppContext
from ...core.task_scheduler import TaskScheduler
from ...ui.cowork_tab import CoworkTab
from ...ui.sidebar import HistorySidebar
from ..graph.structure_graph_view import StructureGraphView
from ...ui.workspace_tab import WorkspaceTab
@@ -109,9 +111,10 @@ class MainWindow(NavRailMixin, RailProjectMixin, TopBarMixin,
# Workspace screen (per selected project). GraphRAG's heavy
# QtWebEngine is still built lazily on first display
# (StructureGraphView._ensure_web).
from ...ui.cowork_tab import CoworkTab
self.cowork = CoworkTab(ctx)
self.structure = None
self.structure = StructureGraphView(ctx)
self.structure.status_message.connect(self.statusBar().showMessage)
self.cowork.output_changed.connect(self.structure.schedule_rescan)
self.cowork.status_message.connect(self.statusBar().showMessage)
# Refresh History (list + running markers + current highlight) whenever a
# conversation is created/updated or a turn finishes.
@@ -215,11 +218,6 @@ class MainWindow(NavRailMixin, RailProjectMixin, TopBarMixin,
self._set_nav_width_range(_NAV_MIN_WIDTH, self._nav_max_width())
# Keep the floating Help assistant pinned to the bottom-right corner.
if getattr(self, "help_agent", None) is not None:
# The Cowork composer can wrap an extra control row as the window
# narrows/widens, which changes how much bottom guard the dock
# needs — recompute it on every resize, not just reposition with
# whatever guard height was last measured at tab-entry time.
self._update_dock_guard()
self.help_agent.reposition()
def showEvent(self, event): # noqa: N802 - Qt override
+12 -10
View File
@@ -81,7 +81,7 @@ class NavRailMixin:
# 16px icon up with the nav items' icons below (1px list frame + item
# padding) — same indent level, same icon size as e.g. Dashboard.
toggle_row = QHBoxLayout()
toggle_row.setContentsMargins(10, 8, 10, 8)
toggle_row.setContentsMargins(0, 8, 10, 8)
toggle_row.addWidget(self._nav_toggle_btn, 0, Qt.AlignLeft)
toggle_row.addStretch(1)
nvl.addLayout(toggle_row)
@@ -111,7 +111,7 @@ class NavRailMixin:
self.nav_project_btn.menu().aboutToShow.connect(self._fill_rail_project_menu)
self.nav_project_btn.setVisible(False)
head = QVBoxLayout()
head.setContentsMargins(10, 0, 10, 6)
head.setContentsMargins(6, 0, 6, 6)
head.setSpacing(6)
head.addWidget(self.nav_project)
head.addWidget(self.nav_project_btn)
@@ -136,7 +136,7 @@ class NavRailMixin:
self._nav_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_body = QWidget()
sv = QVBoxLayout(scroll_body)
sv.setContentsMargins(6, 0, 6, 0)
sv.setContentsMargins(0, 0, 0, 0)
sv.setSpacing(0)
sv.addWidget(self.nav, 0)
# RECENTS — the threads of the project named in the picker above, right
@@ -197,9 +197,9 @@ class NavRailMixin:
def _nav_rows(self):
"""(tree, page, sub, label, icon, enabled) for every row, rail order.
Workspace contributes all five of its sub-views; ``_rebuild_nav`` bỏ
những hàng mà cổng project đang đóng (Cowork, GraphRAG) thay vì hiện
chúng ở dạng mờ.
Workspace contributes all five of its sub-views — including the two the
project gate currently disables — so the rail never changes shape while
the user is looking at it.
"""
rows = [(self.nav, self._ROW_WORKSPACE, sub, label, ic, on)
for label, sub, ic, on in self.workspace.nav_entries()]
@@ -238,13 +238,15 @@ class NavRailMixin:
tree.clear()
tree.blockSignals(blocked)
for tree, page, sub, label, icon_name, enabled in spec:
if not enabled:
# Cổng project đóng → bỏ hẳn hàng, không hiện dạng mờ nữa.
continue
it = QTreeWidgetItem([""] if self._nav_collapsed else [label])
it.setIcon(0, _icon(icon_name))
it.setData(0, Qt.UserRole, {"page": page, "sub": sub})
if self._nav_collapsed:
if not enabled:
# Same gate as before, shown instead of hidden: the row stays
# in place, greyed, and says why it cannot be opened.
it.setDisabled(True)
it.setToolTip(0, tr("app.nav.needs_project"))
elif self._nav_collapsed:
it.setToolTip(0, label)
blocked = tree.blockSignals(True)
tree.addTopLevelItem(it)
+2 -3
View File
@@ -142,11 +142,10 @@ class PageRegistryMixin:
Vệt sáng trên thanh menu cũng cập nhật ở đây, để nó đi theo NỘI DUNG chứ
không theo thứ vừa được bấm.
"""
was_page = self.pages.currentIndex()
self._ensure_page(page) # build lazy page on first visit
self.pages.setCurrentIndex(page)
if page == self._ROW_WORKSPACE and was_page != page:
self.workspace.refresh() # refresh only when entering Workspace
if page == self._ROW_WORKSPACE:
self.workspace.refresh() # re-list projects + threads on entry
widget = self._page_widgets[page]
if sub is not None and hasattr(widget, "select_subtab"):
# Enforce the project gate here rather than at each entry point. A
+4 -3
View File
@@ -13,14 +13,15 @@ from PySide6.QtWidgets import QStyledItemDelegate
# ---- kích thước ---------------------------------------------------------
_NAV_EXPANDED_WIDTH = 232
_NAV_COLLAPSED_WIDTH = 54
_NAV_ROW_INSET = 8
_NAV_ROW_INSET = 4
_NAV_ROW_GAP = 6
# Khe TRÊN nút Cài đặt, tính bằng khoảng trống thật trong layout của rail.
# Không đặt bằng ``margin`` trong QSS: margin của stylesheet được vẽ BÊN TRONG
# hộp của widget, mà nút này lại bị ``_rebuild_nav`` ghim đúng chiều cao một
# dòng menu — nên margin không mua được một pixel khoảng cách nào.
# Settings dùng cùng nhịp hàng với Dashboard và Monitoring.
_NAV_SETTINGS_GAP = 0
# 10 -> 4: đủ để Cài đặt không dính vào nhóm Dashboard/Giám sát, nhưng không
# rộng đến mức trông như hai khu tách rời.
_NAV_SETTINGS_GAP = 4
# 132 -> 232: o 132px nhan "Cuoc tro chuyen moi" bi cat mat chu. San phai du
# rong cho nhan DAI NHAT tren thanh, khong phai cho nhan trung binh.
_NAV_MIN_WIDTH = 232
-6
View File
@@ -42,12 +42,6 @@ class RailProjectMixin:
# No project yet: say so, and say what to do about it, instead of
# leaving an empty box and a button that silently does nothing.
self.nav_project.addItem(tr("app.nav.no_project"), "")
elif not current:
# Có project nhưng CHƯA chọn cái nào (mở app lên, hoặc vừa xoá
# project đang mở). Không có mục này thì combo rơi về mục 0 và
# chỉ bừa vào project đầu danh sách, trong khi cổng
# Cowork/GraphRAG vẫn đóng — hai chỗ nói hai đằng.
self.nav_project.insertItem(0, tr("app.nav.pick_project"), "")
idx = self.nav_project.findData(current)
if idx >= 0:
self.nav_project.setCurrentIndex(idx)
+2 -10
View File
@@ -42,14 +42,7 @@ class SessionEventsMixin:
self.sidebar.refresh()
self._refresh_rail_recents() # the rail shortcut follows the panel
# Coalesce bursts from turn/tool/history signals into one sidebar read.
timer = getattr(self, "_history_refresh_timer", None)
if timer is None:
timer = QTimer(self)
timer.setSingleShot(True)
timer.timeout.connect(_do)
self._history_refresh_timer = timer
timer.start(0)
QTimer.singleShot(0, _do)
def _on_scheduled_task_done(self, task_id: str, ok: bool) -> None:
"""Desktop notification for a finished scheduled task (toast always,
tray balloon when the window isn't focused), then refresh History —
@@ -113,5 +106,4 @@ class SessionEventsMixin:
"""Project được tạo/sửa/xoá: gom nhóm lại cột lịch sử và cập nhật nhãn thư mục."""
self.sidebar.refresh() # History regroups by project
self.cowork._apply_output_folder_label() # project may have been renamed
if getattr(self, "structure", None) is not None:
self.structure._refresh_project_combo() # GraphRAG's project lock list follows too
self.structure._refresh_project_combo() # GraphRAG's project lock list follows too
+6 -12
View File
@@ -32,10 +32,10 @@ class TopBarMixin:
``_build_account_row`` ngay bên dưới, chỉ khác chỗ đặt trên màn hình.
"""
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QStyle
from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton
from ...i18n import tr
from ...ui.icons import icon as _icon
from .rail_metrics import _NAV_ROW_INSET, _NAV_SETTINGS_GAP
from .rail_metrics import _NAV_ROW_GAP, _NAV_ROW_INSET, _NAV_SETTINGS_GAP
# Bottom-pinned group: the places you visit occasionally, kept out of the
# way of the ones you live in. A hairline (styled via #navrailBottom in
@@ -59,17 +59,11 @@ class TopBarMixin:
# that number. Adding it again here made the row taller than the button
# (28 wanted, 20 given), which both clipped the icon and pushed the text
# 8px below an even pitch with Dashboard / Giám sát.
srow.setContentsMargins(_NAV_ROW_INSET + 2, 0, 8, 0)
# Khe giữa icon và chữ phải là khe của STYLE, không phải nhịp riêng của
# rail: delegate của cây vẽ chữ ngay sau hộp icon, cách đúng
# ``PM_FocusFrameHMargin + 1``. Đặt ``_NAV_ROW_GAP + 4`` (=10) ở đây cộng
# với 10px lề trái và hộp icon 22px thành 42 — trong khi Dashboard /
# Giám sát đặt chữ ở 35, nên hàng Cài đặt thụt phải 7px.
srow.setSpacing(
self.nav_bottom.style().pixelMetric(QStyle.PM_FocusFrameHMargin) + 1)
srow.setContentsMargins(_NAV_ROW_INSET, 0, 8, 0)
srow.setSpacing(_NAV_ROW_GAP)
self._nav_settings_icon = QLabel()
self._nav_settings_icon.setPixmap(_icon("gear").pixmap(16, 16))
self._nav_settings_icon.setFixedSize(22, 16)
self._nav_settings_icon.setPixmap(_icon("settings").pixmap(16, 16))
self._nav_settings_icon.setFixedSize(16, 16)
self._nav_settings_text = QLabel(tr("app.settings"))
srow.addWidget(self._nav_settings_icon)
srow.addWidget(self._nav_settings_text)
+8 -25
View File
@@ -52,7 +52,7 @@ class ProjectRow(QWidget):
lay = QVBoxLayout(self)
lay.setContentsMargins(6, 4, 6, 4)
lay.setSpacing(3)
lay.setSpacing(0)
self.title_label = QLabel(name)
self.counts_label = QLabel()
self.counts_label.setObjectName("hint")
@@ -90,7 +90,6 @@ def _row_layout_of(widget: QWidget) -> QLayout | None:
return None
class ProjectEditingMixin:
"""Danh sách project + CRUD + chế độ sửa. Trộn vào ``WorkspaceTab``.
@@ -134,17 +133,10 @@ class ProjectEditingMixin:
# dung luat ma _new_btn da theo (_new_btn.setVisible(on_project) trong
# WorkspaceTab._apply_pane_visibility) — hai nut nay phai theo y nhu vay.
self.tabs.currentChanged.connect(self._sync_project_buttons)
# Đổi project cũng phải đồng bộ lại: ``_load_current`` nạp form và đặt
# ``_current_id`` rồi phát tín hiệu này, nhưng không đụng tới ba nút.
self.project_selected.connect(self._sync_project_buttons)
self.project_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.project_list.customContextMenuRequested.connect(self._show_project_menu)
# Luật "mỗi thư mục một project" sống ở module riêng — xem
# ``project_folder_rules.py`` về lý do nó không nằm trong file này.
self.install_project_folder_rule()
self.set_project_editable(False)
# ---- chế độ chỉ-xem / sửa -------------------------------------------
@@ -161,14 +153,15 @@ class ProjectEditingMixin:
Bật: ngược lại, và nút Lưu chuyển sang màu xác nhận (token ``success``).
"""
self._project_editable = on
has_project = bool(getattr(self, "_current_id", ""))
for field in self._editable_fields():
# setReadOnly thay vì setEnabled: ô mờ đi thì không bôi đen copy
# được nữa, mà đọc và copy chính là việc của chế độ chỉ-xem.
field.setReadOnly(not on)
# Ba nút không tự bật/tắt ở đây: ``_sync_project_buttons`` mới là nơi
# duy nhất tính trạng thái của chúng, vì nó còn chạy cả khi người dùng
# đổi project — lúc đó ``set_project_editable`` không được gọi.
self._browse_btn.setEnabled(on and has_project)
self._save_btn.setEnabled(on and has_project)
self._edit_btn.setEnabled(not on and has_project)
self._sync_project_buttons()
# Nút Lưu xanh lá khi đang sửa (hành động xác nhận), về màu nhấn mặc
@@ -178,25 +171,15 @@ class ProjectEditingMixin:
self._repolish(self._edit_btn)
def _sync_project_buttons(self, *_a) -> None:
"""Đồng bộ CẢ hiện/ẩn LẪN bật/mờ của ba nút theo trạng thái hiện tại.
"""Ẩn "Sửa project" và "Lưu project" ngoài sub-tab Project.
Ẩn ngoài sub-tab Project: chúng nằm trên hàng tiêu đề dùng chung, nên
không tự ẩn là chúng hiện cả ở Cowork — nơi không có biểu mẫu project
nào để sửa hay lưu.
Bật/mờ cũng tính ở đây chứ không ở ``set_project_editable``: đổi
project KHÔNG đi qua hàm đó (``_load_current`` chỉ nạp lại form), nên
để ở đó thì "Sửa project" giữ nguyên trạng thái tính từ lúc dựng —
lúc chưa project nào được chọn — và cứ mờ mãi dù project đã mở.
Chúng nằm trên hàng tiêu đề dùng chung, nên không tự ẩn là chúng hiện
cả ở Cowork — nơi không có biểu mẫu project nào để sửa hay lưu.
"""
on_project = self.tabs.currentIndex() == self._project_tab_idx
has_project = bool(getattr(self, "_current_id", ""))
dang_sua = bool(getattr(self, "_project_editable", False))
self._edit_btn.setVisible(on_project and has_project)
self._save_btn.setVisible(on_project and has_project)
self._edit_btn.setEnabled(not dang_sua and has_project)
self._save_btn.setEnabled(dang_sua and has_project)
self._browse_btn.setEnabled(dang_sua and has_project)
@staticmethod
def _repolish(widget: QWidget) -> None:
@@ -1,139 +0,0 @@
"""Luật "mỗi thư mục làm việc chỉ thuộc về MỘT project".
Tách khỏi ``project_editing.py`` chứ không nhét thêm vào đó: file kia đã gom
bốn tính năng và thêm luật này là chạm trần 400 dòng của
``scripts/check_loc.py``. Đây cũng là một mối quan tâm riêng — nó không nói về
việc *sửa* một project mà về việc hai project không được giẫm lên nhau.
Luật có hai nửa, cố ý không đối xứng:
* **Chặn lúc CHỌN.** Ba nơi đặt được thư mục làm việc (nút "Đổi" ở màn Project,
thư mục cloud, nút chọn thư mục trong tab Cowork) đều đi qua
:func:`folder_taken_blocked`, để cả ba chặn giống hệt nhau. Không chặn ở
"Lưu project": nút đó chỉ ghi tên/mô tả/chỉ dẫn, chặn ở đó sẽ khoá luôn việc
đổi tên một project lỡ đang trùng thư mục.
* **Cảnh báo cho cái ĐANG sai.** Dữ liệu cũ có thể đã có hai project trỏ vào
cùng một thư mục, mà nửa trên chỉ chặn từ nay trở đi. Nhãn dưới ô "Thư mục
làm việc" nói ra điều đó và để người dùng tự đổi — sửa hộ là tự ý đụng vào
dữ liệu của họ.
Phép so trùng nằm ở ``core/projects.py::folder_conflict`` (thuần, không Qt).
"""
from __future__ import annotations
from PySide6.QtWidgets import QLabel, QLayout, QMessageBox, QWidget
from ...i18n import tr
from .project_editing import _row_layout_of
def _layout_chua(layout: QLayout, con: QLayout) -> "tuple | None":
"""``(layout_cha, vị_trí)`` của ``con`` bên trong ``layout``, duyệt đệ quy."""
for i in range(layout.count()):
item = layout.itemAt(i)
ben_trong = item.layout()
if ben_trong is con:
return layout, i
if ben_trong is not None:
tim = _layout_chua(ben_trong, con)
if tim is not None:
return tim
return None
def folder_taken_blocked(parent: QWidget, path: str, ignore_id: str) -> bool:
"""``True`` nếu ``path`` đã thuộc project khác — và đã báo cho người dùng.
Dùng chung cho cả ba nơi đặt được thư mục làm việc (nút "Đổi" ở màn
Project, thư mục cloud, và nút chọn thư mục trong tab Cowork), để cả ba
chặn giống hệt nhau thay vì mỗi nơi tự nghĩ ra một luật.
Chặn ở lúc CHỌN chứ không ở lúc Lưu: "Lưu project" chỉ ghi tên, mô tả và
chỉ dẫn — chặn ở đó sẽ khoá luôn việc đổi tên một project lỡ đang trùng
thư mục, tức phạt người dùng vì một trạng thái họ chưa kịp sửa.
"""
from ...core.projects import folder_conflict
khac = folder_conflict(path, ignore_id=ignore_id)
if khac is None:
return False
QMessageBox.warning(parent, tr("workspace.folder_taken_title"),
tr("workspace.folder_taken_body", name=khac.name,
folder=str(khac.workspace_dir())))
return True
class ProjectFolderRuleMixin:
"""Nửa giao diện của luật. Trộn vào ``WorkspaceTab``."""
def install_project_folder_rule(self) -> None:
"""Dựng nhãn cảnh báo và nối nó vào việc đổi project.
Gọi từ ``install_project_editing``, tức sau khi form đã dựng xong.
"""
self._folder_warn_lbl = QLabel()
self._folder_warn_lbl.setObjectName("warning") # màu lấy từ theme/
self._folder_warn_lbl.setWordWrap(True)
self._folder_warn_lbl.hide()
self._gan_nhan_canh_bao_thu_muc()
self.project_selected.connect(self._sync_folder_warning)
def rebind_workspace_folder(self) -> None:
"""Thư mục làm việc vừa đổi — trỏ lại những màn đang bám vào nó.
Đổi thư mục KHÔNG làm project id đổi, nên không có gì trong luồng
chọn project chạy lại: ``_pick_folder`` ghi ``output_dir`` rồi dừng.
Tab Thư mục và màn GraphRAG vì thế giữ nguyên đường dẫn cũ — tên
project vẫn đúng nên nhìn qua tưởng ổn, nhưng GraphRAG quét nhầm
thư mục.
Cố ý KHÔNG gọi ``_load_current``: hàm đó nạp lại cả biểu mẫu từ đĩa,
nên gọi nó lúc người dùng đang sửa dở Tên/Mô tả là xoá mất phần chưa
lưu.
"""
from ...core.projects import load_project
pid = getattr(self, "_current_id", "")
project = load_project(pid) if pid else None
if project is None:
return
if getattr(self, "_folder", None) is not None:
self._folder.set_project_root(str(project.workspace_dir()))
if getattr(self, "_structure", None) is not None:
self._structure.set_workspace_project(pid)
# Thư mục mới có thể vừa gỡ bỏ (hoặc tạo ra) một cảnh báo dùng chung.
self._sync_folder_warning()
def _gan_nhan_canh_bao_thu_muc(self) -> None:
"""Chèn nhãn cảnh báo ngay DƯỚI hàng chứa ô Thư mục làm việc.
Chèn từ đây thay vì thêm dòng vào ``_build_project_tab``: file
``ui/workspace_tab.py`` đang vượt trần của ``scripts/check_loc.py``,
nên mọi dòng mới đều phải tránh nó (cùng lý do nút "Sửa project" được
chèn bằng ``_row_layout_of``).
"""
hang = _row_layout_of(self.folder_lbl)
cha = self.folder_lbl.parentWidget()
if hang is None or cha is None or cha.layout() is None:
return
tim = _layout_chua(cha.layout(), hang)
if tim is None:
return
layout, vi_tri = tim
layout.insertWidget(vi_tri + 1, self._folder_warn_lbl)
def _sync_folder_warning(self, *_a) -> None:
"""Hiện/ẩn cảnh báo "thư mục đang dùng chung" theo project đang mở."""
from ...core.projects import folder_conflict, load_project
pid = getattr(self, "_current_id", "")
project = load_project(pid) if pid else None
khac = (folder_conflict(project.workspace_dir(), ignore_id=pid)
if project is not None else None)
if khac is None:
self._folder_warn_lbl.hide()
return
self._folder_warn_lbl.setText(
tr("workspace.folder_shared_warning", name=khac.name))
self._folder_warn_lbl.show()
+1 -8
View File
@@ -278,17 +278,10 @@ class AnthropicProvider(Provider):
raise ProviderError(f"Anthropic: {evt.get('error', {}).get('message', 'error')}")
resp.close()
break # stream finished normally (or cancelled)
except Exception as exc: # noqa: BLE001 — lọc lại ngay bên dưới
except requests.RequestException as exc:
resp.close()
# Huỷ giữa chừng đóng socket, và urllib3 ném AttributeError
# ("'NoneType' object has no attribute 'read'") chứ KHÔNG phải
# RequestException — bắt hẹp là lỗi đó lọt ra ngoài và người dùng
# thấy một lỗi Python đỏ thay vì "đã dừng". Chỉ nuốt khi thật sự
# đang huỷ; lỗi khác vẫn ném tiếp nguyên vẹn.
if self._is_cancelled(cancel):
break
if not isinstance(exc, requests.RequestException):
raise
if text_parts or blocks:
if on_text:
on_text("\n⚠ Kết nối bị ngắt giữa chừng — hiển thị phần đã nhận được.\n")
+2 -8
View File
@@ -254,19 +254,13 @@ class OpenAICompatProvider(Provider):
slot["args"] += fn["arguments"]
resp.close()
break # stream finished normally (or cancelled)
except Exception as exc: # noqa: BLE001 — lọc lại ngay bên dưới
except requests.RequestException as exc:
resp.close()
# Huỷ giữa chừng đóng socket, và urllib3 ném AttributeError
# ("'NoneType' object has no attribute 'read'") chứ KHÔNG phải
# RequestException — bắt hẹp là lỗi đó lọt ra ngoài và người dùng
# thấy một lỗi Python đỏ thay vì "đã dừng". Chỉ nuốt khi thật sự
# đang huỷ; lỗi khác vẫn ném tiếp nguyên vẹn.
# If cancel was requested, close cleanly without retry
if cancel_event is not None and cancel_event.is_set():
break
if self._is_cancelled(cancel):
break
if not isinstance(exc, requests.RequestException):
raise
if text_parts or tool_acc:
# Partial answer already on screen — keep it, note the cut.
if on_text:
-22
View File
@@ -19,14 +19,6 @@ set "APPHOME=%LOCALAPPDATA%\CoworkLocal"
set "VENV=%APPHOME%\venv"
set "LAUNCHER=%APPHOME%\launcher"
rem An cua so console NGAY TU DAU, ke ca trong luc kiem tra ben duoi — khong
rem chi truoc luc chay app. Moi cho bao loi (echo + pause) ben duoi tu hien
rem lai cua so truoc khi in, de thong bao van doc duoc.
set "CONSOLE_VIS=%REPO%\scripts\console_visibility.ps1"
if exist "%CONSOLE_VIS%" (
powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 0 >nul 2>&1
)
rem --------------------------------------------------------------------------
rem 1. Chon trinh thong dich
rem
@@ -46,7 +38,6 @@ if exist "%VENV%\Scripts\python.exe" (
)
if not defined RUNPY (
if exist "%CONSOLE_VIS%" powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 5 >nul 2>&1
echo.
echo [LỖI] Không tìm thấy Python. Chạy install.bat trước đã.
echo.
@@ -60,7 +51,6 @@ rem biet la phai chay install.bat.
if not exist "%VENV%\Scripts\python.exe" (
!RUNPY! -c "import PySide6" >nul 2>&1
if errorlevel 1 (
if exist "%CONSOLE_VIS%" powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 5 >nul 2>&1
echo.
echo [LỖI] Thư viện chưa được cài. Chạy install.bat trước đã.
echo.
@@ -104,7 +94,6 @@ if /I "%REPO_NAME%"=="cowork_local" (
if exist "!PKGPATH!\cowork_local" rmdir "!PKGPATH!\cowork_local" >nul 2>&1
mklink /J "!PKGPATH!\cowork_local" "%REPO%" >nul 2>&1
if errorlevel 1 (
if exist "%CONSOLE_VIS%" powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 5 >nul 2>&1
echo.
echo [LOI] Khong tao duoc lien ket thu muc:
echo "!PKGPATH!\cowork_local" -> "%REPO%"
@@ -123,7 +112,6 @@ rem Chot lai: goi phai THAT SU nhin thay duoc qua duong dan vua dung. Khong co
rem buoc nay thi mot junction hong chi hien ra duoi dang loi Python kho hieu
rem ("'cowork_local' is a package and cannot be directly executed").
if not exist "!PKGPATH!\cowork_local\__main__.py" (
if exist "%CONSOLE_VIS%" powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 5 >nul 2>&1
echo.
echo [LOI] Khong tim thay cowork_local\__main__.py qua duong dan:
echo "!PKGPATH!"
@@ -150,20 +138,10 @@ if defined PYTHONPATH (
set "PYTHONIOENCODING=utf-8"
cd /d "%REPO%"
rem --------------------------------------------------------------------------
rem 4. Chay app
rem
rem App la GUI (Qt), khong can console — cua so console da bi an tu dau file
rem roi (xem khoi CONSOLE_VIS phia tren), chi hien lai NEU app thoat loi, de
rem thong bao loi ben duoi van doc duoc.
rem --------------------------------------------------------------------------
!RUNPY! -m cowork_local %*
set "RC=%ERRORLEVEL%"
if not "%RC%"=="0" (
if exist "%CONSOLE_VIS%" (
powershell -NoProfile -ExecutionPolicy Bypass -File "%CONSOLE_VIS%" -Mode 5 >nul 2>&1
)
echo.
echo Ứng dụng thoát với mã lỗi %RC%. Xem thông báo ở trên.
echo.
-22
View File
@@ -1,22 +0,0 @@
<#
.SYNOPSIS
Ẩn/hiện cửa sổ console hiện tại — dùng bởi run.bat để không hiện cửa sổ
cmd đen suốt phiên chạy app (app là GUI Qt, không cần console), nhưng vẫn
hiện lại được nếu app thoát lỗi để người dùng đọc thông báo.
.PARAMETER Mode
0 = ẩn (SW_HIDE), 5 = hiện lại (SW_SHOW).
#>
param(
[int]$Mode = 0
)
Add-Type -Name Win32 -Namespace CoworkLocalNative -MemberDefinition @"
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("kernel32.dll")] public static extern IntPtr GetConsoleWindow();
"@
$hwnd = [CoworkLocalNative.Win32]::GetConsoleWindow()
if ($hwnd -ne [IntPtr]::Zero) {
[CoworkLocalNative.Win32]::ShowWindow($hwnd, $Mode) | Out-Null
}
-32
View File
@@ -73,38 +73,6 @@ _MODERATE_PATTERNS = [
r'\b(test|pytest|jest|mocha)\b',
]
# Tools that reach the network over ICMP/raw sockets/direct DNS instead of an
# HTTP(S) connection — none of them read HTTP_PROXY/HTTPS_PROXY, so
# core/deps.py::network_blocked_env()'s proxy-env-var block (the only network
# control this sandbox actually enforces) has no effect on them at all. Used
# by command_bypasses_network_proxy() to deny these BY NAME when the user has
# "Chặn mạng cho lệnh do agent chạy" on, since the proxy trick alone silently
# lets them through (see DF-005 in Defect Management).
_NETWORK_PROXY_BYPASS_PATTERNS = [
r'\bping\b', r'\btracert\b', r'\btraceroute\b', r'\bnslookup\b', r'\bdig\b',
r'\btelnet\b', r'\bftp\b', r'\bsftp\b', r'\bscp\b', r'\bssh\b',
r'\bnc\b', r'\bncat\b', r'\bnetcat\b', r'\barp\b',
r'\btest-netconnection\b', r'\btest-connection\b', r'\bresolve-dnsname\b',
]
def command_bypasses_network_proxy(command: str) -> Optional[str]:
"""Tên công cụ mạng đầu tiên khớp trong ``command`` mà không tôn trọng
HTTP_PROXY/HTTPS_PROXY — None nếu không có công cụ nào như vậy.
``network_blocked_env()`` chỉ set biến proxy, nên chỉ chặn được các công
cụ có ĐỌC biến đó (curl/pip/requests...). ``ping`` (ICMP), ``nslookup``
(DNS trực tiếp), ``ssh``/``ftp`` (TCP thô)... đều đi qua giao thức khác,
biến proxy không có tác dụng gì với chúng — phải chặn riêng theo tên lệnh
khi ``block_network`` đang bật.
"""
cmd_lower = command.lower()
for pattern in _NETWORK_PROXY_BYPASS_PATTERNS:
m = re.search(pattern, cmd_lower, re.IGNORECASE)
if m:
return m.group()
return None
def classify_command(command: str, is_cowork_mode: bool = True) -> RiskResult:
"""Chấm điểm rủi ro một lệnh shell.
+5 -13
View File
@@ -90,7 +90,7 @@ class AppContext:
return load_project(pid)
def project_routing_mode(self, surface: str) -> str:
"""Effective Auto/Manual routing mode for a chat ``surface``
"""Effective Off/Auto/Manual/Fallback routing mode for a chat ``surface``
in the ACTIVE workspace: the workspace's own override wins; otherwise the
global default (``config.routing_mode_for``). This is what makes each
workspace keep its own routing mode.
@@ -101,15 +101,15 @@ class AppContext:
project = self._current_project()
if project is not None:
mode = (project.routing_modes or {}).get(surface, "")
if mode in self.config.ROUTING_MODES: # old off/fallback → auto
return self.config.user_routing_mode(mode)
if mode in self.config.ROUTING_MODES:
return mode
return self.config.routing_mode_for(surface)
def set_project_routing_mode(self, surface: str, mode: str) -> None:
"""Persist a surface's routing mode for the ACTIVE workspace. With no
workspace selected, falls back to the global setting so behaviour
outside a project stays global."""
mode = self.config.user_routing_mode(mode)
mode = mode if mode in self.config.ROUTING_MODES else "off"
project = self._current_project()
if project is None:
self.config.set_routing_mode_for(surface, mode)
@@ -233,20 +233,11 @@ class AppContext:
connections across calls/turns (spawning a subprocess per turn would
be slow and wasteful). A server/connector that fails to connect is
skipped, not a hard failure for the turn."""
# Sandbox Security Layer blocks agent-owned network connectors before
# they can spawn a server or issue a REST request — and stops the ones
# already running, which could otherwise keep talking to the network.
blocked = bool(self.config.agent_security.get("block_network", False))
if blocked:
self.stop_mcp_connections()
# Master switch (Monitoring → Tools → Connector): when the admin turns
# "Connect to external" off, the agent connects to NO external
# connectors/MCP at all — no subprocesses spawned, no REST calls.
if not self.config.connect_external:
return [], None
from .core.ms365_local import build_ms365_local_tools
if blocked: # the locally-synced OneDrive folders need no network
return build_ms365_local_tools(self.config)
from .core.ext_connectors import build_ext_connector_tools
from .core.mcp_client import build_mcp_tools as _merge_mcp_tools
from .core.tools import combine_tool_sources
@@ -281,6 +272,7 @@ class AppContext:
# Locally-synced OneDrive/SharePoint (no sign-in) — reads/writes the
# OneDrive-desktop-synced folders directly, gated on ms365.connectors.
from .core.ms365_local import build_ms365_local_tools
local_tools, local_executor = build_ms365_local_tools(self.config)
return combine_tool_sources((mcp_tools, mcp_executor), (ext_tools, ext_executor),
-14
View File
@@ -73,17 +73,3 @@ def _bind_checkout_as_package() -> None:
_bind_checkout_as_package()
import pytest # noqa: E402 - after the package binding above
@pytest.fixture(autouse=True)
def _reset_network_guard():
"""``build_context()`` binds the process-wide "Block network" gate to that
context's config (default: blocked). Unbind after every test so one test
that built a real context cannot silently block the network for the rest."""
yield
from cowork_local.application.network import network_guard
network_guard.bind(None)
@@ -1,95 +0,0 @@
"""Đổi tên hội thoại ở cột lịch sử thì thanh tiêu đề Cowork đổi theo ngay.
Trước đây nhãn tiêu đề giữ tên cũ cho tới khi người dùng mở lại hội thoại, và
``self.title`` cũ còn ghi đè tên mới ở lượt chat kế tiếp.
"""
from __future__ import annotations
import os
from pathlib import Path
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from cowork_local.config import AppConfig # noqa: E402
from cowork_local.presentation.chat.chat_helpers import clip_chars # noqa: E402
from cowork_local.state import AppContext # noqa: E402
pytest.importorskip("PySide6", reason="Qt is required for the integration suite")
@pytest.fixture(scope="module")
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def cowork(qt_app, tmp_path: Path):
from cowork_local.ui.cowork_tab import CoworkTab
tab = CoworkTab(AppContext(AppConfig.load(tmp_path / "config.json")))
yield tab
tab.deleteLater()
def test_clip_chars_keeps_ten_characters():
assert clip_chars("Tên ngắn") == "Tên ngắn"
assert clip_chars("0123456789") == "0123456789"
assert clip_chars("0123456789AB") == "0123456789…"
assert clip_chars("Dự án mới toanh") == "Dự án mới…" # không để khoảng trắng trước "…"
def test_rename_of_open_conversation_updates_header(cowork):
cowork.load_conversation({"session_id": "s1", "title": "Tên cũ", "messages": []})
assert cowork._title_lbl.text() == "Tên cũ"
cowork.apply_renamed_title("s1", "Tên mới")
assert cowork.title == "Tên mới" # lượt chat sau lưu bằng tên mới
assert cowork._title_lbl.text() == "Tên mới"
def test_rename_of_other_conversation_is_ignored(cowork):
cowork.load_conversation({"session_id": "s1", "title": "Đang mở", "messages": []})
cowork.apply_renamed_title("s2", "Khác")
assert cowork._title_lbl.text() == "Đang mở"
def test_long_title_is_clipped_with_full_tooltip(cowork):
long_title = "Báo cáo doanh thu quý 3"
cowork.load_conversation({"session_id": "s1", "title": "x", "messages": []})
cowork.apply_renamed_title("s1", long_title)
assert cowork._title_lbl.text() == "Báo cáo do…"
assert cowork._title_lbl.toolTip() == long_title
def test_history_list_clips_title_to_ten_chars(qt_app, tmp_path):
from PySide6.QtCore import Qt
from cowork_local.core.history import save_conversation
from cowork_local.ui.sidebar import HistorySidebar
ctx = AppContext(AppConfig.load(tmp_path / "config.json"))
ctx.config.data.setdefault("history", {})["custom_dir"] = str(tmp_path / "history")
assert ctx.config.history_dir() == tmp_path / "history" # không đọc lịch sử thật
title = "Báo cáo doanh thu quý 3"
save_conversation(tmp_path / "history", "cowork", "s1",
[{"role": "user", "content": "hi"}], title, project_id="p-test")
sb = HistorySidebar(ctx)
sb._project_filter = "p-test" # chỉ đọc history_dir() tạm, không gộp các project thật
sb.refresh()
items = []
stack = [sb.tree.topLevelItem(i) for i in range(sb.tree.topLevelItemCount())]
while stack:
it = stack.pop()
if it.data(0, Qt.UserRole):
items.append(it)
stack.extend(it.child(i) for i in range(it.childCount()))
assert len(items) == 1
assert items[0].text(0).splitlines()[0] == "Báo cáo do…"
assert items[0].toolTip(0) == title
assert items[0].data(0, Qt.UserRole + 3) == title # đổi tên vẫn điền tên đầy đủ
sb.deleteLater()
-96
View File
@@ -1,96 +0,0 @@
"""crash_guard ghi lại exception chưa bắt và phát hiện giao diện bị treo."""
from __future__ import annotations
import os
import threading
import time
import pytest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
pytest.importorskip("PySide6")
from cowork_local.presentation.shell import crash_guard # noqa: E402
@pytest.fixture
def qt_app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def guard(tmp_path, monkeypatch):
import faulthandler
import sys
from PySide6.QtCore import qInstallMessageHandler
monkeypatch.setattr(sys, "excepthook", sys.excepthook)
monkeypatch.setattr(threading, "excepthook", threading.excepthook)
crash_guard.install(tmp_path)
yield tmp_path
qInstallMessageHandler(None)
faulthandler.disable()
crash_guard._crash_file.close()
crash_guard._crash_file = None
crash_guard._log_dir = None
def test_uncaught_thread_exception_is_logged_not_fatal(guard):
def boom():
raise ValueError("lỗi luồng nền")
t = threading.Thread(target=boom, name="worker-x")
t.start()
t.join()
log = (guard / "crash.log").read_text(encoding="utf-8")
assert "ValueError: lỗi luồng nền" in log
assert "worker-x" in log
def test_watchdog_dumps_stacks_and_pops_up_while_gui_is_stalled(guard, qt_app, monkeypatch):
monkeypatch.setattr(crash_guard, "HANG_SECONDS", 0.6)
events = []
monkeypatch.setattr(crash_guard.HangWatchdog, "_show_popup", lambda self: events.append("show"))
monkeypatch.setattr(crash_guard.HangWatchdog, "_close_popup", lambda self: events.append("close"))
dog = crash_guard.HangWatchdog("t")
try:
qt_app.processEvents()
time.sleep(1.5) # luồng giao diện "đứng"
assert events == ["show"]
end = time.time() + 2
while "close" not in events and time.time() < end:
qt_app.processEvents() # giao diện chạy lại
time.sleep(0.05)
assert events == ["show", "close"]
finally:
dog.stop()
assert "giao diện đứng" in (guard / "hang.log").read_text(encoding="utf-8")
@pytest.mark.parametrize("lang, expected", [
("vi", "Đang xử lý"), ("en", "Processing"), ("ja", "処理中"),
])
def test_popup_text_follows_the_current_app_language(qt_app, monkeypatch, lang, expected):
import sys
import types
from cowork_local.i18n import get_language, set_language
shown = []
fake_user32 = types.SimpleNamespace(MessageBoxW=lambda h, msg, title, f: shown.append(msg))
monkeypatch.setattr(sys, "platform", "win32")
monkeypatch.setitem(sys.modules, "ctypes", types.SimpleNamespace(
windll=types.SimpleNamespace(user32=fake_user32)))
before = get_language()
dog = crash_guard.HangWatchdog("t")
try:
set_language(lang)
dog._show_popup()
dog._popup.join(1)
finally:
dog.stop()
set_language(before)
assert shown and expected in shown[0]
@@ -234,16 +234,16 @@ def test_mode_comes_from_the_workspace_when_not_pinned(ctx, app_service) -> None
assert outcome.switched is True
def test_removed_modes_resolve_to_auto(ctx) -> None:
"""Off/Fallback were removed from the UI: a stored value resolves to Auto."""
for legacy in ("off", "fallback"):
ctx.config.set_routing_mode_for("cowork", legacy)
assert ctx.config.routing_mode_for("cowork") == "auto"
assert ctx.project_routing_mode("cowork") == "auto"
def test_fallback_mode_survives_a_round_trip_through_config(ctx) -> None:
"""The new mode must be persistable, or the toggle could never select it."""
ctx.config.set_routing_mode_for("cowork", "fallback")
assert ctx.config.routing_mode_for("cowork") == "fallback"
assert ctx.project_routing_mode("cowork") == "fallback"
def test_unknown_persisted_mode_degrades_to_auto(ctx) -> None:
"""A hand-edited config resolves to the default mode (Auto)."""
def test_unknown_persisted_mode_degrades_to_off(ctx) -> None:
"""A hand-edited config must not enable routing by accident."""
ctx.config.routing["surface_modes"]["cowork"] = "turbo"
assert ctx.config.routing_mode_for("cowork") == "auto"
assert ctx.config.routing_mode_for("cowork") == "off"
+9 -26
View File
@@ -32,29 +32,16 @@ def _mk(ctx, name):
def test_defaults_follow_global_when_no_override(ctx):
a = _mk(ctx, "Alpha")
ctx.active_project_id = a.project_id
# Global default switch_mode is "auto" (Off was removed).
assert ctx.project_routing_mode("cowork") == "auto"
# Global default switch_mode is "off".
assert ctx.project_routing_mode("cowork") == "off"
# Change the GLOBAL default → project with no override follows it.
ctx.config.data["routing"]["switch_mode"] = "manual"
assert ctx.project_routing_mode("cowork") == "manual"
def test_legacy_off_and_fallback_resolve_to_auto(ctx):
a = _mk(ctx, "Alpha")
ctx.active_project_id = a.project_id
ctx.config.data["routing"]["switch_mode"] = "manual"
for legacy in ("off", "fallback"):
a.routing_modes = {"cowork": legacy}
save_project(a)
assert ctx.project_routing_mode("cowork") == "auto"
ctx.set_project_routing_mode("cowork", "off")
ctx.config.data["routing"]["switch_mode"] = "auto"
assert ctx.project_routing_mode("cowork") == "auto"
def test_per_workspace_routing_is_isolated(ctx):
a = _mk(ctx, "Alpha")
b = _mk(ctx, "Beta")
ctx.config.data["routing"]["switch_mode"] = "manual"
ctx.active_project_id = a.project_id
ctx.set_project_routing_mode("cowork", "auto")
@@ -62,19 +49,16 @@ def test_per_workspace_routing_is_isolated(ctx):
# Switching to workspace B must NOT see A's override (falls back to global).
ctx.active_project_id = b.project_id
assert ctx.project_routing_mode("cowork") == "manual"
assert ctx.project_routing_mode("cowork") == "off"
# B sets its own, independently.
ctx.set_project_routing_mode("cowork", "auto")
ctx.active_project_id = a.project_id
ctx.set_project_routing_mode("cowork", "manual")
ctx.active_project_id = b.project_id
assert ctx.project_routing_mode("cowork") == "auto"
# A keeps its own.
ctx.active_project_id = a.project_id
assert ctx.project_routing_mode("cowork") == "manual"
# A is unchanged.
ctx.active_project_id = a.project_id
assert ctx.project_routing_mode("cowork") == "auto"
def test_per_surface_isolated_within_a_workspace(ctx):
a = _mk(ctx, "Alpha")
@@ -84,8 +68,7 @@ def test_per_surface_isolated_within_a_workspace(ctx):
# co4e untouched → global default.
assert ctx.project_routing_mode("cowork") == "auto"
assert ctx.project_routing_mode("ai_edit") == "manual"
ctx.config.data["routing"]["switch_mode"] = "manual"
assert ctx.project_routing_mode("co4e") == "manual"
assert ctx.project_routing_mode("co4e") == "off"
def test_routing_mode_persists_to_disk(ctx):
+6 -15
View File
@@ -88,21 +88,12 @@ def test_best_for_returns_strong(service):
assert ranking.best.assessment.metadata.model_id == "strong-model"
def test_route_off_explicit_override_never_switches(service):
# "off" is no longer user-selectable, but the engine still honours it
# when passed explicitly.
service.reassess()
r = service.route("cowork", "Write a Python function", "anthropic", "weak-model",
mode_override="off")
assert r.mode == SwitchMode.OFF
assert r.should_switch is False
def test_legacy_off_in_config_routes_as_auto(service):
def test_route_off_never_switches(service):
service.reassess()
service.ctx.config.data["routing"]["switch_mode"] = "off"
r = service.route("cowork", "Write a Python function", "anthropic", "weak-model")
assert r.mode == SwitchMode.AUTO
assert r.mode == SwitchMode.OFF
assert r.should_switch is False
def test_route_auto_switches_to_strong(service):
@@ -156,12 +147,12 @@ def test_route_never_raises_on_broken_store(ctx, tmp_path):
def test_per_surface_mode_override(service):
service.reassess()
service.ctx.config.data["routing"]["switch_mode"] = "manual"
service.ctx.config.data["routing"]["switch_mode"] = "off"
service.ctx.config.data["routing"]["surface_modes"]["co4e"] = "auto"
# cowork follows global (manual); co4e overridden to auto
# cowork follows global (off); co4e overridden to auto
r_cowork = service.route("cowork", "Write a Python function", "anthropic", "weak-model")
r_co4e = service.route("co4e", "Write a Python function", "anthropic", "weak-model")
assert r_cowork.mode == SwitchMode.MANUAL
assert r_cowork.mode == SwitchMode.OFF
assert r_co4e.mode == SwitchMode.AUTO
assert r_co4e.should_switch is True
-68
View File
@@ -1,68 +0,0 @@
"""DF-008 — presentation/folder/ai_file_editor_dialog.py::_AutoExpandInput.
The AI-edit instruction box was a fixed-height single-line QLineEdit (read as
cramped); it is now a QPlainTextEdit that grows with content, submits on
Enter, and inserts a newline on Shift+Enter — same convention as the Cowork
composer's input (presentation/chat/chat_input_box.py::_Input)."""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
QApplication = pytest.importorskip("PySide6.QtWidgets").QApplication
from PySide6.QtCore import Qt
from PySide6.QtGui import QKeyEvent
from PySide6.QtCore import QEvent
from cowork_local.presentation.folder.ai_file_editor_dialog import _AutoExpandInput
@pytest.fixture(scope="module")
def qapp():
app = QApplication.instance() or QApplication([])
yield app
def _press_enter(widget, shift: bool = False) -> None:
mods = Qt.ShiftModifier if shift else Qt.NoModifier
event = QKeyEvent(QEvent.KeyPress, Qt.Key_Return, mods)
widget.keyPressEvent(event)
def test_starts_at_min_height(qapp) -> None:
box = _AutoExpandInput()
assert box.height() == _AutoExpandInput.MIN_HEIGHT
def test_grows_with_multiline_content(qapp) -> None:
box = _AutoExpandInput()
start_height = box.height()
box.setPlainText("\n".join(f"line {i}" for i in range(10)))
assert box.height() > start_height
assert box.height() <= _AutoExpandInput.MAX_HEIGHT
def test_enter_emits_submit_and_does_not_insert_newline(qapp) -> None:
box = _AutoExpandInput()
box.setPlainText("hello")
received = []
box.submit.connect(lambda: received.append(True))
_press_enter(box)
assert received == [True]
assert box.toPlainText() == "hello" # Enter did not add a newline
def test_shift_enter_inserts_newline_without_submitting(qapp) -> None:
box = _AutoExpandInput()
box.setPlainText("hello")
cursor = box.textCursor()
cursor.movePosition(cursor.MoveOperation.End)
box.setTextCursor(cursor)
received = []
box.submit.connect(lambda: received.append(True))
_press_enter(box, shift=True)
assert received == []
assert box.toPlainText() == "hello\n"
-132
View File
@@ -1,132 +0,0 @@
"""DF-007 — core/cloud_workspace_sync.py: mirror a cloud folder to/from a
local directory. All Graph calls are faked (monkeypatch on the ``graph``
module the sync module imports) — no network."""
from __future__ import annotations
from pathlib import Path
import pytest
from cowork_local.core import cloud_workspace_sync as sync
from cowork_local.core import ms365_graph as graph
def _fake_tree():
"""root/
a.txt
sub/
b.txt
"""
files = {"a.txt": b"hello", "sub/b.txt": b"world"}
listing = {
"": [{"name": "a.txt"}, {"name": "sub", "folder": {}}],
"sub": [{"name": "b.txt"}],
}
return files, listing
def test_download_folder_mirrors_tree(tmp_path: Path, monkeypatch) -> None:
files, listing = _fake_tree()
def fake_list_onedrive_files(token, path=""):
return listing.get(path, [])
def fake_download_bytes(token, path):
return files[path]
monkeypatch.setattr(graph, "list_onedrive_files", fake_list_onedrive_files)
monkeypatch.setattr(graph, "download_onedrive_file_bytes", fake_download_bytes)
local_dir = tmp_path / "mirror"
report = sync.download_folder("tok", {"provider": "onedrive", "remote_path": ""}, local_dir)
assert report.transferred == 2
assert report.errors == []
assert (local_dir / "a.txt").read_bytes() == b"hello"
assert (local_dir / "sub" / "b.txt").read_bytes() == b"world"
def test_download_folder_collects_errors_without_raising(tmp_path: Path, monkeypatch) -> None:
def fake_list_onedrive_files(token, path=""):
raise graph.Ms365GraphError("boom")
monkeypatch.setattr(graph, "list_onedrive_files", fake_list_onedrive_files)
local_dir = tmp_path / "mirror"
report = sync.download_folder("tok", {"provider": "onedrive", "remote_path": ""}, local_dir)
assert report.transferred == 0
assert len(report.errors) == 1
assert "boom" in report.errors[0]
def test_upload_folder_pushes_every_file(tmp_path: Path, monkeypatch) -> None:
local_dir = tmp_path / "mirror"
(local_dir / "sub").mkdir(parents=True)
(local_dir / "a.txt").write_bytes(b"hello")
(local_dir / "sub" / "b.txt").write_bytes(b"world")
uploaded = {}
def fake_upload_bytes(token, path, data):
uploaded[path] = data
return {}
monkeypatch.setattr(graph, "upload_onedrive_file_bytes", fake_upload_bytes)
report = sync.upload_folder("tok", {"provider": "onedrive", "remote_path": "work"}, local_dir)
assert report.transferred == 2
assert uploaded == {"work/a.txt": b"hello", "work/sub/b.txt": b"world"}
def test_upload_folder_reports_files_over_the_simple_upload_limit(tmp_path: Path, monkeypatch) -> None:
local_dir = tmp_path / "mirror"
local_dir.mkdir()
(local_dir / "big.bin").write_bytes(b"x")
def fake_upload_bytes(token, path, data):
raise graph.Ms365GraphError("File too large for simple upload (huge > 4 bytes)")
monkeypatch.setattr(graph, "upload_onedrive_file_bytes", fake_upload_bytes)
report = sync.upload_folder("tok", {"provider": "onedrive", "remote_path": ""}, local_dir)
assert report.transferred == 0
assert report.skipped_too_large == ["big.bin"]
assert report.errors == []
def test_upload_size_guard_rejects_before_any_request(monkeypatch) -> None:
huge = b"x" * (graph.MAX_SIMPLE_UPLOAD_BYTES + 1)
def fail_if_called(*a, **k): # pragma: no cover - must not be reached
raise AssertionError("_request should not be called for an oversized upload")
monkeypatch.setattr(graph, "_request", fail_if_called)
with pytest.raises(graph.Ms365GraphError, match="too large"):
graph.upload_onedrive_file_bytes("tok", "a.bin", huge)
def test_sharepoint_provider_uses_site_scoped_calls(tmp_path: Path, monkeypatch) -> None:
seen = {}
def fake_list_sharepoint_files(token, site_id, path=""):
seen["list_site_id"] = site_id
return [{"name": "a.txt"}] if path == "" else []
def fake_download_sharepoint_bytes(token, site_id, path):
seen["download_site_id"] = site_id
return b"hi"
monkeypatch.setattr(graph, "list_sharepoint_files", fake_list_sharepoint_files)
monkeypatch.setattr(graph, "download_sharepoint_file_bytes", fake_download_sharepoint_bytes)
local_dir = tmp_path / "mirror"
cloud_source = {"provider": "sharepoint", "site_id": "site-123", "remote_path": ""}
report = sync.download_folder("tok", cloud_source, local_dir)
assert report.transferred == 1
assert seen["list_site_id"] == "site-123"
assert seen["download_site_id"] == "site-123"
-55
View File
@@ -1,55 +0,0 @@
"""DF-002 (phần b) — node đang chạy HOẶC đã chạy xong không cho edit thông
tin trong Node. Trước khi sửa, ``_LOCKED_NODE_STATUSES`` khoá cả STEP_RUNNING
lẫn STEP_DONE, nên một bước đã chạy xong không bao giờ sửa lại được nữa.
Fix: chỉ khoá khi bước ĐANG chạy (STEP_RUNNING) — chạy xong rồi thì mở khoá
trở lại. Test này chốt cả nguồn sự thật (tuple
``co4e_workflow_crud._LOCKED_NODE_STATUSES``) lẫn hành vi ở widget
(``StepConfigPanel.set_locked``), để không bị hồi quy về hành vi cũ.
"""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
QApplication = pytest.importorskip("PySide6.QtWidgets").QApplication
from cowork_local.core.co4e import (
STEP_DONE, STEP_ERROR, STEP_IDLE, STEP_PLANNED, STEP_RUNNING,
)
from cowork_local.presentation.co4e.co4e_workflow_crud import _LOCKED_NODE_STATUSES
from cowork_local.presentation.co4e.node_property_panel import StepConfigPanel
@pytest.fixture(scope="module")
def qapp():
app = QApplication.instance() or QApplication([])
yield app
def test_only_running_status_is_locked() -> None:
"""Một bước đã chạy xong (STEP_DONE) phải sửa lại được — chỉ bước đang
thực sự chạy (STEP_RUNNING) mới bị khoá."""
assert _LOCKED_NODE_STATUSES == (STEP_RUNNING,)
assert STEP_DONE not in _LOCKED_NODE_STATUSES
assert STEP_IDLE not in _LOCKED_NODE_STATUSES
assert STEP_ERROR not in _LOCKED_NODE_STATUSES
assert STEP_PLANNED not in _LOCKED_NODE_STATUSES
def test_set_locked_disables_then_reenables_edit_fields(qapp) -> None:
panel = StepConfigPanel()
panel.setEnabled(True) # panel starts disabled until a step is loaded
panel.set_locked(True)
assert not panel.label_edit.isEnabled()
assert not panel.instructions_edit.isEnabled()
assert not panel.model_combo.isEnabled()
panel.set_locked(False)
assert panel.label_edit.isEnabled()
assert panel.instructions_edit.isEnabled()
assert panel.model_combo.isEnabled()
-140
View File
@@ -1,140 +0,0 @@
"""DF-006 — the "Số dòng/trang" (rows per page) control plus real prev/next
pagination: EventTable's page-size/page-index state
(presentation/monitoring/shared/event_table.py) and its QComboBox + pager
button wiring in build_filter_scaffold (.../shared/filter_scaffold.py).
Options are 5/10/20/50/100 with a next/prev pager, per the QA follow-up on
DF-006 — the earlier fix only trimmed to a page size (dropping every row past
it with no way back); this exercises the real paging end to end."""
from __future__ import annotations
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
QApplication = pytest.importorskip("PySide6.QtWidgets").QApplication
QWidget = pytest.importorskip("PySide6.QtWidgets").QWidget
from cowork_local.presentation.monitoring.shared.event_table import (
PAGE_SIZE_OPTIONS, EventTable,
)
from cowork_local.presentation.monitoring.shared.filter_scaffold import build_filter_scaffold
@pytest.fixture(scope="module")
def qapp():
app = QApplication.instance() or QApplication([])
yield app
def _events(n: int):
return [{"ts": f"2026-09-0{i % 9 + 1}T00:00:0{i % 9}", "kind": "tool_call",
"name": f"e{i}", "ok": True, "detail": ""} for i in range(n)]
def test_page_size_options_are_5_10_20_50_100() -> None:
assert PAGE_SIZE_OPTIONS == (5, 10, 20, 50, 100)
def test_default_page_size(qapp) -> None:
table = EventTable()
assert table.page_size() == 20
table.set_events(_events(45))
assert table.rowCount() == 20
assert table.page_count() == 3
assert table.current_page() == 0
def test_set_page_size_resets_to_first_page(qapp) -> None:
table = EventTable()
table.set_events(_events(45))
table.next_page()
assert table.current_page() == 1
table.set_page_size(50)
assert table.page_size() == 50
assert table.current_page() == 0
assert table.rowCount() == 45 # only 45 events total, fits in one page of 50
def test_next_prev_page_navigate_without_dropping_rows(qapp) -> None:
table = EventTable()
table.set_events(_events(45))
table.set_page_size(20)
assert table.rowCount() == 20
table.next_page()
assert table.current_page() == 1
assert table.rowCount() == 20
table.next_page()
assert table.current_page() == 2
assert table.rowCount() == 5 # last page: remainder
table.next_page() # already on last page — stays put
assert table.current_page() == 2
table.prev_page()
assert table.current_page() == 1
table.prev_page()
table.prev_page() # already on first page — stays put
assert table.current_page() == 0
def test_page_changed_signal_reports_current_and_total(qapp) -> None:
table = EventTable()
seen = []
table.page_changed.connect(lambda cur, total: seen.append((cur, total)))
table.set_events(_events(45))
table.set_page_size(20)
table.next_page()
assert seen[-1] == (1, 3)
def test_page_size_combo_is_only_added_when_requested(qapp) -> None:
page = QWidget()
table = EventTable()
parts = build_filter_scaffold(page, table, on_refresh=lambda: None, with_page_size=False)
assert "page_size_combo" not in parts
assert "page_prev_btn" not in parts
def test_page_size_combo_changes_the_table(qapp) -> None:
page = QWidget()
table = EventTable()
table.set_events(_events(45))
parts = build_filter_scaffold(page, table, on_refresh=lambda: None, with_page_size=True)
combo = parts["page_size_combo"]
assert combo.count() == len(PAGE_SIZE_OPTIONS)
assert combo.currentData() == 20 # matches EventTable's current page_size
idx = PAGE_SIZE_OPTIONS.index(10)
combo.setCurrentIndex(idx)
assert table.page_size() == 10
assert table.rowCount() == 10
def test_pager_buttons_disable_at_bounds_and_indicator_updates(qapp) -> None:
page = QWidget()
table = EventTable()
table.set_events(_events(45))
parts = build_filter_scaffold(page, table, on_refresh=lambda: None, with_page_size=True)
table.set_page_size(20)
prev_btn, next_btn = parts["page_prev_btn"], parts["page_next_btn"]
indicator = parts["page_indicator_label"]
assert not prev_btn.isEnabled()
assert next_btn.isEnabled()
assert indicator.text() == "Trang 1/3"
next_btn.click()
assert prev_btn.isEnabled()
assert next_btn.isEnabled()
assert indicator.text() == "Trang 2/3"
next_btn.click()
assert prev_btn.isEnabled()
assert not next_btn.isEnabled()
assert indicator.text() == "Trang 3/3"
-77
View File
@@ -1,77 +0,0 @@
"""DF-007 — construction smoke tests for the two new MS365 cloud dialogs.
Not a full characterization suite (see tests/test_monitoring_tab_container.py
for the convention this follows) — just proves each dialog builds against a
real AppConfig/AppContext without touching the network (Graph calls faked via
monkeypatch)."""
from __future__ import annotations
import copy
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
QApplication = pytest.importorskip("PySide6.QtWidgets").QApplication
QDialog = pytest.importorskip("PySide6.QtWidgets").QDialog
from cowork_local.config import AppConfig, DEFAULT_CONFIG
from cowork_local.core import ms365_auth
from cowork_local.core import ms365_graph as graph
from cowork_local.ui.cloud_folder_picker_dialog import CloudFolderPickerDialog
from cowork_local.ui.ms365_signin_dialog import Ms365SignInDialog, ensure_signed_in
@pytest.fixture(scope="module")
def qapp():
app = QApplication.instance() or QApplication([])
yield app
@pytest.fixture()
def config(tmp_path):
return AppConfig(data=copy.deepcopy(DEFAULT_CONFIG), path=tmp_path / "config.json")
def test_signin_dialog_constructs(qapp, config) -> None:
dialog = Ms365SignInDialog(config)
assert dialog.windowTitle()
def test_ensure_signed_in_short_circuits_when_already_signed_in(qapp, config, monkeypatch) -> None:
monkeypatch.setattr(ms365_auth, "is_signed_in", lambda cfg: True)
assert ensure_signed_in(None, config) is True
def test_cloud_folder_picker_constructs_and_lists_onedrive_root(qapp, config, monkeypatch) -> None:
monkeypatch.setattr(ms365_auth, "get_access_token", lambda tenant_id, client_id: "fake-token")
monkeypatch.setattr(graph, "list_onedrive_files", lambda token, path="": [
{"name": "Documents", "folder": {}},
{"name": "readme.txt"},
])
dialog = CloudFolderPickerDialog(config)
assert dialog._tree.topLevelItemCount() == 2
source = dialog.cloud_source()
assert source == {"provider": "onedrive", "site_id": "", "site_name": "", "remote_path": ""}
def test_cloud_folder_picker_navigates_into_a_folder(qapp, config, monkeypatch) -> None:
monkeypatch.setattr(ms365_auth, "get_access_token", lambda tenant_id, client_id: "fake-token")
def fake_list(token, path=""):
if path == "":
return [{"name": "Documents", "folder": {}}]
if path == "Documents":
return [{"name": "report.docx"}]
return []
monkeypatch.setattr(graph, "list_onedrive_files", fake_list)
dialog = CloudFolderPickerDialog(config)
folder_item = dialog._tree.topLevelItem(0)
dialog._on_item_activated(folder_item, 0)
assert dialog._current_remote_path() == "Documents"
assert dialog.cloud_source()["remote_path"] == "Documents"
-389
View File
@@ -1,389 +0,0 @@
"""Công tắc "Chặn mạng" phải chặn mọi đường ra mạng của app, TRỪ nhà cung cấp AI.
Bản đồ ``infura/network-map.html`` liệt kê các làn trước đây "không kiểm soát"
hoặc chỉ chặn một phần: M365, Teams và nút Test, connector/MCP đang chạy,
task script và link đính kèm task, tự cài thư viện, xem trước HTML, lệnh shell
chỉ bị proxy giả. Mỗi làn có ít nhất một bài ở đây:
* **bật** — làn từ chối TRƯỚC khi chạm mạng (mọi lời gọi HTTP thật đều nổ);
* **tắt** — đường cũ giữ nguyên, vì chặn một chiều là hỏng tính năng.
"""
from __future__ import annotations
import socket
import sys
import threading
from pathlib import Path
import pytest
from cowork_local.application.network import network_guard
def _no_network(*args, **kwargs):
raise AssertionError("đã chạm mạng dù 'Chặn mạng' đang bật")
@pytest.fixture
def chan_mang(monkeypatch):
"""Bật công tắc qua cổng chung và làm nổ mọi lời gọi HTTP thật."""
import requests
from cowork_local.core import tls_trust
for name in ("request", "get", "post", "put", "patch", "delete"):
monkeypatch.setattr(requests, name, _no_network)
monkeypatch.setattr(tls_trust, "request", _no_network)
monkeypatch.setattr(tls_trust, "request_any_method", _no_network)
network_guard.bind(lambda: True)
yield
network_guard.bind(None)
@pytest.fixture(autouse=True)
def _go_cong_sau_moi_bai():
yield
network_guard.bind(None)
# ---- cổng chung ------------------------------------------------------------
def test_chua_noi_day_thi_khong_chan():
network_guard.bind(None)
assert network_guard.is_blocked() is False
network_guard.ensure_allowed("x")
def test_doc_cong_tac_loi_thi_coi_nhu_dang_chan():
"""Không đọc được công tắc thì đóng cửa, không mở toang."""
def hong():
raise KeyError("agent_security")
network_guard.bind(hong)
with pytest.raises(network_guard.NetworkBlockedError):
network_guard.ensure_allowed("Teams")
def test_cong_doc_cau_hinh_song_khong_chup_lai(tmp_path):
"""Đổi công tắc trong Settings có hiệu lực ngay, không cần mở lại app."""
from cowork_local.presentation.shell.bootstrap import build_context
ctx = build_context(tmp_path / "config.json")
ctx.config.agent_security["block_network"] = True
assert network_guard.is_blocked() is True
ctx.config.agent_security["block_network"] = False
assert network_guard.is_blocked() is False
# ---- Microsoft 365 -----------------------------------------------------------
def test_graph_tu_choi_bang_loi_ma_noi_goi_da_bat(chan_mang):
from cowork_local.core import ms365_graph
with pytest.raises(ms365_graph.Ms365GraphError, match="Sandbox Security Layer"):
ms365_graph.list_onedrive_files("token")
def test_dang_nhap_va_lay_token_tu_choi(chan_mang, monkeypatch):
from cowork_local.core import ms365_auth
monkeypatch.setattr(ms365_auth, "_app", _no_network)
with pytest.raises(ms365_auth.Ms365AuthError, match="blocked"):
ms365_auth.get_access_token("", "")
with pytest.raises(ms365_auth.Ms365AuthError, match="blocked"):
ms365_auth.sign_in_device_code("", "", lambda flow: None)
def test_kiem_tra_da_dang_nhap_khong_dung_msal_khi_chan(chan_mang, monkeypatch):
"""Dựng app MSAL là tải cấu hình OpenID của tenant — phải đọc kho token trực tiếp."""
from cowork_local.core import ms365_auth
monkeypatch.setattr(ms365_auth, "_app", _no_network)
monkeypatch.setattr(ms365_auth, "_cached_account_offline",
lambda: {"username": "a@b.c"})
assert ms365_auth.signed_in_account("", "") == {"username": "a@b.c"}
def test_mail_canh_bao_khong_gui_khi_chan(chan_mang, monkeypatch):
from types import SimpleNamespace
from cowork_local.core import agent_security_alert, ms365_auth
from cowork_local.core.agent_security_types import SecurityVerdict
monkeypatch.setattr(ms365_auth, "_app", _no_network)
config = SimpleNamespace(data={"agent_security": {"admin_email": "admin@x.y"}}, ms365={})
verdict = SecurityVerdict(allowed=False, layer="command", reason="test")
sent, note = agent_security_alert.notify_admin(config, verdict)
assert sent is False
assert "blocked" in note
# ---- Teams, connector REST, Jira, nút Test ---------------------------------
def test_teams_tu_choi(chan_mang):
from cowork_local.core.teams import TeamsNotifier
ok, detail = TeamsNotifier("https://x.webhook.office.com/hook").send("t", "b")
assert ok is False
assert "blocked" in detail
def test_connector_rest_va_nut_test_tu_choi(chan_mang):
from cowork_local.core.ext_connectors import RestApiConnector
rc = RestApiConnector({"id": "erp", "name": "ERP", "base_url": "https://erp.example"})
assert rc.call({"method": "GET", "path": "items"})["ok"] is False
ok, message = rc.test_connection()
assert ok is False and "blocked" in message
def test_nut_test_jira_tu_choi(chan_mang):
from cowork_local.core import jira_tool
cfg = {"base_url": "https://jira.example", "email": "a@b.c", "api_token": "t"}
out = jira_tool.search(cfg, "order by created DESC", 1)
assert out.startswith("Jira search failed") and "blocked" in out
# ---- MCP -------------------------------------------------------------------
def test_mcp_khong_khoi_dong_va_khong_goi_khi_chan(chan_mang):
from cowork_local.core.mcp_client import McpServerConnection, McpServerError
conn = McpServerConnection("srv", "definitely-not-run")
with pytest.raises(McpServerError, match="blocked"):
conn.start(timeout=1)
assert conn.call_tool("srv__search", {})["ok"] is False
def _context(tmp_path, block: bool):
from cowork_local.config import AppConfig
from cowork_local.state import AppContext
ctx = AppContext(AppConfig.load(tmp_path / "config.json"))
ctx.config.agent_security["block_network"] = block
return ctx
def test_chuan_bi_connector_dung_mcp_dang_chay_va_giu_onedrive_cuc_bo(tmp_path, monkeypatch):
from cowork_local.core import ms365_local
ctx = _context(tmp_path, block=True)
stopped = []
monkeypatch.setattr(ctx, "stop_mcp_connections", lambda: stopped.append(True))
local = (["ms365_local__onedrive_list"], object())
monkeypatch.setattr(ms365_local, "build_ms365_local_tools", lambda config: local)
monkeypatch.setattr(ctx._mcp_manager, "ensure", _no_network)
assert ctx.build_mcp_tools() == local
assert stopped == [True]
# ---- task lập lịch -----------------------------------------------------------
def test_link_dinh_kem_task_khong_tai(chan_mang):
from cowork_local.core.tasks import resolve_input_text
text = resolve_input_text({"input": {"mode": "empty", "links": ["https://example.com/a"]}})
assert "not fetched" in text
def test_task_script_chay_trong_tien_trinh_khong_mang(chan_mang, monkeypatch, tmp_path):
from cowork_local.core import deps, task_script
calls = []
def fake_run(command, **kwargs):
calls.append(kwargs)
return 0, "done", False, False, False
monkeypatch.setattr(deps, "run_cancellable", fake_run)
assert task_script.run_script("echo hi", tmp_path, 30) == "done"
assert calls and calls[0]["isolate_network"] is True
def test_task_script_khong_co_lap_duoc_thi_khong_chay(chan_mang, monkeypatch, tmp_path):
from cowork_local.core import deps, task_script
monkeypatch.setattr(deps, "run_cancellable",
lambda command, **kw: (None, "no AppContainer", False, False, False))
with pytest.raises(RuntimeError, match="could not be isolated"):
task_script.run_script("echo hi", tmp_path, 30)
def test_tat_chan_mang_thi_task_script_chay_nhu_cu(tmp_path):
from cowork_local.core import task_script
assert "hi" in task_script.run_script("echo hi", tmp_path, 30)
# ---- tự cài thư viện ---------------------------------------------------------
def test_khong_tu_cai_thu_vien_khi_chan(chan_mang, monkeypatch):
from cowork_local.core import deps
monkeypatch.setattr(deps, "run_cancellable", _no_network)
assert deps.ensure_module("khong_ton_tai_xyz_123") is None
assert "khong_ton_tai_xyz_123" not in deps._FAILED # thử lại khi mở mạng
ok, detail = deps.pip_install("requests")
assert ok is False and "blocked" in detail
def test_pptx_khong_bi_nho_la_thieu_khi_chi_do_chan_mang(chan_mang, monkeypatch):
from cowork_local.application.workspaces import file_preview_helpers as fph
from cowork_local.core import deps
monkeypatch.setattr(fph, "_PPTX_READY", None)
monkeypatch.setattr(deps, "ensure_module", lambda *a, **k: None)
assert fph.pptx_available() is False
assert fph._PPTX_READY is None
# ---- lệnh shell của agent ----------------------------------------------------
@pytest.mark.parametrize("backend", ["direct", "integrity_job_wfp", "appcontainer", "windows_sandbox"])
def test_moi_backend_deu_chay_co_lap_mang(monkeypatch, tmp_path, backend):
"""Các backend cũ chỉ đặt biến proxy — khi chặn mạng, tất cả đi qua lớp cô lập của OS."""
from cowork_local.core import deps
from cowork_local.core.sandbox_manager import SandboxManager
calls = []
def fake_run(command, **kwargs):
calls.append(kwargs)
return 0, "ok", False, False, False
monkeypatch.setattr(deps, "run_cancellable", fake_run)
result = SandboxManager()._execute_with_backend(backend, "echo hi", str(tmp_path), True, 30)
assert calls and calls[0]["isolate_network"] is True
assert result["ok"] is True and result["sandbox"] == "network_isolated"
def test_lenh_khong_co_lap_duoc_thi_bi_tu_choi(monkeypatch, tmp_path):
from cowork_local.core import deps
from cowork_local.core.sandbox_manager import SandboxManager
monkeypatch.setattr(deps, "run_cancellable",
lambda command, **kw: (None, "no isolation", False, False, False))
result = SandboxManager()._execute_with_backend("direct", "echo hi", str(tmp_path), True, 30)
assert result["ok"] is False and result["sandbox"] == "blocked"
def test_he_dieu_hanh_khong_ho_tro_thi_bao_loi_khong_chay(monkeypatch):
from cowork_local.infrastructure.sandbox import network_isolation
monkeypatch.setattr(network_isolation.sys, "platform", "sunos5")
with pytest.raises(network_isolation.NetworkIsolationUnavailable):
network_isolation.spawn_without_network("echo hi", None, None)
def _listening_socket():
server = socket.socket()
server.bind(("127.0.0.1", 0))
server.listen(4)
def serve():
try:
for _ in range(4):
server.accept()
except OSError:
pass # socket closed at the end of the test
threading.Thread(target=serve, daemon=True).start()
return server
@pytest.mark.skipif(sys.platform != "win32", reason="AppContainer chỉ có trên Windows")
def test_appcontainer_that_su_cat_mang_nhung_van_ghi_duoc_thu_muc(tmp_path):
"""Bài thật, không giả lập: cùng một lệnh Python nối tới một cổng đang nghe,
ngoài sandbox thì được, trong sandbox thì bị kernel từ chối."""
from cowork_local.core.deps import run_cancellable
server = _listening_socket()
port = server.getsockname()[1]
probe = (f'"{sys.executable}" -c "import socket;'
"print('PYTHON'+'_RAN');"
f"socket.create_connection(('127.0.0.1',{port}),5);print('CONN'+'ECTED')\"")
try:
rc, out, *_ = run_cancellable(probe, cwd=str(tmp_path), timeout=60, shell=True)
assert rc == 0 and "CONNECTED" in out
rc, out, *_ = run_cancellable(probe + " & echo written> marker.txt",
cwd=str(tmp_path), timeout=60, isolate_network=True)
assert "PYTHON_RAN" in out, out # Python itself starts in the sandbox
assert "CONNECTED" not in out, out
assert (Path(tmp_path) / "marker.txt").read_text().strip() == "written"
finally:
server.close()
# ---- xem trước HTML ------------------------------------------------------------
class _FakeUrl:
def __init__(self, scheme):
self._scheme = scheme
def scheme(self):
return self._scheme
class _FakeRequest:
def __init__(self, scheme):
self._url = _FakeUrl(scheme)
self.blocked = False
def requestUrl(self): # noqa: N802 - Qt name
return self._url
def block(self, flag):
self.blocked = flag
@pytest.mark.parametrize("scheme,expected", [
("https", True), ("http", True), ("wss", True), ("file", False), ("data", False),
])
def test_xem_truoc_html_chan_tai_nguyen_web(chan_mang, scheme, expected):
pytest.importorskip("PySide6.QtWebEngineCore")
from cowork_local.presentation.folder.offline_web_page import RemoteRequestBlocker
req = _FakeRequest(scheme)
RemoteRequestBlocker().interceptRequest(req)
assert req.blocked is expected
def test_xem_truoc_html_tai_binh_thuong_khi_tat():
pytest.importorskip("PySide6.QtWebEngineCore")
from cowork_local.presentation.folder.offline_web_page import RemoteRequestBlocker
req = _FakeRequest("https")
RemoteRequestBlocker().interceptRequest(req)
assert req.blocked is False
@pytest.mark.skipif(sys.platform != "win32", reason="AppContainer chỉ có trên Windows")
def test_khong_cap_quyen_ke_thua_len_thu_muc_chua_qt(tmp_path, monkeypatch):
"""Quyền AppContainer kế thừa xuống Qt6WebEngineCore.dll làm tiến trình render
của WebEngine không nạp được DLL — tab Graph và xem trước HTML trắng trơn."""
from cowork_local.infrastructure.sandbox import appcontainer_process as ac
qt_dir = tmp_path / "venv" / "Lib" / "site-packages" / "PySide6"
qt_dir.mkdir(parents=True)
monkeypatch.setattr(ac, "_qt_package_dir", lambda: str(qt_dir))
monkeypatch.setattr(ac, "_icacls", _no_network)
with pytest.raises(ac.NetworkIsolationUnavailable, match="Qt runtime"):
ac.grant_access(str(tmp_path / "venv"), "S-1-15-2-1", "read")
with pytest.raises(ac.NetworkIsolationUnavailable, match="Qt runtime"):
ac.grant_access(str(tmp_path), "S-1-15-2-1", "write")
def test_quyen_cho_python_khong_bao_gio_phu_len_thu_vien_qt(monkeypatch, tmp_path):
from cowork_local.infrastructure.sandbox import appcontainer_process as ac
venv, base = tmp_path / "venv", tmp_path / "base"
monkeypatch.setattr(ac.sys, "prefix", str(venv))
monkeypatch.setattr(ac.sys, "base_prefix", str(base))
for qt_dir in (venv / "Lib" / "site-packages" / "PySide6",
base / "Lib" / "site-packages" / "PySide6"):
monkeypatch.setattr(ac, "_qt_package_dir", lambda d=qt_dir: str(d))
for folder, mode in ac._interpreter_grants():
assert mode == "read_here" or not ac._covers(folder, str(qt_dir)), (folder, mode)
-125
View File
@@ -1,125 +0,0 @@
"""Công tắc "Chặn mạng cho lệnh do agent chạy" phải chặn MỌI đường ra mạng của
agent, không riêng ``run_command``.
Trước đây ``block_network`` chỉ được đọc ở đúng một chỗ —
``infrastructure/filesystem/command_tools.py`` trong ``run_command`` — nên bốn
tool mang ``ToolCapability.NETWORK`` (``fetch_url``, ``jira_search``,
``jira_get_issue``, ``install_package``) vẫn ra internet bình thường trong khi
màn Monitoring báo "Mạng: Bị chặn" và docstring của ``fetch_tools`` tự nhận là
*"Honors the Sandbox Security Layer's Block network policy"*. Người dùng bật
công tắc rồi thấy agent vẫn search web được — đúng triệu chứng được báo.
Hai nhóm bài:
* **hành vi** — bật thì mọi tool NETWORK từ chối TRƯỚC khi chạm mạng, tắt thì
đường cũ giữ nguyên (chặn một chiều là hỏng tính năng);
* **guardrail** — thêm tool mạng mới mà quên chặn thì bài ở đây đỏ ngay.
"""
from __future__ import annotations
from typing import Dict
import pytest
from cowork_local.core.tools import ToolContext
from cowork_local.domain.tools import BUILT_IN_CAPABILITIES, ToolCapability
from cowork_local.infrastructure.filesystem import command_tools, fetch_tools
# tên tool -> (handler, args hợp lệ tối thiểu). Args phải hợp lệ, nếu không bài
# test sẽ đỏ vì lỗi thiếu tham số chứ không vì cổng chặn mạng.
_TOOL_MANG: Dict[str, tuple] = {
"fetch_url": (fetch_tools.fetch_url, {"url": "https://example.com/"}),
"jira_search": (fetch_tools.jira_search, {"jql": "project = ABC"}),
"jira_get_issue": (fetch_tools.jira_get_issue, {"key": "ABC-1"}),
"install_package": (command_tools.install_package, {"package": "requests"}),
}
@pytest.fixture
def cam_ra_mang(monkeypatch):
"""Mọi đường ra mạng thật đều nổ.
Vừa giữ cho bộ test không chạm internet, vừa làm lộ tool nào lọt qua cổng
chặn: nó sẽ đỏ ngay tại lời gọi mạng thay vì im lặng đi ra ngoài.
"""
def no_ra_mang(*args, **kwargs):
raise AssertionError("tool đã chạm mạng dù 'Chặn mạng' đang bật")
from cowork_local.core import deps, jira_tool, link_fetch
monkeypatch.setattr(link_fetch, "fetch_link_preview", no_ra_mang)
monkeypatch.setattr(jira_tool, "search", no_ra_mang)
monkeypatch.setattr(jira_tool, "get_issue", no_ra_mang)
monkeypatch.setattr(jira_tool, "get_issue_by_url", no_ra_mang)
monkeypatch.setattr(deps, "pip_install", no_ra_mang)
# ---- hành vi: bật công tắc thì mọi tool mạng đều bị chặn -----------------
@pytest.mark.parametrize("ten", sorted(_TOOL_MANG))
def test_bat_chan_mang_thi_tool_tu_choi_truoc_khi_cham_mang(tmp_path, cam_ra_mang, ten):
"""Đây là chính triệu chứng người dùng báo: bật rồi mà vẫn ra được web."""
handler, args = _TOOL_MANG[ten]
ctx = ToolContext(tmp_path, block_network=True)
ket_qua = handler(ctx, args)
assert ket_qua["ok"] is False, f"{ten} vẫn chạy khi đang chặn mạng"
assert "Sandbox Security Layer" in ket_qua["output"], ket_qua["output"]
def test_allow_url_fetch_khong_lach_duoc_chan_mang(tmp_path, cam_ra_mang):
"""Hai công tắc vẫn độc lập, nhưng "Chặn mạng" là cái mạnh hơn: bật nó thì
"Cho phép agent lấy dữ liệu từ URL" không mở lại đường được."""
ctx = ToolContext(tmp_path, block_network=True, allow_url_fetch=True)
ket_qua = fetch_tools.fetch_url(ctx, {"url": "https://example.com/"})
assert ket_qua["ok"] is False
# ---- hành vi: tắt công tắc thì đường cũ giữ nguyên -----------------------
def test_tat_chan_mang_thi_fetch_url_van_doc_duoc(tmp_path, monkeypatch):
"""Chặn một chiều là hỏng tính năng — cổng phải mở lại được."""
from cowork_local.core import link_fetch
monkeypatch.setattr(link_fetch, "fetch_link_preview",
lambda url: f"nội dung của {url}")
ctx = ToolContext(tmp_path, block_network=False)
ket_qua = fetch_tools.fetch_url(ctx, {"url": "https://example.com/"})
assert ket_qua["ok"] is True
assert "example.com" in ket_qua["output"]
def test_tat_chan_mang_thi_install_package_van_chay(tmp_path, monkeypatch):
from cowork_local.core import deps
da_goi = []
def gia_lap_pip(package, **kwargs):
da_goi.append(package)
return True, "ok"
monkeypatch.setattr(deps, "pip_install", gia_lap_pip)
ctx = ToolContext(tmp_path, block_network=False)
ket_qua = command_tools.install_package(ctx, {"package": "requests"})
assert da_goi == ["requests"]
assert ket_qua["ok"] is True
# ---- guardrail: danh sách tool mạng không được lệch ----------------------
def test_moi_tool_mang_deu_co_bai_o_day():
"""``BUILT_IN_CAPABILITIES`` là nơi duy nhất khai báo tool nào chạm mạng.
Thêm một tool NETWORK mới mà quên chặn thì bài này đỏ ngay."""
tag_mang = {ten for ten, cap in BUILT_IN_CAPABILITIES.items()
if cap & ToolCapability.NETWORK}
assert tag_mang == set(_TOOL_MANG), (
"danh sách tool mạng đã đổi — chặn tool mới ở cổng block_network "
"rồi bổ sung vào _TOOL_MANG")

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