Files
cowork-local/CLAUDE.md
T
a03a740ea1
CI / test (push) Canceled after 0s
Feature/perf ui logic (#13)
## Summary

Nhánh `feature/perf-ui-logic`: tối ưu hiệu năng/UI, sửa lỗi workspace và điều hướng, và làm cho công tắc **"Block network for agent-run commands"** chặn thật mọi đường ra mạng của app, **trừ nhà cung cấp AI**.

**Chặn mạng (b78d483, 8c497cf, 10b8379)**
- Bộ kiểm tra chung `application/network/network_guard.py`, nối vào cấu hình đang chạy ở Composition Root: đổi công tắc trong Settings là có hiệu lực ngay.
- Lệnh shell của agent và task script chạy trong **Windows AppContainer không có quyền mạng**: kernel chặn socket, ping, DNS, Invoke-WebRequest… Không cần quyền admin. Không cô lập được thì lệnh bị từ chối, không chạy khi mạng còn mở. macOS dùng `sandbox-exec`, Linux dùng `unshare --net`.
- Bật chặn thì: dừng MCP đang chạy, không khởi động server mới, từ chối lời gọi connector; Microsoft 365 (đăng nhập, Graph, đồng bộ cloud, rules, mail), Teams, nút Test REST/Jira/MCP, link đính kèm task, pip tự cài và tài nguyên web trong xem trước HTML đều bị từ chối.
- Vẫn dùng được: chat, tải danh sách model, thử model; tool OneDrive đã đồng bộ trên máy.
- Công tắc **mặc định tắt** khi mở app lần đầu; nhãn giữ nguyên như cũ.
- Xem trước HTML trong tab Folder giờ hiện được ảnh/CSS/JS từ web khi mạng mở (trước đây trang `file://` không tải được).
- Sửa lỗi app văng khi chuyển tab Graph → Folder: profile WebEngine của trang xem trước bị huỷ trước trang (`0xc0000409` trong Qt6Core.dll); giờ dùng một profile chung thuộc QApplication.
- Không cấp quyền AppContainer kế thừa lên thư mục chứa PySide6 (nếu có, Chromium không nạp được `Qt6WebEngineCore.dll` và tab Graph trắng).
- Cột mục lục trong Settings tính độ rộng theo kiểu chữ của mục đang chọn, "Sandbox Security Layer" không còn bị cắt.

**Các commit khác trong nhánh**
- `b7a41b3` mỗi thư mục làm việc chỉ thuộc về một project · `bbdf146` bật nút Sửa project khi đã có project đang mở
- `35f24e0`, `cc8d5c8`, `2e3e719`, `c699beb` canh hàng / khoảng cách thanh điều hướng
- `2759ed9` không refresh workspace khi chuyển tab Cowork · `7607f44` checkpoint hiệu năng và UI
- `8548c1e` chặn tool mạng của agent · `caf3b74` renderer GraphRAG native trên macOS · `c00b83c` khoảng cách metadata hàng project · `a04f8a9` ẩn picker workspace cloud

## Change Type

- [x] Cowork feature
- [x] Bug fix
- [ ] Core AI contribution
- [x] Test / hardening
- [x] Performance
- [ ] Documentation

## Related Work

Cowork Task:

Core Repo: http://34.143.229.138/gitea-admin/fsg-ai-core-assets

Core AI Issue:

Core Task:

Related PR:

## Scope

What is intentionally included?
- Mọi đường ra mạng do app tự mở, trừ nhà cung cấp AI (xem Summary).
- Test: `tests/test_network_guard_lanes.py` (có bài chạy AppContainer thật trên Windows), `tests/ui/test_html_preview_remote_images.py`.

What is intentionally NOT included?
- Chặn cả nhà cung cấp AI / chạy model trên máy (Phương án 2).
- Terminal người dùng tự gõ trong tab Folder, sinh ảnh, cơ chế tự tin chứng chỉ lạ (`tls_trust`).
- Huy hiệu trạng thái "đang chặn" trên thanh trên cùng.

## Validation

- [x] Unit tests
- [x] Integration tests
- [x] Manual verification
- [x] Regression check

Commands / evidence:
- `python -m pytest tests/test_network_guard_lanes.py tests/test_sandbox_block_network.py tests/ui -q` → chỉ còn 1 bài fail, fail cả trên `b7a41b3` (nhãn `ProjectRow` 'Project' chưa dịch, `tests/ui/test_i18n_khong_con_chu_cu.py`).
- `python -m pytest tests -q --ignore=tests/ui` → 4 bài fail, cả 4 cũng fail trên `b7a41b3` (`test_canonical_audit_logger`, 2 bài `test_mcp_audit_security`, `test_monitoring_tab_container`).
- Chạy cả `tests` trong một lượt thì treo ở các test dựng MainWindow trong `tests/ui`; `b7a41b3` cũng treo đúng chỗ đó.
- `check_imports.py` và `check_orphan_modules.py` PASS. `check_loc.py` báo 9 file quá dài, giống hệt trước khi sửa (không file nào do nhánh này làm dài thêm).
- Kiểm tra tay trên Windows 11: trong AppContainer, Python báo `WinError 10013`, ping/nslookup/PowerShell/curl đều không ra được mạng; cmd, git, python chạy bình thường.
- Kiểm tra tay trên Windows 11: xem trước HTML tải được 4/4 tài nguyên web khi mạng mở, 0/4 khi bật chặn; tab Graph hoạt động; tạo/huỷ trang xem trước nhiều lần không còn cảnh báo profile của Qt.

## Security Impact

Permission / credential / network / customer data impact:
- Network: khi bật công tắc, chỉ nhà cung cấp AI còn ra mạng; nội dung chat vẫn gửi tới nhà cung cấp AI.
- Permission: lần đầu chạy lệnh trong sandbox, app **thêm quyền (ACE) cho SID AppContainer** trên thư mục làm việc (ghi), thư mục cài Python gốc (đọc), gốc venv và `Scripts` (đọc). Không xoá quyền nào. Thư mục chứa PySide6 không bao giờ nhận quyền kế thừa; một quyền kế thừa sai trên venv (từ bản dev trước) được tự gỡ.
- Credential: không đổi. Khi chặn, trạng thái đăng nhập M365 được đọc thẳng từ kho token trên máy, không dựng MSAL.

## Compatibility

- [x] No breaking change
- [ ] Breaking change documented

Ghi chú: `block_network` mặc định đổi từ bật sang tắt cho cấu hình mới; máy đã lưu `true` thì giữ nguyên. Khi đang chặn, lệnh dùng công cụ cài trong thư mục người dùng (ngoài Program Files) có thể báo Access denied; thư viện trong venv của app không dùng được trong sandbox.

## Reviewer Notes

- `infrastructure/sandbox/appcontainer_process.py` gọi Win32 bằng ctypes (CreateAppContainerProfile, CreateProcessW với SECURITY_CAPABILITIES) và dùng `icacls` để cấp quyền: nên xem kỹ phần cấp quyền.
- `tests/conftest.py` thêm fixture autouse gỡ `network_guard` sau mỗi test, vì `build_context()` gắn cổng này ở mức process.
- `core/task_executors.py` đang đúng bằng trần LOC nên `_run_script` được tách sang `core/task_script.py`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: minhanhpkpro <minhanhpkpro@gmail.com>
Co-authored-by: Duy Le Huu <duylh19@fpt.com>
Co-authored-by: thanhnv <thanhnv.ip@gmail.com>
Reviewed-on: #13
2026-09-20 12:26:03 +00:00

7.6 KiB

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

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 AgentEvents 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.