Compare commits
5
Commits
2f3cd100f8
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a03a740ea1 | ||
|
|
cbae2604db | ||
|
|
b71a622227 | ||
|
|
1b8429e33a | ||
|
|
13e2c22067 |
@@ -0,0 +1,82 @@
|
||||
# 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.
+1
-1
@@ -15,7 +15,7 @@ network control, permission management, audit log). No login required —
|
||||
starts directly with full admin access.
|
||||
"""
|
||||
|
||||
__version__ = "2.26.0"
|
||||
__version__ = "0.0.1"
|
||||
# Internal/technical name — config dir (~/.cowork_local), QSettings org keys,
|
||||
# packaging scripts and docs still use this; do NOT rebrand it.
|
||||
APP_NAME = "Cowork Local"
|
||||
|
||||
+62
-8
@@ -21,6 +21,7 @@ Anti-pattern mà bộ này cố tình tránh (mục 10 của tài liệu trainin
|
||||
| Không có Output Contract | Mọi output đi qua template trong `output/` |
|
||||
| Không có Quality Gate | Mỗi role có Quality Gate riêng + `checklist/` dùng chung |
|
||||
| Không có example | `examples/good_fix.md` và `examples/bad_fix.md` |
|
||||
| Effort cố định bất kể lỗi to nhỏ | `roles/0_fix_dispatcher.md` chấm tier trước, lỗi 4px chạy 0 agent |
|
||||
|
||||
Sáu role **không** bị tách thành 7 file nhỏ mỗi role (role/task/process/...). Lý do:
|
||||
phần bị lặp giữa các role chính là guardrail, knowledge và checklist — chúng đã được
|
||||
@@ -47,7 +48,8 @@ agent/
|
||||
│ ├─ qt_pitfalls.md ← 20 nguyên nhân gốc hay gặp của bug UI PySide6
|
||||
│ ├─ secrets_and_config.md ← SecretStore, schema migration, bẫy .get() trên config merge
|
||||
│ └─ quality_gates.md ← CASAN gate, lệnh chạy, test headless
|
||||
├─ roles/ ← 7 agent chuyên biệt
|
||||
├─ roles/ ← 1 hub + 7 agent chuyên biệt
|
||||
│ ├─ 0_fix_dispatcher.md ← HUB: chấm tier T0/T1/T2/T3, chọn lane, tách defect
|
||||
│ ├─ 1_ui_bug_triage.md
|
||||
│ ├─ 2_ui_visual_fixer.md
|
||||
│ ├─ 3_ux_flow_fixer.md
|
||||
@@ -55,14 +57,17 @@ agent/
|
||||
│ ├─ 5_fix_implementer.md
|
||||
│ ├─ 6_regression_reviewer.md
|
||||
│ └─ 7_security_defect_fixer.md
|
||||
├─ commands/
|
||||
│ └─ fix.md ← nguồn của slash command /fix (điểm vào của hub)
|
||||
├─ workflow/
|
||||
│ ├─ intake_to_fix.md ← pipeline end-to-end, ai làm gì ở bước nào
|
||||
│ ├─ intake_to_fix.md ← pipeline end-to-end, 4 lane theo tier
|
||||
│ └─ handoff_contract.md ← envelope truyền giữa các agent
|
||||
├─ checklist/
|
||||
│ ├─ ui_review.md
|
||||
│ ├─ ux_review.md
|
||||
│ └─ pr_readiness.md
|
||||
├─ output/
|
||||
│ ├─ dispatch_plan.md ← template điều phối (output của Hub)
|
||||
│ ├─ defect_record.md ← template hồ sơ lỗi (output của Triage)
|
||||
│ ├─ fix_plan.md ← template phương án sửa (output của Fixer)
|
||||
│ ├─ fix_report.md ← template báo cáo sau khi sửa (output của Implementer)
|
||||
@@ -74,10 +79,11 @@ agent/
|
||||
|
||||
---
|
||||
|
||||
## 3. Bảy agent và khi nào dùng
|
||||
## 3. Một hub + bảy agent, và khi nào dùng
|
||||
|
||||
| # | Agent | Pattern | Nhận vào | Trả ra |
|
||||
|---|---|---|---|---|
|
||||
| **0** | **Fix Dispatcher** (hub) | Router | Phản ánh thô của người dùng | `dispatch_plan.md` — tier + lane + tách defect |
|
||||
| 1 | **UI Bug Triage** | Reviewer | Lời kể lộn xộn của user, ảnh chụp màn hình, log | `defect_record.md` + phân loại + route |
|
||||
| 2 | **UI Visual Fixer** | Generator | defect_record (loại `visual`) | `fix_plan.md` — layout/QSS/theme/icon/DPI |
|
||||
| 3 | **UX Flow Fixer** | Generator | defect_record (loại `flow`) | `fix_plan.md` — luồng, trạng thái, phản hồi |
|
||||
@@ -86,19 +92,36 @@ agent/
|
||||
| 6 | **Regression Reviewer** | Reviewer | Patch + fix_report | Verdict PASS/FAIL + `pr_body.md` |
|
||||
| 7 | **Security Defect Fixer** | Generator | defect_record (loại `security`) | `fix_plan.md` — credential, secret, migration |
|
||||
|
||||
Đây là **Multi-Agent Pattern**: `Triage (Planner) → Specialist → Implementer (Executor)
|
||||
→ Reviewer`. Không bỏ bước. Đặc biệt không bỏ bước 1: 80% bug UI báo lên là mô tả
|
||||
triệu chứng, không phải nguyên nhân.
|
||||
Đây là **Multi-Agent Pattern**: `Dispatcher (Router) → Triage (Planner) → Specialist →
|
||||
Implementer (Executor) → Reviewer`.
|
||||
|
||||
**Số bước thực chạy do agent 0 quyết định, không phải mặc định 5.** Bộ v1.2 chạy đủ pipeline
|
||||
cho mọi lỗi, kể cả đổi một giá trị 4px — đó là lý do agent 0 ra đời. Bốn lane:
|
||||
|
||||
| Tier | Lỗi kiểu gì | Lane | Gọi agent |
|
||||
|---|---|---|---|
|
||||
| **T0** | Đổi số đo hiển thị, sai chính tả chuỗi có key sẵn, đổi token màu có sẵn | DIRECT | **0 lần** — hub sửa luôn + 4 cổng máy |
|
||||
| **T1** | Nguyên nhân gốc đã rõ kèm `file:line`, 1 màn, ≤ 3 file, ≤ 40 LOC | SOLO | 1 lần |
|
||||
| **T2** | Nguyên nhân chưa rõ nhưng đã khoanh 1 màn; chạm QSS/token/i18n dùng chung | PAIR | 3 lần |
|
||||
| **T3** | Mô tả thuần triệu chứng, không tái hiện được, nhiều category, > 150 LOC | FULL | 4–5 lần |
|
||||
|
||||
Bước 1 vẫn **không** được bỏ ở T3 — 80% bug UI báo lên là mô tả triệu chứng, không phải
|
||||
nguyên nhân. Ở T1/T2, phần triage do hub tự làm trong `dispatch_plan`, và chỉ hợp lệ khi
|
||||
phản ánh đã tự chỉ ra màn hình + triệu chứng cụ thể. Bước 6 chỉ được bỏ ở T0/T1, và phải
|
||||
nêu rõ cổng nào thay thế.
|
||||
|
||||
Agent 7 là specialist thứ tư, ngang hàng 2/3/4 trong pipeline, nhưng khác ở hai điểm: nó
|
||||
được phép chạm `config.py`, `infrastructure/`, `core/` (ba role kia bị chặn ở tầng
|
||||
presentation), và nó **không được tự quyết chính sách bảo mật** — bốn câu hỏi bắt buộc trả
|
||||
về cho Cowork Team.
|
||||
|
||||
### Routing rule (Triage quyết định)
|
||||
### Routing rule (Hub chấm tier → Triage chọn specialist)
|
||||
|
||||
```text
|
||||
Người dùng báo lỗi
|
||||
│
|
||||
├─ agent 0 tách thành N defect_id, chấm tier từng cái
|
||||
│ (≤ 5 lệnh đọc/grep, 0 subagent; hết mà chưa chấm được → T2)
|
||||
│
|
||||
├─ "nhìn sai / lệch / mất chữ / màu lạ / bị che" → 2. UI Visual Fixer
|
||||
├─ "bấm không ăn / không biết đang chạy / mất dữ liệu" → 3. UX Flow Fixer
|
||||
@@ -108,12 +131,36 @@ Người dùng báo lỗi
|
||||
Trả về, mở issue type:bug thường.
|
||||
|
||||
Nhóm `security` THẮNG mọi nhóm khác: lỗi vừa lệch layout vừa lộ credential thì đi 7 trước.
|
||||
Tín hiệu bảo mật cũng ép tier lên **T3-SEC** bất kể diff nhỏ cỡ nào — một dòng `==` so
|
||||
mật khẩu không bao giờ là T0.
|
||||
```
|
||||
|
||||
Tier chỉ đi **lên**. FAIL ở bước 6 → tier +1 rồi chạy lại, không sửa lại ở nguyên tier cũ.
|
||||
|
||||
---
|
||||
|
||||
## 4. Cách dùng
|
||||
|
||||
### 4.0 Điểm vào (khuyến nghị)
|
||||
|
||||
Cài một lần cho mỗi máy — `.claude/` nằm trong `.gitignore`, nên nó **không** theo
|
||||
clone; `agent/` mới là bản gốc được version:
|
||||
|
||||
```bash
|
||||
mkdir -p .claude/agents .claude/commands
|
||||
cp agent/roles/[1-7]_*.md .claude/agents/
|
||||
cp agent/commands/fix.md .claude/commands/
|
||||
```
|
||||
|
||||
Rồi:
|
||||
|
||||
```text
|
||||
/fix màn Folder kéo to ra thì mất cây thư mục bên trái
|
||||
```
|
||||
|
||||
Hub sẽ chấm tier, in `dispatch_plan`, rồi tự chạy đúng lane. Chỉ gọi trực tiếp role 1–7
|
||||
khi đã biết chắc tier.
|
||||
|
||||
### 4.1 Dùng thủ công (mọi trợ lý AI)
|
||||
|
||||
Nạp theo đúng thứ tự này rồi dán bug report của user vào:
|
||||
@@ -122,6 +169,7 @@ Nạp theo đúng thứ tự này rồi dán bug report của user vào:
|
||||
agent/system/guardrail.md
|
||||
agent/system/security.md
|
||||
agent/system/response_policy.md
|
||||
agent/roles/0_fix_dispatcher.md ← luôn nạp trước, để biết cần chạy tới đâu
|
||||
agent/roles/<role đang dùng>.md
|
||||
+ các file knowledge/ mà role đó liệt kê ở mục "KNOWLEDGE"
|
||||
```
|
||||
@@ -133,9 +181,13 @@ subagent, copy sang `.claude/agents/`:
|
||||
|
||||
```bash
|
||||
mkdir -p .claude/agents
|
||||
cp agent/roles/*.md .claude/agents/
|
||||
cp agent/roles/[1-7]_*.md .claude/agents/
|
||||
```
|
||||
|
||||
`0_fix_dispatcher.md` **không** copy vào `.claude/agents/`: hub cần quyền gọi agent khác,
|
||||
mà subagent trong Claude Code không gọi được subagent. Hub chạy ở session chính, qua
|
||||
`/fix` (`.claude/commands/fix.md`).
|
||||
|
||||
Sau đó gọi bằng tên: `ui-bug-triage`, `ui-visual-fixer`, `ux-flow-fixer`,
|
||||
`i18n-a11y-fixer`, `fix-implementer`, `regression-reviewer`, `security-defect-fixer`.
|
||||
|
||||
@@ -154,4 +206,6 @@ trong commit message — instruction cũng là code.
|
||||
|---|---|---|
|
||||
| 1.0 | 2026-09-07 | Bản đầu: 6 role, 6 knowledge module, 4 output contract |
|
||||
| 1.1 | 2026-09-07 | Thêm role 7 `security-defect-fixer` + `knowledge/secrets_and_config.md`. Lý do: bộ v1.0 chỉ phủ UI/UX, nên credential hardcode phát hiện qua màn Settings bị rơi vào `not-ui` và không ai nhận |
|
||||
| 1.4 | 2026-09-08 | Nạp bài học từ lượt audit i18n toàn app. `knowledge/i18n_rules.md` §2.0 (`bind_*` là cách mặc định cho chuỗi tĩnh, `bind_dynamic` cho chữ theo trạng thái, không bind dữ liệu), §"Cách TÌM ra hết các chỗ bị lỗi" (grep chuỗi tiếng Việt ra 962 dòng mà **không** dòng nào là lỗi thật; phép đo đúng là thay `tr()` bằng chuỗi mốc trên `MainWindow` thật), và 3 mục checklist mới. Lý do: bộ v1.3 không có cách nào phát hiện lỗi "chữ không được áp lại" — nó không để lại dấu vết nào trong source |
|
||||
| 1.3 | 2026-09-08 | Thêm hub `0_fix_dispatcher` + `output/dispatch_plan.md` + `/fix`. Lý do: bộ v1.2 không có tầng điều phối, nên **mọi** lỗi đều kéo cả pipeline 4–5 agent — kể cả nới một `setMinimumWidth` lên 232px. Bổ sung 4 lane theo tier, danh sách đóng T0 (6 loại + 9 disqualifier), 4 cổng máy thay reviewer ở T0, luật escalate một chiều, và luật tách một phản ánh thành nhiều `defect_id` chấm tier riêng |
|
||||
| 1.2 | 2026-09-07 | Nạp bài học từ lần chạy thật đầu tiên (`SEC-20260907-01`). Bản vá của bước 5 mang một blocker mà **không mục nào trong bộ v1.1 bắt được** — reviewer tìm ra bằng tay. Bổ sung: `secrets_and_config.md` §9 (chặn rỗng, `compare_digest` + ASCII, và luật "API an toàn hơn thường có miền đầu vào hẹp hơn"); `6_regression_reviewer.md` Bước 2.1 (ràng buộc miền đầu vào) và 4.1 (test rỗng ruột); `5_fix_implementer.md` + `quality_gates.md` (baseline bằng `comm -13` trên tên test, guard `git add`, và thực tế suite vốn đã đỏ 11+66); `bad_fix.md` ca 11-12 — hai ví dụ **có thật** đầu tiên trong file |
|
||||
|
||||
+144
-39
@@ -1,53 +1,158 @@
|
||||
# Checklist sẵn sàng tạo PR
|
||||
|
||||
Dùng bởi `fix-implementer` (bước 9) và `regression-reviewer` (bước 8).
|
||||
Bám theo `.gitea/PULL_REQUEST_TEMPLATE.md` và `docs/governance/definition-of-done.md`.
|
||||
Checklist này được sử dụng bởi:
|
||||
|
||||
## A. Cổng chất lượng
|
||||
* `fix-implementer` — kiểm tra ở bước 9.
|
||||
* `regression-reviewer` — kiểm tra ở bước 8.
|
||||
|
||||
- [ ] `python scripts/run_quality_gate.py` — xanh cả 5 cổng, **có dán output thật**.
|
||||
- [ ] Gate C: `domain/`/`application/` không import PySide6/PyQt/`ui`/`app`.
|
||||
- [ ] Gate A: không secret/plaintext mới.
|
||||
- [ ] Gate S: không file nào > 400 LOC.
|
||||
- [ ] Gate O: không module mồ côi (file mới đã được import trong cùng commit).
|
||||
- [ ] Gate A/N: pytest xanh; test vốn đỏ từ trước được ghi riêng.
|
||||
Tham chiếu:
|
||||
|
||||
## B. Kiểm chứng
|
||||
* `.gitea/PULL_REQUEST_TEMPLATE.md`
|
||||
* `docs/governance/definition-of-done.md`
|
||||
|
||||
- [ ] Test regression tồn tại và **đỏ trước / xanh sau**.
|
||||
- [ ] Test chạy được headless (`QT_QPA_PLATFORM=offscreen`).
|
||||
- [ ] Đã kiểm bằng mắt ở dark + light — hoặc ghi rõ "chưa kiểm chứng bằng mắt" kèm lý do.
|
||||
- [ ] Đã kiểm ở các ngôn ngữ liên quan.
|
||||
---
|
||||
|
||||
## C. Phạm vi & lịch sử
|
||||
## A. Kiểm tra chất lượng
|
||||
|
||||
- [ ] Một PR = một thay đổi logic. Không refactor lẫn vào.
|
||||
- [ ] Không đổi format/indent toàn file; diff đọc được.
|
||||
- [ ] Nhánh riêng, không commit thẳng `main`.
|
||||
- [ ] Commit message nêu nguyên nhân gốc + `file:line` + issue.
|
||||
- [ ] Không commit `.env`, `config.json` local, dữ liệu dưới `.cowork_local/`, `.venv`.
|
||||
* [ ] Chạy `python scripts/run_quality_gate.py`.
|
||||
Cả **5 quality gate đều phải PASS** và phải ghi lại **output thực tế**.
|
||||
|
||||
## D. Bảo mật
|
||||
* [ ] **Gate C:** Các thư mục `domain/` và `application/` không được import:
|
||||
- `PySide6`
|
||||
- `PyQt`
|
||||
- `ui`
|
||||
- `app`
|
||||
|
||||
- [ ] Không secret/PII/đường dẫn cá nhân trong code, test fixture, commit message, PR body.
|
||||
- [ ] Ảnh chụp màn hình đính kèm đã được redact.
|
||||
- [ ] Nếu chạm permission / credential / MCP write-exec / sandbox / network / TLS /
|
||||
isolation / model routing / xoá dữ liệu → đánh dấu `security-review: required` và ghi
|
||||
rõ trong PR rằng **CI xanh không đủ để merge**.
|
||||
* [ ] **Gate A:** Không tạo thêm secret hoặc thông tin nhạy cảm dạng plaintext.
|
||||
|
||||
## E. Nội dung PR
|
||||
* [ ] **Gate S:** Không có file nào vượt quá **400 dòng code (LOC)**.
|
||||
|
||||
- [ ] Summary nói **tại sao**, không chỉ **cái gì**.
|
||||
- [ ] Change Type đã tick.
|
||||
- [ ] Scope: nêu rõ cả phần **cố ý không** làm.
|
||||
- [ ] Validation: có lệnh và output thật.
|
||||
- [ ] Security Impact: đã điền, kể cả khi là "không có".
|
||||
- [ ] Compatibility: đã tick.
|
||||
- [ ] Reviewer Notes: chỉ ra chỗ cần soi kỹ nhất.
|
||||
- [ ] Tài liệu (`docs/`, ảnh `docs/screens/`) đã cập nhật nếu cần.
|
||||
* [ ] **Gate O:** Không có file/module mới bị bỏ quên.
|
||||
File Python mới phải được sử dụng/import trong cùng thay đổi.
|
||||
|
||||
## F. Ranh giới
|
||||
* [ ] **Gate A/N:** Test phải PASS.
|
||||
Nếu đã có test FAIL từ trước thì phải ghi rõ đó là **lỗi có sẵn**, không phải lỗi do bản sửa này gây ra.
|
||||
|
||||
- [ ] Agent **không** tự merge, **không** tự đóng issue.
|
||||
- [ ] Nếu là đóng góp của FSG AI Core: hiểu rằng chỉ "Done" khi PR đã merge vào Cowork Local,
|
||||
kèm đủ core issue reference, PR, evidence, reviewer phía Cowork, merge reference.
|
||||
---
|
||||
|
||||
## B. Kiểm tra bản sửa
|
||||
|
||||
* [ ] Có **regression test** cho lỗi đã sửa.
|
||||
|
||||
* [ ] Regression test phải chứng minh được:
|
||||
- **Trước khi sửa:** test FAIL.
|
||||
- **Sau khi sửa:** test PASS.
|
||||
|
||||
* [ ] Test chạy được ở chế độ headless:
|
||||
`QT_QPA_PLATFORM=offscreen`
|
||||
|
||||
* [ ] Nếu thay đổi liên quan đến UI:
|
||||
- Đã kiểm tra giao diện ở **Dark Mode**.
|
||||
- Đã kiểm tra giao diện ở **Light Mode**.
|
||||
- Nếu chưa thể kiểm tra bằng mắt, phải ghi rõ:
|
||||
**"Chưa kiểm chứng bằng mắt"** và nêu lý do.
|
||||
|
||||
* [ ] Nếu thay đổi liên quan đến ngôn ngữ:
|
||||
đã kiểm tra các ngôn ngữ bị ảnh hưởng.
|
||||
|
||||
---
|
||||
|
||||
## C. Kiểm tra phạm vi thay đổi và Git
|
||||
|
||||
* [ ] Một PR chỉ giải quyết **một thay đổi logic chính**.
|
||||
Không đưa refactor không liên quan vào cùng PR.
|
||||
|
||||
* [ ] Không tự ý format hoặc thay đổi indent của toàn bộ file.
|
||||
Diff phải rõ ràng và dễ review.
|
||||
|
||||
* [ ] Làm việc trên **branch riêng**.
|
||||
Không commit trực tiếp vào `main`.
|
||||
|
||||
* [ ] Commit message phải nêu:
|
||||
- Nguyên nhân gốc của lỗi.
|
||||
- Vị trí code liên quan (`file:line`).
|
||||
- Issue liên quan.
|
||||
|
||||
* [ ] Không commit các file/dữ liệu sau:
|
||||
- `.env`
|
||||
- `config.json` local
|
||||
- `.cowork_local/`
|
||||
- `.venv/`
|
||||
|
||||
---
|
||||
|
||||
## D. Kiểm tra bảo mật
|
||||
|
||||
* [ ] Không có các thông tin sau trong code, test fixture, commit message hoặc PR body:
|
||||
- Secret
|
||||
- PII/thông tin cá nhân
|
||||
- Đường dẫn chứa thông tin cá nhân trên máy local
|
||||
|
||||
* [ ] Nếu có ảnh chụp màn hình trong PR:
|
||||
đã che (redact) toàn bộ thông tin nhạy cảm trước khi đính kèm.
|
||||
|
||||
* [ ] Nếu thay đổi liên quan đến một trong các nội dung sau:
|
||||
|
||||
```
|
||||
- Permission/quyền truy cập
|
||||
- Credential/thông tin xác thực
|
||||
- MCP write/exec
|
||||
- Sandbox
|
||||
- Network
|
||||
- TLS
|
||||
- Isolation
|
||||
- Model routing
|
||||
- Xóa dữ liệu
|
||||
|
||||
thì phải:
|
||||
|
||||
1. Đặt `security-review: required`.
|
||||
2. Ghi rõ trong PR rằng:
|
||||
**"CI xanh không có nghĩa là có thể merge ngay."**
|
||||
3. Chờ security review theo quy trình trước khi merge.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## E. Kiểm tra nội dung PR
|
||||
|
||||
* [ ] **Summary** phải giải thích **tại sao cần sửa**, không chỉ mô tả đã sửa cái gì.
|
||||
|
||||
* [ ] Đã chọn **Change Type** phù hợp.
|
||||
|
||||
* [ ] **Scope** phải ghi rõ:
|
||||
- Những gì đã thay đổi.
|
||||
- Những gì **cố ý không thay đổi**.
|
||||
|
||||
* [ ] **Validation** phải ghi:
|
||||
- Lệnh đã chạy.
|
||||
- Kết quả thực tế/output.
|
||||
|
||||
* [ ] **Security Impact** phải được điền.
|
||||
Nếu không ảnh hưởng bảo mật, ghi rõ **"Không có"**.
|
||||
|
||||
* [ ] Đã chọn **Compatibility** phù hợp.
|
||||
|
||||
* [ ] **Reviewer Notes** phải chỉ ra những phần reviewer cần kiểm tra kỹ nhất.
|
||||
|
||||
* [ ] Đã cập nhật tài liệu nếu cần:
|
||||
- `docs/`
|
||||
- Ảnh màn hình trong `docs/screens/`
|
||||
|
||||
---
|
||||
|
||||
## F. Giới hạn quyền của Agent
|
||||
|
||||
* [ ] Agent **không được tự merge PR**.
|
||||
|
||||
* [ ] Agent **không được tự đóng issue**.
|
||||
|
||||
* [ ] Nếu đây là đóng góp từ **FSG AI Core**, cần hiểu rằng trạng thái **"Done"** chỉ được xác nhận khi PR đã thực sự được merge vào Cowork Local và có đầy đủ:
|
||||
|
||||
```
|
||||
- Core issue reference
|
||||
- PR reference
|
||||
- Evidence
|
||||
- Reviewer phía Cowork
|
||||
- Merge reference
|
||||
```
|
||||
|
||||
+190
-36
@@ -1,49 +1,203 @@
|
||||
# Checklist review bản vá UI (visual)
|
||||
# Checklist review bản vá UI (Visual)
|
||||
|
||||
Dùng bởi `ui-visual-fixer` (bước 7) và `regression-reviewer` (bước 5).
|
||||
Checklist này được sử dụng bởi:
|
||||
|
||||
## A. Đúng file
|
||||
* `ui-visual-fixer` — kiểm tra ở bước 7.
|
||||
* `regression-reviewer` — kiểm tra ở bước 5.
|
||||
|
||||
- [ ] Đã `grep` cả `ui/` và `presentation/`; file được sửa là file thực sự import vào runtime.
|
||||
- [ ] Widget này không có bản trùng tên ở thư mục còn lại.
|
||||
Mục tiêu: đảm bảo bản vá UI sửa đúng nguyên nhân, không phá theme, layout, icon hoặc vòng đời của giao diện.
|
||||
|
||||
## B. Màu & theme
|
||||
---
|
||||
|
||||
- [ ] Không hex literal (`#rrggbb`), không tên màu (`"red"`) ngoài `theme/`.
|
||||
- [ ] Không `setStyleSheet` cục bộ mới; style đi qua `objectName` + `theme/qss.py`.
|
||||
- [ ] Token mới có ở **cả** `DARK` và `LIGHT`.
|
||||
- [ ] Chữ trên nền đặc dùng `accent_solid`, không dùng `accent`.
|
||||
- [ ] Bậc bề mặt đúng ngữ nghĩa: `bg` / `surface` / `surface_raised` / `overlay` / `sunken`.
|
||||
- [ ] Contrast ≥ 4.5:1 cho body text và chữ trên nút đặc, ở cả hai theme.
|
||||
- [ ] Không thêm gradient/glow (trái ràng buộc thiết kế).
|
||||
- [ ] Nav rail vẫn tối hơn vùng nội dung.
|
||||
- [ ] Không trả bốn giá trị đã nhích lên WCAG AA về giá trị VS Code gốc.
|
||||
- [ ] Nếu chạm `_TEMPLATE`: đã liệt kê phạm vi ảnh hưởng toàn app.
|
||||
## A. Kiểm tra đúng file
|
||||
|
||||
## C. Layout & kích thước
|
||||
* [ ] Đã tìm kiếm trong **cả `ui/` và `presentation/`** để xác định file thực sự được ứng dụng sử dụng khi chạy.
|
||||
|
||||
- [ ] Không thêm `setFixedWidth` / `setFixedSize` / `setFixedHeight` mới.
|
||||
- [ ] Stretch factor / size policy được đặt tường minh.
|
||||
- [ ] `QScrollArea` có `setWidgetResizable(True)`.
|
||||
- [ ] Margin/spacing của layout lồng nhau không cộng dồn ngoài ý muốn.
|
||||
- [ ] Còn đúng ở cửa sổ nhỏ nhất **và** maximize.
|
||||
- [ ] Còn đúng ở scale 125% / 150% nếu bản vá chạm kích thước.
|
||||
* [ ] Đã kiểm tra xem widget có file/bản triển khai trùng tên ở thư mục còn lại hay không.
|
||||
|
||||
## D. Icon & vẽ tay
|
||||
* [ ] Nếu có nhiều file cùng chức năng, đã xác định rõ **file nào thực sự được import và chạy**.
|
||||
|
||||
- [ ] Icon lấy qua `ui/icons.py::icon`, không load file trực tiếp.
|
||||
- [ ] `paintEvent` đọc màu qua `current_palette()`, không đọc lại config.
|
||||
- [ ] Dùng `update()`, không `repaint()` trong vòng lặp.
|
||||
- [ ] `QPainter` có `end()`; nền được xoá đúng cách.
|
||||
---
|
||||
|
||||
## E. Vòng đời
|
||||
## B. Kiểm tra màu sắc và Theme
|
||||
|
||||
- [ ] Bản vá còn đúng khi đổi theme **trước** rồi mới mở màn dựng lười (P07).
|
||||
- [ ] `setProperty` để đổi style động có kèm `unpolish`/`polish`.
|
||||
- [ ] Không `connect()` lặp lại trong hàm được gọi nhiều lần.
|
||||
* [ ] Không thêm mã màu trực tiếp như `#rrggbb` hoặc tên màu như `"red"` bên ngoài thư mục `theme/`.
|
||||
|
||||
## F. Bằng chứng
|
||||
* [ ] Không thêm `setStyleSheet()` trực tiếp vào widget.
|
||||
Style phải được quản lý thông qua:
|
||||
|
||||
- [ ] Đã đối chiếu `docs/screens/<slug>-dark.png` và `<slug>-light.png`.
|
||||
- [ ] Ảnh trong `docs/screens/` cần cập nhật thì đã nêu.
|
||||
- [ ] Có test regression chạy headless, đỏ-trước-xanh-sau.
|
||||
```
|
||||
`objectName` → `theme/qss.py`
|
||||
```
|
||||
|
||||
* [ ] Nếu thêm token màu mới, token đó phải được khai báo cho **cả `DARK` và `LIGHT`**.
|
||||
|
||||
* [ ] Khi đặt chữ trên nền màu đặc, dùng `accent_solid`.
|
||||
Không dùng `accent` cho trường hợp này.
|
||||
|
||||
* [ ] Dùng đúng loại màu nền theo mục đích:
|
||||
|
||||
```
|
||||
- `bg` — nền chính.
|
||||
- `surface` — bề mặt thông thường.
|
||||
- `surface_raised` — bề mặt nổi.
|
||||
- `overlay` — lớp phủ.
|
||||
- `sunken` — khu vực chìm.
|
||||
```
|
||||
|
||||
* [ ] Contrast của chữ đạt tối thiểu **4.5:1** đối với:
|
||||
- Body text.
|
||||
- Chữ trên nút có nền đặc.
|
||||
- Cả Dark Mode và Light Mode.
|
||||
|
||||
* [ ] Không thêm:
|
||||
- Gradient.
|
||||
- Glow.
|
||||
|
||||
```
|
||||
Đây là các kiểu không phù hợp với design constraint hiện tại.
|
||||
```
|
||||
|
||||
* [ ] `Nav rail` vẫn **tối hơn khu vực nội dung**.
|
||||
Đây là thiết kế có chủ ý, không tự ý làm sáng lên.
|
||||
|
||||
* [ ] Không khôi phục các giá trị màu cũ theo VS Code nếu các giá trị hiện tại đã được điều chỉnh để đạt WCAG AA.
|
||||
|
||||
* [ ] Nếu thay đổi `_TEMPLATE`:
|
||||
đã đánh giá và ghi rõ **phạm vi ảnh hưởng trên toàn ứng dụng** vì `_TEMPLATE` có thể ảnh hưởng nhiều màn hình.
|
||||
|
||||
---
|
||||
|
||||
## C. Kiểm tra Layout và kích thước
|
||||
|
||||
* [ ] Không thêm mới:
|
||||
|
||||
```
|
||||
- `setFixedWidth()`
|
||||
- `setFixedHeight()`
|
||||
- `setFixedSize()`
|
||||
|
||||
để che hoặc né lỗi layout.
|
||||
```
|
||||
|
||||
* [ ] `stretch factor` và `size policy` được thiết lập rõ ràng khi cần.
|
||||
|
||||
* [ ] Nếu sử dụng `QScrollArea`, phải có:
|
||||
|
||||
```
|
||||
`setWidgetResizable(True)`
|
||||
```
|
||||
|
||||
* [ ] Kiểm tra margin và spacing của các layout lồng nhau.
|
||||
Không được để chúng cộng dồn khiến UI bị lệch hoặc quá rộng.
|
||||
|
||||
* [ ] UI vẫn hiển thị đúng ở:
|
||||
- Kích thước cửa sổ nhỏ nhất.
|
||||
- Cửa sổ maximize.
|
||||
|
||||
* [ ] Nếu bản vá liên quan đến kích thước, phải kiểm tra thêm ở:
|
||||
- Scale 125%.
|
||||
- Scale 150%.
|
||||
|
||||
---
|
||||
|
||||
## D. Kiểm tra Icon và Custom Painting
|
||||
|
||||
* [ ] Icon phải được lấy thông qua:
|
||||
|
||||
```
|
||||
`ui/icons.py::icon`
|
||||
|
||||
Không tự load file icon trực tiếp.
|
||||
```
|
||||
|
||||
* [ ] Trong `paintEvent()`, màu sắc phải lấy từ:
|
||||
|
||||
```
|
||||
`current_palette()`
|
||||
|
||||
Không đọc lại màu trực tiếp từ config.
|
||||
```
|
||||
|
||||
* [ ] Trong các vòng lặp hoặc thao tác cập nhật UI, dùng:
|
||||
|
||||
```
|
||||
`update()`
|
||||
|
||||
Không dùng `repaint()` nếu không thực sự cần thiết.
|
||||
```
|
||||
|
||||
* [ ] `QPainter` được kết thúc đúng cách bằng `end()` khi sử dụng thủ công.
|
||||
|
||||
* [ ] Nền của khu vực custom painting được xử lý/xóa đúng cách, không để lại hình ảnh hoặc pixel cũ.
|
||||
|
||||
---
|
||||
|
||||
## E. Kiểm tra vòng đời UI
|
||||
|
||||
* [ ] UI vẫn hoạt động đúng nếu người dùng:
|
||||
|
||||
```
|
||||
1. Đổi theme trước.
|
||||
2. Sau đó mới mở màn hình được tạo theo kiểu lazy.
|
||||
|
||||
Đặc biệt kiểm tra lỗi **P07**.
|
||||
```
|
||||
|
||||
* [ ] Nếu dùng `setProperty()` để thay đổi style động:
|
||||
phải gọi `unpolish()` và `polish()` khi cần để QSS được áp dụng lại.
|
||||
|
||||
* [ ] Không gọi `connect()` nhiều lần trong một hàm có thể được gọi nhiều lần.
|
||||
|
||||
* [ ] Không tạo signal/slot bị kết nối lặp, gây ra:
|
||||
- Event chạy nhiều lần.
|
||||
- UI cập nhật nhiều lần.
|
||||
- Memory leak hoặc hành vi bất thường.
|
||||
|
||||
---
|
||||
|
||||
## F. Kiểm tra bằng chứng
|
||||
|
||||
* [ ] Đã đối chiếu với screenshot trong:
|
||||
|
||||
```
|
||||
`docs/screens/<slug>-dark.png`
|
||||
|
||||
và
|
||||
|
||||
`docs/screens/<slug>-light.png`
|
||||
```
|
||||
|
||||
* [ ] Nếu bản vá làm thay đổi giao diện, đã xác định screenshot nào cần cập nhật.
|
||||
|
||||
* [ ] Nếu cần cập nhật screenshot trong `docs/screens/`, phải ghi rõ trong phạm vi thay đổi.
|
||||
|
||||
* [ ] Có regression test cho lỗi đã sửa.
|
||||
|
||||
* [ ] Regression test chạy được ở chế độ headless:
|
||||
|
||||
```
|
||||
`QT_QPA_PLATFORM=offscreen`
|
||||
```
|
||||
|
||||
* [ ] Regression test chứng minh được:
|
||||
|
||||
```
|
||||
**Trước khi sửa → FAIL**
|
||||
|
||||
**Sau khi sửa → PASS**
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Kết luận
|
||||
|
||||
Chỉ đánh giá bản vá là **PASS** khi:
|
||||
|
||||
1. Sửa đúng file thực sự chạy.
|
||||
2. Không phá theme hoặc layout hiện có.
|
||||
3. Không dùng workaround để che lỗi.
|
||||
4. Không tạo regression.
|
||||
5. Có regression test phù hợp.
|
||||
6. Có đủ bằng chứng kiểm chứng.
|
||||
7. Các vấn đề liên quan đến security hoặc product decision đã được route đúng agent/người phụ trách.
|
||||
|
||||
+198
-34
@@ -1,48 +1,212 @@
|
||||
# Checklist review bản vá UX (flow)
|
||||
# Checklist review bản vá UX (Flow)
|
||||
|
||||
Dùng bởi `ux-flow-fixer` (bước 8) và `regression-reviewer`.
|
||||
Checklist này được sử dụng bởi:
|
||||
|
||||
## A. Bốn trạng thái
|
||||
* `ux-flow-fixer` — kiểm tra ở bước 8.
|
||||
* `regression-reviewer` — kiểm tra trong quá trình review bản vá.
|
||||
|
||||
Cho mỗi view có dữ liệu bất đồng bộ:
|
||||
Mục tiêu: đảm bảo người dùng luôn biết **hệ thống đang làm gì, chuyện gì xảy ra và cần làm gì tiếp theo**, đồng thời không bị mất dữ liệu.
|
||||
|
||||
- [ ] **Rỗng** — hiện thông điệp có nghĩa, nói được bước tiếp theo (không phải màn trắng).
|
||||
- [ ] **Đang tải** — có dấu hiệu chuyển động; nút bị vô hiệu hoá để chống bấm đúp.
|
||||
- [ ] **Lỗi** — nói *cái gì hỏng* và *làm gì tiếp*; có đường thử lại; không in nguyên exception.
|
||||
- [ ] **Thành công** — có xác nhận rõ; có undo nếu hành động khó đảo ngược.
|
||||
---
|
||||
|
||||
## B. An toàn dữ liệu
|
||||
## A. Kiểm tra 4 trạng thái chính
|
||||
|
||||
- [ ] Ô nhập dài (instruction, composer, node property, AI Edit) không mất nội dung khi
|
||||
chuyển tab / đóng dialog / đổi project.
|
||||
- [ ] Có dirty-state; `closeEvent` chặn khi còn thay đổi chưa lưu.
|
||||
- [ ] Hành động phá huỷ (xoá project/task, ghi đè file) có xác nhận.
|
||||
- [ ] Xác nhận nêu rõ **cái gì** sẽ mất, không phải "Bạn có chắc không?".
|
||||
- [ ] Nút phá huỷ **không** phải default button, **không** nhận Enter.
|
||||
Đối với mỗi màn hình có dữ liệu hoặc thao tác chạy bất đồng bộ, phải kiểm tra đủ 4 trạng thái:
|
||||
|
||||
## C. Phản hồi theo thời gian
|
||||
### 1. Trạng thái Rỗng (Empty)
|
||||
|
||||
- [ ] 100ms-1s: đổi con trỏ hoặc vô hiệu hoá nút.
|
||||
- [ ] 1s-10s: chỉ báo tiến trình rõ ràng.
|
||||
- [ ] \>10s: có tiến trình, **huỷ được**, không chặn phần còn lại của UI.
|
||||
- [ ] Việc nặng chạy ở service `application/`, không ở GUI thread.
|
||||
- [ ] Bấm hai lần không chạy hai lần (kiểm `connect()` trùng — P10).
|
||||
* [ ] Khi chưa có dữ liệu, màn hình phải hiển thị thông báo có ý nghĩa.
|
||||
|
||||
## D. Khám phá được
|
||||
* [ ] Thông báo phải cho người dùng biết **cần làm gì tiếp theo**.
|
||||
|
||||
- [ ] Mọi nút icon-only có tooltip (nav rail thu gọn, toolbar Co4E, top bar).
|
||||
- [ ] Nút bị vô hiệu hoá nói được **lý do** (mẫu đúng: `app.nav.needs_project`).
|
||||
- [ ] Chức năng chính không bị chôn sau menu chuột phải mà không có lối vào khác.
|
||||
- [ ] Thứ tự control khớp thứ tự người dùng thực hiện.
|
||||
* [ ] Không để màn hình trắng khiến người dùng không biết chuyện gì đang xảy ra.
|
||||
|
||||
## E. Nhất quán
|
||||
### 2. Trạng thái Đang tải (Loading)
|
||||
|
||||
- [ ] Cùng một hành động dùng cùng một từ trên mọi màn (không chỗ "Lưu" chỗ "Cập nhật").
|
||||
- [ ] Vị trí nút chính/phụ giống các dialog khác.
|
||||
- [ ] Chuỗi mới đi qua `tr()` với đủ `en`/`ja`/`vi`.
|
||||
* [ ] Có dấu hiệu rõ ràng cho biết hệ thống đang xử lý, ví dụ loading indicator.
|
||||
|
||||
## F. Phạm vi
|
||||
* [ ] Các nút có thể gây chạy lại cùng một thao tác được vô hiệu hóa trong lúc đang xử lý.
|
||||
|
||||
- [ ] Bản vá chọn mức can thiệp thấp nhất (thêm thông tin trước, đổi luồng sau).
|
||||
- [ ] Thay đổi luồng được đánh dấu là **đề xuất** cần Cowork Team duyệt.
|
||||
- [ ] Có test regression cho signal/state, chạy headless.
|
||||
* [ ] Bấm liên tục hoặc bấm đúp không được tạo ra nhiều request/thao tác giống nhau.
|
||||
|
||||
### 3. Trạng thái Lỗi (Error)
|
||||
|
||||
* [ ] Thông báo lỗi phải cho biết:
|
||||
- **Chuyện gì đã xảy ra.**
|
||||
- **Người dùng cần làm gì tiếp theo.**
|
||||
|
||||
* [ ] Có cách để người dùng **thử lại** khi phù hợp.
|
||||
|
||||
* [ ] Không hiển thị nguyên exception, stack trace hoặc thông tin kỹ thuật khó hiểu cho người dùng.
|
||||
|
||||
### 4. Trạng thái Thành công (Success)
|
||||
|
||||
* [ ] Sau khi thao tác thành công, phải có thông báo/xác nhận rõ ràng.
|
||||
|
||||
* [ ] Với thao tác khó hoặc không thể hoàn tác, phải có cơ chế **Undo** nếu phù hợp.
|
||||
|
||||
---
|
||||
|
||||
## B. Kiểm tra an toàn dữ liệu
|
||||
|
||||
* [ ] Các ô nhập nội dung dài, ví dụ:
|
||||
- Instruction
|
||||
- Composer
|
||||
- Node property
|
||||
- AI Edit
|
||||
|
||||
```
|
||||
không được mất nội dung khi:
|
||||
|
||||
- Chuyển tab.
|
||||
- Đóng/mở dialog.
|
||||
- Đổi project.
|
||||
```
|
||||
|
||||
* [ ] Có cơ chế xác định **dirty-state** khi dữ liệu đã thay đổi nhưng chưa lưu.
|
||||
|
||||
* [ ] `closeEvent` phải cảnh báo hoặc chặn việc đóng màn hình khi vẫn còn thay đổi chưa lưu.
|
||||
|
||||
* [ ] Các thao tác có thể làm mất dữ liệu phải có bước xác nhận, ví dụ:
|
||||
- Xóa project.
|
||||
- Xóa task.
|
||||
- Ghi đè file.
|
||||
|
||||
* [ ] Nội dung xác nhận phải nói rõ **dữ liệu nào sẽ bị mất**.
|
||||
|
||||
```
|
||||
Không dùng thông báo quá chung chung như:
|
||||
|
||||
`"Bạn có chắc không?"`
|
||||
```
|
||||
|
||||
* [ ] Nút thực hiện thao tác phá hủy dữ liệu:
|
||||
- Không được đặt làm **default button**.
|
||||
- Không được thực hiện khi người dùng chỉ nhấn `Enter`.
|
||||
|
||||
---
|
||||
|
||||
## C. Kiểm tra phản hồi theo thời gian
|
||||
|
||||
Phản hồi của UI phải phù hợp với thời gian xử lý:
|
||||
|
||||
* [ ] **100ms – 1s:**
|
||||
Có thể thay đổi con trỏ hoặc vô hiệu hóa nút để người dùng biết thao tác đã được nhận.
|
||||
|
||||
* [ ] **1s – 10s:**
|
||||
Hiển thị chỉ báo tiến trình rõ ràng.
|
||||
|
||||
* [ ] **Trên 10s:**
|
||||
- Có chỉ báo tiến trình.
|
||||
- Người dùng có thể **hủy thao tác** khi phù hợp.
|
||||
- Không khóa toàn bộ UI nếu không cần thiết.
|
||||
|
||||
* [ ] Các tác vụ xử lý nặng không được chạy trực tiếp trên GUI thread.
|
||||
Phải chuyển phần xử lý nặng sang service trong `application/`.
|
||||
|
||||
* [ ] Một thao tác không được chạy hai lần khi người dùng bấm liên tục hoặc bấm đúp.
|
||||
|
||||
* [ ] Kiểm tra các `connect()` có bị đăng ký nhiều lần hay không, đặc biệt với lỗi **P10**.
|
||||
|
||||
---
|
||||
|
||||
## D. Kiểm tra khả năng khám phá chức năng
|
||||
|
||||
Người dùng phải dễ dàng biết **nút này làm gì và tìm chức năng ở đâu**.
|
||||
|
||||
* [ ] Tất cả các nút chỉ có icon (`icon-only`) đều có tooltip.
|
||||
|
||||
```
|
||||
Đặc biệt kiểm tra:
|
||||
- Nav rail khi thu gọn.
|
||||
- Toolbar Co4E.
|
||||
- Top bar.
|
||||
```
|
||||
|
||||
* [ ] Nút đang bị vô hiệu hóa phải cho người dùng biết **tại sao không thể bấm**.
|
||||
|
||||
```
|
||||
Ví dụ sử dụng key:
|
||||
|
||||
`app.nav.needs_project`
|
||||
```
|
||||
|
||||
* [ ] Chức năng chính không được chỉ nằm trong menu chuột phải nếu không có cách truy cập khác.
|
||||
|
||||
* [ ] Thứ tự các control trên màn hình phải phù hợp với **thứ tự người dùng thực hiện công việc**.
|
||||
|
||||
---
|
||||
|
||||
## E. Kiểm tra tính nhất quán
|
||||
|
||||
* [ ] Một hành động phải sử dụng **cùng một thuật ngữ** trên toàn bộ ứng dụng.
|
||||
|
||||
```
|
||||
Ví dụ:
|
||||
|
||||
Nếu dùng `"Lưu"` ở một màn hình thì không nên dùng `"Cập nhật"` ở màn hình khác cho cùng một hành động.
|
||||
```
|
||||
|
||||
* [ ] Vị trí của nút chính và nút phụ phải nhất quán với các dialog khác.
|
||||
|
||||
* [ ] Chuỗi text mới phải sử dụng `tr()`.
|
||||
|
||||
* [ ] Chuỗi mới phải có bản dịch đầy đủ cho:
|
||||
|
||||
```
|
||||
- `en`
|
||||
- `ja`
|
||||
- `vi`
|
||||
```
|
||||
|
||||
* [ ] Không hardcode text mới trực tiếp trong UI code nếu text đó cần hỗ trợ đa ngôn ngữ.
|
||||
|
||||
---
|
||||
|
||||
## F. Kiểm tra phạm vi thay đổi
|
||||
|
||||
* [ ] Bản vá sử dụng **cách can thiệp nhỏ nhất có thể**.
|
||||
|
||||
```
|
||||
Ưu tiên:
|
||||
|
||||
**Bổ sung thông tin → cải thiện feedback → điều chỉnh control → thay đổi flow**
|
||||
|
||||
Không thay đổi cả luồng khi chỉ cần bổ sung thông tin.
|
||||
```
|
||||
|
||||
* [ ] Nếu cần thay đổi flow của người dùng, thay đổi đó phải được ghi rõ là:
|
||||
|
||||
```
|
||||
**ĐỀ XUẤT**
|
||||
```
|
||||
|
||||
* [ ] Agent không tự quyết định thay đổi product/UX quan trọng.
|
||||
|
||||
* [ ] Các thay đổi flow cần được **Cowork Team xem xét và phê duyệt**.
|
||||
|
||||
* [ ] Có regression test kiểm tra:
|
||||
- Signal.
|
||||
- State.
|
||||
- Chuyển trạng thái.
|
||||
- Hành vi của user flow liên quan.
|
||||
|
||||
* [ ] Regression test chạy được ở chế độ headless:
|
||||
|
||||
```
|
||||
`QT_QPA_PLATFORM=offscreen`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Kết luận
|
||||
|
||||
Bản vá UX chỉ nên được đánh giá là đạt khi:
|
||||
|
||||
1. Người dùng biết rõ trạng thái hiện tại của hệ thống.
|
||||
2. Không có nguy cơ mất dữ liệu ngoài ý muốn.
|
||||
3. UI phản hồi phù hợp với thời gian xử lý.
|
||||
4. Chức năng dễ tìm và dễ hiểu.
|
||||
5. Cách gọi tên và cách bố trí control nhất quán.
|
||||
6. Thay đổi flow lớn đã được đánh dấu để Cowork Team phê duyệt.
|
||||
7. Có regression test chứng minh flow vẫn hoạt động đúng.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
description: Điều phối fix bug UI/UX — chấm tier T0/T1/T2/T3 rồi chạy đúng số agent cần thiết
|
||||
argument-hint: <phản ánh của người dùng, dán nguyên văn>
|
||||
---
|
||||
|
||||
Bạn đang chạy với vai **`fix-dispatcher`** — agent hub điều phối của bộ agent trong `agent/`.
|
||||
|
||||
Nạp theo đúng thứ tự rồi làm theo:
|
||||
|
||||
1. @agent/system/guardrail.md
|
||||
2. @agent/system/security.md
|
||||
3. @agent/system/response_policy.md
|
||||
4. @agent/roles/0_fix_dispatcher.md
|
||||
5. @agent/output/dispatch_plan.md
|
||||
|
||||
Phản ánh cần xử lý:
|
||||
|
||||
$ARGUMENTS
|
||||
|
||||
Trình tự bắt buộc:
|
||||
|
||||
- Tách defect (Bước 1) → xét override bảo mật (Bước 2) → chấm tier (Bước 3).
|
||||
- Trần chấm điểm: **≤ 5 lệnh đọc/grep, 0 subagent**. Hết mà chưa chấm được → T2.
|
||||
- In `dispatch_plan` (≤ 30 dòng phần người đọc) **trước** khi chạy bất kỳ agent nào.
|
||||
- Rồi chạy đúng lane ở bảng Bước 4:
|
||||
- **T0** → tự sửa, sau đó chạy đủ 4 cổng máy ở §4.1 và dán output thật.
|
||||
- **T1** → gọi `fix-implementer`, rồi tự review bằng @agent/checklist/ui_review.md.
|
||||
- **T2** → specialist → `fix-implementer` → `regression-reviewer`.
|
||||
- **T3** → `ui-bug-triage` → specialist → `fix-implementer` → `regression-reviewer`.
|
||||
- **T3-SEC** → `security-defect-fixer`, dừng chờ Cowork Team trả 4 câu chính sách.
|
||||
- Các `defect_id` độc lập gọi song song trong **một** message. Các bước trong cùng một
|
||||
`defect_id` chạy tuần tự.
|
||||
- Escalate theo Bước 5. Tier chỉ đi lên. Không tự merge (`guardrail.md` G9).
|
||||
+379
-52
@@ -1,71 +1,398 @@
|
||||
# i18n — luật chuỗi hiển thị
|
||||
# i18n — Quy tắc xử lý chuỗi hiển thị
|
||||
|
||||
Nguồn: docstring `i18n/__init__.py`.
|
||||
**Nguồn:** docstring `i18n/__init__.py`
|
||||
|
||||
---
|
||||
|
||||
## 1. Ba ngôn ngữ, mặc định tiếng Việt
|
||||
## 1. Ngôn ngữ được hỗ trợ
|
||||
|
||||
Cowork Local hỗ trợ 3 ngôn ngữ:
|
||||
|
||||
```python
|
||||
LANGUAGES = {"en": "English", "ja": "日本語", "vi": "Tiếng Việt"}
|
||||
LANGUAGE_SHORT = {"en": "EN", "ja": "JP", "vi": "VN"} # switcher gọn ở top bar
|
||||
LANGUAGES = {
|
||||
"en": "English",
|
||||
"ja": "日本語",
|
||||
"vi": "Tiếng Việt",
|
||||
}
|
||||
|
||||
LANGUAGE_SHORT = {
|
||||
"en": "EN",
|
||||
"ja": "JP",
|
||||
"vi": "VN",
|
||||
}
|
||||
|
||||
DEFAULT_LANGUAGE = "vi"
|
||||
```
|
||||
|
||||
`tr(key, **kwargs)` trả chuỗi theo ngôn ngữ hiện tại, fallback lần lượt:
|
||||
**ngôn ngữ hiện tại → `en` → chính cái key**. Nghĩa là thiếu entry thì UI hiện ra
|
||||
`workspace.tab_folder` chứ không crash — nếu người dùng chụp màn hình có chuỗi dạng
|
||||
`a.b_c` thì đó chính là triệu chứng thiếu key.
|
||||
Ngôn ngữ mặc định là **Tiếng Việt (`vi`)**.
|
||||
|
||||
`.format(**kwargs)` được áp dụng khi có placeholder: `tr("composer.attachments", n=3)`.
|
||||
### Hàm `tr()`
|
||||
|
||||
## 2. Widget nào phải đăng ký callback
|
||||
Sử dụng:
|
||||
|
||||
| Loại widget | Cách xử lý |
|
||||
|---|---|
|
||||
| **Sống lâu** — chrome cửa sổ chính, tab, sidebar, composer | Đăng ký `on_language_changed(cb)`; `cb` áp lại `tr()` cho chính widget đó. Callback chạy **ngay một lần** và mỗi lần đổi ngôn ngữ |
|
||||
| **Tạm thời** — Settings, Skills, Flow, Permission dialog | Dựng lại từ đầu mỗi lần mở, nên chỉ cần gọi `tr()` lúc construct, **không** đăng ký |
|
||||
|
||||
Quy ước đặt tên hàm callback trong repo: `_retranslate()` / `_apply_i18n()` — xem
|
||||
`ui/workspace_tab.py:484` trở đi làm mẫu chuẩn.
|
||||
|
||||
**Bug điển hình:** "Đổi ngôn ngữ nhưng nhãn X không đổi" → widget sống lâu mà quên đăng ký,
|
||||
hoặc có đăng ký nhưng callback bỏ sót đúng nhãn đó. Không sửa bằng cách gọi `tr()` lại ở
|
||||
chỗ khác — sửa trong callback.
|
||||
|
||||
## 3. File từ điển
|
||||
|
||||
`i18n/` chia theo màn hình, không phải một file khổng lồ:
|
||||
|
||||
```text
|
||||
i18n/login_dialog.py i18n/sidebar.py i18n/composer.py
|
||||
i18n/cowork_tab.py i18n/settings_dialog.py i18n/skills_dialog.py
|
||||
i18n/libreoffice_view.py i18n/agents_admin_tab.py i18n/monitoring_overview.py
|
||||
i18n/hint.py
|
||||
```python
|
||||
tr(key, **kwargs)
|
||||
```
|
||||
|
||||
Mỗi file export dict `key -> {"en":..., "ja":..., "vi":...}`, được `i18n/__init__.py`
|
||||
import và gộp lại. Thêm key mới:
|
||||
để lấy chuỗi hiển thị theo ngôn ngữ hiện tại.
|
||||
|
||||
1. Chọn đúng file theo màn hình (không nhét đại vào `login_dialog.py` chỉ vì nó lớn nhất).
|
||||
2. Điền **đủ 3 ngôn ngữ**. Thiếu `ja` là lỗi hay gặp nhất và chỉ lộ ra khi khách Nhật dùng.
|
||||
3. Đặt key theo `<màn>.<thành_phần>` — `workspace.tab_folder`, `app.nav.recents`.
|
||||
Thứ tự fallback:
|
||||
|
||||
## 4. Rủi ro riêng của tiếng Nhật và tiếng Việt
|
||||
```text
|
||||
Ngôn ngữ hiện tại → English (en) → chính key
|
||||
```
|
||||
|
||||
| Rủi ro | Triệu chứng | Cách xử lý |
|
||||
|---|---|---|
|
||||
| Tiếng Nhật ngắn hơn, tiếng Việt dài hơn tiếng Anh | Nút vừa với `EN`, tràn với `VI`; label bị `...` với `JA` | Không `setFixedWidth` theo chuỗi tiếng Anh. Dùng `sizeHint` + `minimumWidth`, hoặc cho phép wrap |
|
||||
| Dấu tiếng Việt bị cắt phần trên/dưới | `Ắ`, `ộ` mất dấu ở nhãn cao cố định | Không đặt `setFixedHeight` cho label theo pixel; để layout tự tính |
|
||||
| Font mặc định thiếu glyph Nhật | Ô vuông tofu `□□□` trên máy chưa cài font | Kiểm tra `_FONT` trong `theme/palettes.py`, khai báo fallback |
|
||||
| Sắp xếp / so sánh chuỗi | Danh sách project sắp sai với tên có dấu | Dùng `locale`-aware sort, không `sorted()` thô |
|
||||
| Chiều dài chuỗi tính bằng ký tự ≠ chiều rộng hiển thị | Elide sai với chữ Nhật | Đo bằng `QFontMetrics.horizontalAdvance`, không `len()` |
|
||||
Ví dụ, nếu đang dùng tiếng Nhật nhưng key `workspace.tab_folder` chưa có bản dịch tiếng Nhật:
|
||||
|
||||
## 5. Checklist sửa bug i18n
|
||||
```text
|
||||
JA → EN → workspace.tab_folder
|
||||
```
|
||||
|
||||
- [ ] Key mới có đủ `en` / `ja` / `vi`?
|
||||
- [ ] Đã thử đổi qua cả 3 ngôn ngữ **trong lúc app đang chạy** (không phải restart)?
|
||||
- [ ] Widget sống lâu đã đăng ký `on_language_changed`?
|
||||
- [ ] Không còn chuỗi hardcode nào trong bản vá?
|
||||
- [ ] Layout còn đúng với chuỗi dài nhất trong 3 ngôn ngữ?
|
||||
- [ ] Không dùng `len()` để đo bề rộng chữ?
|
||||
Ứng dụng **không được crash** chỉ vì thiếu bản dịch.
|
||||
|
||||
Nếu UI hiển thị một chuỗi dạng:
|
||||
|
||||
```text
|
||||
workspace.tab_folder
|
||||
```
|
||||
|
||||
thì đây là dấu hiệu cho thấy **đang thiếu translation key**.
|
||||
|
||||
### Placeholder
|
||||
|
||||
Nếu chuỗi có placeholder, truyền giá trị thông qua `kwargs`:
|
||||
|
||||
```python
|
||||
tr("composer.attachments", n=3)
|
||||
```
|
||||
|
||||
Việc `.format(**kwargs)` được thực hiện sau khi lấy chuỗi dịch.
|
||||
|
||||
---
|
||||
|
||||
## 2. Widget nào phải cập nhật khi đổi ngôn ngữ?
|
||||
|
||||
Có 2 loại widget:
|
||||
|
||||
| Loại widget | Cách xử lý |
|
||||
| ------------------- | ----------------------------------------------------- |
|
||||
| **Widget sống lâu** | `bind_*` cho chuỗi tĩnh; `on_language_changed(cb)` cho phần còn lại |
|
||||
| **Widget tạm thời** | Không cần đăng ký callback; gọi `tr()` khi tạo widget |
|
||||
|
||||
### 2.0. `bind_*` — cách mặc định cho chuỗi tĩnh
|
||||
|
||||
`w.setToolTip(tr("k"))` chỉ đúng ở đúng thời điểm chạy dòng đó. `bind_*` gộp "gán ngay"
|
||||
và "gán lại sau mỗi lần đổi ngôn ngữ" vào một lời gọi, dùng `weakref` nên không giữ widget
|
||||
sống thêm và tự dọn khi widget bị xoá:
|
||||
|
||||
```python
|
||||
from ...i18n import bind_dynamic, bind_items, bind_placeholder, bind_text, bind_tip
|
||||
|
||||
self.save_btn = bind_text(QPushButton(), "co4e.save") # thay QPushButton(tr(...))
|
||||
bind_tip(self.save_btn, "co4e.tt_save") # thay .setToolTip(tr(...))
|
||||
bind_placeholder(self.chat_input, "co4e.chat_placeholder")
|
||||
bind_items(self.perm_combo, [f"co4e.perm.{p}" for p in PERMISSION_PRESETS])
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_label"), self.label_edit) # KHÔNG addRow(tr(...))
|
||||
```
|
||||
|
||||
Ba luật:
|
||||
|
||||
1. **Chuỗi tĩnh → `bind_*`.** Đổi tại chỗ, **không thêm dòng** — quan trọng với file đã
|
||||
sát trần Gate S hoặc đang bị bánh cóc `LEGACY_ALLOWANCE` chốt (`quality_gates.md` §4).
|
||||
2. **Chữ phụ thuộc trạng thái → `bind_dynamic(w, setter, fn)`**, với `fn` đọc trạng thái:
|
||||
nút Chạy ⇄ Dừng, tooltip Thu gọn ⇄ Mở rộng, nhãn có số đếm. Các nhánh xử lý trạng thái
|
||||
**vẫn** gọi setter trực tiếp như cũ để phản hồi ngay khi bấm; `bind_dynamic` chỉ lo lúc
|
||||
đổi ngôn ngữ. Bind cứng một nhãn động sẽ **xoá** trạng thái khi người dùng đổi ngôn ngữ
|
||||
giữa lúc đang chạy.
|
||||
3. **Chữ là DỮ LIỆU thì không bind.** Tên agent, tên project, tên nhà cung cấp trong
|
||||
`config.PROVIDER_LABELS` — dịch danh tính là sai.
|
||||
|
||||
`QFormLayout.addRow(tr(...), w)` và `_add_section(outer, tr(...))` là hai bẫy hay gặp:
|
||||
chúng tự dựng `QLabel` bên trong, không giữ tham chiếu nào để áp lại. Truyền
|
||||
`bind_text(QLabel(), key)` hoặc truyền **khoá** thay vì chuỗi đã dịch.
|
||||
|
||||
### 2.0b. Nút do CHÍNH Qt vẽ chữ — `ui/dialog_buttons.py`
|
||||
|
||||
`tr()` không với tới được nhãn nút của mấy widget dựng sẵn: Qt lấy chữ từ bảng dịch của
|
||||
riêng nó, mà ứng dụng không cài `QTranslator` nào (bản PySide6 đang dùng cũng không đóng
|
||||
gói file `qtbase_*.qm` nào để cài). Kết quả: **luôn là tiếng Anh ở cả ba ngôn ngữ.**
|
||||
|
||||
| Không dùng | Dùng thay |
|
||||
| --- | --- |
|
||||
| `QDialogButtonBox(Save \| Cancel)` | `dialog_buttons(Save \| Cancel)` |
|
||||
| `QMessageBox.question(...) == QMessageBox.Yes` | `confirm(parent, title, body)` |
|
||||
| `QInputDialog.getText / getMultiLineText / getItem` | `ask_text` / `ask_multiline` / `ask_item` |
|
||||
|
||||
Muốn một nút mang chữ riêng thì truyền khoá vào `dialog_buttons`, **không** `setText(tr(...))`
|
||||
sau khi dựng — lần đổi ngôn ngữ kế tiếp, ràng buộc sẽ áp lại khoá mặc định và xoá mất chữ đó:
|
||||
|
||||
```python
|
||||
self.buttons = dialog_buttons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
|
||||
ok="schedtask.ai_confirm")
|
||||
```
|
||||
|
||||
Ba cổng trong `tests/ui/test_i18n_khong_hardcode_chu.py` canh việc này.
|
||||
|
||||
### 2.1. Widget sống lâu
|
||||
|
||||
Ví dụ:
|
||||
|
||||
* Chrome của cửa sổ chính.
|
||||
* Tab.
|
||||
* Sidebar.
|
||||
* Composer.
|
||||
|
||||
Các widget này vẫn tồn tại khi người dùng đổi ngôn ngữ.
|
||||
|
||||
Vì vậy phải:
|
||||
|
||||
1. Đăng ký `on_language_changed(cb)`.
|
||||
2. Trong callback, gọi lại `tr()` cho các text của chính widget.
|
||||
3. Callback phải chạy:
|
||||
|
||||
* Một lần ngay khi đăng ký.
|
||||
* Mỗi lần người dùng đổi ngôn ngữ.
|
||||
|
||||
Tên callback được sử dụng trong repo:
|
||||
|
||||
```text
|
||||
_retranslate()
|
||||
_apply_i18n()
|
||||
```
|
||||
|
||||
Có thể tham khảo implementation chuẩn từ:
|
||||
|
||||
```text
|
||||
ui/workspace_tab.py:484
|
||||
```
|
||||
|
||||
### 2.2. Widget tạm thời
|
||||
|
||||
Ví dụ:
|
||||
|
||||
* Settings dialog.
|
||||
* Skills dialog.
|
||||
* Flow dialog.
|
||||
* Permission dialog.
|
||||
|
||||
Các dialog này được tạo lại từ đầu mỗi lần mở.
|
||||
|
||||
Vì vậy chỉ cần gọi `tr()` khi construct widget.
|
||||
|
||||
**Không cần đăng ký `on_language_changed()`**.
|
||||
|
||||
### Bug thường gặp
|
||||
|
||||
Triệu chứng:
|
||||
|
||||
> Đổi ngôn ngữ nhưng một label/nút vẫn giữ ngôn ngữ cũ.
|
||||
|
||||
Nguyên nhân thường là:
|
||||
|
||||
* Widget sống lâu nhưng chưa đăng ký `on_language_changed()`.
|
||||
* Callback có đăng ký nhưng quên cập nhật label đó.
|
||||
|
||||
**Cách sửa đúng:**
|
||||
|
||||
`bind_*` tại chính dòng đang gán (mục 2.0), hoặc — nếu chữ phụ thuộc trạng thái/dữ liệu —
|
||||
sửa trong `_retranslate()` / `_apply_i18n()` của chính widget.
|
||||
|
||||
**Không** giải quyết bằng cách gọi `tr()` ở một nơi khác chỉ để ép label thay đổi.
|
||||
|
||||
### Cách TÌM ra hết các chỗ bị lỗi
|
||||
|
||||
Đừng grep chuỗi tiếng Việt trong source: lượt audit tháng 9/2026 grep ra 962 dòng mà
|
||||
**không dòng nào** là lỗi thật (toàn docstring), trong khi 84 lỗi thật lại không xuất hiện
|
||||
— vì chúng đi qua `tr()` đúng cách, chỉ thiếu người áp lại.
|
||||
|
||||
Phép đo đúng nằm ở `tests/ui/test_i18n_khong_con_chu_cu.py`: dựng `MainWindow` thật, thay
|
||||
`tr()` bằng chuỗi **mốc**, gọi `set_language()`, rồi tìm chỗ **không** mang mốc. Hai chi
|
||||
tiết mà bản kiểm ngây thơ sẽ sai:
|
||||
|
||||
* `from ...i18n import tr` copy tham chiếu vào namespace từng module → phải thay `tr` ở
|
||||
**mọi** module đã import, không chỉ `i18n.tr`;
|
||||
* lưới vẽ lại bằng `deleteLater()` để lại widget cũ còn sống → không
|
||||
`sendPostedEvents(DeferredDelete)` thì báo oan hàng chục widget bóng ma (lượt audit đầu
|
||||
báo 84 lỗi, trong đó 65 là bóng ma và widget bị `id()` cấp lại làm cắt vòng quét).
|
||||
|
||||
Chạy: `QT_QPA_PLATFORM=offscreen pytest tests/ui/test_i18n_khong_con_chu_cu.py -q`
|
||||
|
||||
---
|
||||
|
||||
## 3. Tổ chức file translation
|
||||
|
||||
Thư mục `i18n/` được chia theo **màn hình/chức năng**, không gom tất cả translation vào một file lớn.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
i18n/
|
||||
├── login_dialog.py
|
||||
├── sidebar.py
|
||||
├── composer.py
|
||||
├── cowork_tab.py
|
||||
├── settings_dialog.py
|
||||
├── skills_dialog.py
|
||||
├── libreoffice_view.py
|
||||
├── agents_admin_tab.py
|
||||
├── monitoring_overview.py
|
||||
└── hint.py
|
||||
```
|
||||
|
||||
Mỗi file export một dictionary có dạng:
|
||||
|
||||
```text
|
||||
key → {
|
||||
"en": "...",
|
||||
"ja": "...",
|
||||
"vi": "..."
|
||||
}
|
||||
```
|
||||
|
||||
`i18n/__init__.py` sẽ import và gộp các dictionary này.
|
||||
|
||||
### Khi thêm key mới
|
||||
|
||||
Thực hiện theo 3 bước:
|
||||
|
||||
#### Bước 1 — Chọn đúng file
|
||||
|
||||
Đưa key vào file tương ứng với màn hình/chức năng.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
workspace.* → file liên quan đến workspace
|
||||
composer.* → composer.py
|
||||
settings.* → settings_dialog.py
|
||||
```
|
||||
|
||||
**Không** đưa key vào `login_dialog.py` chỉ vì file đó đang có nhiều key nhất.
|
||||
|
||||
#### Bước 2 — Điền đủ 3 ngôn ngữ
|
||||
|
||||
Mỗi key mới phải có:
|
||||
|
||||
```text
|
||||
en
|
||||
ja
|
||||
vi
|
||||
```
|
||||
|
||||
Thiếu `ja` là lỗi đặc biệt cần chú ý vì có thể chỉ được phát hiện khi khách hàng Nhật sử dụng.
|
||||
|
||||
#### Bước 3 — Đặt tên key nhất quán
|
||||
|
||||
Format khuyến nghị:
|
||||
|
||||
```text
|
||||
<màn hình>.<thành phần>
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
workspace.tab_folder
|
||||
app.nav.recents
|
||||
```
|
||||
|
||||
Tên key phải mô tả rõ nó được dùng ở đâu và cho thành phần nào.
|
||||
|
||||
---
|
||||
|
||||
## 4. Các rủi ro thường gặp với tiếng Nhật và tiếng Việt
|
||||
|
||||
| Vấn đề | Triệu chứng | Cách xử lý |
|
||||
| ---------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| Độ dài chuỗi khác nhau | EN vừa nút nhưng VI bị tràn hoặc JA bị `...` | Không đặt width cố định dựa trên tiếng Anh. Dùng `sizeHint()`, `minimumWidth` hoặc cho phép wrap |
|
||||
| Dấu tiếng Việt bị cắt | Các chữ như `Ắ`, `ộ` bị mất dấu | Không dùng `setFixedHeight()` cho label. Để layout tự tính chiều cao |
|
||||
| Thiếu font/glyph tiếng Nhật | Xuất hiện `□□□` | Kiểm tra `_FONT` trong `theme/palettes.py` và khai báo font fallback |
|
||||
| Sắp xếp chuỗi | Project có dấu được sắp xếp không đúng | Dùng locale-aware sorting, không dùng `sorted()` một cách máy móc |
|
||||
| Số ký tự không phản ánh chiều rộng | Text bị elide sai, đặc biệt với tiếng Nhật | Dùng `QFontMetrics.horizontalAdvance()`, không dùng `len()` để đo chiều rộng |
|
||||
|
||||
### Đặc biệt lưu ý về độ dài text
|
||||
|
||||
Không được giả định:
|
||||
|
||||
```text
|
||||
số ký tự = chiều rộng hiển thị
|
||||
```
|
||||
|
||||
Ví dụ hai chuỗi có cùng số ký tự nhưng có thể có chiều rộng hiển thị khác nhau.
|
||||
|
||||
Khi cần đo text trên UI, dùng:
|
||||
|
||||
```python
|
||||
QFontMetrics.horizontalAdvance(...)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Checklist khi sửa lỗi i18n
|
||||
|
||||
Trước khi hoàn thành bản vá i18n, phải kiểm tra:
|
||||
|
||||
* [ ] Key mới có đủ **`en` / `ja` / `vi`**?
|
||||
|
||||
* [ ] Đã chuyển qua cả 3 ngôn ngữ **ngay trong lúc app đang chạy** chưa?
|
||||
|
||||
```
|
||||
Không chỉ restart app rồi kiểm tra.
|
||||
```
|
||||
|
||||
* [ ] `ja` có **khác** `en` không? Bằng nhau nghĩa là chưa dịch — trừ tên thương hiệu /
|
||||
ký hiệu, và khi đó phải khai vào `KHOA_KHONG_CAN_DICH` kèm lý do.
|
||||
|
||||
* [ ] Chuỗi tĩnh đã dùng `bind_text` / `bind_tip` / `bind_placeholder` / `bind_items`
|
||||
thay cho `setX(tr(...))` một lần?
|
||||
|
||||
* [ ] Chữ phụ thuộc trạng thái đã dùng `bind_dynamic` (không bind cứng, kẻo mất trạng thái)?
|
||||
|
||||
* [ ] Nếu widget sống lâu và còn phần không bind được, đã đăng ký:
|
||||
|
||||
```
|
||||
`on_language_changed(...)`
|
||||
```
|
||||
|
||||
* [ ] Callback `_retranslate()` hoặc `_apply_i18n()` đã cập nhật **tất cả text liên quan**?
|
||||
|
||||
* [ ] Đã chạy `pytest tests/ui/test_i18n_khong_con_chu_cu.py -q` và nó **xanh**?
|
||||
|
||||
* [ ] Không còn chuỗi hardcode mới trong bản vá?
|
||||
|
||||
* [ ] Nút hộp thoại đi qua `ui/dialog_buttons.py` (mục 2.0b), không dựng
|
||||
`QDialogButtonBox` / `QMessageBox.question` / `QInputDialog.get*` trực tiếp?
|
||||
|
||||
* [ ] Layout vẫn đúng với **chuỗi dài nhất** trong 3 ngôn ngữ?
|
||||
|
||||
* [ ] Không dùng `len()` để tính chiều rộng text?
|
||||
|
||||
* [ ] Nếu có thay đổi UI, đã kiểm tra cả Dark Mode và Light Mode?
|
||||
|
||||
---
|
||||
|
||||
## 6. Nguyên tắc quan trọng
|
||||
|
||||
Khi sửa lỗi i18n, **không sửa triệu chứng ở nơi khác**.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Đổi ngôn ngữ
|
||||
↓
|
||||
Label X không thay đổi
|
||||
↓
|
||||
Kiểm tra widget X
|
||||
↓
|
||||
Widget sống lâu?
|
||||
↓
|
||||
Có on_language_changed()?
|
||||
↓
|
||||
_retranslate() có cập nhật Label X?
|
||||
```
|
||||
|
||||
Nếu thiếu callback hoặc callback bỏ sót label, hãy sửa **đúng callback của widget đó**.
|
||||
|
||||
Không thêm các lệnh `tr()` rải rác ở nơi khác chỉ để làm cho UI thay đổi.
|
||||
|
||||
Mục tiêu là đảm bảo cơ chế i18n hoạt động đúng và nhất quán cho toàn bộ ứng dụng.
|
||||
|
||||
+443
-58
@@ -1,95 +1,480 @@
|
||||
# Screen Map — dịch lời người dùng thành file:line
|
||||
# Screen Map — Tra mô tả của người dùng về đúng file:line
|
||||
|
||||
Người dùng báo lỗi bằng lời ("cái bảng bên phải màn thống kê"). File này để agent
|
||||
Triage quy nó về đúng widget.
|
||||
Người dùng thường mô tả lỗi bằng ngôn ngữ tự nhiên, ví dụ:
|
||||
|
||||
> "Cái bảng bên phải của màn thống kê bị lệch."
|
||||
|
||||
Agent phải dùng file này để chuyển mô tả đó thành:
|
||||
|
||||
```text
|
||||
Màn hình → Tab/View → Widget → File → Line → Control
|
||||
```
|
||||
|
||||
Mục tiêu là tìm được **đúng widget và đúng vị trí code**, thay vì đoán file dựa trên tên.
|
||||
|
||||
---
|
||||
|
||||
## 1. Nav rail — bốn màn chính
|
||||
## 1. Bốn màn hình chính trong Nav Rail
|
||||
|
||||
Định nghĩa tại `presentation/shell/main_window.py:151` (`_nav_defs`), thứ tự = page index:
|
||||
Các màn hình chính được định nghĩa tại:
|
||||
|
||||
| Row | i18n key | Icon | Dựng | Widget |
|
||||
|---|---|---|---|---|
|
||||
| 0 | `app.tab.dashboard` | `dashboard` | lười | `presentation/dashboard/dashboard_tab.py::DashboardTab` |
|
||||
| 1 | `app.tab.schedule` | `schedule` | lười | `presentation/scheduling/schedule_task_tab.py::ScheduleTaskTab` |
|
||||
| 2 | `app.tab.workspace` | `workspaces` | **ngay** (màn HOME) | `ui/workspace_tab.py::WorkspaceTab` |
|
||||
| 3 | `app.tab.monitoring` | `monitoring` | lười | `ui/monitoring_tab.py::MonitoringTab` |
|
||||
```text
|
||||
presentation/shell/main_window.py:151
|
||||
```
|
||||
|
||||
App mở lên là ở **Workspace ▸ Project**.
|
||||
Danh sách nằm trong `_nav_defs`.
|
||||
|
||||
## 2. Sub-tab của Workspace
|
||||
**Thứ tự trong bảng chính là page index.**
|
||||
|
||||
`ui/workspace_tab.py:214-245`:
|
||||
| Row | i18n key | Icon | Cách tạo | Widget |
|
||||
| --: | -------------------- | ------------ | --------------- | --------------------------------------------------------------- |
|
||||
| 0 | `app.tab.dashboard` | `dashboard` | Lazy | `presentation/dashboard/dashboard_tab.py::DashboardTab` |
|
||||
| 1 | `app.tab.schedule` | `schedule` | Lazy | `presentation/scheduling/schedule_task_tab.py::ScheduleTaskTab` |
|
||||
| 2 | `app.tab.workspace` | `workspaces` | Ngay khi mở app | `ui/workspace_tab.py::WorkspaceTab` |
|
||||
| 3 | `app.tab.monitoring` | `monitoring` | Lazy | `ui/monitoring_tab.py::MonitoringTab` |
|
||||
|
||||
| Tab | i18n key | Widget |
|
||||
|---|---|---|
|
||||
| Project | `workspace.tab_project` | `_build_project_tab()` trong chính file đó |
|
||||
| Cowork | `workspace.tab_cowork` | `ui/cowork_tab.py` |
|
||||
| Co4E | `workspace.tab_co4e` | `ui/co4e_tab.py` → `presentation/co4e/` |
|
||||
| Folder | `workspace.tab_folder` | `presentation/folder/folder_tab.py` |
|
||||
| GraphRAG | `workspace.tab_graphrag` | `presentation/graph/structure_graph_view.py` |
|
||||
### Màn hình mặc định
|
||||
|
||||
Monitoring **giữ tab strip riêng** với 8 sub-view (tổng quan, trạng thái agent, công cụ,
|
||||
nhật ký hành động, lịch sử gọi MCP, sự kiện bảo mật, agents admin, icon). Workspace là màn
|
||||
duy nhất giấu tab strip đi.
|
||||
Khi mở app, người dùng bắt đầu tại:
|
||||
|
||||
## 3. Thành phần luôn nổi trên mọi màn
|
||||
```text
|
||||
Workspace → Project
|
||||
```
|
||||
|
||||
| Thành phần | File | Triệu chứng người dùng hay mô tả |
|
||||
|---|---|---|
|
||||
| Nav rail trái, nút thu gọn | `presentation/shell/nav_rail.py` | "menu bị co lại", "không thấy tên project" |
|
||||
| Top bar (theme, ngôn ngữ) | `presentation/shell/top_bar.py` | "đổi giao diện không ăn" |
|
||||
| Toast góc trên trái | `presentation/shell/toast.py` | "thông báo xong việc che mất nút" |
|
||||
| Help agent nổi góc dưới phải | `ui/help_agent_widget.py` | "con robot che nút gửi" |
|
||||
| Status bar dưới cùng | `main_window.statusBar()` | "dòng chữ dưới đáy không đổi" |
|
||||
### Lưu ý về Lazy
|
||||
|
||||
## 4. Dialog
|
||||
`Dashboard`, `Schedule` và `Monitoring` được tạo **lazy** — chỉ được dựng khi người dùng mở màn hình.
|
||||
|
||||
`ui/`: `login_dialog.py`, `permission_dialog.py`, `settings_dialog.py`, `skills_dialog.py`,
|
||||
`task_editor_dialog.py`, `file_edit_dialog.py`, `flow_dialog.py`, `mcp_servers_dialog.py`,
|
||||
`co4e_agent_dialog.py`, `ext_connector_dialog.py`.
|
||||
Vì vậy, khi điều tra lỗi liên quan đến các màn hình này, phải kiểm tra cả **thời điểm widget được tạo** và **vòng đời của widget**.
|
||||
|
||||
## 5. 🔎 Hai file tra cứu bắt buộc dùng
|
||||
---
|
||||
|
||||
### `docs/screens/manifest.json`
|
||||
## 2. Các tab bên trong Workspace
|
||||
|
||||
Mỗi màn đã chụp ảnh có một entry: `slug`, `title`, `theme`, `note` (**đúng `file.py:line`
|
||||
nơi màn đó được dựng**), `file` (ảnh), `nav`.
|
||||
Các tab được định nghĩa trong:
|
||||
|
||||
```text
|
||||
ui/workspace_tab.py:214-245
|
||||
```
|
||||
|
||||
| Tab | i18n key | Widget/File |
|
||||
| -------- | ------------------------ | -------------------------------------------------- |
|
||||
| Project | `workspace.tab_project` | `_build_project_tab()` trong `ui/workspace_tab.py` |
|
||||
| Cowork | `workspace.tab_cowork` | `ui/cowork_tab.py` |
|
||||
| Co4E | `workspace.tab_co4e` | `ui/co4e_tab.py` → `presentation/co4e/` |
|
||||
| Folder | `workspace.tab_folder` | `presentation/folder/folder_tab.py` |
|
||||
| GraphRAG | `workspace.tab_graphrag` | `presentation/graph/structure_graph_view.py` |
|
||||
|
||||
### Monitoring có cấu trúc khác
|
||||
|
||||
Monitoring có **tab strip riêng**, gồm 8 sub-view:
|
||||
|
||||
1. Tổng quan.
|
||||
2. Trạng thái Agent.
|
||||
3. Công cụ.
|
||||
4. Nhật ký hành động.
|
||||
5. Lịch sử gọi MCP.
|
||||
6. Sự kiện bảo mật.
|
||||
7. Agents Admin.
|
||||
8. Icon.
|
||||
|
||||
**Workspace là màn hình duy nhất không hiển thị tab strip theo cách này.**
|
||||
|
||||
Nếu người dùng nói:
|
||||
|
||||
> "Tab trạng thái agent trong màn Monitoring"
|
||||
|
||||
thì không được nhầm nó với một tab của Workspace.
|
||||
|
||||
---
|
||||
|
||||
## 3. Các thành phần luôn xuất hiện trên mọi màn hình
|
||||
|
||||
Một số thành phần nằm ngoài nội dung của từng màn hình.
|
||||
|
||||
| Thành phần | File | Cách người dùng thường mô tả |
|
||||
| ------------------------------- | -------------------------------- | -------------------------------------------------- |
|
||||
| Nav rail bên trái / nút thu gọn | `presentation/shell/nav_rail.py` | "Menu bị co lại", "Không thấy tên project" |
|
||||
| Top bar / theme / ngôn ngữ | `presentation/shell/top_bar.py` | "Đổi giao diện không ăn", "Đổi ngôn ngữ không đổi" |
|
||||
| Toast góc trên trái | `presentation/shell/toast.py` | "Thông báo xong việc che mất nút" |
|
||||
| Help Agent góc dưới phải | `ui/help_agent_widget.py` | "Con robot che nút gửi" |
|
||||
| Status bar phía dưới | `main_window.statusBar()` | "Dòng chữ dưới đáy không đổi" |
|
||||
|
||||
### Quy tắc
|
||||
|
||||
Nếu người dùng mô tả một thành phần thuộc nhóm trên, **không cần tìm sub-tab trước**.
|
||||
|
||||
Hãy kiểm tra trực tiếp file tương ứng.
|
||||
|
||||
---
|
||||
|
||||
## 4. Các Dialog
|
||||
|
||||
Các dialog chính nằm trong `ui/`:
|
||||
|
||||
```text
|
||||
ui/
|
||||
├── login_dialog.py
|
||||
├── permission_dialog.py
|
||||
├── settings_dialog.py
|
||||
├── skills_dialog.py
|
||||
├── task_editor_dialog.py
|
||||
├── file_edit_dialog.py
|
||||
├── flow_dialog.py
|
||||
├── mcp_servers_dialog.py
|
||||
├── co4e_agent_dialog.py
|
||||
└── ext_connector_dialog.py
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
> "Khi mở Permission thì nút Allow bị..."
|
||||
|
||||
→ kiểm tra trước:
|
||||
|
||||
```text
|
||||
ui/permission_dialog.py
|
||||
```
|
||||
|
||||
Không tự động tìm trong `presentation/` chỉ vì lỗi xảy ra trên UI.
|
||||
|
||||
---
|
||||
|
||||
# 5. Hai file tra cứu bắt buộc
|
||||
|
||||
Khi cần chuyển mô tả của người dùng thành `file:line`, phải ưu tiên sử dụng:
|
||||
|
||||
```text
|
||||
docs/screens/manifest.json
|
||||
docs/screens/controls.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5.1. `docs/screens/manifest.json`
|
||||
|
||||
File này chứa thông tin về các màn hình đã được chụp screenshot.
|
||||
|
||||
Mỗi màn hình có các thông tin chính:
|
||||
|
||||
```text
|
||||
slug
|
||||
title
|
||||
theme
|
||||
note
|
||||
file
|
||||
nav
|
||||
```
|
||||
|
||||
Trong đó:
|
||||
|
||||
* `slug` — tên định danh của màn hình.
|
||||
* `title` — tên hiển thị.
|
||||
* `theme` — Dark hoặc Light.
|
||||
* `note` — **vị trí code dựng màn hình (`file.py:line`)**.
|
||||
* `file` — đường dẫn đến screenshot.
|
||||
* `nav` — màn hình thuộc nav nào.
|
||||
|
||||
### Ví dụ
|
||||
|
||||
Người dùng nói:
|
||||
|
||||
> "Màn Kanban lịch trình bị lỗi."
|
||||
|
||||
Có thể tìm màn hình liên quan bằng:
|
||||
|
||||
```bash
|
||||
# Người dùng nói "màn Kanban lịch trình"
|
||||
python -c "import json;print([e for e in json.load(open('docs/screens/manifest.json')) if 'schedule' in e['slug']])"
|
||||
```
|
||||
|
||||
Ảnh có **cả bản dark và light** (`*-dark.png` / `*-light.png`) — dùng để đối chiếu trước/sau
|
||||
và để kiểm tra bug chỉ xảy ra ở một theme.
|
||||
Sau đó lấy `note` để biết:
|
||||
|
||||
### `docs/screens/controls.json`
|
||||
```text
|
||||
file.py:line
|
||||
```
|
||||
|
||||
Danh mục **mọi control** đã trích tự động từ source: `file`, `var`, `type` (`QLineEdit`...),
|
||||
`kind` (mô tả tiếng Việt: "ô nhập", "nút"...), `label`, `line`, `signals`, `object_name`.
|
||||
### Screenshot Dark và Light
|
||||
|
||||
Mỗi màn hình thường có hai ảnh:
|
||||
|
||||
```text
|
||||
<slug>-dark.png
|
||||
<slug>-light.png
|
||||
```
|
||||
|
||||
Dùng hai ảnh này để:
|
||||
|
||||
* So sánh trước/sau.
|
||||
* Kiểm tra lỗi chỉ xảy ra ở một theme.
|
||||
* Kiểm tra sự khác biệt giữa Dark Mode và Light Mode.
|
||||
|
||||
---
|
||||
|
||||
## 5.2. `docs/screens/controls.json`
|
||||
|
||||
Đây là danh sách các control được trích tự động từ source code.
|
||||
|
||||
Mỗi control có thông tin như:
|
||||
|
||||
```text
|
||||
file
|
||||
var
|
||||
type
|
||||
kind
|
||||
label
|
||||
line
|
||||
signals
|
||||
object_name
|
||||
```
|
||||
|
||||
Trong đó:
|
||||
|
||||
* `file` — file chứa control.
|
||||
* `var` — tên biến.
|
||||
* `type` — loại widget, ví dụ `QLineEdit`.
|
||||
* `kind` — mô tả dễ hiểu, ví dụ `"ô nhập"`, `"nút"`.
|
||||
* `label` — text/label liên quan.
|
||||
* `line` — dòng code.
|
||||
* `signals` — signal liên quan.
|
||||
* `object_name` — `objectName` của widget.
|
||||
|
||||
### Ví dụ
|
||||
|
||||
Người dùng nói:
|
||||
|
||||
> "Ô nhập email trong màn tài khoản bị lỗi."
|
||||
|
||||
Có thể tìm control bằng:
|
||||
|
||||
```bash
|
||||
# Người dùng nói "ô nhập email trong màn tài khoản"
|
||||
python - <<'PY'
|
||||
import json
|
||||
|
||||
for f in json.load(open('docs/screens/controls.json')):
|
||||
for c in f['controls']:
|
||||
if 'email' in (c['var'] + c['label']).lower():
|
||||
print(f["file"], c["line"], c["var"], c["type"], c["object_name"])
|
||||
text = (c['var'] + c['label']).lower()
|
||||
if 'email' in text:
|
||||
print(
|
||||
f["file"],
|
||||
c["line"],
|
||||
c["var"],
|
||||
c["type"],
|
||||
c["object_name"]
|
||||
)
|
||||
PY
|
||||
```
|
||||
|
||||
Cột `object_name` đặc biệt quan trọng khi sửa bug màu/style: rỗng nghĩa là widget **chưa**
|
||||
được style qua `_TEMPLATE`, nên nó đang ăn style mặc định của class — thường chính là
|
||||
nguyên nhân của "chỗ này nhìn khác chỗ kia".
|
||||
Từ kết quả có thể xác định:
|
||||
|
||||
## 6. Quy trình tra 4 bước cho Triage
|
||||
```text
|
||||
file
|
||||
line
|
||||
variable
|
||||
widget type
|
||||
objectName
|
||||
```
|
||||
|
||||
1. Xác định **nav row** (Dashboard / Schedule / Workspace / Monitoring) từ mô tả hoặc ảnh.
|
||||
2. Xác định **sub-tab / dialog**.
|
||||
3. Tra `manifest.json` → lấy `note` = `file.py:line`.
|
||||
4. Tra `controls.json` → lấy đúng `var` + `line` + `object_name` của control bị lỗi.
|
||||
---
|
||||
|
||||
Không qua đủ 4 bước thì `confidence` tối đa là `low`.
|
||||
## 6. `object_name` đặc biệt quan trọng khi điều tra UI
|
||||
|
||||
Khi sửa lỗi màu hoặc style, phải chú ý đến:
|
||||
|
||||
```text
|
||||
object_name
|
||||
```
|
||||
|
||||
Nếu `object_name` đang rỗng, có nghĩa widget đó **chưa được gắn `objectName` để áp style theo cơ chế template/QSS**.
|
||||
|
||||
Khi đó widget có thể đang sử dụng style mặc định của class.
|
||||
|
||||
Đây thường là nguyên nhân khiến người dùng thấy:
|
||||
|
||||
> "Chỗ này nhìn khác chỗ kia."
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Widget A → objectName = "project_title"
|
||||
↓
|
||||
QSS áp style riêng
|
||||
|
||||
Widget B → objectName = ""
|
||||
↓
|
||||
dùng style mặc định
|
||||
```
|
||||
|
||||
Vì vậy, khi gặp lỗi visual liên quan đến màu/style, hãy kiểm tra `object_name` trước khi tự thêm màu hoặc `setStyleSheet()`.
|
||||
|
||||
---
|
||||
|
||||
# 7. Quy trình 4 bước dành cho Triage
|
||||
|
||||
Khi người dùng báo lỗi bằng ngôn ngữ tự nhiên, thực hiện theo thứ tự sau:
|
||||
|
||||
### Bước 1 — Xác định màn hình chính
|
||||
|
||||
Xác định lỗi thuộc:
|
||||
|
||||
```text
|
||||
Dashboard
|
||||
Schedule
|
||||
Workspace
|
||||
Monitoring
|
||||
```
|
||||
|
||||
Dựa trên mô tả của người dùng hoặc screenshot.
|
||||
|
||||
---
|
||||
|
||||
### Bước 2 — Xác định tab/view/dialog
|
||||
|
||||
Tiếp tục xác định:
|
||||
|
||||
```text
|
||||
Sub-tab
|
||||
→ View
|
||||
→ Dialog
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Workspace
|
||||
→ Co4E
|
||||
→ Agent Dialog
|
||||
```
|
||||
|
||||
hoặc:
|
||||
|
||||
```text
|
||||
Monitoring
|
||||
→ Security Events
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Bước 3 — Tra `manifest.json`
|
||||
|
||||
Mở:
|
||||
|
||||
```text
|
||||
docs/screens/manifest.json
|
||||
```
|
||||
|
||||
Tìm màn hình tương ứng và lấy:
|
||||
|
||||
```text
|
||||
note → file.py:line
|
||||
```
|
||||
|
||||
Đây là điểm bắt đầu để tìm code dựng màn hình.
|
||||
|
||||
---
|
||||
|
||||
### Bước 4 — Tra `controls.json`
|
||||
|
||||
Nếu lỗi liên quan đến một control cụ thể, tiếp tục tìm trong:
|
||||
|
||||
```text
|
||||
docs/screens/controls.json
|
||||
```
|
||||
|
||||
Lấy:
|
||||
|
||||
```text
|
||||
var
|
||||
line
|
||||
type
|
||||
object_name
|
||||
```
|
||||
|
||||
Sau đó xác định chính xác widget bị lỗi.
|
||||
|
||||
---
|
||||
|
||||
# 8. Quy tắc về Confidence
|
||||
|
||||
Triage phải phản ánh đúng mức độ chắc chắn của kết quả.
|
||||
|
||||
Nếu chưa hoàn thành đủ 4 bước:
|
||||
|
||||
```text
|
||||
1. Nav
|
||||
2. Tab/View/Dialog
|
||||
3. manifest.json
|
||||
4. controls.json
|
||||
```
|
||||
|
||||
thì:
|
||||
|
||||
```yaml
|
||||
confidence: low
|
||||
```
|
||||
|
||||
Không được tự nâng lên `medium` hoặc `high` chỉ vì file nhìn có vẻ đúng.
|
||||
|
||||
### Khi nào có thể tăng Confidence?
|
||||
|
||||
Chỉ tăng khi có bằng chứng cụ thể, ví dụ:
|
||||
|
||||
```text
|
||||
User description
|
||||
↓
|
||||
Dashboard
|
||||
↓
|
||||
Statistics view
|
||||
↓
|
||||
manifest.json
|
||||
↓
|
||||
presentation/dashboard/dashboard_tab.py:123
|
||||
↓
|
||||
controls.json
|
||||
↓
|
||||
QTableView
|
||||
↓
|
||||
line 245
|
||||
```
|
||||
|
||||
Khi đó mới có đủ cơ sở để ghi nhận `file:line` và đánh giá confidence cao hơn.
|
||||
|
||||
---
|
||||
|
||||
# 9. Nguyên tắc quan trọng
|
||||
|
||||
**Không đoán file từ tên.**
|
||||
|
||||
Không nên suy luận kiểu:
|
||||
|
||||
> "Lỗi ở Workspace nên chắc chắn nằm trong `workspace_tab.py`."
|
||||
|
||||
Thay vào đó:
|
||||
|
||||
```text
|
||||
Mô tả của user
|
||||
↓
|
||||
Xác định màn hình
|
||||
↓
|
||||
Xác định tab/view/dialog
|
||||
↓
|
||||
Tra manifest.json
|
||||
↓
|
||||
Xác định file:line
|
||||
↓
|
||||
Tra controls.json
|
||||
↓
|
||||
Xác định widget/control
|
||||
↓
|
||||
Đánh giá confidence
|
||||
```
|
||||
|
||||
Mục tiêu cuối cùng của Screen Map là biến một mô tả mơ hồ của người dùng thành một đầu vào có thể sử dụng được cho `defect_record`, đặc biệt là:
|
||||
|
||||
```text
|
||||
screen
|
||||
widget
|
||||
file
|
||||
line
|
||||
object_name
|
||||
confidence
|
||||
```
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+635
-71
@@ -1,101 +1,665 @@
|
||||
# Theme & Design Tokens — luật màu sắc của Cowork Local
|
||||
# Theme & Design Tokens — Luật màu sắc của Cowork Local
|
||||
|
||||
Nguồn: docstring đầu `theme/__init__.py`, `theme/palettes.py`, `theme/qss.py`,
|
||||
`theme/qss_controls.py`.
|
||||
> Knowledge module dành cho các agent xử lý **UI Visual / Theme / QSS** của Cowork Local.
|
||||
|
||||
## Nguồn chính
|
||||
|
||||
* `theme/__init__.py` — docstring và API theme
|
||||
* `theme/palettes.py` — định nghĩa Palette/token
|
||||
* `theme/qss.py` — `_TEMPLATE` và stylesheet
|
||||
* `theme/qss_controls.py` — style cho các Qt controls
|
||||
|
||||
---
|
||||
|
||||
## 1. Luật gốc
|
||||
# 1. Luật quan trọng nhất
|
||||
|
||||
> **Không file nào ngoài `theme/` được đặt tên một màu.**
|
||||
> **Ngoài thư mục `theme/`, không file nào được tự định nghĩa màu.**
|
||||
|
||||
Cơ chế duy nhất:
|
||||
Luồng màu chuẩn của Cowork Local:
|
||||
|
||||
```text
|
||||
Palette (token ngữ nghĩa) → _TEMPLATE (một QSS duy nhất) → stylesheet(theme)
|
||||
Palette
|
||||
↓
|
||||
token ngữ nghĩa
|
||||
↓
|
||||
_TEMPLATE
|
||||
↓
|
||||
stylesheet(theme)
|
||||
↓
|
||||
QApplication.setStyleSheet(...)
|
||||
```
|
||||
|
||||
Hai cách hợp lệ để một widget có màu:
|
||||
Nói đơn giản:
|
||||
|
||||
1. **Khai báo** — gán `objectName` cho widget, style nó trong `_TEMPLATE`
|
||||
(`theme/qss.py`). Đây là cách mặc định.
|
||||
2. **Vẽ tay** — widget vẽ bằng `QPainter` (chart, canvas, syntax highlighter) thì gọi
|
||||
`current_palette()` rồi đọc token.
|
||||
> **Widget không tự chọn màu. Theme quyết định màu.**
|
||||
|
||||
Cách **không** hợp lệ, bị reject review:
|
||||
---
|
||||
|
||||
# 2. Hai cách hợp lệ để widget có màu
|
||||
|
||||
## Cách 1 — Style bằng QSS
|
||||
|
||||
Đây là cách mặc định.
|
||||
|
||||
Widget đặt `objectName`, sau đó style được định nghĩa trong:
|
||||
|
||||
```text
|
||||
theme/qss.py
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```python
|
||||
self.label.setStyleSheet("color: #dc2626;") # ❌ hex ngoài theme/
|
||||
pen.setColor(QColor("red")) # ❌ tên màu literal
|
||||
self.card.setStyleSheet("background: rgba(0,0,0,.1)") # ❌
|
||||
widget.setObjectName("my_widget")
|
||||
```
|
||||
|
||||
## 2. API cần nhớ
|
||||
và style tương ứng nằm trong `_TEMPLATE`.
|
||||
|
||||
| Hàm | Dùng khi |
|
||||
|---|---|
|
||||
| `theme.stylesheet(theme)` | Sinh QSS toàn app, truyền vào `QApplication.setStyleSheet` |
|
||||
| `theme.set_active_theme(theme)` | **Phải** gọi ngay cạnh mỗi `setStyleSheet(stylesheet(...))` |
|
||||
| `theme.current_theme()` | `'dark'` / `'light'` đang hiển thị |
|
||||
| `theme.current_palette()` | Token của theme đang hiển thị — dùng trong `paintEvent` |
|
||||
| `theme.palette(theme)` | Token của một theme cụ thể |
|
||||
| `theme.resolve_theme('system')` | Suy ra dark/light từ color scheme của OS |
|
||||
| `theme.role_colors(theme)` | Màu theo vai trò hội thoại: user/assistant/tool/result/error |
|
||||
---
|
||||
|
||||
`current_palette()` tồn tại để code vẽ **không** phải đọc lại `config.json` mỗi lần
|
||||
repaint — đó từng là bug hiệu năng thật. Không thay bằng đọc config.
|
||||
## Cách 2 — Widget tự vẽ bằng `QPainter`
|
||||
|
||||
## 3. Nhóm token
|
||||
Dùng cho các thành phần như:
|
||||
|
||||
Palette là `@dataclass(frozen=True)`. Các nhóm chính:
|
||||
* chart;
|
||||
* canvas;
|
||||
* syntax highlighter;
|
||||
* custom painting.
|
||||
|
||||
| Nhóm | Token | Ý nghĩa |
|
||||
|---|---|---|
|
||||
| Bề mặt (thang 4 bậc) | `bg` | nền cửa sổ / canvas |
|
||||
| | `surface` | panel, card, group box (**không** phải nav rail) |
|
||||
| | `surface_raised` | input, list, tree — thứ người dùng gõ/chọn |
|
||||
| | `overlay` | menu, tooltip, popup |
|
||||
| | `sunken` | log, code, terminal — thứ để đọc vào |
|
||||
| | `hover` / `active` | trạng thái hover / đang bấm |
|
||||
| Chữ | `text`, `text_muted`, ... | |
|
||||
| Nhấn | `accent`, `accent_solid` | **Hai token khác nhau có chủ đích**: màu đọc được *dạng chữ* trên nền tối thì quá nhạt để làm *nền* cho chữ trắng |
|
||||
| Trạng thái | `danger`, ... | |
|
||||
| Vai trò hội thoại | `role_user`, `role_assistant`, `role_tool`, `role_result`, `role_error` | |
|
||||
| Code | `code_string`, ... | syntax highlighting |
|
||||
Code phải lấy màu từ:
|
||||
|
||||
Token là **ngữ nghĩa**, không phải literal: `danger` / `text_muted` — không bao giờ
|
||||
`blue` / `grey2`. Thêm một theme = thêm một `Palette`, không phải sửa stylesheet.
|
||||
```python
|
||||
current_palette()
|
||||
```
|
||||
|
||||
## 4. Ràng buộc thiết kế (đừng "sửa" nhầm thành bug)
|
||||
Ví dụ:
|
||||
|
||||
- **Không gradient, không glow.** Bảng màu lấy từ VS Code "Dark Modern" / "Light Modern".
|
||||
Bề mặt phẳng, góc gần vuông, một màu accent chỉ dành cho thứ người dùng thao tác.
|
||||
- **Chiều sâu đến từ thang bề mặt và viền mảnh**, không từ màu.
|
||||
- **Silhouette VS Code:** nav rail **tối hơn** vùng nội dung, không sáng hơn.
|
||||
Người dùng báo "menu trái tối quá" — đó là thiết kế, không phải bug. Xem `examples/bad_fix.md`.
|
||||
- **Contrast giữ ở WCAG AA (4.5:1)** cho body text và cho chữ trên nút đặc.
|
||||
- Bốn giá trị của VS Code không đạt AA đã được nhích lên vừa đủ (số dòng dark 3.59:1,
|
||||
chữ mờ trên sidebar sáng 4.28:1, xanh lá sáng 4.33:1, hổ phách sáng 3.12:1). Mỗi chỗ có
|
||||
comment ghi giá trị gốc — **không** trả chúng về giá trị VS Code.
|
||||
```python
|
||||
palette = current_palette()
|
||||
```
|
||||
|
||||
## 5. Mũi tên combo box (`_chevron_asset`)
|
||||
Sau đó dùng token từ palette.
|
||||
|
||||
QSS `image:` chỉ nhận đường dẫn file/resource, không nhận `QPixmap`. Và một khi
|
||||
`::drop-down` / `::up-button` / `::down-button` bị style, Qt **ngừng vẽ mũi tên mặc định**.
|
||||
Vì vậy `theme/palettes.py::_chevron_asset` render sẵn PNG chevron ra thư mục tạm và cache
|
||||
theo hash `(direction, color)`.
|
||||
---
|
||||
|
||||
Hệ quả khi debug:
|
||||
# 3. Những cách KHÔNG được phép
|
||||
|
||||
- "Combo box mất mũi tên" → gần như luôn do một stylesheet cục bộ đè lên `::drop-down`.
|
||||
- File cache nằm ở `%TEMP%/cowork_local_theme/chevron_*.png`. Xoá nó để buộc render lại
|
||||
khi test màu mới.
|
||||
Không được tự đặt màu trong UI code.
|
||||
|
||||
## 6. Checklist sửa bug liên quan màu sắc
|
||||
### ❌ Hardcode HEX
|
||||
|
||||
- [ ] Đã kiểm tra bug xuất hiện ở **cả** dark và light chưa? (`docs/screens/*-dark.png` / `*-light.png`)
|
||||
- [ ] Bản sửa dùng token, không dùng hex?
|
||||
- [ ] Nếu thêm token mới: đã thêm cho **cả** `DARK` và `LIGHT`?
|
||||
- [ ] Nếu là chữ trên nền đặc: đã dùng `accent_solid` thay vì `accent`?
|
||||
- [ ] Contrast còn ≥ 4.5:1?
|
||||
- [ ] Widget dựng sau khi đổi theme có nhận đúng stylesheet? (xem `qt_pitfalls.md` P07)
|
||||
```python
|
||||
self.label.setStyleSheet("color: #dc2626;")
|
||||
```
|
||||
|
||||
### ❌ Hardcode tên màu
|
||||
|
||||
```python
|
||||
pen.setColor(QColor("red"))
|
||||
```
|
||||
|
||||
### ❌ Hardcode RGBA
|
||||
|
||||
```python
|
||||
self.card.setStyleSheet(
|
||||
"background: rgba(0,0,0,.1)"
|
||||
)
|
||||
```
|
||||
|
||||
Các trường hợp này phải bị reject khi review.
|
||||
|
||||
### Rule ngắn gọn
|
||||
|
||||
```text
|
||||
Không có màu literal ngoài theme/
|
||||
```
|
||||
|
||||
Không chỉ tránh `#hex`, mà cả:
|
||||
|
||||
* tên màu;
|
||||
* RGB;
|
||||
* RGBA;
|
||||
* stylesheet cục bộ chứa màu.
|
||||
|
||||
---
|
||||
|
||||
# 4. API Theme cần nhớ
|
||||
|
||||
| API | Dùng để |
|
||||
| ------------------------------- | --------------------------------------------------- |
|
||||
| `theme.stylesheet(theme)` | Tạo QSS cho toàn app |
|
||||
| `theme.set_active_theme(theme)` | Ghi nhận theme hiện đang active |
|
||||
| `theme.current_theme()` | Lấy theme hiện tại: `dark` / `light` |
|
||||
| `theme.current_palette()` | Lấy Palette của theme hiện tại |
|
||||
| `theme.palette(theme)` | Lấy Palette của một theme cụ thể |
|
||||
| `theme.resolve_theme("system")` | Xác định dark/light theo OS |
|
||||
| `theme.role_colors(theme)` | Lấy màu theo role: user/assistant/tool/result/error |
|
||||
|
||||
---
|
||||
|
||||
## Khi đổi theme
|
||||
|
||||
Hai lệnh này phải đi cùng nhau:
|
||||
|
||||
```python
|
||||
theme.set_active_theme(theme)
|
||||
app.setStyleSheet(theme.stylesheet(theme))
|
||||
```
|
||||
|
||||
Không được chỉ gọi `setStyleSheet()` mà quên cập nhật active theme.
|
||||
|
||||
---
|
||||
|
||||
# 5. `current_palette()` dùng để làm gì?
|
||||
|
||||
Code vẽ bằng `QPainter` phải dùng:
|
||||
|
||||
```python
|
||||
current_palette()
|
||||
```
|
||||
|
||||
Không được mỗi lần `paintEvent()` lại đọc:
|
||||
|
||||
```text
|
||||
config.json
|
||||
```
|
||||
|
||||
Lý do:
|
||||
|
||||
```text
|
||||
paintEvent()
|
||||
↓
|
||||
repaint
|
||||
↓
|
||||
đọc config
|
||||
↓
|
||||
lặp lại rất nhiều lần
|
||||
```
|
||||
|
||||
Điều này từng gây vấn đề hiệu năng thực tế.
|
||||
|
||||
Vì vậy:
|
||||
|
||||
> `current_palette()` tồn tại để custom painting lấy màu nhanh từ theme hiện tại.
|
||||
|
||||
---
|
||||
|
||||
# 6. Palette và Design Token
|
||||
|
||||
`Palette` là:
|
||||
|
||||
```python
|
||||
@dataclass(frozen=True)
|
||||
```
|
||||
|
||||
Token phải mang **ý nghĩa**, không phải tên màu.
|
||||
|
||||
### ❌ Không đặt token kiểu:
|
||||
|
||||
```text
|
||||
blue
|
||||
grey2
|
||||
dark_blue
|
||||
light_grey
|
||||
```
|
||||
|
||||
### ✅ Đặt theo vai trò:
|
||||
|
||||
```text
|
||||
accent
|
||||
danger
|
||||
text
|
||||
text_muted
|
||||
surface
|
||||
surface_raised
|
||||
```
|
||||
|
||||
Lợi ích:
|
||||
|
||||
> Thêm theme mới = thêm một `Palette`, không phải viết lại stylesheet.
|
||||
|
||||
---
|
||||
|
||||
# 7. Các nhóm token chính
|
||||
|
||||
## 7.1. Surface — các mức bề mặt
|
||||
|
||||
| Token | Dùng cho |
|
||||
| ---------------- | -------------------------------------------- |
|
||||
| `bg` | Nền chính của cửa sổ/canvas |
|
||||
| `surface` | Panel, card, group box |
|
||||
| `surface_raised` | Input, list, tree — nơi người dùng nhập/chọn |
|
||||
| `overlay` | Menu, tooltip, popup |
|
||||
| `sunken` | Log, code, terminal — vùng chủ yếu để đọc |
|
||||
| `hover` | Trạng thái hover |
|
||||
| `active` | Trạng thái đang active/pressed |
|
||||
|
||||
### Lưu ý
|
||||
|
||||
`surface` **không có nghĩa là nav rail**.
|
||||
|
||||
Nav rail có chủ đích riêng về độ sáng/tối.
|
||||
|
||||
---
|
||||
|
||||
## 7.2. Text
|
||||
|
||||
Các token chính:
|
||||
|
||||
```text
|
||||
text
|
||||
text_muted
|
||||
...
|
||||
```
|
||||
|
||||
Dùng token theo vai trò thay vì tự chọn màu.
|
||||
|
||||
---
|
||||
|
||||
## 7.3. Accent
|
||||
|
||||
Có hai token:
|
||||
|
||||
```text
|
||||
accent
|
||||
accent_solid
|
||||
```
|
||||
|
||||
**Hai token này khác nhau có chủ đích.**
|
||||
|
||||
### `accent`
|
||||
|
||||
Dùng cho accent thông thường, ví dụ:
|
||||
|
||||
* trạng thái;
|
||||
* thành phần UI;
|
||||
* điểm nhấn.
|
||||
|
||||
### `accent_solid`
|
||||
|
||||
Dùng khi accent trở thành **nền đặc và bên trên có chữ**.
|
||||
|
||||
Lý do:
|
||||
|
||||
> Một màu accent có thể đủ sáng để đọc khi dùng như chữ trên nền tối, nhưng lại quá sáng khi dùng làm nền cho chữ trắng.
|
||||
|
||||
Vì vậy:
|
||||
|
||||
```text
|
||||
Chữ trên nền accent đặc
|
||||
↓
|
||||
accent_solid
|
||||
```
|
||||
|
||||
Không tự lấy `accent` chỉ vì nó có vẻ "cùng màu".
|
||||
|
||||
---
|
||||
|
||||
## 7.4. State
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
danger
|
||||
...
|
||||
```
|
||||
|
||||
Các state token cũng phải mang ý nghĩa, không đặt theo tên màu.
|
||||
|
||||
---
|
||||
|
||||
## 7.5. Conversation roles
|
||||
|
||||
Có các token:
|
||||
|
||||
```text
|
||||
role_user
|
||||
role_assistant
|
||||
role_tool
|
||||
role_result
|
||||
role_error
|
||||
```
|
||||
|
||||
Dùng để phân biệt các role trong giao diện hội thoại.
|
||||
|
||||
---
|
||||
|
||||
## 7.6. Code / Syntax
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
code_string
|
||||
...
|
||||
```
|
||||
|
||||
Dùng cho syntax highlighting.
|
||||
|
||||
---
|
||||
|
||||
# 8. Các nguyên tắc thiết kế — đừng nhầm thành bug
|
||||
|
||||
Một số đặc điểm nhìn "khác mắt" nhưng **có chủ đích**.
|
||||
|
||||
Không được tự ý sửa chỉ vì người dùng nói "trông hơi tối" hoặc "không giống app hiện đại".
|
||||
|
||||
---
|
||||
|
||||
## 8.1. Không gradient, không glow
|
||||
|
||||
Thiết kế lấy cảm hứng từ:
|
||||
|
||||
```text
|
||||
VS Code Dark Modern
|
||||
VS Code Light Modern
|
||||
```
|
||||
|
||||
Phong cách chính:
|
||||
|
||||
* surface phẳng;
|
||||
* góc gần vuông;
|
||||
* không gradient;
|
||||
* không glow;
|
||||
* một accent chính;
|
||||
* accent dành cho thứ người dùng tương tác.
|
||||
|
||||
---
|
||||
|
||||
## 8.2. Độ sâu đến từ surface và border
|
||||
|
||||
Không tạo chiều sâu bằng cách:
|
||||
|
||||
```text
|
||||
đổi màu quá mạnh
|
||||
```
|
||||
|
||||
Thay vào đó dùng:
|
||||
|
||||
```text
|
||||
surface hierarchy
|
||||
+
|
||||
border mảnh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 9. Nav rail tối hơn là thiết kế có chủ đích
|
||||
|
||||
Silhouette của Cowork Local lấy theo VS Code:
|
||||
|
||||
```text
|
||||
NAV RAIL
|
||||
↓
|
||||
tối hơn
|
||||
↓
|
||||
CONTENT AREA
|
||||
```
|
||||
|
||||
Không phải:
|
||||
|
||||
```text
|
||||
nav rail sáng hơn content
|
||||
```
|
||||
|
||||
Vì vậy nếu user báo:
|
||||
|
||||
> "Menu bên trái tối quá."
|
||||
|
||||
thì **chưa được kết luận ngay là visual bug**.
|
||||
|
||||
Đây có thể là design intent.
|
||||
|
||||
Xem thêm:
|
||||
|
||||
```text
|
||||
examples/bad_fix.md
|
||||
```
|
||||
|
||||
để tránh sửa nhầm.
|
||||
|
||||
---
|
||||
|
||||
# 10. Contrast — WCAG AA
|
||||
|
||||
Body text và chữ trên button nền đặc phải đạt:
|
||||
|
||||
```text
|
||||
Contrast ratio ≥ 4.5:1
|
||||
```
|
||||
|
||||
Đây là yêu cầu tối thiểu.
|
||||
|
||||
Khi thay token/màu:
|
||||
|
||||
```text
|
||||
Dark theme
|
||||
+
|
||||
Light theme
|
||||
+
|
||||
text/background
|
||||
```
|
||||
|
||||
đều phải được kiểm tra.
|
||||
|
||||
---
|
||||
|
||||
## Không khôi phục màu VS Code cũ nếu màu đó không đạt AA
|
||||
|
||||
Một số màu gốc của VS Code không đạt yêu cầu AA.
|
||||
|
||||
Các giá trị đã được Cowork Local điều chỉnh vừa đủ, ví dụ:
|
||||
|
||||
| Trường hợp | Contrast cũ |
|
||||
| ------------------------ | ----------: |
|
||||
| Dark line | 3.59:1 |
|
||||
| Chữ mờ trên sidebar sáng | 4.28:1 |
|
||||
| Xanh lá sáng | 4.33:1 |
|
||||
| Hổ phách sáng | 3.12:1 |
|
||||
|
||||
Các chỗ này có comment ghi lại giá trị gốc.
|
||||
|
||||
### Rule
|
||||
|
||||
**Không đưa chúng trở lại giá trị VS Code ban đầu.**
|
||||
|
||||
Mục tiêu của Cowork Local là:
|
||||
|
||||
```text
|
||||
VS Code silhouette
|
||||
+
|
||||
WCAG AA
|
||||
```
|
||||
|
||||
không phải copy nguyên xi mọi giá trị màu của VS Code.
|
||||
|
||||
---
|
||||
|
||||
# 11. ⚠️ Combo Box và `_chevron_asset`
|
||||
|
||||
Một lỗi dễ gặp:
|
||||
|
||||
> Combo box mất mũi tên.
|
||||
|
||||
Nguyên nhân liên quan đến cách Qt xử lý QSS.
|
||||
|
||||
---
|
||||
|
||||
## 11.1. `image:` trong QSS không nhận `QPixmap`
|
||||
|
||||
QSS:
|
||||
|
||||
```text
|
||||
image:
|
||||
```
|
||||
|
||||
chỉ nhận đường dẫn tới:
|
||||
|
||||
* file;
|
||||
* resource.
|
||||
|
||||
Không nhận trực tiếp:
|
||||
|
||||
```text
|
||||
QPixmap
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11.2. Style `::drop-down` sẽ làm Qt ngừng vẽ arrow mặc định
|
||||
|
||||
Khi style các selector như:
|
||||
|
||||
```text
|
||||
::drop-down
|
||||
::up-button
|
||||
::down-button
|
||||
```
|
||||
|
||||
Qt có thể ngừng vẽ mũi tên mặc định.
|
||||
|
||||
---
|
||||
|
||||
## 11.3. Cowork Local dùng `_chevron_asset`
|
||||
|
||||
Trong:
|
||||
|
||||
```text
|
||||
theme/palettes.py
|
||||
```
|
||||
|
||||
`_chevron_asset`:
|
||||
|
||||
1. render chevron thành PNG;
|
||||
2. lưu vào thư mục tạm;
|
||||
3. cache theo:
|
||||
|
||||
```text
|
||||
(direction, color)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Khi debug combo box
|
||||
|
||||
Nếu thấy:
|
||||
|
||||
> Combo box mất mũi tên.
|
||||
|
||||
Hãy kiểm tra trước:
|
||||
|
||||
```text
|
||||
stylesheet cục bộ
|
||||
↓
|
||||
::drop-down
|
||||
```
|
||||
|
||||
Đây thường là nguyên nhân.
|
||||
|
||||
Cache nằm tại:
|
||||
|
||||
```text
|
||||
%TEMP%/cowork_local_theme/chevron_*.png
|
||||
```
|
||||
|
||||
Nếu đang test màu mới, có thể xóa cache để buộc render lại.
|
||||
|
||||
---
|
||||
|
||||
# 12. Checklist sửa bug màu sắc/theme
|
||||
|
||||
Trước khi hoàn thành visual fix, kiểm tra:
|
||||
|
||||
### Theme coverage
|
||||
|
||||
* [ ] Bug đã được kiểm tra trên **Dark** chưa?
|
||||
* [ ] Bug đã được kiểm tra trên **Light** chưa?
|
||||
* [ ] Có thể dùng screenshot:
|
||||
|
||||
* `docs/screens/*-dark.png`
|
||||
* `docs/screens/*-light.png`
|
||||
|
||||
### Token
|
||||
|
||||
* [ ] Patch dùng semantic token thay vì hex literal?
|
||||
* [ ] Không có `setStyleSheet()` cục bộ để thay màu?
|
||||
* [ ] Không có `QColor("red")`, `QColor("blue")`, v.v.?
|
||||
* [ ] Nếu thêm token mới, đã thêm cho **cả `DARK` và `LIGHT`**?
|
||||
* [ ] Token mới có tên theo **ý nghĩa**, không theo màu?
|
||||
|
||||
### Accent
|
||||
|
||||
* [ ] Chữ trên nền accent đặc đã dùng `accent_solid`?
|
||||
* [ ] Không dùng `accent` chỉ vì hai token có vẻ giống nhau?
|
||||
|
||||
### Accessibility
|
||||
|
||||
* [ ] Contrast đạt **≥ 4.5:1**?
|
||||
* [ ] Đã kiểm tra cả text và button có nền đặc?
|
||||
|
||||
### Theme lifecycle
|
||||
|
||||
* [ ] Widget tạo sau khi đổi theme có nhận đúng stylesheet?
|
||||
* [ ] Đã kiểm tra vấn đề lazy screen theo `qt_pitfalls.md` **P07**?
|
||||
|
||||
### Design intent
|
||||
|
||||
* [ ] Không vô tình thêm gradient?
|
||||
* [ ] Không thêm glow?
|
||||
* [ ] Không làm nav rail sáng hơn content?
|
||||
* [ ] Không khôi phục các màu VS Code cũ đã bị loại vì không đạt WCAG AA?
|
||||
|
||||
---
|
||||
|
||||
# 13. Quy tắc review nhanh
|
||||
|
||||
Khi gặp một defect liên quan màu sắc, đi theo thứ tự:
|
||||
|
||||
```text
|
||||
1. Xác định widget
|
||||
↓
|
||||
2. Kiểm tra objectName
|
||||
↓
|
||||
3. Tìm rule trong theme/qss.py
|
||||
↓
|
||||
4. Kiểm tra token trong palettes.py
|
||||
↓
|
||||
5. Kiểm tra DARK + LIGHT
|
||||
↓
|
||||
6. Kiểm tra contrast
|
||||
↓
|
||||
7. Kiểm tra local setStyleSheet()
|
||||
↓
|
||||
8. Kiểm tra lazy theme lifecycle (P07)
|
||||
↓
|
||||
9. Xác định đây là bug thật hay design intent
|
||||
↓
|
||||
10. Chỉ sau đó mới tạo fix_plan
|
||||
```
|
||||
|
||||
## Nguyên tắc cuối
|
||||
|
||||
```text
|
||||
UI code
|
||||
↓
|
||||
không tự chọn màu
|
||||
↓
|
||||
semantic token
|
||||
↓
|
||||
Palette
|
||||
↓
|
||||
_TEMPLATE / current_palette()
|
||||
↓
|
||||
theme
|
||||
```
|
||||
|
||||
**Nếu một màu mới cần xuất hiện, trước tiên hỏi:**
|
||||
|
||||
> "Màu này đang đại diện cho vai trò gì?"
|
||||
|
||||
Sau đó tạo hoặc dùng **semantic token** phù hợp.
|
||||
|
||||
Không hỏi:
|
||||
|
||||
> "Mình muốn màu xanh nào?"
|
||||
|
||||
Vì trong Cowork Local, **ý nghĩa của màu quan trọng hơn bản thân màu**.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# Output Contract — `dispatch_plan`
|
||||
|
||||
Do `fix-dispatcher` sinh ra, trước khi bất kỳ agent nào khác chạy.
|
||||
Đây là thứ quyết định **effort** của cả lượt xử lý, nên nó phải chứng minh được lựa chọn
|
||||
của mình — nhưng phải ngắn. Trần: **30 dòng** cho phần người đọc.
|
||||
|
||||
---
|
||||
|
||||
```yaml
|
||||
---
|
||||
report_id: RPT-<YYYYMMDD>-<NN> # một phản ánh của người dùng = một report_id
|
||||
defects:
|
||||
- defect_id: UI-<YYYYMMDD>-<NN>
|
||||
tier: <T0 | T1 | T2 | T3 | T3-SEC>
|
||||
lane: <DIRECT | SOLO | PAIR | FULL | FULL-SEC>
|
||||
category: <visual | flow | i18n-a11y | security | not-ui>
|
||||
severity: <S1 | S2 | S3 | S4>
|
||||
confidence: <low | medium | high>
|
||||
reproducible: <yes | no | intermittent>
|
||||
security_review: <required | not-required>
|
||||
entry_agent: <fix-implementer | ui-visual-fixer | ux-flow-fixer | i18n-a11y-fixer | security-defect-fixer | ui-bug-triage | SELF | RETURN_TO_REPORTER>
|
||||
affected_files: [path/to/file.py:123]
|
||||
tier_evidence: "<dòng nào của roles/0_fix_dispatcher.md Bước 3 đã trúng>"
|
||||
budget_calls: <số lần gọi agent dự kiến>
|
||||
execution:
|
||||
parallel: [[UI-...-01, UI-...-02]] # các defect_id độc lập, chạy cùng lúc
|
||||
sequential: [UI-...-03] # phụ thuộc, hoặc T3 cần triage trước
|
||||
blocked_on: []
|
||||
---
|
||||
```
|
||||
|
||||
# 1. Phản ánh gốc
|
||||
|
||||
Nguyên văn của người báo lỗi, **đã redact** (`system/security.md`). Không diễn giải lại.
|
||||
|
||||
# 2. Tách defect
|
||||
|
||||
| defect_id | Triệu chứng người dùng thấy | Category | Tier |
|
||||
|---|---|---|---|
|
||||
| | | | |
|
||||
|
||||
Một dòng = một nguyên nhân gốc. Chỉ có một defect thì bảng có một dòng — không xoá bảng.
|
||||
|
||||
# 3. Bằng chứng chấm tier
|
||||
|
||||
Mỗi defect **một dòng**, trích đúng tiêu chí đã trúng. Không được viết "trông đơn giản".
|
||||
|
||||
| defect_id | Tier | Trúng tiêu chí | Lệnh đã dùng để xác nhận |
|
||||
|---|---|---|---|
|
||||
| | T0 | loại 1 (số đo hiển thị), 0 disqualifier | `check_loc.py`, `grep -rn` blast radius |
|
||||
| | T2 | "chạm QSS/token dùng chung" | `grep -rn "<objectName>"` |
|
||||
|
||||
Với **T0** bắt buộc có cột lệnh — Gate S và blast radius phải đo, không được ước lượng.
|
||||
|
||||
# 4. Kế hoạch chạy
|
||||
|
||||
```text
|
||||
UI-...-01 T0 DIRECT → hub sửa luôn, cổng máy §4.1
|
||||
UI-...-02 T2 PAIR → ui-visual-fixer → fix-implementer → regression-reviewer
|
||||
UI-...-03 T3 FULL → ui-bug-triage → ... (chờ triage mới biết specialist nào)
|
||||
```
|
||||
|
||||
Ngân sách tổng: `___` lần gọi agent (bảng §4 của role 0 cho phép `___`).
|
||||
|
||||
# 5. Điều đã cố ý KHÔNG làm
|
||||
|
||||
- Không gọi `ui-bug-triage` cho defect nào? Vì sao được phép bỏ (phản ánh đã tự chỉ ra
|
||||
màn hình + triệu chứng cụ thể).
|
||||
- Không gọi `regression-reviewer` cho defect nào? Chỉ hợp lệ ở T0/T1 — nêu rõ cổng nào
|
||||
thay thế.
|
||||
|
||||
# 6. Open question
|
||||
|
||||
Tối đa 3, mỗi câu kèm phương án mặc định nếu người dùng không trả lời
|
||||
(`response_policy.md` R3). Câu hỏi **chặn** thì đưa vào `blocked_on`.
|
||||
File diff suppressed because it is too large
Load Diff
+429
-43
@@ -1,81 +1,467 @@
|
||||
# Guardrail — luật bất biến cho mọi agent trong `agent/`
|
||||
# Guardrail — Luật bất biến cho mọi agent trong `agent/`
|
||||
|
||||
Áp dụng cho cả 6 role. Role nào mâu thuẫn với file này thì **file này thắng**.
|
||||
> **PRECEDENCE:** File này áp dụng cho **tất cả 6 role** trong `agent/`.
|
||||
>
|
||||
> Nếu role-specific instruction mâu thuẫn với bất kỳ quy tắc nào dưới đây, **Guardrail này thắng**.
|
||||
|
||||
---
|
||||
|
||||
## G1. Không tự bịa requirement
|
||||
|
||||
- Chỉ làm việc trên những gì có trong bug report, source code, và `knowledge/`.
|
||||
- Thiếu thông tin → ghi vào mục **Assumption** hoặc **Open Question**, KHÔNG tự suy diễn
|
||||
rồi sửa theo suy diễn đó.
|
||||
- Không tự ý "tiện tay cải thiện UX" ngoài phạm vi lỗi được báo. Phát hiện vấn đề khác →
|
||||
ghi vào mục **Out of scope (đề xuất issue riêng)**.
|
||||
* Chỉ làm việc dựa trên:
|
||||
|
||||
* bug report;
|
||||
* source code thực tế;
|
||||
* các tài liệu trong `knowledge/`;
|
||||
* governance và security policy liên quan.
|
||||
* Nếu thiếu thông tin:
|
||||
|
||||
* ghi vào `Assumption`; hoặc
|
||||
* ghi vào `Open Question`.
|
||||
* **Không được tự suy diễn requirement rồi sửa theo suy diễn đó.**
|
||||
* Không tự ý "tiện tay cải thiện UX", refactor hoặc đổi behavior ngoài phạm vi bug.
|
||||
* Nếu phát hiện vấn đề khác:
|
||||
|
||||
* ghi vào `Out of scope (đề xuất issue riêng)`;
|
||||
* không sửa trong cùng patch.
|
||||
|
||||
---
|
||||
|
||||
## G2. Không đoán vị trí code
|
||||
|
||||
- Mọi khẳng định về code phải kèm `path/file.py:line`. Chưa đọc file thì chưa được kết luận.
|
||||
- Người dùng mô tả bằng tiếng Việt/Nhật → tra `knowledge/screen_map.md` và
|
||||
`docs/screens/controls.json` để tìm đúng widget, không đoán theo tên gọi.
|
||||
* Không được kết luận về code khi chưa đọc code thực tế.
|
||||
* Mọi khẳng định cụ thể về implementation phải kèm:
|
||||
|
||||
```text
|
||||
path/file.py:line
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Root cause nằm tại presentation/shell/nav_rail.py:242
|
||||
```
|
||||
|
||||
* Khi người dùng mô tả bằng tiếng Việt hoặc tiếng Nhật:
|
||||
|
||||
1. tra `knowledge/screen_map.md`;
|
||||
2. tra `docs/screens/manifest.json`;
|
||||
3. tra `docs/screens/controls.json`;
|
||||
4. xác nhận `screen → view → widget → file → line`.
|
||||
* **Không đoán file chỉ dựa vào tên widget hoặc tên màn hình.**
|
||||
* Nếu chưa đủ bằng chứng để xác định vị trí:
|
||||
|
||||
* `confidence: low`;
|
||||
* ghi rõ thông tin còn thiếu.
|
||||
|
||||
---
|
||||
|
||||
## G3. Sửa đúng tầng
|
||||
|
||||
Cowork Local là Clean Architecture 4 tầng, phụ thuộc chỉ hướng vào trong:
|
||||
Cowork Local sử dụng Clean Architecture 4 tầng:
|
||||
|
||||
```text
|
||||
presentation/ → application/ → domain/ ← infrastructure/
|
||||
```
|
||||
|
||||
- Bug UI/UX được sửa ở `presentation/`, `ui/`, `theme/`, `i18n/`. Đó là mặc định.
|
||||
- Nếu buộc phải đụng `application/` hoặc `domain/`, phải nêu rõ **lý do tại sao không
|
||||
sửa được ở tầng trên** trong `fix_plan.md`, và coi đó là thay đổi cần reviewer chú ý.
|
||||
- `domain/` và `application/` là **100% Pure Python**. Tuyệt đối không thêm import
|
||||
`PySide6`/`PyQt` vào hai tầng này — Gate C sẽ chặn.
|
||||
- Widget chỉ gọi xuống service của `application/`. Không query SQLite/JSON trực tiếp,
|
||||
không gọi LLM trực tiếp trong GUI thread.
|
||||
### Quy tắc
|
||||
|
||||
* Bug UI/UX mặc định được xử lý tại:
|
||||
|
||||
* `presentation/`
|
||||
* `ui/`
|
||||
* `theme/`
|
||||
* `i18n/`
|
||||
|
||||
* Nếu buộc phải sửa `application/` hoặc `domain/`:
|
||||
|
||||
* phải giải thích trong `fix_plan.md` **tại sao không thể giải quyết ở tầng trên**;
|
||||
* phải đánh dấu đây là thay đổi cần reviewer chú ý.
|
||||
|
||||
### Pure Python boundary
|
||||
|
||||
`domain/` và `application/` phải là **100% Pure Python**.
|
||||
|
||||
**Tuyệt đối không thêm:**
|
||||
|
||||
```python
|
||||
from PySide6 ...
|
||||
from PyQt...
|
||||
```
|
||||
|
||||
vào hai tầng này.
|
||||
|
||||
Gate C sẽ chặn vi phạm này.
|
||||
|
||||
### GUI boundary
|
||||
|
||||
Widget:
|
||||
|
||||
* chỉ gọi service/use case của `application/`;
|
||||
* không query SQLite trực tiếp;
|
||||
* không đọc/ghi JSON repository trực tiếp;
|
||||
* không gọi LLM trực tiếp trong GUI thread.
|
||||
|
||||
---
|
||||
|
||||
## G4. Không đặt tên màu ngoài `theme/`
|
||||
|
||||
- Không hex literal (`#1f6fb2`), không `QColor("red")`, không `setStyleSheet("color: blue")`
|
||||
trong bất kỳ file nào ngoài `theme/`.
|
||||
- Sửa màu = sửa/đọc token trong `theme/palettes.py`, hoặc gán `objectName` rồi style trong
|
||||
`theme/qss.py`. Chi tiết: `knowledge/theme_tokens.md`.
|
||||
- Đây là lỗi bị từ chối review thường xuyên nhất khi sửa bug UI.
|
||||
Ngoài `theme/`, tuyệt đối không định nghĩa màu trực tiếp.
|
||||
|
||||
### Không được dùng
|
||||
|
||||
```python
|
||||
"#1f6fb2"
|
||||
QColor("red")
|
||||
setStyleSheet("color: blue")
|
||||
```
|
||||
|
||||
Cũng không được tạo màu bằng:
|
||||
|
||||
* hex literal;
|
||||
* color name;
|
||||
* RGB/RGBA literal;
|
||||
* stylesheet màu viết trực tiếp.
|
||||
|
||||
### Cách đúng
|
||||
|
||||
Màu phải đi qua theme system:
|
||||
|
||||
```text
|
||||
Palette
|
||||
↓
|
||||
semantic token
|
||||
↓
|
||||
QSS template / current_palette()
|
||||
↓
|
||||
widget
|
||||
```
|
||||
|
||||
Có hai cách hợp lệ:
|
||||
|
||||
1. Widget có `objectName` và được style trong `theme/qss.py`.
|
||||
2. Custom painting dùng `current_palette()`.
|
||||
|
||||
Chi tiết xem:
|
||||
|
||||
```text
|
||||
knowledge/theme_tokens.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## G5. Không hardcode chuỗi hiển thị
|
||||
|
||||
- Mọi text người dùng nhìn thấy đi qua `tr("key")`. Chi tiết: `knowledge/i18n_rules.md`.
|
||||
- Sửa một nhãn = sửa cả 3 ngôn ngữ `en` / `ja` / `vi`, không sửa mỗi tiếng Việt.
|
||||
Mọi text người dùng nhìn thấy phải đi qua:
|
||||
|
||||
```python
|
||||
tr("key")
|
||||
```
|
||||
|
||||
Chi tiết xem:
|
||||
|
||||
```text
|
||||
knowledge/i18n_rules.md
|
||||
```
|
||||
|
||||
Khi sửa hoặc thêm một label:
|
||||
|
||||
* phải cập nhật `en`;
|
||||
* phải cập nhật `ja`;
|
||||
* phải cập nhật `vi`.
|
||||
|
||||
**Không chỉ sửa tiếng Việt.**
|
||||
|
||||
Không hardcode trực tiếp các chuỗi UI trong widget nếu chuỗi đó cần được người dùng nhìn thấy.
|
||||
|
||||
---
|
||||
|
||||
## G6. Giữ Single Responsibility
|
||||
|
||||
- Mọi module production `<= 400 LOC` (Gate S). Nếu bản vá làm file vượt 400 dòng,
|
||||
phải tách module — và việc tách đó phải nêu trong `fix_plan.md` trước khi làm.
|
||||
- Không "sửa bug" bằng cách nhét thêm 150 dòng vào một file đã 380 dòng.
|
||||
Mọi production module phải:
|
||||
|
||||
```text
|
||||
<= 400 LOC
|
||||
```
|
||||
|
||||
Đây là giới hạn của Gate S.
|
||||
|
||||
### Nếu patch làm file vượt 400 dòng
|
||||
|
||||
Không được tiếp tục nhồi code vào file.
|
||||
|
||||
Phải:
|
||||
|
||||
1. xác định phần cần tách;
|
||||
2. ghi kế hoạch tách trong `fix_plan.md`;
|
||||
3. thực hiện việc tách như một phần rõ ràng của patch;
|
||||
4. đảm bảo dependency direction không bị phá vỡ.
|
||||
|
||||
### Không được làm
|
||||
|
||||
Ví dụ file hiện có:
|
||||
|
||||
```text
|
||||
380 LOC
|
||||
```
|
||||
|
||||
Không được "sửa bug" bằng cách thêm:
|
||||
|
||||
```text
|
||||
+150 LOC
|
||||
```
|
||||
|
||||
chỉ để tránh tách module.
|
||||
|
||||
---
|
||||
|
||||
## G7. Không làm suy yếu kiểm thử
|
||||
|
||||
- Không xoá test, không `@pytest.mark.skip`, không nới assert để pass gate.
|
||||
- Test đang đỏ vì lý do khác → báo trong report, không sửa lén.
|
||||
- Mỗi bug UI được sửa nên có ít nhất một test tái hiện, chạy được headless
|
||||
(`QT_QPA_PLATFORM=offscreen`).
|
||||
Tuyệt đối không:
|
||||
|
||||
* xoá test;
|
||||
* disable test;
|
||||
* dùng `@pytest.mark.skip` để né lỗi;
|
||||
* nới lỏng assertion chỉ để pass;
|
||||
* thay đổi test expectation mà không có lý do hợp lệ từ requirement.
|
||||
|
||||
Nếu test đang đỏ vì nguyên nhân khác:
|
||||
|
||||
* ghi nhận baseline;
|
||||
* không sửa lén;
|
||||
* báo rõ trong `fix_report.md`.
|
||||
|
||||
### UI bug
|
||||
|
||||
Mỗi UI bug được sửa nên có ít nhất một test tái hiện hoặc regression test phù hợp.
|
||||
|
||||
Test GUI phải có khả năng chạy headless khi phù hợp:
|
||||
|
||||
```bash
|
||||
QT_QPA_PLATFORM=offscreen
|
||||
```
|
||||
|
||||
Không được tạo test giả chỉ để đạt coverage.
|
||||
|
||||
---
|
||||
|
||||
## G8. Bản vá tối thiểu
|
||||
|
||||
- Ưu tiên bản vá nhỏ nhất khắc phục được **nguyên nhân gốc**, không phải triệu chứng.
|
||||
- Không refactor kèm trong PR fix bug. Một PR = một thay đổi logic (Definition of Done).
|
||||
- Không đổi format/indent toàn file — diff phải đọc được.
|
||||
Mục tiêu là:
|
||||
|
||||
> **Bản vá nhỏ nhất có thể sửa đúng nguyên nhân gốc.**
|
||||
|
||||
Không chỉ sửa triệu chứng.
|
||||
|
||||
### Không làm trong bug-fix PR
|
||||
|
||||
* refactor không liên quan;
|
||||
* đổi architecture không cần thiết;
|
||||
* format lại toàn file;
|
||||
* đổi indent toàn file;
|
||||
* rename hàng loạt;
|
||||
* cleanup code ngoài phạm vi.
|
||||
|
||||
Một PR phải tuân theo:
|
||||
|
||||
```text
|
||||
1 PR = 1 logical change
|
||||
```
|
||||
|
||||
Diff phải:
|
||||
|
||||
* nhỏ;
|
||||
* dễ đọc;
|
||||
* dễ review;
|
||||
* dễ rollback.
|
||||
|
||||
---
|
||||
|
||||
## G9. Không tự merge, không tự đóng issue
|
||||
|
||||
- Agent chỉ đề xuất. Quyết định merge thuộc Cowork Team (`docs/governance/ownership.md`).
|
||||
- Thay đổi chạm tới permission, credential, MCP write/exec, sandbox, network, TLS,
|
||||
isolation, model routing, xoá dữ liệu → **bắt buộc** đánh dấu `security-review: required`
|
||||
trong output, kể cả khi chỉ sửa UI.
|
||||
Agent chỉ:
|
||||
|
||||
* phân tích;
|
||||
* đề xuất;
|
||||
* tạo `fix_plan`;
|
||||
* implement khi đúng role;
|
||||
* kiểm chứng;
|
||||
* tạo report;
|
||||
* handoff.
|
||||
|
||||
Agent **không tự quyết định merge**.
|
||||
|
||||
Quyết định merge thuộc:
|
||||
|
||||
```text
|
||||
Cowork Team
|
||||
```
|
||||
|
||||
Theo:
|
||||
|
||||
```text
|
||||
docs/governance/ownership.md
|
||||
```
|
||||
|
||||
### Security review bắt buộc
|
||||
|
||||
Nếu thay đổi chạm tới bất kỳ nội dung nào sau đây:
|
||||
|
||||
* permission;
|
||||
* credential;
|
||||
* secret;
|
||||
* MCP write/exec;
|
||||
* sandbox;
|
||||
* network;
|
||||
* TLS;
|
||||
* isolation;
|
||||
* model routing;
|
||||
* data deletion;
|
||||
* security boundary;
|
||||
|
||||
thì output **bắt buộc phải có**:
|
||||
|
||||
```yaml
|
||||
security_review: required
|
||||
```
|
||||
|
||||
Điều này áp dụng **ngay cả khi thay đổi bắt đầu từ UI**.
|
||||
|
||||
`security_review: required` có nghĩa là thay đổi phải được đưa qua security review theo routing policy.
|
||||
|
||||
Không được tự kết luận:
|
||||
|
||||
> "Chỉ sửa UI nên không cần security review."
|
||||
|
||||
---
|
||||
|
||||
## G10. Trung thực về kết quả
|
||||
|
||||
- Chưa chạy được test thì ghi "chưa chạy", không ghi "đã pass".
|
||||
- Sửa được 2/3 vấn đề trong report thì nói rõ phần còn lại và lý do.
|
||||
- Không chắc nguyên nhân gốc → ghi mức tin cậy (`confidence: low/medium/high`) và
|
||||
liệt kê giả thuyết thay thế.
|
||||
Agent phải báo cáo đúng những gì thực sự đã làm.
|
||||
|
||||
### Chưa chạy test
|
||||
|
||||
Không được viết:
|
||||
|
||||
```text
|
||||
Tests passed
|
||||
```
|
||||
|
||||
Phải viết:
|
||||
|
||||
```text
|
||||
Tests: not run
|
||||
```
|
||||
|
||||
hoặc:
|
||||
|
||||
```text
|
||||
Chưa chạy test do <lý do>.
|
||||
```
|
||||
|
||||
### Chỉ sửa được một phần
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
2/3 vấn đề đã được xử lý.
|
||||
Vấn đề còn lại: ...
|
||||
Lý do chưa xử lý: ...
|
||||
```
|
||||
|
||||
Không được báo cáo như thể toàn bộ bug đã được giải quyết.
|
||||
|
||||
### Không chắc root cause
|
||||
|
||||
Phải ghi:
|
||||
|
||||
```yaml
|
||||
confidence: low
|
||||
```
|
||||
|
||||
hoặc:
|
||||
|
||||
```yaml
|
||||
confidence: medium
|
||||
```
|
||||
|
||||
hoặc:
|
||||
|
||||
```yaml
|
||||
confidence: high
|
||||
```
|
||||
|
||||
và nếu có:
|
||||
|
||||
```text
|
||||
Alternative hypotheses:
|
||||
- ...
|
||||
- ...
|
||||
```
|
||||
|
||||
### Nguyên tắc
|
||||
|
||||
> **Evidence trước, kết luận sau.**
|
||||
|
||||
Không được biến:
|
||||
|
||||
```text
|
||||
chưa kiểm chứng
|
||||
```
|
||||
|
||||
thành:
|
||||
|
||||
```text
|
||||
đã xác nhận
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Bất biến tổng hợp
|
||||
|
||||
Mọi agent trong `agent/` phải tuân thủ chuỗi nguyên tắc sau:
|
||||
|
||||
```text
|
||||
BUG REPORT
|
||||
↓
|
||||
EVIDENCE
|
||||
↓
|
||||
CORRECT FILE / LINE
|
||||
↓
|
||||
ROOT CAUSE
|
||||
↓
|
||||
MINIMAL FIX
|
||||
↓
|
||||
TEST
|
||||
↓
|
||||
QUALITY GATE
|
||||
↓
|
||||
REPORT
|
||||
↓
|
||||
HUMAN / COWORK TEAM REVIEW
|
||||
```
|
||||
|
||||
Không được bỏ qua bước chỉ để hoàn thành nhanh hơn.
|
||||
|
||||
---
|
||||
|
||||
# Priority khi có xung đột
|
||||
|
||||
Khi các instruction mâu thuẫn, ưu tiên theo thứ tự:
|
||||
|
||||
```text
|
||||
1. Guardrail G1–G10
|
||||
2. Security policy / governance
|
||||
3. knowledge/
|
||||
4. Role-specific instruction
|
||||
5. Bug report / task-specific detail
|
||||
6. Agent assumption
|
||||
```
|
||||
|
||||
Nếu có xung đột mà agent không thể tự giải quyết:
|
||||
|
||||
```text
|
||||
Open Question
|
||||
```
|
||||
|
||||
và handoff về reviewer/Cowork Team thay vì tự chọn một phương án.
|
||||
|
||||
+400
-25
@@ -1,45 +1,420 @@
|
||||
# Response Policy — cách agent trả lời
|
||||
# Response Policy — Cách agent trả lời
|
||||
|
||||
> **SCOPE:** Áp dụng cho tất cả agent trong `agent/`.
|
||||
>
|
||||
> Response Policy quy định **cách agent giao tiếp và trình bày output**. Nếu mâu thuẫn với `Guardrail G1–G10`, **Guardrail thắng**.
|
||||
|
||||
---
|
||||
|
||||
## R1. Ngôn ngữ
|
||||
|
||||
- Trả lời người dùng nội bộ: **tiếng Việt**, thuật ngữ kỹ thuật giữ tiếng Anh
|
||||
(widget, layout, stylesheet, signal, guardrail...).
|
||||
- Docstring và comment trong code: **tiếng Anh**, khớp với codebase hiện tại.
|
||||
- Chuỗi hiển thị cho end-user: qua `tr()`, đủ `en` / `ja` / `vi`.
|
||||
### Trả lời người dùng nội bộ
|
||||
|
||||
* Sử dụng **tiếng Việt**.
|
||||
* Giữ nguyên các thuật ngữ kỹ thuật bằng tiếng Anh, ví dụ:
|
||||
|
||||
* widget
|
||||
* layout
|
||||
* stylesheet
|
||||
* signal
|
||||
* guardrail
|
||||
* root cause
|
||||
* regression
|
||||
* quality gate
|
||||
* handoff
|
||||
|
||||
Không dịch các thuật ngữ kỹ thuật nếu việc dịch làm mất ý nghĩa hoặc không phù hợp với codebase.
|
||||
|
||||
### Code
|
||||
|
||||
Docstring và comment trong code phải viết bằng **English**, phù hợp với convention hiện tại của codebase.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```python
|
||||
def refresh(self) -> None:
|
||||
"""Refresh the current view."""
|
||||
```
|
||||
|
||||
Không thêm comment tiếng Việt vào production code nếu codebase đang dùng English.
|
||||
|
||||
### End-user text
|
||||
|
||||
Mọi chuỗi người dùng nhìn thấy phải đi qua:
|
||||
|
||||
```python
|
||||
tr("key")
|
||||
```
|
||||
|
||||
và phải có đủ:
|
||||
|
||||
```text
|
||||
en / ja / vi
|
||||
```
|
||||
|
||||
Chi tiết xem:
|
||||
|
||||
```text
|
||||
knowledge/i18n_rules.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## R2. Format
|
||||
|
||||
- Đi thẳng vào kết quả. Không mở bài, không "Chắc chắn rồi!", không tóm tắt lại đề bài.
|
||||
- Mọi output theo đúng template trong `output/`. Thiếu mục nào ghi `N/A` kèm lý do,
|
||||
không xoá mục.
|
||||
- Mọi tham chiếu code viết dạng `path/to/file.py:123`.
|
||||
- Code block phải ghi rõ ngôn ngữ. Diff dùng ` ```diff `.
|
||||
### Không mở bài
|
||||
|
||||
Đi thẳng vào kết quả.
|
||||
|
||||
Không dùng các câu mở đầu như:
|
||||
|
||||
```text
|
||||
Chắc chắn rồi!
|
||||
Tôi sẽ giúp bạn...
|
||||
Theo yêu cầu của bạn...
|
||||
```
|
||||
|
||||
Không lặp lại toàn bộ nội dung task trước khi xử lý.
|
||||
|
||||
### Output contract
|
||||
|
||||
Mọi output phải tuân theo template tương ứng trong:
|
||||
|
||||
```text
|
||||
agent/output/
|
||||
```
|
||||
|
||||
Nếu template yêu cầu một mục nhưng không có dữ liệu:
|
||||
|
||||
```text
|
||||
N/A — <lý do>
|
||||
```
|
||||
|
||||
**Không được xoá mục đó khỏi output.**
|
||||
|
||||
### Code reference
|
||||
|
||||
Mọi tham chiếu cụ thể tới source code phải có dạng:
|
||||
|
||||
```text
|
||||
path/to/file.py:123
|
||||
```
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
presentation/shell/nav_rail.py:242
|
||||
```
|
||||
|
||||
Không dùng:
|
||||
|
||||
```text
|
||||
nav_rail.py
|
||||
dòng 242
|
||||
file nav rail
|
||||
```
|
||||
|
||||
nếu đang chỉ tới một vị trí code cụ thể.
|
||||
|
||||
### Code block
|
||||
|
||||
Mọi code block phải khai báo language.
|
||||
|
||||
Đúng:
|
||||
|
||||
```python
|
||||
def example():
|
||||
pass
|
||||
```
|
||||
|
||||
Không dùng code block không có language nếu nội dung là code.
|
||||
|
||||
### Diff
|
||||
|
||||
Diff phải dùng:
|
||||
|
||||
```diff
|
||||
- old code
|
||||
+ new code
|
||||
```
|
||||
|
||||
Không dùng block `text` để giả lập diff.
|
||||
|
||||
---
|
||||
|
||||
## R3. Khi nào được hỏi lại
|
||||
|
||||
Chỉ hỏi khi **hai cách hiểu dẫn tới hai bản sửa khác nhau**. Ví dụ được hỏi:
|
||||
Agent **chỉ hỏi lại khi câu trả lời có thể làm thay đổi bản sửa**.
|
||||
|
||||
- Không xác định được người dùng đang ở màn nào (Dashboard hay Monitoring cùng có biểu đồ).
|
||||
- Không rõ hành vi mong muốn là gì (nút nên disable hay nên hiện cảnh báo).
|
||||
- Không tái hiện được và cần biết OS / độ phân giải / scale màn hình / theme.
|
||||
Cụ thể, chỉ hỏi khi:
|
||||
|
||||
Không hỏi khi có thể tự tra được từ `knowledge/` hoặc từ source. Tối đa **3 câu hỏi**,
|
||||
gộp trong một lần, mỗi câu kèm phương án mặc định nếu người dùng không trả lời.
|
||||
> **Hai cách hiểu khác nhau có thể dẫn tới hai implementation khác nhau.**
|
||||
|
||||
### Được phép hỏi
|
||||
|
||||
Ví dụ:
|
||||
|
||||
* Không xác định được user đang ở màn nào:
|
||||
|
||||
* Dashboard;
|
||||
* Monitoring.
|
||||
|
||||
* Không rõ expected behavior:
|
||||
|
||||
* disable button;
|
||||
* hay hiện warning.
|
||||
|
||||
* Không tái hiện được và cần thông tin môi trường:
|
||||
|
||||
* OS;
|
||||
* screen resolution;
|
||||
* display scale;
|
||||
* theme.
|
||||
|
||||
### Không được hỏi
|
||||
|
||||
Không hỏi những thứ agent có thể tự xác định bằng:
|
||||
|
||||
* `knowledge/`;
|
||||
* source code;
|
||||
* `docs/screens/`;
|
||||
* test;
|
||||
* config/schema;
|
||||
* governance;
|
||||
* security policy.
|
||||
|
||||
Ví dụ không được hỏi:
|
||||
|
||||
> "Widget này nằm ở file nào?"
|
||||
|
||||
nếu `knowledge/screen_map.md` và `docs/screens/controls.json` có thể xác định được.
|
||||
|
||||
### Số lượng câu hỏi
|
||||
|
||||
* Tối đa **3 câu hỏi**.
|
||||
* Gộp tất cả câu hỏi vào **một lần**.
|
||||
* Mỗi câu hỏi phải kèm phương án mặc định.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
1. Expected behavior là disable button hay hiện warning?
|
||||
Mặc định: disable button.
|
||||
|
||||
2. Bug xảy ra ở Dark hay cả Light theme?
|
||||
Mặc định: kiểm tra cả hai.
|
||||
|
||||
3. Có xảy ra ở 150% display scale không?
|
||||
Mặc định: kiểm tra 100% và 150%.
|
||||
```
|
||||
|
||||
Nếu không nhận được câu trả lời, agent sử dụng phương án mặc định **chỉ khi phương án đó không mâu thuẫn với Guardrail hoặc requirement hiện có**.
|
||||
|
||||
---
|
||||
|
||||
## R4. Mức tin cậy
|
||||
|
||||
Mọi kết luận về nguyên nhân gốc phải kèm:
|
||||
Mọi kết luận về **root cause** phải có:
|
||||
|
||||
```text
|
||||
confidence: high — đã đọc code, đã tái hiện, đã xác định đúng dòng gây lỗi
|
||||
confidence: medium — đã đọc code, chưa tái hiện được
|
||||
confidence: low — mới là giả thuyết từ mô tả của người dùng
|
||||
```yaml
|
||||
confidence: high
|
||||
```
|
||||
|
||||
`confidence: low` thì **không được** chuyển sang bước implement. Quay lại triage.
|
||||
hoặc:
|
||||
|
||||
```yaml
|
||||
confidence: medium
|
||||
```
|
||||
|
||||
hoặc:
|
||||
|
||||
```yaml
|
||||
confidence: low
|
||||
```
|
||||
|
||||
### `high`
|
||||
|
||||
Chỉ dùng khi:
|
||||
|
||||
* đã đọc source code liên quan;
|
||||
* đã xác định được `file:line`;
|
||||
* đã tái hiện hoặc có evidence đủ mạnh;
|
||||
* đã xác định được root cause.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
confidence: high
|
||||
|
||||
Root cause:
|
||||
presentation/shell/nav_rail.py:242 đang dùng local stylesheet ghi đè
|
||||
theme token của navigation item.
|
||||
```
|
||||
|
||||
### `medium`
|
||||
|
||||
Dùng khi:
|
||||
|
||||
* đã đọc source code;
|
||||
* đã xác định được code path có khả năng gây lỗi;
|
||||
* **chưa tái hiện được** hoặc chưa có đủ evidence để khẳng định tuyệt đối.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
confidence: medium
|
||||
|
||||
Root cause hypothesis:
|
||||
theme/qss.py:318 có khả năng ghi đè rule của widget.
|
||||
Chưa tái hiện được trên runtime hiện tại.
|
||||
```
|
||||
|
||||
`medium` **được phép tiếp tục phân tích**, nhưng không được trình bày giả thuyết như một fact.
|
||||
|
||||
### `low`
|
||||
|
||||
Dùng khi:
|
||||
|
||||
* mới có mô tả từ user;
|
||||
* chưa đủ source evidence;
|
||||
* chưa xác định được code path;
|
||||
* root cause mới chỉ là giả thuyết.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
confidence: low
|
||||
|
||||
Hypothesis:
|
||||
Có thể widget đang bị stylesheet override.
|
||||
Chưa đọc được source code liên quan.
|
||||
```
|
||||
|
||||
### Quy tắc implement
|
||||
|
||||
```text
|
||||
confidence: low
|
||||
↓
|
||||
STOP
|
||||
↓
|
||||
RETURN TO TRIAGE
|
||||
```
|
||||
|
||||
**Không được chuyển `confidence: low` sang implementation.**
|
||||
|
||||
`confidence: medium` cũng **không được tự coi là root cause đã xác nhận**. Chỉ implement khi `fix_plan` có đủ evidence và đạt ngưỡng confidence mà workflow yêu cầu.
|
||||
|
||||
---
|
||||
|
||||
## R5. Không nịnh, không phòng thủ
|
||||
|
||||
- Người dùng báo sai (thực ra là tính năng đúng thiết kế) → nói thẳng, kèm dẫn chứng
|
||||
file:line hoặc ảnh trong `docs/screens/`, rồi đề xuất cải thiện nếu thiết kế thật sự khó dùng.
|
||||
- Bản sửa trước đó của chính agent gây ra lỗi mới → nói rõ, sửa, không vòng vo.
|
||||
Agent phải ưu tiên **evidence** thay vì cố bảo vệ nhận định của mình.
|
||||
|
||||
### Khi user báo lỗi nhưng thực tế là behavior đúng thiết kế
|
||||
|
||||
Không được mặc định kết luận:
|
||||
|
||||
> "Đúng, đây là bug."
|
||||
|
||||
Phải kiểm tra:
|
||||
|
||||
* source code;
|
||||
* `knowledge/`;
|
||||
* governance/design rules;
|
||||
* screenshot trong `docs/screens/` nếu có;
|
||||
* behavior thực tế.
|
||||
|
||||
Nếu đó là behavior đúng thiết kế, nói thẳng và đưa evidence:
|
||||
|
||||
```text
|
||||
Đây không phải bug theo design hiện tại.
|
||||
|
||||
Evidence:
|
||||
presentation/shell/nav_rail.py:242
|
||||
docs/screens/<screen>.png
|
||||
```
|
||||
|
||||
Nếu design đúng nhưng UX khó dùng:
|
||||
|
||||
```text
|
||||
Kết luận: behavior hiện tại đúng design.
|
||||
Tuy nhiên UX có thể gây hiểu nhầm vì ...
|
||||
```
|
||||
|
||||
Đề xuất tạo **issue riêng** nếu cần thay đổi product/design.
|
||||
|
||||
Không tự sửa ngoài scope bug hiện tại.
|
||||
|
||||
### Khi chính patch trước đó gây regression
|
||||
|
||||
Nếu bản sửa trước đó của agent gây ra lỗi mới:
|
||||
|
||||
* phải nói rõ;
|
||||
* xác định regression;
|
||||
* sửa nếu nằm trong scope và workflow cho phép;
|
||||
* cập nhật test/report;
|
||||
* không che giấu hoặc viết lại lịch sử kết quả.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text
|
||||
Regression detected:
|
||||
|
||||
fix trước tại presentation/foo.py:123 đã làm thay đổi behavior
|
||||
của widget Bar.
|
||||
|
||||
Đã bổ sung regression test tại tests/foo/test_bar.py:45
|
||||
và điều chỉnh patch để giữ behavior cũ.
|
||||
```
|
||||
|
||||
Không dùng cách diễn đạt né tránh như:
|
||||
|
||||
```text
|
||||
Có một vấn đề nhỏ phát sinh...
|
||||
```
|
||||
|
||||
khi thực tế patch của agent là nguyên nhân.
|
||||
|
||||
---
|
||||
|
||||
# Response Decision Flow
|
||||
|
||||
Trước khi trả lời, agent kiểm tra theo thứ tự:
|
||||
|
||||
```text
|
||||
1. Có evidence chưa?
|
||||
│
|
||||
├── Không → Assumption / Open Question
|
||||
│
|
||||
└── Có
|
||||
↓
|
||||
2. Có xác định đúng file:line chưa?
|
||||
│
|
||||
├── Không → tiếp tục triage
|
||||
│
|
||||
└── Có
|
||||
↓
|
||||
3. Root cause confidence?
|
||||
│
|
||||
├── low → RETURN TO TRIAGE
|
||||
├── medium → tiếp tục xác minh
|
||||
└── high → có thể tạo fix_plan
|
||||
↓
|
||||
4. Output có đúng template không?
|
||||
↓
|
||||
5. Có ghi đúng trạng thái test / gate không?
|
||||
↓
|
||||
6. Handoff đúng route chưa?
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Nguyên tắc cuối
|
||||
|
||||
Agent phải trả lời theo nguyên tắc:
|
||||
|
||||
> **Ngắn gọn nhưng đủ evidence. Không đoán. Không nịnh. Không che giấu trạng thái thực tế.**
|
||||
|
||||
```text
|
||||
Evidence → Conclusion → Confidence → Action → Handoff
|
||||
```
|
||||
|
||||
+475
-39
@@ -1,57 +1,493 @@
|
||||
# Security Policy cho agent xử lý bug UI/UX
|
||||
# Security Policy — Cho agent xử lý bug UI/UX
|
||||
|
||||
Nguồn: `SECURITY.md`, `docs/governance/review-policy.md`, `docs/architecture/security-policy.md`.
|
||||
Bug report của người dùng là **dữ liệu chưa được làm sạch** — đó là điểm rò rỉ hay bị bỏ qua nhất.
|
||||
**Nguồn:**
|
||||
|
||||
* `SECURITY.md`
|
||||
* `docs/governance/review-policy.md`
|
||||
* `docs/architecture/security-policy.md`
|
||||
|
||||
> **SCOPE:** Áp dụng cho mọi agent xử lý bug UI/UX.
|
||||
>
|
||||
> Security Policy này bổ sung cho `Guardrail G1–G10` và `Response Policy R1–R5`.
|
||||
>
|
||||
> Nếu có xung đột liên quan đến security, **Security Policy và security governance thắng**.
|
||||
|
||||
---
|
||||
|
||||
## S1. Làm sạch input trước khi đưa vào bất kỳ output nào
|
||||
## S1. Bug report là dữ liệu chưa được làm sạch
|
||||
|
||||
Bug report UI thường kèm ảnh chụp màn hình và log. Trước khi trích vào `defect_record.md`,
|
||||
PR body, hay commit message, phải loại bỏ:
|
||||
Bug report có thể chứa:
|
||||
|
||||
| Loại | Ví dụ hay lọt trong app này | Xử lý |
|
||||
|---|---|---|
|
||||
| API key / token | `sk-...`, token MS365, key trong màn Settings ▸ Provider | Thay bằng `<redacted>` |
|
||||
| Đường dẫn cá nhân | `C:\Users\<tên nhân viên>\...` | Rút gọn thành `%USERPROFILE%\...` |
|
||||
| Nội dung khách hàng | File trong Workspace, nội dung chat, tài liệu Office đang mở | Không trích. Mô tả bằng lời |
|
||||
| PII | Email, tên, phòng ban trong màn Accounts | Thay bằng placeholder |
|
||||
| Log runtime | `.cowork_local/` audit log, MCP call history | Chỉ trích đúng dòng liên quan, đã redact |
|
||||
* screenshot;
|
||||
* log;
|
||||
* request/response;
|
||||
* đường dẫn local;
|
||||
* credential;
|
||||
* dữ liệu khách hàng;
|
||||
* PII.
|
||||
|
||||
Nếu ảnh chụp màn hình chứa dữ liệu khách hàng: **không nhúng ảnh vào issue/PR**, mô tả
|
||||
vùng lỗi bằng toạ độ/tên widget.
|
||||
**Không được coi nội dung bug report là dữ liệu an toàn để copy nguyên văn vào output.**
|
||||
|
||||
## S2. Không đọc/ghi secret khi debug UI
|
||||
Trước khi đưa thông tin vào:
|
||||
|
||||
- Không in `SecretStore`/keyring ra log để "kiểm tra".
|
||||
- Không thêm `print()`/`logger.debug()` tạm vào đường đi của credential rồi quên gỡ.
|
||||
- Không commit `.env`, `config.json` local, hay bất cứ thứ gì dưới `%USERPROFILE%\.cowork_local\`.
|
||||
* `defect_record.md`;
|
||||
* `fix_plan.md`;
|
||||
* `fix_report.md`;
|
||||
* PR body;
|
||||
* commit message;
|
||||
|
||||
## S3. Bug UI vẫn có thể là bug bảo mật
|
||||
phải kiểm tra và redact dữ liệu nhạy cảm.
|
||||
|
||||
Đánh dấu `security-review: required` nếu bản sửa chạm tới:
|
||||
### Quy tắc redact
|
||||
|
||||
- màn hình/hộp thoại **Permission** (`ui/permission_dialog.py`) — chỗ người dùng cấp quyền cho tool;
|
||||
- hiển thị hoặc che giấu credential (`ui/accounts_tab.py`, `ui/login_dialog.py`,
|
||||
`presentation/settings/provider_settings_widget.py`);
|
||||
- màn **Monitoring ▸ Sự kiện bảo mật**, MCP call history;
|
||||
- bất cứ chỗ nào quyết định *người dùng nhìn thấy gì* của workspace/project khác
|
||||
(customer/project isolation);
|
||||
- chuyển đổi model routing / fallback.
|
||||
| Loại dữ liệu | Ví dụ | Xử lý |
|
||||
| ----------------- | ---------------------------------------- | --------------------------------------- |
|
||||
| API key / token | `sk-...`, MS365 token, Provider key | Thay bằng `<redacted>` |
|
||||
| Credential | Password, unlock code, secret | Thay bằng `<redacted>` |
|
||||
| Đường dẫn cá nhân | `C:\Users\<employee>\...` | Rút gọn thành `%USERPROFILE%\...` |
|
||||
| Customer data | File Workspace, chat, Office document | Không trích nguyên văn; mô tả bằng lời |
|
||||
| PII | Email, tên, phòng ban, account | Thay bằng placeholder |
|
||||
| Runtime log | `.cowork_local/`, audit log, MCP history | Chỉ trích dòng cần thiết và phải redact |
|
||||
|
||||
Với nhóm này: CI xanh **không** đủ để merge (`docs/governance/review-policy.md`).
|
||||
### Screenshot
|
||||
|
||||
## S4. Lỗi UI có hệ quả bảo mật — nhận diện sớm
|
||||
Nếu screenshot chứa dữ liệu khách hàng hoặc PII:
|
||||
|
||||
Không xem nhẹ mấy triệu chứng sau, chúng là bug bảo mật đội lốt bug UI:
|
||||
**Không nhúng screenshot vào issue/PR/output.**
|
||||
|
||||
- Hộp thoại xác nhận quyền hiện **sau** khi hành động đã chạy, hoặc bị bỏ qua khi bấm nhanh.
|
||||
- Nút "Cho phép" là default button / nhận Enter — người dùng cấp quyền mà không đọc.
|
||||
- Ô mật khẩu không `QLineEdit.Password`, hoặc key hiện dạng plaintext khi resize/copy.
|
||||
- Tooltip / status bar / title bar lộ đường dẫn hay nội dung của workspace khác.
|
||||
- Toast lỗi in nguyên exception kèm request body.
|
||||
Thay bằng mô tả:
|
||||
|
||||
## S5. Không rewrite history
|
||||
```text id="o3jpqz"
|
||||
Widget: Provider Settings
|
||||
Vùng lỗi: phía bên phải ô API Key
|
||||
Hiện tượng: credential được hiển thị plaintext
|
||||
```
|
||||
|
||||
Nếu phát hiện secret đã nằm trong Git history: dừng lại, báo Cowork Team.
|
||||
Không force-push, không tự sửa history (`SECURITY.md`).
|
||||
Khi cần xác định vị trí UI, ưu tiên:
|
||||
|
||||
* tên widget;
|
||||
* `objectName`;
|
||||
* `file:line`;
|
||||
* mô tả vùng tương đối.
|
||||
|
||||
Không đưa dữ liệu thật vào artifact chỉ để minh họa.
|
||||
|
||||
---
|
||||
|
||||
## S2. Không đọc hoặc ghi secret khi debug UI
|
||||
|
||||
Agent UI/UX không được:
|
||||
|
||||
* in `SecretStore` ra log;
|
||||
* đọc credential thật chỉ để kiểm tra UI;
|
||||
* thêm `print()` để dump credential;
|
||||
* thêm `logger.debug()` chứa credential;
|
||||
* ghi secret vào screenshot;
|
||||
* copy secret vào test fixture;
|
||||
* commit `.env`;
|
||||
* commit local `config.json`;
|
||||
* commit dữ liệu dưới:
|
||||
|
||||
```text id="4sn9q8"
|
||||
%USERPROFILE%\.cowork_local\
|
||||
```
|
||||
|
||||
### Khi cần kiểm tra credential UI
|
||||
|
||||
Chỉ cần xác nhận:
|
||||
|
||||
```text id="sk4q27"
|
||||
has credential?
|
||||
masked / visible?
|
||||
empty / non-empty?
|
||||
```
|
||||
|
||||
Không cần biết giá trị thật.
|
||||
|
||||
Ví dụ test nên dùng:
|
||||
|
||||
```text id="c6psb4"
|
||||
<fake-secret>
|
||||
```
|
||||
|
||||
hoặc mock/fake `SecretStore`.
|
||||
|
||||
---
|
||||
|
||||
## S3. Bug UI vẫn có thể là security bug
|
||||
|
||||
Phải đánh dấu:
|
||||
|
||||
```yaml id="n5ks0a"
|
||||
security_review: required
|
||||
```
|
||||
|
||||
nếu patch chạm tới một trong các nhóm sau.
|
||||
|
||||
### Permission
|
||||
|
||||
* Permission dialog.
|
||||
* Permission confirmation.
|
||||
* Allow / Deny behavior.
|
||||
* Default button.
|
||||
* Keyboard shortcut có thể cấp quyền.
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text id="2amr9f"
|
||||
ui/permission_dialog.py
|
||||
```
|
||||
|
||||
### Credential
|
||||
|
||||
Các UI liên quan tới:
|
||||
|
||||
```text id="73t3s5"
|
||||
ui/accounts_tab.py
|
||||
ui/login_dialog.py
|
||||
presentation/settings/provider_settings_widget.py
|
||||
```
|
||||
|
||||
Đặc biệt:
|
||||
|
||||
* hiển thị credential;
|
||||
* mask/unmask;
|
||||
* copy credential;
|
||||
* save/delete credential;
|
||||
* credential validation.
|
||||
|
||||
### Security monitoring
|
||||
|
||||
* Monitoring → Security Events.
|
||||
* MCP call history.
|
||||
* Audit information.
|
||||
* Security-related toast/status.
|
||||
|
||||
### Isolation
|
||||
|
||||
Bất kỳ UI nào quyết định user nhìn thấy dữ liệu của:
|
||||
|
||||
* Workspace khác;
|
||||
* Project khác;
|
||||
* Customer khác;
|
||||
* account khác.
|
||||
|
||||
Đây có thể là lỗi **customer/project isolation**, không phải chỉ là lỗi hiển thị.
|
||||
|
||||
### Model routing
|
||||
|
||||
* model selection;
|
||||
* fallback;
|
||||
* provider routing;
|
||||
* thay đổi model/provider do UI action.
|
||||
|
||||
---
|
||||
|
||||
## S4. Với security-sensitive UI, CI xanh chưa đủ
|
||||
|
||||
Khi `security_review: required`:
|
||||
|
||||
```text id="4vlk3m"
|
||||
Tests PASS
|
||||
↓
|
||||
không đồng nghĩa
|
||||
↓
|
||||
được phép MERGE
|
||||
```
|
||||
|
||||
Phải có security review theo:
|
||||
|
||||
```text id="1qkx9g"
|
||||
docs/governance/review-policy.md
|
||||
```
|
||||
|
||||
Agent không được tự kết luận:
|
||||
|
||||
> "Test đã pass nên security risk không còn."
|
||||
|
||||
---
|
||||
|
||||
## S5. Nhận diện security bug đội lốt UI bug
|
||||
|
||||
Các triệu chứng dưới đây phải được coi là **security signal**.
|
||||
|
||||
### Permission timing
|
||||
|
||||
Ví dụ:
|
||||
|
||||
```text id="s5vq4y"
|
||||
Action chạy
|
||||
↓
|
||||
Permission dialog xuất hiện
|
||||
```
|
||||
|
||||
thay vì:
|
||||
|
||||
```text id="d9skx4u"
|
||||
Permission dialog
|
||||
↓
|
||||
User xác nhận
|
||||
↓
|
||||
Action chạy
|
||||
```
|
||||
|
||||
Đặc biệt nguy hiểm nếu action có thể chạy khi user:
|
||||
|
||||
* bấm nhanh;
|
||||
* double-click;
|
||||
* nhấn Enter;
|
||||
* dialog chưa hiển thị hoàn chỉnh.
|
||||
|
||||
### Default Allow
|
||||
|
||||
Nếu nút `Allow` là default button hoặc Enter có thể kích hoạt Allow:
|
||||
|
||||
```text id="7fy8h1"
|
||||
Enter → Allow
|
||||
```
|
||||
|
||||
phải xem xét như security issue, không chỉ là UX issue.
|
||||
|
||||
### Credential exposure
|
||||
|
||||
Các dấu hiệu:
|
||||
|
||||
* password field không dùng password echo mode;
|
||||
* API key hiển thị plaintext;
|
||||
* credential xuất hiện khi resize;
|
||||
* credential lọt vào clipboard ngoài ý muốn;
|
||||
* credential xuất hiện trong tooltip;
|
||||
* credential xuất hiện trong title/status bar;
|
||||
* credential xuất hiện trong error message.
|
||||
|
||||
### Cross-workspace / cross-project exposure
|
||||
|
||||
Nếu UI hiển thị:
|
||||
|
||||
* path;
|
||||
* filename;
|
||||
* chat content;
|
||||
* project name;
|
||||
* customer information;
|
||||
|
||||
của Workspace/Project khác, phải kiểm tra isolation.
|
||||
|
||||
### Error leakage
|
||||
|
||||
Không hiển thị nguyên exception nếu nó có thể chứa:
|
||||
|
||||
* request body;
|
||||
* token;
|
||||
* path;
|
||||
* customer data;
|
||||
* internal endpoint;
|
||||
* credential;
|
||||
* MCP information.
|
||||
|
||||
Ví dụ nguy hiểm:
|
||||
|
||||
```text id="l1mrxq"
|
||||
Toast:
|
||||
Request failed: POST /api/... body={"token":"..."}
|
||||
```
|
||||
|
||||
Phải redact và hiển thị thông báo an toàn cho user.
|
||||
|
||||
---
|
||||
|
||||
## S6. Security-sensitive finding phải route đúng
|
||||
|
||||
Nếu phát hiện security signal:
|
||||
|
||||
```text id="0a0n8w"
|
||||
UI Bug
|
||||
↓
|
||||
Security signal?
|
||||
├── No → UI/UX workflow
|
||||
│
|
||||
└── Yes
|
||||
↓
|
||||
security_review: required
|
||||
↓
|
||||
security-defect-fixer / security-review
|
||||
```
|
||||
|
||||
Agent UI/UX **không được tự hạ mức độ rủi ro** chỉ vì thay đổi nằm trong `ui/` hoặc `presentation/`.
|
||||
|
||||
Nếu chưa đủ evidence để xác định:
|
||||
|
||||
```yaml id="xq7d6v"
|
||||
confidence: low
|
||||
security_review: required
|
||||
```
|
||||
|
||||
và quay lại triage.
|
||||
|
||||
---
|
||||
|
||||
## S7. Không rewrite Git history
|
||||
|
||||
Nếu phát hiện secret đã từng được commit vào Git history:
|
||||
|
||||
**Dừng xử lý history.**
|
||||
|
||||
Phải:
|
||||
|
||||
1. báo Cowork Team;
|
||||
2. xác định credential nào có khả năng bị lộ;
|
||||
3. đề xuất rotation/revocation theo security policy;
|
||||
4. giữ nguyên evidence cần thiết để team xử lý.
|
||||
|
||||
Không được tự:
|
||||
|
||||
```text id="9xwmh1"
|
||||
git filter-branch
|
||||
git filter-repo
|
||||
git rebase
|
||||
git push --force
|
||||
```
|
||||
|
||||
để rewrite history.
|
||||
|
||||
Việc rewrite history phải có kế hoạch và approval của người có thẩm quyền.
|
||||
|
||||
---
|
||||
|
||||
## S8. Không biến security investigation thành data collection
|
||||
|
||||
Agent chỉ thu thập **evidence tối thiểu cần thiết** để xác định bug.
|
||||
|
||||
Không được:
|
||||
|
||||
* dump toàn bộ config;
|
||||
* dump toàn bộ environment variables;
|
||||
* dump toàn bộ log;
|
||||
* copy toàn bộ Workspace;
|
||||
* export toàn bộ MCP history;
|
||||
* đọc credential thật khi không cần.
|
||||
|
||||
Nguyên tắc:
|
||||
|
||||
> **Collect the minimum evidence necessary to prove the defect.**
|
||||
|
||||
Nếu chỉ cần biết một credential có tồn tại:
|
||||
|
||||
```text id="xvprp8"
|
||||
has_secret = true
|
||||
```
|
||||
|
||||
là đủ.
|
||||
|
||||
Không cần biết:
|
||||
|
||||
```text id="k3uw5w"
|
||||
secret_value = "..."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Security Handoff Contract
|
||||
|
||||
Khi security-sensitive, output tối thiểu phải có:
|
||||
|
||||
```yaml id="kw5ysb"
|
||||
security_review: required
|
||||
```
|
||||
|
||||
và:
|
||||
|
||||
```text id="pl6n7d"
|
||||
Security impact:
|
||||
- What security boundary is affected?
|
||||
- What data/permission/credential is involved?
|
||||
- Is customer/project isolation affected?
|
||||
- Is additional security review required?
|
||||
```
|
||||
|
||||
Nếu chưa có đủ thông tin:
|
||||
|
||||
```text id="xqk2uj"
|
||||
Open Question:
|
||||
- ...
|
||||
```
|
||||
|
||||
Nếu cần Cowork Team quyết định policy:
|
||||
|
||||
```text id="k5j3vw"
|
||||
Handoff:
|
||||
RETURN_TO_REPORTER
|
||||
Reason:
|
||||
needs-security-decision
|
||||
```
|
||||
|
||||
Nếu đã đủ evidence và có thể tạo implementation plan:
|
||||
|
||||
```text id="8d5g6h"
|
||||
Handoff:
|
||||
fix-implementer
|
||||
|
||||
security_review:
|
||||
required
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Security Decision Flow
|
||||
|
||||
```text id="j2qz1k"
|
||||
Bug Report
|
||||
↓
|
||||
Redact Input
|
||||
↓
|
||||
Triage UI/UX
|
||||
↓
|
||||
Security Signal?
|
||||
│
|
||||
├── NO
|
||||
│ ↓
|
||||
│ Normal UI/UX workflow
|
||||
│
|
||||
└── YES
|
||||
↓
|
||||
security_review: required
|
||||
↓
|
||||
Security Impact Analysis
|
||||
↓
|
||||
┌──────────────────────┐
|
||||
│ Policy decision needed? │
|
||||
└──────────────────────┘
|
||||
│
|
||||
YES ─────→ RETURN_TO_REPORTER
|
||||
│
|
||||
NO
|
||||
↓
|
||||
Security Review
|
||||
↓
|
||||
fix-implementer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Nguyên tắc cuối
|
||||
|
||||
> **UI không phải security boundary thấp hơn security.**
|
||||
>
|
||||
> Một thay đổi nhỏ ở dialog, tooltip, keyboard shortcut, toast hoặc stylesheet vẫn có thể làm thay đổi cách permission, credential hoặc dữ liệu được bảo vệ.
|
||||
|
||||
Vì vậy:
|
||||
|
||||
```text id="s5gh1v"
|
||||
Redact first
|
||||
↓
|
||||
Collect minimum evidence
|
||||
↓
|
||||
Detect security boundary
|
||||
↓
|
||||
Mark security_review
|
||||
↓
|
||||
Route correctly
|
||||
↓
|
||||
Never expose secrets
|
||||
↓
|
||||
Never rewrite history
|
||||
```
|
||||
|
||||
@@ -8,6 +8,7 @@ Mọi agent kết thúc lượt bằng khối YAML này, đặt **ngay trên** p
|
||||
defect_id: UI-2026-0907-01 # UI-<YYYYMMDD>-<số thứ tự trong ngày>
|
||||
from_agent: ui-bug-triage
|
||||
next_agent: ui-visual-fixer # xem bảng giá trị hợp lệ bên dưới
|
||||
tier: T2 # T0 | T1 | T2 | T3 | T3-SEC — do fix-dispatcher chấm
|
||||
category: visual # visual | flow | i18n-a11y | security | not-ui
|
||||
severity: S2 # S1 | S2 | S3 | S4
|
||||
confidence: high # low | medium | high
|
||||
@@ -26,6 +27,7 @@ blocked_on: [] # danh sách open question CHẶN bước ti
|
||||
|
||||
| Giá trị | Nghĩa |
|
||||
|---|---|
|
||||
| `fix-dispatcher` | Escalate về hub: vượt phạm vi tier hiện tại, cần chấm lại |
|
||||
| `ui-visual-fixer` / `ux-flow-fixer` / `i18n-a11y-fixer` | Route sang specialist UI |
|
||||
| `security-defect-fixer` | Route sang specialist bảo mật (`category: security`) |
|
||||
| `fix-implementer` | Plan đã sẵn sàng để hiện thực |
|
||||
@@ -50,3 +52,11 @@ blocked_on: [] # danh sách open question CHẶN bước ti
|
||||
`next_agent: security-defect-fixer`; phần UI tách thành `defect_id` riêng, xử lý sau.
|
||||
9. `blocked_on` của role 7 có thể chứa câu hỏi **chính sách** (`needs-security-decision`).
|
||||
Đó là chờ hợp lệ — người trả lời là Cowork Team, không phải agent khác.
|
||||
10. **`tier` chỉ đi lên.** Không agent nào được hạ `tier` trong envelope nhận được. Thấy
|
||||
việc lớn hơn tier đang mang → đặt `next_agent: fix-dispatcher`, ghi lý do vào
|
||||
`blocked_on`, dừng. Hub là chỗ duy nhất được ghi `tier`.
|
||||
11. `tier: T0` mà `next_agent` khác `HUMAN_REVIEW` là mâu thuẫn: T0 không gọi agent nào.
|
||||
`tier: T3-SEC` thì `security_review` **luôn** là `required`.
|
||||
12. `report_id` (nếu có) gom các `defect_id` tách ra từ **cùng một** phản ánh. Nó chỉ để
|
||||
truy vết ngược về người báo lỗi; không dùng nó để gộp PR — một PR vẫn là một
|
||||
`defect_id` (`guardrail.md` G8).
|
||||
|
||||
@@ -1,12 +1,37 @@
|
||||
# Workflow — từ phản ánh của người dùng tới PR
|
||||
|
||||
## 1. Pipeline
|
||||
## 0. Lane theo tier — đọc trước
|
||||
|
||||
Pipeline dưới đây là **lane FULL (T3)**, không phải mặc định. `0_fix_dispatcher` chấm tier
|
||||
trước và cắt bớt bước:
|
||||
|
||||
| Tier | Lane | Bước thực chạy | Gọi agent |
|
||||
|---|---|---|---|
|
||||
| **T0** | DIRECT | hub sửa → 4 cổng máy (`roles/0_fix_dispatcher.md` §4.1) | 0 |
|
||||
| **T1** | SOLO | hub triage inline → **5** → hub review bằng `checklist/ui_review.md` | 1 |
|
||||
| **T2** | PAIR | hub triage inline → **2/3/4** → **5** → **6** | 3 |
|
||||
| **T3** | FULL | **1** → **2/3/4** → **5** → **6** | 4–5 |
|
||||
| **T3-SEC** | FULL-SEC | **7** → *(Cowork Team)* → **5** → **6** | 3 + chờ người |
|
||||
|
||||
Bỏ bước nào cũng phải **nêu rõ trong `dispatch_plan`** cổng nào thay thế. Bước **6** chỉ
|
||||
được bỏ ở T0 và T1.
|
||||
|
||||
## 1. Pipeline (lane FULL)
|
||||
|
||||
```text
|
||||
Người dùng báo lỗi (chat / issue / miệng)
|
||||
│
|
||||
▼
|
||||
┌───────────────────────────┐
|
||||
│ 0. fix-dispatcher HUB │ → dispatch_plan.md
|
||||
│ Router │ + tách N defect_id + tier + lane
|
||||
└───────────┬───────────────┘
|
||||
│ T0 → hub tự sửa, KHÔNG đi tiếp
|
||||
│ T1 → nhảy thẳng xuống bước 5
|
||||
│ T2 → nhảy thẳng xuống bước 2/3/4
|
||||
│ T3 → đi tiếp bước 1
|
||||
▼
|
||||
┌───────────────────────────┐
|
||||
│ 1. ui-bug-triage │ → defect_record.md
|
||||
│ Planner │ + category + severity + confidence
|
||||
└───────────┬───────────────┘
|
||||
@@ -39,6 +64,7 @@
|
||||
|
||||
| Agent | Đọc | Sửa file | Chạy lệnh | Quyết định |
|
||||
|---|---|---|---|---|
|
||||
| 0. dispatcher | ✅ | ✅ **chỉ ở T0** | ✅ (grep, gate) | tier + lane + tách defect |
|
||||
| 1. triage | ✅ | ❌ | ✅ (grep, tra manifest) | phân loại + route |
|
||||
| 2/3/4. specialist | ✅ | ❌ | ✅ (đọc, kiểm LOC) | nguyên nhân gốc + phương án |
|
||||
| 7. security | ✅ | ❌ | ✅ (đọc, `git log -S`) | lỗ hổng + migration; **không** quyết chính sách |
|
||||
@@ -48,12 +74,19 @@
|
||||
|
||||
Chỉ **một** agent được sửa file. Ranh giới này là thứ giữ cho pipeline review được.
|
||||
|
||||
Ngoại lệ duy nhất là hub ở **T0**, và nó bị bó rất chặt để đổi lại: danh sách đóng 6 loại
|
||||
thay đổi, 9 disqualifier, trần ≤ 2 file / ≤ 10 dòng, và 4 cổng máy bắt buộc dán output thật.
|
||||
Vượt bất kỳ ràng buộc nào → `git checkout --` rồi chấm lại T2. Hub **không** được sửa file ở
|
||||
T1/T2/T3 — ở đó nó chỉ điều phối và (ở T1) review, vì reviewer không được là người viết patch.
|
||||
|
||||
## 3. Cổng chuyển bước
|
||||
|
||||
Không bước nào được đi tiếp nếu chưa đạt:
|
||||
|
||||
| Từ → Đến | Điều kiện |
|
||||
|---|---|
|
||||
| 0 → bất kỳ | Mỗi defect_id có đúng 1 tier + 1 lane, tier ≠ T0 dẫn được về một dòng cụ thể của Bước 3, đã xét override bảo mật trước |
|
||||
| 0 → tự sửa (T0) | Trúng danh sách đóng, 0 disqualifier, Gate S + blast radius đã **đo bằng lệnh** |
|
||||
| 1 → 2/3/4 | `confidence >= medium`, có ít nhất một `file:line`, đã redact |
|
||||
| 2/3/4 → 5 | Đúng **một** nguyên nhân gốc, có cách kiểm chứng, không vượt 400 LOC (hoặc đã có kế hoạch tách) |
|
||||
| 7 → 5 | Như trên, **cộng thêm**: có đường di trú cho cả 4 nhóm người dùng, và 4 câu chính sách đã có đáp án của Cowork Team |
|
||||
@@ -65,27 +98,49 @@ Không bước nào được đi tiếp nếu chưa đạt:
|
||||
## 4. Vòng lặp và giới hạn
|
||||
|
||||
- FAIL ở bước 6 → về bước 5 (lỗi hiện thực) hoặc về 2/3/4 (sai nguyên nhân gốc).
|
||||
- **Tier +1 mỗi lần FAIL.** Chạy lại ở nguyên tier cũ là lỗi điều phối: hai lần thất bại ở
|
||||
cùng độ sâu gần như luôn có nghĩa là hồ sơ lỗi sai từ đầu.
|
||||
- Tier chỉ đi **lên**. Không có đường hạ tier giữa dòng, kể cả khi diff hoá ra nhỏ.
|
||||
- Quá **2 vòng** mà vẫn FAIL → dừng, đưa người thật vào. Vòng thứ ba thường có nghĩa là
|
||||
`defect_record` sai từ đầu, không phải bản vá sai.
|
||||
|
||||
## 5. Đường tắt hợp lệ
|
||||
|
||||
| Tình huống | Đường tắt |
|
||||
|---|---|
|
||||
| Lỗi chính tả một chuỗi, đã biết chính xác key | 1 → 4 → 5 → 6, bỏ giai đoạn điều tra ở bước 4 |
|
||||
| Thiếu key i18n, UI hiện ra `a.b_c` | 1 → 4 → 5 → 6 |
|
||||
| Lỗi do chính bản vá vừa merge | về thẳng 5 nếu nguyên nhân gốc chưa đổi |
|
||||
| Dev báo thẳng một lỗ hổng, không qua triệu chứng giao diện | vào thẳng 7, bỏ bước 1 |
|
||||
Đây là các đường tắt hub được phép chọn ở Bước 3. Chúng **thay thế** phần "đường tắt" của
|
||||
bộ v1.2 — trước đây tự phát, giờ có tier và có cổng bù.
|
||||
|
||||
Không có đường tắt nào bỏ qua bước **6**.
|
||||
| Tình huống | Tier | Đường tắt |
|
||||
|---|---|---|
|
||||
| Nới một số đo hiển thị (px, margin, spacing) | T0 | hub sửa, 0 agent |
|
||||
| Sai chính tả / sai dấu một chuỗi đã có key | T0 | hub sửa, đủ 3 ngôn ngữ, **vẫn phải có test** |
|
||||
| Đổi token màu có sẵn sang token có sẵn | T0 | hub sửa, 0 agent |
|
||||
| Thiếu key i18n, UI hiện ra `a.b_c`, đã biết file | T1 | 5 → hub review |
|
||||
| Nguyên nhân gốc đã có `file:line` từ người báo (dev) | T1 | 5 → hub review |
|
||||
| Chạm QSS/token dùng chung, phải kiểm 2 theme | T2 | 4 (hoặc 2) → 5 → 6 |
|
||||
| Lỗi do chính bản vá vừa merge | T3 | đủ pipeline — regression nghĩa là nguyên nhân gốc lần trước sai |
|
||||
| Dev báo thẳng một lỗ hổng | T3-SEC | vào thẳng 7, bỏ bước 1 |
|
||||
|
||||
Bước **6** chỉ được bỏ ở T0 và T1. Ở T0 nó được thay bằng 4 cổng máy; ở T1 nó được thay bằng
|
||||
hub review với `checklist/ui_review.md` (hợp lệ vì hub không viết patch ở T1). Ở T2/T3/T3-SEC
|
||||
không có đường tắt nào bỏ qua bước 6.
|
||||
|
||||
## 6. Chạy bằng Claude Code
|
||||
|
||||
```bash
|
||||
mkdir -p .claude/agents && cp agent/roles/*.md .claude/agents/
|
||||
mkdir -p .claude/agents .claude/commands
|
||||
cp agent/roles/[1-7]_*.md .claude/agents/
|
||||
cp agent/commands/fix.md .claude/commands/
|
||||
```
|
||||
|
||||
Rồi lần lượt:
|
||||
`.claude/` nằm trong `.gitignore` (dòng 109) nên phải cài lại trên mỗi clone — `agent/`
|
||||
là bản gốc. `0_fix_dispatcher.md` không copy sang `agents/`: hub chạy ở session chính vì
|
||||
subagent không gọi được subagent. Điểm vào:
|
||||
|
||||
```text
|
||||
> /fix màn Folder kéo to ra thì mất cây thư mục bên trái
|
||||
```
|
||||
|
||||
Hub in `dispatch_plan` rồi tự chạy lane. Muốn chạy tay lane FULL:
|
||||
|
||||
```text
|
||||
> dùng ui-bug-triage cho phản ánh này: "màn Folder kéo to ra thì mất cây thư mục bên trái"
|
||||
@@ -94,4 +149,5 @@ Rồi lần lượt:
|
||||
> dùng regression-reviewer với patch vừa rồi
|
||||
```
|
||||
|
||||
Chạy tuần tự, không song song — mỗi bước phụ thuộc output của bước trước.
|
||||
Các bước trong **một** `defect_id` chạy tuần tự — mỗi bước phụ thuộc output của bước trước.
|
||||
Các `defect_id` **độc lập** thì chạy song song được, gọi trong cùng một message.
|
||||
|
||||
@@ -74,6 +74,14 @@ 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}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""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"]
|
||||
@@ -0,0 +1,61 @@
|
||||
"""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,9 +21,14 @@ def pptx_available() -> bool:
|
||||
try:
|
||||
from cowork_local.core.deps import ensure_module
|
||||
|
||||
_PPTX_READY = ensure_module("pptx", "python-pptx") is not None
|
||||
ready = ensure_module("pptx", "python-pptx") is not None
|
||||
except Exception: # noqa: BLE001
|
||||
_PPTX_READY = False
|
||||
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
|
||||
return _PPTX_READY
|
||||
|
||||
|
||||
|
||||
@@ -100,11 +100,15 @@ 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": True, # strip proxy env / point at a black-hole address for agent-run commands
|
||||
# "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,
|
||||
# Allow the agent's fetch_url tool to read web pages / online documents /
|
||||
# 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.
|
||||
# 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.
|
||||
"allow_url_fetch": True,
|
||||
"sandbox_pw": "", # set through COWORK_SANDBOX_PASSWORD
|
||||
"rulebase_path": "", # custom RULEBASE.md — attached to every agent execution
|
||||
|
||||
@@ -527,6 +527,15 @@ 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.
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""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
|
||||
+6
-1
@@ -327,7 +327,12 @@ def run_code(
|
||||
else:
|
||||
emit({"type": "tool_start", "id": tc_id, "name": name})
|
||||
if is_extra and extra_executor is not None:
|
||||
result = extra_executor(name, args)
|
||||
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)
|
||||
else:
|
||||
def on_output(line: str, _id=tc_id, _name=name) -> None:
|
||||
emit({"type": "tool_output", "id": _id, "name": _name, "delta": line})
|
||||
|
||||
+24
-5
@@ -91,6 +91,7 @@ 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.
|
||||
|
||||
@@ -117,17 +118,27 @@ 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:
|
||||
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:
|
||||
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
|
||||
return None, str(exc), False, False, False
|
||||
|
||||
with _active_pids_lock:
|
||||
@@ -266,6 +277,10 @@ 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)
|
||||
@@ -339,6 +354,10 @@ 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:
|
||||
|
||||
+19
-8
@@ -94,17 +94,28 @@ 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:
|
||||
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
|
||||
)
|
||||
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)
|
||||
except OSError:
|
||||
return [], 0
|
||||
files = matched if max_files <= 0 else matched[:max_files]
|
||||
return files, len(matched)
|
||||
files.sort(key=lambda p: str(p).lower())
|
||||
return files, total
|
||||
|
||||
|
||||
def find_soffice() -> str | None:
|
||||
|
||||
@@ -132,8 +132,11 @@ 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)
|
||||
@@ -164,10 +167,13 @@ 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] = (
|
||||
|
||||
+30
-1
@@ -16,6 +16,17 @@ 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."""
|
||||
@@ -78,6 +89,7 @@ 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
|
||||
|
||||
|
||||
@@ -85,6 +97,7 @@ 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
|
||||
|
||||
@@ -96,6 +109,7 @@ 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:
|
||||
@@ -105,6 +119,7 @@ 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]:
|
||||
@@ -197,8 +212,16 @@ 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]] = []
|
||||
for path in directory.glob("*.json"):
|
||||
with span("history.list", query=bool(q)):
|
||||
for path in directory.glob("*.json"):
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
@@ -221,4 +244,10 @@ 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
|
||||
|
||||
@@ -85,8 +85,10 @@ 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) —
|
||||
|
||||
@@ -147,6 +147,12 @@ 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.
|
||||
|
||||
+12
-1
@@ -88,7 +88,14 @@ 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, ...)."""
|
||||
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}'"))
|
||||
self._thread = threading.Thread(target=self._run_loop, daemon=True)
|
||||
self._thread.start()
|
||||
if not self._ready.wait(timeout):
|
||||
@@ -174,6 +181,10 @@ 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 {}))
|
||||
|
||||
@@ -137,8 +137,34 @@ 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:
|
||||
@@ -156,6 +182,7 @@ 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:
|
||||
@@ -183,6 +210,7 @@ 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:
|
||||
@@ -228,6 +256,7 @@ 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)
|
||||
|
||||
@@ -43,6 +43,10 @@ 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))
|
||||
@@ -196,6 +200,40 @@ 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)."""
|
||||
@@ -229,6 +267,24 @@ 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."""
|
||||
|
||||
@@ -24,6 +24,7 @@ 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
|
||||
@@ -65,6 +66,13 @@ 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
|
||||
@@ -75,6 +83,53 @@ 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."""
|
||||
|
||||
+48
-4
@@ -218,8 +218,13 @@ class SandboxManager:
|
||||
timeout_sec: int,
|
||||
cancel: Optional[Callable[[], bool]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Dispatch execution to the selected backend."""
|
||||
if backend == "direct":
|
||||
"""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":
|
||||
return self._run_direct(command, workdir, block_network, timeout_sec, cancel)
|
||||
|
||||
if backend == "integrity_job_wfp":
|
||||
@@ -274,7 +279,8 @@ class SandboxManager:
|
||||
env = os.environ.copy()
|
||||
if block_network:
|
||||
from .deps import network_blocked_env
|
||||
env = network_blocked_env(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)
|
||||
|
||||
if cancel is not None:
|
||||
from .deps import run_cancellable
|
||||
@@ -334,4 +340,42 @@ 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",
|
||||
}
|
||||
|
||||
+1
-13
@@ -19,7 +19,6 @@ 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
|
||||
@@ -30,6 +29,7 @@ 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,18 +358,6 @@ 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]:
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""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"]
|
||||
+13
-8
@@ -258,9 +258,13 @@ def dependencies_met(task: Dict[str, Any], directory: Path = None) -> bool:
|
||||
def depends_cycle_error(tasks: List[Dict[str, Any]], task_id: str,
|
||||
depends_on: List[str]) -> Optional[str]:
|
||||
"""Validate a proposed depends_on list: no self-wait, no wait-cycle
|
||||
(A waits B while B — directly or transitively — waits A)."""
|
||||
(A waits B while B — directly or transitively — waits A).
|
||||
|
||||
Trả về KHOÁ i18n chứ không phải câu đã dịch: tầng này không biết người dùng
|
||||
đang chọn ngôn ngữ nào, nên nơi hiển thị mới là nơi gọi ``tr()``.
|
||||
"""
|
||||
if task_id in (depends_on or []):
|
||||
return "A task cannot wait for itself."
|
||||
return "schedtask.err_self_wait"
|
||||
by_id = {t["task_id"]: t for t in tasks}
|
||||
# DFS from each proposed prerequisite through ITS prerequisites.
|
||||
for start in depends_on or []:
|
||||
@@ -268,7 +272,7 @@ def depends_cycle_error(tasks: List[Dict[str, Any]], task_id: str,
|
||||
while stack:
|
||||
cur = stack.pop()
|
||||
if cur == task_id:
|
||||
return "This would create a circular wait between tasks."
|
||||
return "schedtask.err_wait_cycle"
|
||||
if cur in seen:
|
||||
continue
|
||||
seen.add(cur)
|
||||
@@ -280,22 +284,23 @@ def depends_cycle_error(tasks: List[Dict[str, Any]], task_id: str,
|
||||
def chain_error(tasks: List[Dict[str, Any]], task_id: str,
|
||||
next_task_id: Optional[str]) -> Optional[str]:
|
||||
"""Validate assigning ``next_task_id`` as ``task_id``'s next task.
|
||||
Returns an error string (self-link / circular chain / unknown id), or
|
||||
None when the assignment is safe."""
|
||||
Returns an i18n KEY for the problem (self-link / circular chain / unknown
|
||||
id), or None when the assignment is safe. Khoá chứ không phải câu đã dịch —
|
||||
xem ``depends_cycle_error``."""
|
||||
if not next_task_id:
|
||||
return None
|
||||
if next_task_id == task_id:
|
||||
return "A task cannot chain to itself."
|
||||
return "schedtask.err_self_chain"
|
||||
by_id = {t["task_id"]: t for t in tasks}
|
||||
if next_task_id not in by_id:
|
||||
return "Next task does not exist."
|
||||
return "schedtask.err_next_missing"
|
||||
# Walk forward from the proposed next task; reaching task_id again means
|
||||
# the new edge would close a cycle.
|
||||
seen = {task_id}
|
||||
cur = next_task_id
|
||||
while cur:
|
||||
if cur in seen:
|
||||
return "This would create a circular task chain."
|
||||
return "schedtask.err_chain_cycle"
|
||||
seen.add(cur)
|
||||
cur = (by_id.get(cur) or {}).get("dependency", {}).get("next_task_id")
|
||||
return None
|
||||
|
||||
@@ -43,6 +43,10 @@ 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.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
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.
|
||||
+101
-2
@@ -13,10 +13,19 @@ again every time the language changes. Transient dialogs (Settings, Skills,
|
||||
Flow, Permission...) are rebuilt from scratch each time they are opened, so
|
||||
they simply call ``tr()`` while constructing their widgets and need no
|
||||
registration.
|
||||
|
||||
``setText(tr("k"))`` on its own is only correct for the instant it runs, and a
|
||||
screen with dozens of such one-shot calls is where "I picked English and half
|
||||
the screen is still Vietnamese" comes from. The :func:`bind_text` family
|
||||
attaches the key to the widget instead, so every future language change
|
||||
re-applies it — one line per widget, and nothing to remember in a separate
|
||||
``retranslate`` method. Bindings hold the widget WEAKLY, so they are safe for
|
||||
widgets that get rebuilt constantly (Kanban rows, calendar cells).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable, Dict, List
|
||||
import weakref
|
||||
from typing import Any, Callable, Dict, Iterable, List, Tuple
|
||||
|
||||
LANGUAGES: Dict[str, str] = {"en": "English", "ja": "日本語", "vi": "Tiếng Việt"}
|
||||
# Short codes shown in the compact top-bar switcher (Settings keeps the full names above).
|
||||
@@ -25,6 +34,8 @@ DEFAULT_LANGUAGE = "vi"
|
||||
|
||||
_current = DEFAULT_LANGUAGE
|
||||
_listeners: List[Callable[[], None]] = []
|
||||
#: (weak ref to the widget, how to re-apply its text) — see :func:`bind_text`.
|
||||
_bindings: List[Tuple["weakref.ref", Callable[[Any], None]]] = []
|
||||
|
||||
# key -> {"en": ..., "ja": ..., "vi": ...}
|
||||
from . import login_dialog as _login_dialog
|
||||
@@ -37,6 +48,9 @@ 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
|
||||
|
||||
# Gộp theo đúng thứ tự cũ: khoá trùng thì cụm sau thắng, y như khi tất cả
|
||||
# còn nằm chung một dict literal.
|
||||
@@ -51,6 +65,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
**_libreoffice_view.STRINGS,
|
||||
**_agents_admin_tab.STRINGS,
|
||||
**_monitoring_overview.STRINGS,
|
||||
**_cloud_workspace.STRINGS,
|
||||
**_dialog_buttons.STRINGS,
|
||||
**_connectors.STRINGS,
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +79,7 @@ def set_language(lang: str) -> None:
|
||||
if lang == _current:
|
||||
return
|
||||
_current = lang
|
||||
_apply_bindings()
|
||||
for fn in list(_listeners):
|
||||
try:
|
||||
fn()
|
||||
@@ -96,6 +114,87 @@ def on_language_changed(fn: Callable[[], None]) -> None:
|
||||
"""Register a callback that re-applies translations to a persistent widget.
|
||||
|
||||
Called once immediately (to apply the current language) and again on every
|
||||
future call to :func:`set_language`."""
|
||||
future call to :func:`set_language`. For a single widget whose text is one
|
||||
key, prefer :func:`bind_text` and friends — they need no callback of their
|
||||
own and cannot keep a destroyed widget alive."""
|
||||
_listeners.append(fn)
|
||||
fn()
|
||||
|
||||
|
||||
# ---- per-widget bindings -------------------------------------------------
|
||||
|
||||
def _bind(widget: Any, apply: Callable[[Any], None]) -> Any:
|
||||
"""Attach a text re-application to one widget, run it now, return the widget.
|
||||
|
||||
``apply`` takes the widget as its argument rather than closing over it: a
|
||||
closure would keep the widget alive for the life of the process, which is
|
||||
exactly what the weak reference here exists to avoid.
|
||||
|
||||
The widget comes back out so a call site can bind IN PLACE of the one-shot
|
||||
call it replaces — ``bind_text(QLabel(), k)`` where ``QLabel(tr(k))`` was —
|
||||
without spending a line, which several screens here cannot afford (Gate S).
|
||||
"""
|
||||
_bindings.append((weakref.ref(widget), apply))
|
||||
apply(widget)
|
||||
return widget
|
||||
|
||||
|
||||
def _apply_bindings() -> None:
|
||||
"""Re-apply every live binding; drop the ones whose widget is gone.
|
||||
|
||||
Both halves of "gone" are handled: the Python wrapper collected (the weak
|
||||
ref answers None) and the C++ object deleted underneath a live wrapper
|
||||
(``RuntimeError``). Neither may stop the remaining widgets from updating.
|
||||
"""
|
||||
alive: List[Tuple["weakref.ref", Callable[[Any], None]]] = []
|
||||
for ref, apply in _bindings:
|
||||
widget = ref()
|
||||
if widget is None:
|
||||
continue
|
||||
try:
|
||||
apply(widget)
|
||||
except RuntimeError:
|
||||
continue
|
||||
alive.append((ref, apply))
|
||||
_bindings[:] = alive
|
||||
|
||||
|
||||
def bind_text(widget: Any, key: str, **kwargs) -> Any:
|
||||
"""Keep ``widget``'s label on ``key`` through every language change."""
|
||||
return _bind(widget, lambda w: w.setText(tr(key, **kwargs)))
|
||||
|
||||
|
||||
def bind_tip(widget: Any, key: str, **kwargs) -> Any:
|
||||
"""Keep ``widget``'s tooltip on ``key`` through every language change."""
|
||||
return _bind(widget, lambda w: w.setToolTip(tr(key, **kwargs)))
|
||||
|
||||
|
||||
def bind_placeholder(widget: Any, key: str, **kwargs) -> Any:
|
||||
"""Keep an input's placeholder on ``key`` through every language change."""
|
||||
return _bind(widget, lambda w: w.setPlaceholderText(tr(key, **kwargs)))
|
||||
|
||||
|
||||
def bind_items(widget: Any, keys: Iterable[str]) -> Any:
|
||||
"""Keep a combo's item LABELS on ``keys``, by position.
|
||||
|
||||
``setItemText`` on purpose: clearing and re-adding the items would drop the
|
||||
per-item data every caller persists (routing mode, task type) and reset the
|
||||
current selection as a side effect of a translation.
|
||||
"""
|
||||
keys = list(keys)
|
||||
|
||||
def _apply(w: Any) -> None:
|
||||
"""Re-label each item that still exists, leaving its data alone."""
|
||||
for i, key in enumerate(keys[:w.count()]):
|
||||
w.setItemText(i, tr(key))
|
||||
|
||||
return _bind(widget, _apply)
|
||||
|
||||
|
||||
def bind_dynamic(widget: Any, apply: Callable[[], None]) -> Any:
|
||||
"""Bind text that is not one plain key — a count, a name, a joined list.
|
||||
|
||||
``apply`` takes no argument and re-reads whatever it needs itself; the
|
||||
widget is still what decides how long the binding lives.
|
||||
"""
|
||||
return _bind(widget, lambda _w: apply())
|
||||
|
||||
@@ -158,7 +158,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"vi": "Không tìm thấy agent '{name}'."},
|
||||
|
||||
# ---- agents_admin_tab.py — Admin-only agent catalog -------------------
|
||||
"agents_admin.page_title": {"en": "Agents Admin", "ja": "Agents Admin", "vi": "Agents Admin"},
|
||||
"agents_admin.page_title": {"en": "Agents Admin", "ja": "エージェント管理", "vi": "Agents Admin"},
|
||||
"agents_admin.edit_row_tooltip": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
|
||||
"agents_admin.delete_row_tooltip": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
|
||||
"agents_admin.hint": {
|
||||
@@ -179,7 +179,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"en": "Extra instructions this agent always follows (optional)…",
|
||||
"ja": "このエージェントが常に従う追加指示(任意)…",
|
||||
"vi": "Chỉ dẫn bổ sung agent này luôn tuân theo (tùy chọn)…"},
|
||||
"agents_admin.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Provider"},
|
||||
"agents_admin.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Nhà cung cấp"},
|
||||
"agents_admin.provider_default": {
|
||||
"en": "(machine's active provider)", "ja": "(各マシンの現在のプロバイダー)",
|
||||
"vi": "(provider hiện tại của máy)"},
|
||||
@@ -232,6 +232,14 @@ 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)"},
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""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ợ).",
|
||||
},
|
||||
}
|
||||
+16
-16
@@ -168,8 +168,8 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"composer.manage_skills": {"en": "Manage skills…", "ja": "スキルを管理…", "vi": "Quản lý skill…"},
|
||||
|
||||
# ---- schedule_task_tab.py / task_editor_dialog.py -------------------
|
||||
"schedtask.title": {"en": "Schedule Task", "ja": "Schedule Task", "vi": "Schedule Task"},
|
||||
"schedtask.view.kanban": {"en": "Kanban", "ja": "Kanban", "vi": "Kanban"},
|
||||
"schedtask.title": {"en": "Schedule Task", "ja": "タスクスケジュール", "vi": "Schedule Task"},
|
||||
"schedtask.view.kanban": {"en": "Kanban", "ja": "カンバン", "vi": "Kanban"},
|
||||
"schedtask.view.calendar": {"en": "Calendar", "ja": "カレンダー", "vi": "Lịch"},
|
||||
"schedtask.no_title": {"en": "(untitled)", "ja": "(無題)", "vi": "(chưa có tên)"},
|
||||
"schedtask.cal_today": {"en": "Today", "ja": "今日", "vi": "Hôm nay"},
|
||||
@@ -195,23 +195,23 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"en": "Describe what you want in natural language — AI proposes tasks/schedule/chain, you confirm before anything is created.",
|
||||
"ja": "自然文で説明すると、AIがタスク・スケジュール・チェーンを提案します。確認後に作成されます。",
|
||||
"vi": "Mô tả bằng ngôn ngữ tự nhiên — AI đề xuất task/lịch/chuỗi, bạn xác nhận rồi mới tạo."},
|
||||
"schedtask.no_tasks": {"en": "No tasks", "ja": "タスクなし", "vi": "No tasks"},
|
||||
"schedtask.no_tasks": {"en": "No tasks", "ja": "タスクなし", "vi": "Chưa có task"},
|
||||
"schedtask.no_schedule": {"en": "No schedule", "ja": "スケジュールなし", "vi": "Chưa đặt lịch"},
|
||||
"schedtask.last_success": {"en": "Last: Success", "ja": "前回: 成功", "vi": "Lần cuối: Thành công"},
|
||||
"schedtask.last_failed": {"en": "Last: Failed", "ja": "前回: 失敗", "vi": "Lần cuối: Lỗi"},
|
||||
"schedtask.last_never": {"en": "Last: not run", "ja": "前回: 未実行", "vi": "Lần cuối: chưa chạy"},
|
||||
"schedtask.status.backlog": {"en": "Backlog", "ja": "Backlog", "vi": "Backlog"},
|
||||
"schedtask.status.scheduled": {"en": "Scheduled", "ja": "Scheduled", "vi": "Scheduled"},
|
||||
"schedtask.status.running": {"en": "Running", "ja": "Running", "vi": "Running"},
|
||||
"schedtask.status.waiting_input": {"en": "Waiting Input", "ja": "Waiting Input", "vi": "Waiting Input"},
|
||||
"schedtask.status.done": {"en": "Done", "ja": "Done", "vi": "Done"},
|
||||
"schedtask.status.failed": {"en": "Failed", "ja": "Failed", "vi": "Failed"},
|
||||
"schedtask.status.paused": {"en": "Paused", "ja": "Paused", "vi": "Paused"},
|
||||
"schedtask.status.backlog": {"en": "Backlog", "ja": "バックログ", "vi": "Chờ xử lý"},
|
||||
"schedtask.status.scheduled": {"en": "Scheduled", "ja": "予約済み", "vi": "Đã lên lịch"},
|
||||
"schedtask.status.running": {"en": "Running", "ja": "実行中", "vi": "Đang chạy"},
|
||||
"schedtask.status.waiting_input": {"en": "Waiting Input", "ja": "入力待ち", "vi": "Chờ nhập"},
|
||||
"schedtask.status.done": {"en": "Done", "ja": "完了", "vi": "Hoàn thành"},
|
||||
"schedtask.status.failed": {"en": "Failed", "ja": "失敗", "vi": "Thất bại"},
|
||||
"schedtask.status.paused": {"en": "Paused", "ja": "一時停止", "vi": "Tạm dừng"},
|
||||
"schedtask.type.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
|
||||
"schedtask.type.co4e_code": {"en": "Code", "ja": "Code", "vi": "Code"},
|
||||
"schedtask.type.flow": {"en": "Flow", "ja": "Flow", "vi": "Flow"},
|
||||
"schedtask.type.script": {"en": "Script", "ja": "Script", "vi": "Script"},
|
||||
"schedtask.type.manual": {"en": "Manual", "ja": "Manual", "vi": "Manual"},
|
||||
"schedtask.type.flow": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
|
||||
"schedtask.type.script": {"en": "Script", "ja": "スクリプト", "vi": "Script"},
|
||||
"schedtask.type.manual": {"en": "Manual", "ja": "手動", "vi": "Thủ công"},
|
||||
"schedtask.priority.low": {"en": "Low", "ja": "低", "vi": "Thấp"},
|
||||
"schedtask.priority.medium": {"en": "Medium", "ja": "中", "vi": "Trung bình"},
|
||||
"schedtask.priority.high": {"en": "High", "ja": "高", "vi": "Cao"},
|
||||
@@ -229,7 +229,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"vi": "Double-click một dòng để mở thư mục artifact của lần chạy đó."},
|
||||
"schedtask.hist_col_time": {"en": "Finished at", "ja": "完了時刻", "vi": "Hoàn thành lúc"},
|
||||
"schedtask.hist_col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
|
||||
"schedtask.hist_col_run": {"en": "Run ID", "ja": "実行ID", "vi": "Run ID"},
|
||||
"schedtask.hist_col_run": {"en": "Run ID", "ja": "実行ID", "vi": "Mã lần chạy"},
|
||||
"schedtask.hist_col_error": {"en": "Error", "ja": "エラー", "vi": "Lỗi"},
|
||||
"schedtask.menu_create_next": {
|
||||
"en": "Create next task from output", "ja": "出力から次タスクを作成",
|
||||
@@ -261,7 +261,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"schedtask.no_workspace": {"en": "— No workspace —", "ja": "— ワークスペースなし —", "vi": "— Không có workspace —"},
|
||||
"schedtask.f_agent": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
|
||||
"schedtask.no_agent": {"en": "— No agent preset —", "ja": "— エージェントなし —", "vi": "— Không dùng agent —"},
|
||||
"schedtask.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Provider"},
|
||||
"schedtask.f_provider": {"en": "Provider", "ja": "プロバイダー", "vi": "Nhà cung cấp"},
|
||||
"schedtask.provider_default": {
|
||||
"en": "— Default (Settings) —", "ja": "— 既定(設定)—", "vi": "— Mặc định (Settings) —"},
|
||||
"schedtask.f_model": {"en": "Model", "ja": "モデル", "vi": "Model"},
|
||||
@@ -317,7 +317,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"schedtask.repeat.daily": {"en": "Daily", "ja": "毎日", "vi": "Hằng ngày"},
|
||||
"schedtask.repeat.weekly": {"en": "Weekly", "ja": "毎週", "vi": "Hằng tuần"},
|
||||
"schedtask.repeat.monthly": {"en": "Monthly", "ja": "毎月", "vi": "Hằng tháng"},
|
||||
"schedtask.repeat.cron": {"en": "Cron expression", "ja": "Cron式", "vi": "Cron expression"},
|
||||
"schedtask.repeat.cron": {"en": "Cron expression", "ja": "Cron式", "vi": "Biểu thức cron"},
|
||||
"schedtask.f_task_mode": {"en": "Task type", "ja": "タスク種別", "vi": "Loại task"},
|
||||
# Run kind: an AI agent vs a saved Co4E flow + multi-format import
|
||||
"schedtask.f_run_kind": {"en": "Run", "ja": "実行対象", "vi": "Chạy"},
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Chuỗi hiển thị — nhóm Connector (Giám sát ▸ Công cụ ▸ Connector).
|
||||
|
||||
Tên bốn nhóm catalog trên bảng Connector. Đứng riêng một file vì
|
||||
``libreoffice_view.py`` — nơi giữ các khoá ``connectors.*`` cũ — đã sát trần
|
||||
400 dòng của Gate S; khoá connector thêm mới đi vào đây.
|
||||
|
||||
Ba nhóm CAD / CAE / MS365 là DANH SÁCH TÊN SẢN PHẨM nên giống hệt nhau ở cả ba
|
||||
ngôn ngữ (đã khai vào ``KHOA_KHONG_CAN_DICH`` của test i18n). Chỉ nhóm "Other"
|
||||
có chữ thật để dịch — đúng chỗ người dùng báo còn nguyên tiếng Anh.
|
||||
|
||||
``ui/connectors_panel.py`` tách nhãn tại chuỗi ``" ("`` để in phần trong ngoặc
|
||||
bằng kiểu chữ phụ, nên bản dịch phải dùng ngoặc ĐƠN NỬA CHIỀU RỘNG kèm một dấu
|
||||
cách phía trước — dùng ngoặc full-width ``(`` của tiếng Nhật thì không tách
|
||||
được và cả cụm sẽ in đậm thành một khối.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict
|
||||
|
||||
_CAD = "CAD (NX / CATIA / SolidWorks / AutoCAD)"
|
||||
_CAE = "CAE (ANSA / ABAQUS / HyperWorks / ANSYS)"
|
||||
_MS365 = "MS365 (Microsoft 365 / OneDrive / SharePoint)"
|
||||
|
||||
STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"connectors.cat_cad": {"en": _CAD, "ja": _CAD, "vi": _CAD},
|
||||
"connectors.cat_cae": {"en": _CAE, "ja": _CAE, "vi": _CAE},
|
||||
"connectors.cat_ms365": {"en": _MS365, "ja": _MS365, "vi": _MS365},
|
||||
"connectors.cat_other": {
|
||||
"en": "Other (any generic MCP server)",
|
||||
"ja": "その他 (任意の汎用 MCP サーバー)",
|
||||
"vi": "Khác (MCP server bất kỳ)"},
|
||||
}
|
||||
+2
-8
@@ -93,7 +93,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"en": "Enable the predefined Req→Demo flow feature (off by default).",
|
||||
"ja": "定義済みの Req→Demo フロー機能を有効化(初期値はオフ)。",
|
||||
"vi": "Bật tính năng Flow Req→Demo dựng sẵn (mặc định tắt)."},
|
||||
"code.flow_btn": {"en": "Flow Management", "ja": "Flow Management", "vi": "Flow Management"},
|
||||
"code.flow_btn": {"en": "Flow Management", "ja": "フロー管理", "vi": "Flow Management"},
|
||||
"code.flow_btn_tooltip": {
|
||||
"en": "Build and run a multi-stage flow from requirement to demo.",
|
||||
"ja": "要件からデモまでの多段フローを作成・実行します。",
|
||||
@@ -152,7 +152,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
# because until the index existed nothing had to refer to it.
|
||||
"settings.group.general": {"en": "General", "ja": "一般", "vi": "Chung"},
|
||||
"settings.group.provider": {"en": "AI Provider", "ja": "AI プロバイダー", "vi": "Nhà cung cấp AI"},
|
||||
"settings.group.parameter": {"en": "Parameter", "ja": "Parameter", "vi": "Parameter"},
|
||||
"settings.group.parameter": {"en": "Parameter", "ja": "パラメータ", "vi": "Tham số"},
|
||||
"settings.group.about": {"en": "About", "ja": "このアプリについて", "vi": "Giới thiệu"},
|
||||
"settings.param_section_pricing": {
|
||||
"en": "Model pricing", "ja": "モデル価格", "vi": "Bảng giá model"},
|
||||
@@ -344,12 +344,6 @@ 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 がコマンドを実行する前に確認する",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Nhãn cho các nút CHUẨN của Qt (Save/Cancel/OK/Close, Yes/No).
|
||||
|
||||
Qt tự vẽ chữ cho những nút này từ bảng dịch của chính nó, mà ứng dụng không
|
||||
cài ``QTranslator`` nào — nên chúng đứng nguyên tiếng Anh ở cả ba ngôn ngữ.
|
||||
``ui/dialog_buttons.py`` gán lại nhãn bằng các khoá dưới đây.
|
||||
|
||||
Khoá dùng chung cho mọi hộp thoại nên đứng riêng một file, không nhét vào file
|
||||
của một màn hình cụ thể.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict
|
||||
|
||||
STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"dialog.save": {"en": "Save", "ja": "保存", "vi": "Lưu"},
|
||||
"dialog.cancel": {"en": "Cancel", "ja": "キャンセル", "vi": "Hủy"},
|
||||
# "OK" giữ nguyên dạng ở cả ba ngôn ngữ — kể cả bản tiếng Nhật của Qt cũng
|
||||
# dùng "OK". Đã khai vào KHOA_KHONG_CAN_DICH của test i18n.
|
||||
"dialog.ok": {"en": "OK", "ja": "OK", "vi": "OK"},
|
||||
"dialog.close": {"en": "Close", "ja": "閉じる", "vi": "Đóng"},
|
||||
"dialog.yes": {"en": "Yes", "ja": "はい", "vi": "Có"},
|
||||
"dialog.no": {"en": "No", "ja": "いいえ", "vi": "Không"},
|
||||
}
|
||||
+25
-6
@@ -45,8 +45,8 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"schedtask.step_prompt_ph": {"en": "Prompt / command", "ja": "プロンプト/コマンド", "vi": "Prompt / lệnh"},
|
||||
"schedtask.stepexec.cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
|
||||
"schedtask.stepexec.co4e": {"en": "Code", "ja": "Code", "vi": "Code"},
|
||||
"schedtask.stepexec.script": {"en": "Script", "ja": "Script", "vi": "Script"},
|
||||
"schedtask.stepexec.manual": {"en": "Manual", "ja": "Manual", "vi": "Manual"},
|
||||
"schedtask.stepexec.script": {"en": "Script", "ja": "スクリプト", "vi": "Script"},
|
||||
"schedtask.stepexec.manual": {"en": "Manual", "ja": "手動", "vi": "Thủ công"},
|
||||
"schedtask.del_step_tooltip": {"en": "Delete the selected step", "ja": "選択したステップを削除",
|
||||
"vi": "Xóa bước đang chọn"},
|
||||
"schedtask.guide_tooltip": {
|
||||
@@ -168,7 +168,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"en": "Safety: the scheduler will NEVER auto-run this — it parks in Waiting Input until you right-click → Run now.",
|
||||
"ja": "安全: 自動実行されず、Run nowまで待機します。",
|
||||
"vi": "An toàn: scheduler KHÔNG BAO GIỜ tự chạy task này — nó nằm ở Waiting Input tới khi bạn chuột phải → Chạy ngay."},
|
||||
"schedtask.g_input": {"en": "Input", "ja": "入力", "vi": "Input"},
|
||||
"schedtask.g_input": {"en": "Input", "ja": "入力", "vi": "Đầu vào"},
|
||||
"schedtask.f_input_mode": {"en": "Input mode", "ja": "入力モード", "vi": "Chế độ input"},
|
||||
"schedtask.inmode.empty": {"en": "Empty (default)", "ja": "空(既定)", "vi": "Trống (mặc định)"},
|
||||
"schedtask.inmode.manual": {"en": "Manual text", "ja": "手入力テキスト", "vi": "Văn bản nhập tay"},
|
||||
@@ -199,7 +199,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"ja": "各URLを取得し(ベストエフォート)、テキストをコンテキストとして渡します。",
|
||||
"vi": "Mỗi link được tải nội dung (khi có thể) và đưa vào ngữ cảnh cho agent."},
|
||||
"schedtask.f_prev_task": {"en": "Previous task", "ja": "前タスク", "vi": "Task trước"},
|
||||
"schedtask.g_output": {"en": "Output", "ja": "出力", "vi": "Output"},
|
||||
"schedtask.g_output": {"en": "Output", "ja": "出力", "vi": "Đầu ra"},
|
||||
"schedtask.f_output_mode": {"en": "Output mode", "ja": "出力モード", "vi": "Chế độ output"},
|
||||
"schedtask.g_dependency": {"en": "Dependency / Next task", "ja": "依存 / 次タスク", "vi": "Phụ thuộc / Task tiếp theo"},
|
||||
"schedtask.f_next_task": {"en": "Next task", "ja": "次タスク", "vi": "Task tiếp theo"},
|
||||
@@ -244,8 +244,8 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"ja": "プレビュー(確認するまで作成されません):",
|
||||
"vi": "Xem trước (chưa tạo gì cho tới khi bạn xác nhận):"},
|
||||
"schedtask.ai_confirm": {"en": "Create tasks", "ja": "タスクを作成", "vi": "Tạo các task"},
|
||||
"schedtask.tab_ai": {"en": "AI gen task", "ja": "AIタスク生成", "vi": "AI gen task"},
|
||||
"schedtask.tab_import": {"en": "Import", "ja": "インポート", "vi": "Import"},
|
||||
"schedtask.tab_ai": {"en": "AI gen task", "ja": "AIタスク生成", "vi": "Tạo task bằng AI"},
|
||||
"schedtask.tab_import": {"en": "Import", "ja": "インポート", "vi": "Nhập"},
|
||||
"schedtask.export_template_btn": {
|
||||
"en": "Create Excel template…", "ja": "Excelテンプレートを作成…",
|
||||
"vi": "Tạo template Excel…"},
|
||||
@@ -339,4 +339,23 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"en": "No usage recorded in this period yet — run a chat or a task first.",
|
||||
"ja": "この期間の使用記録はまだありません。チャットやタスクを実行してください。",
|
||||
"vi": "Chưa có dữ liệu sử dụng trong giai đoạn này — hãy chạy chat hoặc task trước."},
|
||||
# Lỗi hợp lệ hoá phụ thuộc/chuỗi task: ``core/tasks.py`` trả về KHOÁ, nơi
|
||||
# hiển thị mới gọi ``tr()`` (tầng core không biết ngôn ngữ đang chọn).
|
||||
"schedtask.err_self_wait": {
|
||||
"en": "A task cannot wait for itself.", "ja": "タスクは自分自身を待てません。",
|
||||
"vi": "Một task không thể chờ chính nó."},
|
||||
"schedtask.err_wait_cycle": {
|
||||
"en": "This would create a circular wait between tasks.",
|
||||
"ja": "タスク間で待ち合わせが循環してしまいます。",
|
||||
"vi": "Việc này sẽ tạo vòng chờ luẩn quẩn giữa các task."},
|
||||
"schedtask.err_self_chain": {
|
||||
"en": "A task cannot chain to itself.", "ja": "タスクは自分自身に連結できません。",
|
||||
"vi": "Một task không thể nối tiếp chính nó."},
|
||||
"schedtask.err_next_missing": {
|
||||
"en": "Next task does not exist.", "ja": "次のタスクが存在しません。",
|
||||
"vi": "Task kế tiếp không tồn tại."},
|
||||
"schedtask.err_chain_cycle": {
|
||||
"en": "This would create a circular task chain.",
|
||||
"ja": "タスクの連結が循環してしまいます。",
|
||||
"vi": "Việc này sẽ tạo chuỗi task luẩn quẩn."},
|
||||
}
|
||||
|
||||
@@ -134,6 +134,45 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"vi": "Bật/tắt các tool tích hợp bên dưới. Tool bị tắt sẽ bị loại khỏi bộ công cụ của agent. "
|
||||
"Connector MCP / REST-API được thiết lập ở tab con Connector."},
|
||||
"tools_admin.refresh": {"en": "Refresh", "ja": "更新", "vi": "Làm mới"},
|
||||
# Mô tả tool HIỂN THỊ trên thẻ, một khoá cho mỗi ``TOOL_SPECS[].name``.
|
||||
# KHÔNG dùng ``spec.description``: chuỗi đó là mô tả gửi cho mô hình trong
|
||||
# schema function-calling, phải giữ nguyên tiếng Anh và viết cho máy đọc.
|
||||
"tools_admin.desc.read_file": {
|
||||
"en": "Read the contents of a text file in the working folder.",
|
||||
"ja": "作業フォルダー内のテキストファイルの内容を読み取ります。",
|
||||
"vi": "Đọc nội dung một tệp văn bản trong thư mục làm việc."},
|
||||
"tools_admin.desc.list_dir": {
|
||||
"en": "List files and subfolders at a path (defaults to the workdir root).",
|
||||
"ja": "指定パスのファイルとサブフォルダーを一覧表示します(既定は作業フォルダー直下)。",
|
||||
"vi": "Liệt kê tệp và thư mục con tại một đường dẫn (mặc định là gốc thư mục làm việc)."},
|
||||
"tools_admin.desc.write_file": {
|
||||
"en": "Create a new file or fully rewrite one. For small edits, prefer edit_file.",
|
||||
"ja": "ファイルを新規作成、または全体を書き換えます。小さな修正には edit_file を使います。",
|
||||
"vi": "Tạo tệp mới hoặc ghi đè toàn bộ. Sửa nhỏ thì nên dùng edit_file."},
|
||||
"tools_admin.desc.edit_file": {
|
||||
"en": "Replace an exact snippet inside an existing file — preferred for small edits.",
|
||||
"ja": "既存ファイル内の特定の箇所を置き換えます。小さな修正に適しています。",
|
||||
"vi": "Thay chính xác một đoạn trong tệp có sẵn — hợp cho các sửa đổi nhỏ."},
|
||||
"tools_admin.desc.run_command": {
|
||||
"en": "Run a shell command in the working folder and return its output.",
|
||||
"ja": "作業フォルダーでシェルコマンドを実行し、その出力を返します。",
|
||||
"vi": "Chạy một lệnh shell trong thư mục làm việc và trả về kết quả."},
|
||||
"tools_admin.desc.install_package": {
|
||||
"en": "Install a Python package (pip) so the task can use a missing library.",
|
||||
"ja": "不足しているライブラリを使えるよう Python パッケージ(pip)をインストールします。",
|
||||
"vi": "Cài gói Python (pip) để tác vụ dùng được thư viện còn thiếu."},
|
||||
"tools_admin.desc.fetch_url": {
|
||||
"en": "Fetch a web page or online document by URL and return its text.",
|
||||
"ja": "URL から Web ページやオンライン文書を取得し、テキストを返します。",
|
||||
"vi": "Tải trang web hoặc tài liệu trực tuyến theo URL và trả về nội dung văn bản."},
|
||||
"tools_admin.desc.jira_search": {
|
||||
"en": "Search Jira issues with a JQL query and return a summary list. Read-only.",
|
||||
"ja": "JQL クエリで Jira の課題を検索し、一覧を返します。読み取り専用です。",
|
||||
"vi": "Tìm issue Jira bằng truy vấn JQL và trả về danh sách tóm tắt. Chỉ đọc."},
|
||||
"tools_admin.desc.jira_get_issue": {
|
||||
"en": "Read one Jira issue's details by key, e.g. ABX-123.",
|
||||
"ja": "キー(例: ABX-123)を指定して Jira 課題の詳細を読み取ります。",
|
||||
"vi": "Đọc chi tiết một issue Jira theo mã, ví dụ ABX-123."},
|
||||
"tools_admin.url_fetch_group": {
|
||||
"en": "Web access (fetch_url)", "ja": "Webアクセス (fetch_url)",
|
||||
"vi": "Truy cập web (fetch_url)"},
|
||||
@@ -268,6 +307,12 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"co4e.custom": {"en": "custom", "ja": "カスタム", "vi": "tùy chỉnh"},
|
||||
"co4e.parallel_node": {"en": "Parallel (fan-out)", "ja": "並列(ファンアウト)", "vi": "Song song (fan-out)"},
|
||||
"co4e.add_step": {"en": "Add step", "ja": "ステップ追加", "vi": "Thêm bước"},
|
||||
"co4e.canvas_add_next": {
|
||||
"en": "Add next step", "ja": "次のステップを追加", "vi": "Thêm bước kế"},
|
||||
"co4e.canvas_connect_from": {
|
||||
"en": "Connect from here", "ja": "ここから接続", "vi": "Nối từ đây"},
|
||||
"co4e.canvas_delete_edge": {
|
||||
"en": "Delete connection", "ja": "接続を削除", "vi": "Xóa liên kết"},
|
||||
"co4e.fit": {"en": "Fit", "ja": "全体表示", "vi": "Vừa màn hình"},
|
||||
"co4e.fit_tooltip": {
|
||||
"en": "Auto-fit: zoom to show every step", "ja": "自動フィット:全ステップを表示",
|
||||
|
||||
+12
-3
@@ -149,8 +149,14 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"app.provider": {"en": "Provider:", "ja": "プロバイダー:", "vi": "Nhà cung cấp:"},
|
||||
"app.language": {"en": "Language:", "ja": "言語:", "vi": "Ngôn ngữ:"},
|
||||
"app.settings": {"en": "Settings", "ja": "設定", "vi": "Cài đặt"},
|
||||
"app.tab.dashboard": {"en": "Dashboard", "ja": "Dashboard", "vi": "Dashboard"},
|
||||
"app.tab.schedule": {"en": "Schedule Task", "ja": "Schedule Task", "vi": "Schedule Task"},
|
||||
# Shown on the cover while a language switch blocks the GUI thread. It is
|
||||
# deliberately read BEFORE the switch, so it appears in the language the
|
||||
# user is leaving — the only one they can still read at that moment.
|
||||
"app.lang.switching": {
|
||||
"en": "Switching language…", "ja": "言語を切り替えています…",
|
||||
"vi": "Đang đổi ngôn ngữ…"},
|
||||
"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"},
|
||||
"app.tab.code": {"en": "Code", "ja": "Code", "vi": "Code"},
|
||||
"app.tab.structure": {"en": "GraphRAG", "ja": "GraphRAG", "vi": "GraphRAG"},
|
||||
@@ -158,7 +164,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"app.tab.monitoring": {"en": "Monitoring", "ja": "モニタリング", "vi": "Giám sát"},
|
||||
"app.nav.collapse_tooltip": {"en": "Collapse menu to icons only", "ja": "メニューをアイコンのみに折りたたむ", "vi": "Thu gọn menu về icon"},
|
||||
"app.nav.expand_tooltip": {"en": "Expand menu", "ja": "メニューを展開", "vi": "Mở rộng menu"},
|
||||
"app.nav.menu_label": {"en": "MENU", "ja": "MENU", "vi": "MENU"},
|
||||
"app.nav.menu_label": {"en": "MENU", "ja": "メニュー", "vi": "MENU"},
|
||||
# Shown on the rail rows the project gate disables (Cowork, GraphRAG) —
|
||||
# they stay listed and greyed instead of disappearing from the menu.
|
||||
"app.nav.needs_project": {
|
||||
@@ -171,6 +177,9 @@ 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…"},
|
||||
|
||||
+17
-11
@@ -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. Separate from "
|
||||
"'Block network' (which only sandboxes shell commands). Default: on."),
|
||||
"SharePoint/OneDrive share links to search & process them. 'Block network' "
|
||||
"overrides this switch. 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ý. Tách biệt với 'Chặn mạng' (chỉ áp cho lệnh "
|
||||
"shell). Mặc định: bật.")},
|
||||
"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.")},
|
||||
"settings.test_internet": {
|
||||
"en": "Test Internet", "ja": "インターネット接続テスト", "vi": "Kiểm tra Internet"},
|
||||
"settings.test_internet_tooltip": {
|
||||
@@ -39,12 +39,18 @@ 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": ("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."},
|
||||
"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."},
|
||||
"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ớ"},
|
||||
|
||||
+24
-1
@@ -57,6 +57,17 @@ 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 レポートツールを開発中。命名規則に従うこと …」",
|
||||
@@ -79,7 +90,10 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"app.status.ready": {"en": "Ready.", "ja": "準備完了。", "vi": "Sẵn sàng."},
|
||||
"app.status.using_provider": {"en": "Using {label}.", "ja": "{label} を使用中。", "vi": "Đang dùng {label}."},
|
||||
"app.status.settings_saved": {"en": "Settings saved.", "ja": "設定を保存しました。", "vi": "Đã lưu cài đặt."},
|
||||
"app.credit": {"en": "Made by QuanDH14", "ja": "Made by QuanDH14", "vi": "Made by QuanDH14"},
|
||||
# Con số lấy từ ``cowork_local.__version__`` — một nguồn duy nhất cho tiêu
|
||||
# đề cửa sổ, tab Giới thiệu và góc dưới phải. Giữ nguyên dạng ở cả ba ngôn
|
||||
# ngữ (đã khai vào KHOA_KHONG_CAN_DICH).
|
||||
"app.version": {"en": "Version {v}", "ja": "Version {v}", "vi": "Version {v}"},
|
||||
"app.tray.open": {"en": "Open Cowork Local", "ja": "Cowork Local を開く", "vi": "Mở Cowork Local"},
|
||||
"app.tray.quit": {"en": "Quit", "ja": "終了", "vi": "Thoát"},
|
||||
"app.tray.running_body": {
|
||||
@@ -197,6 +211,15 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"chat.provider_default_short": {
|
||||
"en": "the provider's default model", "ja": "プロバイダー既定のモデル",
|
||||
"vi": "model mặc định của provider"},
|
||||
"chat.provider_default_item": {
|
||||
"en": "(provider default)", "ja": "(プロバイダー既定)",
|
||||
"vi": "(mặc định của provider)"},
|
||||
"chat.record_audio_start": {
|
||||
"en": "Record Voice Note", "ja": "ボイスメモを録音", "vi": "Ghi âm ghi chú"},
|
||||
"chat.record_audio_stop": {
|
||||
"en": "Stop Recording", "ja": "録音を停止", "vi": "Dừng ghi âm"},
|
||||
"chat.record_audio_cancel": {
|
||||
"en": "Cancel recording", "ja": "録音をキャンセル", "vi": "Hủy ghi âm"},
|
||||
"chat.delete_link": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
|
||||
"chat.delete_tooltip": {
|
||||
"en": "Delete this message and its input/output files",
|
||||
|
||||
@@ -123,7 +123,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"vi": "Không phân tích được template này. Kiểm tra file .pptx/.xlsx hợp lệ và provider AI trong Settings hoạt động tốt, hoặc tự thêm skill thủ công."},
|
||||
|
||||
# ---- flow_dialog.py -----------------------------------------------
|
||||
"flow.title": {"en": "Flow Management", "ja": "Flow Management", "vi": "Flow Management"},
|
||||
"flow.title": {"en": "Flow Management", "ja": "フロー管理", "vi": "Flow Management"},
|
||||
"flow.tab_flow": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
|
||||
"flow.tab_agents": {"en": "Agents", "ja": "エージェント", "vi": "Agents"},
|
||||
"flow.tab_skills": {"en": "Skills", "ja": "スキル", "vi": "Skills"},
|
||||
@@ -140,7 +140,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
|
||||
"flow.task_prompt": {"en": "Task (prompt)", "ja": "タスク(プロンプト)", "vi": "Nhiệm vụ (prompt)"},
|
||||
"flow.skill": {"en": "Skill", "ja": "スキル", "vi": "Skill"},
|
||||
"flow.agent": {"en": "AI provider", "ja": "AI プロバイダー", "vi": "AI provider"},
|
||||
"flow.model_label": {"en": "Agent:", "ja": "Agent:", "vi": "Agent:"},
|
||||
"flow.model_label": {"en": "Agent:", "ja": "エージェント:", "vi": "Agent:"},
|
||||
"flow.default_model": {"en": "(provider default)", "ja": "(プロバイダー既定)", "vi": "(mặc định của provider)"},
|
||||
"flow.gen_task_from_hint": {"en": "Generate task from hint", "ja": "ヒントからタスクを生成", "vi": "Tạo task từ gợi ý"},
|
||||
"flow.gen_task_tooltip": {
|
||||
|
||||
@@ -62,7 +62,9 @@ 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
|
||||
from cowork_local.security.command_risk_classifier import (
|
||||
classify_command, command_bypasses_network_proxy,
|
||||
)
|
||||
|
||||
command = str(args.get("command", "")).strip()
|
||||
if not command:
|
||||
@@ -74,6 +76,21 @@ 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,
|
||||
@@ -111,6 +128,15 @@ 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}."
|
||||
|
||||
@@ -6,11 +6,26 @@ tag added in R05-T01/domain/tools/tool_registry.py describes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
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
|
||||
@@ -20,6 +35,9 @@ 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 "
|
||||
@@ -37,6 +55,9 @@ 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", "")),
|
||||
@@ -47,6 +68,9 @@ 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", "")))
|
||||
|
||||
@@ -37,12 +37,16 @@ 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"
|
||||
# (policy-level, see deps.py::network_blocked_env). False (default) =
|
||||
# — 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) =
|
||||
# unrestricted, matching pre-existing behavior.
|
||||
block_network: bool = False
|
||||
# Whether the fetch_url tool may read URLs — SEPARATE from block_network
|
||||
# (reading a web page/share link for info is safe; running networked shell
|
||||
# commands is the risk). Defaults True; set from agent_security.allow_url_fetch.
|
||||
# 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.
|
||||
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"].
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
"""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"]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""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"]
|
||||
@@ -0,0 +1,31 @@
|
||||
"""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 "")
|
||||
@@ -17,7 +17,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from cowork_local.i18n import tr
|
||||
from cowork_local.i18n import bind_dynamic, bind_tip, tr
|
||||
from cowork_local.theme import current_palette
|
||||
from cowork_local.ui.icons import icon
|
||||
|
||||
@@ -57,7 +57,7 @@ class AudioRecorderWidget(QWidget):
|
||||
# Record / Stop toggle button
|
||||
self.record_btn = QPushButton()
|
||||
self.record_btn.setIcon(icon("microphone"))
|
||||
self.record_btn.setToolTip(tr("chat.record_audio_start") if tr("chat.record_audio_start") != "chat.record_audio_start" else "Record Voice Note")
|
||||
bind_dynamic(self.record_btn, self._sync_record_tip)
|
||||
self.record_btn.setFixedSize(32, 32)
|
||||
self.record_btn.clicked.connect(self.toggle_recording)
|
||||
layout.addWidget(self.record_btn)
|
||||
@@ -78,7 +78,7 @@ class AudioRecorderWidget(QWidget):
|
||||
|
||||
self.cancel_btn = QPushButton()
|
||||
self.cancel_btn.setIcon(icon("x"))
|
||||
self.cancel_btn.setToolTip("Cancel recording")
|
||||
bind_tip(self.cancel_btn, "chat.record_audio_cancel")
|
||||
self.cancel_btn.setFixedSize(24, 24)
|
||||
self.cancel_btn.clicked.connect(self.cancel_recording)
|
||||
status_layout.addWidget(self.cancel_btn)
|
||||
@@ -106,7 +106,7 @@ class AudioRecorderWidget(QWidget):
|
||||
self.timer_label.setText("00:00")
|
||||
self.status_container.setVisible(True)
|
||||
self.record_btn.setIcon(icon("square"))
|
||||
self.record_btn.setToolTip("Stop Recording")
|
||||
self._sync_record_tip()
|
||||
self.record_btn.setStyleSheet("background-color: #fca5a5; color: #991b1b;")
|
||||
self._timer.start()
|
||||
self.recording_started.emit()
|
||||
@@ -137,7 +137,12 @@ class AudioRecorderWidget(QWidget):
|
||||
self.status_container.setVisible(False)
|
||||
self.record_btn.setIcon(icon("microphone"))
|
||||
self.record_btn.setStyleSheet("")
|
||||
self.record_btn.setToolTip("Record Voice Note")
|
||||
self._sync_record_tip()
|
||||
|
||||
def _sync_record_tip(self) -> None:
|
||||
"""Tooltip nút ghi âm nói việc nó sẽ làm tiếp, theo trạng thái hiện tại."""
|
||||
self.record_btn.setToolTip(tr("chat.record_audio_stop" if self._is_recording
|
||||
else "chat.record_audio_start"))
|
||||
|
||||
def _on_tick(self) -> None:
|
||||
"""Update recording duration display every second."""
|
||||
|
||||
@@ -115,10 +115,23 @@ class ChatAgentsMixin:
|
||||
if err:
|
||||
self.status_message.emit(tr("chatpanel.agent_list_error", err=err))
|
||||
|
||||
w = AgentWorker(job)
|
||||
w.finished_ok.connect(done)
|
||||
self._agent_worker = w
|
||||
w.start()
|
||||
# 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)
|
||||
|
||||
def _populate_agents(self, models, keep: str) -> None:
|
||||
"""Đổ danh sách vào bộ chọn Agent.
|
||||
@@ -141,7 +154,7 @@ class ChatAgentsMixin:
|
||||
if not items and self.agent_combo.count() == 0:
|
||||
# No models found and none configured — placeholder with data=None so
|
||||
# we fall back to the provider's default model (never a fake name).
|
||||
self.agent_combo.addItem("(provider default)", None)
|
||||
self.agent_combo.addItem(tr("chat.provider_default_item"), None)
|
||||
keep_data = (f"{self._ADMIN_AGENT_PREFIX}{self._admin_agent.agent_id}"
|
||||
if getattr(self, "_admin_agent", None) is not None else keep)
|
||||
idx = self.agent_combo.findData(keep_data) if keep_data else -1
|
||||
|
||||
@@ -51,6 +51,8 @@ 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
|
||||
@@ -164,12 +166,20 @@ 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
|
||||
self.set_markdown(self._text)
|
||||
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)
|
||||
|
||||
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()
|
||||
@@ -393,4 +403,3 @@ class ChatView(QScrollArea):
|
||||
ChatHistoryWidget = ChatView
|
||||
|
||||
__all__ = ["ChatView", "ChatHistoryWidget", "MessageBubble"]
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from ...core.worker import AgentWorker
|
||||
from ...i18n import tr
|
||||
from ...ui.dialog_buttons import confirm
|
||||
|
||||
|
||||
class ChatSessionMixin:
|
||||
@@ -308,7 +308,7 @@ class ChatSessionMixin:
|
||||
prompt = tr("chatpanel.delete_confirm_files", n=len(files), preview=preview)
|
||||
else:
|
||||
prompt = tr("chatpanel.delete_confirm_plain")
|
||||
if QMessageBox.question(self, tr("chatpanel.delete_confirm_title"), prompt) != QMessageBox.Yes:
|
||||
if not confirm(self, tr("chatpanel.delete_confirm_title"), prompt):
|
||||
return
|
||||
for bubble in turn.get("bubbles", []):
|
||||
bubble.setParent(None)
|
||||
|
||||
@@ -35,7 +35,7 @@ from __future__ import annotations
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QHBoxLayout, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_text, bind_tip
|
||||
from ...ui.icons import icon
|
||||
from .palette_list import _PaletteList
|
||||
|
||||
@@ -55,9 +55,11 @@ class AgentListPanel(QWidget):
|
||||
def __init__(self, parent: QWidget | None = None) -> None:
|
||||
"""Danh sách agent ở cột trái Co4E Studio, kèm nút tạo mới."""
|
||||
super().__init__(parent)
|
||||
self.new_btn = QPushButton(tr("co4e.new"))
|
||||
# Bound, not set once: this panel has no retranslate hook of its own, and
|
||||
# Co4ETab (which owns the language callback) cannot reach these tooltips.
|
||||
self.new_btn = bind_text(QPushButton(), "co4e.new")
|
||||
self.new_btn.setIcon(icon("plus"))
|
||||
self.new_btn.setToolTip(tr("co4e.tt_new_agent"))
|
||||
bind_tip(self.new_btn, "co4e.tt_new_agent")
|
||||
self.new_btn.setObjectName("co4eSectionAction")
|
||||
self.new_btn.setFlat(True)
|
||||
self.new_btn.setCursor(Qt.PointingHandCursor)
|
||||
@@ -75,11 +77,11 @@ class AgentListPanel(QWidget):
|
||||
# Edit/delete act on the selected row, so they stay with the list.
|
||||
self.edit_btn = QPushButton()
|
||||
self.edit_btn.setIcon(icon("edit"))
|
||||
self.edit_btn.setToolTip(tr("co4e.tt_edit_agent"))
|
||||
bind_tip(self.edit_btn, "co4e.tt_edit_agent")
|
||||
self.edit_btn.setFixedWidth(34)
|
||||
self.del_btn = QPushButton()
|
||||
self.del_btn.setIcon(icon("trash"))
|
||||
self.del_btn.setToolTip(tr("co4e.tt_del_agent"))
|
||||
bind_tip(self.del_btn, "co4e.tt_del_agent")
|
||||
self.del_btn.setFixedWidth(34)
|
||||
# KHONG noi .clicked o day: cung ly do nhu new_btn o tren.
|
||||
btns.addWidget(self.edit_btn)
|
||||
|
||||
@@ -34,6 +34,7 @@ from PySide6.QtGui import QBrush, QColor, QPainterPath, QPen, QPolygonF
|
||||
from PySide6.QtWidgets import QGraphicsItem, QGraphicsObject, QGraphicsPathItem, QMenu
|
||||
|
||||
from ...core.co4e import STEP_DONE, STEP_ERROR, STEP_PLANNED, STEP_RUNNING, Edge, Node
|
||||
from ...i18n import tr
|
||||
from ...theme import current_palette
|
||||
from .canvas_geometry import _elide, _rounded_path
|
||||
|
||||
@@ -199,6 +200,14 @@ 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ỏ."""
|
||||
@@ -225,9 +234,9 @@ class _NodeItem(QGraphicsObject):
|
||||
def contextMenuEvent(self, e):
|
||||
"""Menu chuột phải trên node: thêm bước kế, nối từ đây, xoá bước."""
|
||||
menu = QMenu()
|
||||
a_add = menu.addAction("+ Add next step")
|
||||
a_conn = menu.addAction("→ Connect from here")
|
||||
a_del = menu.addAction("🗑 Delete step")
|
||||
a_add = menu.addAction("+ " + tr("co4e.canvas_add_next"))
|
||||
a_conn = menu.addAction("→ " + tr("co4e.canvas_connect_from"))
|
||||
a_del = menu.addAction("🗑 " + tr("co4e.delete_step"))
|
||||
chosen = menu.exec(e.screenPos())
|
||||
if chosen is a_add:
|
||||
self.canvas.add_step_below(self.node.id)
|
||||
@@ -334,7 +343,7 @@ class _EdgeItem(QGraphicsPathItem):
|
||||
def contextMenuEvent(self, e):
|
||||
"""Menu chuột phải trên đường nối: xoá liên kết."""
|
||||
menu = QMenu()
|
||||
act_del = menu.addAction("🗑 Delete connection")
|
||||
act_del = menu.addAction("🗑 " + tr("co4e.canvas_delete_edge"))
|
||||
if menu.exec(e.screenPos()) is act_del:
|
||||
self.canvas.delete_edge(self.edge)
|
||||
e.accept()
|
||||
|
||||
@@ -273,6 +273,15 @@ 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():
|
||||
|
||||
@@ -13,7 +13,7 @@ from PySide6.QtWidgets import QSplitter, QWidget
|
||||
from ...core import co4e, skills as skills_mod
|
||||
from ...core.co4e_builtins import BUILTIN_AGENTS
|
||||
from ...core.worker import AgentWorker
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_dynamic, tr
|
||||
from ...ui.chat_view import ChatView
|
||||
from ...ui.icons import icon
|
||||
from ...presentation.co4e.co4e_chat_view import ChatPanel
|
||||
@@ -55,6 +55,12 @@ class Co4EChatMixin:
|
||||
self._co4e_routed_provider = None # routing provider override for the next turn
|
||||
self._vsplit_sizes = [540, 220] # sizes to restore when expanded
|
||||
self._msgs_collapsed = True
|
||||
# The tooltip names the action the button would perform, so it depends on
|
||||
# which way the box is folded — and the fold state lives here, not in the
|
||||
# panel. Bound so a language change re-reads it instead of freezing the
|
||||
# wording set when the tab was built.
|
||||
bind_dynamic(self.chat_toggle_btn, lambda: self.chat_toggle_btn.setToolTip(
|
||||
tr("co4e.tt_expand_msgs" if self._msgs_collapsed else "co4e.tt_collapse_msgs")))
|
||||
return panel
|
||||
def _toggle_messages(self) -> None:
|
||||
"""Show/hide the WHOLE chat box (message list + composer) below the
|
||||
|
||||
@@ -48,7 +48,7 @@ from PySide6.QtWidgets import (
|
||||
|
||||
from ...core import co4e, skills as skills_mod
|
||||
from ...core.co4e_builtins import BUILTIN_AGENTS
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_placeholder, bind_text, tr
|
||||
from ...theme import current_palette
|
||||
from ...ui.icons import icon
|
||||
from ...ui.routing_toggle import RoutingToggle
|
||||
@@ -223,7 +223,8 @@ class ChatPanel(QWidget):
|
||||
self.header = QWidget(); self.header.setObjectName("msgHeader")
|
||||
mh = QHBoxLayout(self.header); mh.setContentsMargins(6, 3, 6, 3); mh.setSpacing(6)
|
||||
self.msgs_icon = QLabel(); self.msgs_icon.setPixmap(icon("message").pixmap(14, 14))
|
||||
self.msgs_title = QLabel(tr("co4e.messages")); self.msgs_title.setObjectName("hint")
|
||||
self.msgs_title = bind_text(QLabel(), "co4e.messages")
|
||||
self.msgs_title.setObjectName("hint")
|
||||
self.chat_toggle_btn = QPushButton()
|
||||
self.chat_toggle_btn.setObjectName("msgToggle")
|
||||
self.chat_toggle_btn.setFlat(True)
|
||||
@@ -253,10 +254,11 @@ class ChatPanel(QWidget):
|
||||
crow.addWidget(self.usage_total_lbl)
|
||||
_inp = QWidget(); row = QHBoxLayout(_inp); row.setContentsMargins(0, 0, 0, 0)
|
||||
self.chat_input = _ChatInput()
|
||||
self.chat_input.setPlaceholderText(tr("co4e.chat_placeholder"))
|
||||
bind_placeholder(self.chat_input, "co4e.chat_placeholder")
|
||||
# KHONG noi .submit o day: cung ly do nhu chat_toggle_btn o tren
|
||||
# (ben goi noi toi _chat_send cua chinh no).
|
||||
self.chat_send_btn = QPushButton(tr("co4e.send")); self.chat_send_btn.setIcon(icon("send"))
|
||||
self.chat_send_btn = bind_text(QPushButton(), "co4e.send")
|
||||
self.chat_send_btn.setIcon(icon("send"))
|
||||
# KHONG noi .clicked o day: cung ly do nhu tren.
|
||||
row.addWidget(self.chat_input, 1)
|
||||
# Off/Auto/Manual routing toggle for Co4E (surface key "co4e").
|
||||
|
||||
@@ -101,6 +101,11 @@ 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)."""
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import List
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtWidgets import QComboBox, QFrame, QHBoxLayout, QLabel, QLineEdit, QPushButton, QScrollArea, QSizePolicy, QSpacerItem, QSplitter, QTabBar, QTabWidget, QVBoxLayout, QWidget
|
||||
from ...core import co4e
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_text, tr
|
||||
from ...theme import current_palette
|
||||
from ...ui.co4e_canvas import Co4ECanvas
|
||||
from ...ui.icons import icon
|
||||
@@ -141,7 +141,9 @@ class Co4ELayoutMixin:
|
||||
self.runs_btn.setToolTip(tr("co4e.tt_runs_tab"))
|
||||
self.runs_btn.toggled.connect(self._show_runs)
|
||||
|
||||
bar.addWidget(QLabel(tr("co4e.flow_name")))
|
||||
# Bound: nothing else holds this label, so a one-shot tr() here would
|
||||
# leave "Flow" stuck in the language the toolbar was built in.
|
||||
bar.addWidget(bind_text(QLabel(), "co4e.flow_name"))
|
||||
bar.addWidget(self.name_edit, 1)
|
||||
bar.addWidget(self.add_step_btn)
|
||||
bar.addWidget(self.save_btn)
|
||||
|
||||
@@ -39,7 +39,7 @@ from PySide6.QtWidgets import (
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_text, bind_tip
|
||||
from ...ui.icons import icon
|
||||
|
||||
|
||||
@@ -66,13 +66,15 @@ class RunsPagePanel(QWidget):
|
||||
hdr = QHBoxLayout()
|
||||
# The Runs page covers the flow toolbar, so it carries its own way back —
|
||||
# otherwise the toggle that opened it is off screen.
|
||||
self.back_btn = QPushButton(tr("co4e.back_to_flow"))
|
||||
# Bound, not set once: this panel has no retranslate hook of its own, and
|
||||
# Co4ETab (which owns the language callback) cannot reach these strings.
|
||||
self.back_btn = bind_text(QPushButton(), "co4e.back_to_flow")
|
||||
self.back_btn.setIcon(icon("chevron-left"))
|
||||
self.back_btn.setToolTip(tr("co4e.tt_back_to_flow"))
|
||||
bind_tip(self.back_btn, "co4e.tt_back_to_flow")
|
||||
# KHONG noi .clicked o day: ben goi (Co4ETab) tu quyet dinh slot nao
|
||||
# xu ly - panel chi dung widget, khong biet _show_runs la gi.
|
||||
hdr.addWidget(self.back_btn)
|
||||
self.title_label = QLabel(tr("co4e.running_flows"))
|
||||
self.title_label = bind_text(QLabel(), "co4e.running_flows")
|
||||
self.title_label.setObjectName("hint")
|
||||
hdr.addWidget(self.title_label)
|
||||
# Show + open the workspace folder where flow outputs land (below the tab,
|
||||
@@ -85,21 +87,21 @@ class RunsPagePanel(QWidget):
|
||||
# ca hai deu thuoc Co4ETab (can ctx/manager de biet duong dan that).
|
||||
hdr.addWidget(self.ws_folder_btn)
|
||||
hdr.addStretch(1)
|
||||
self.stop_btn = QPushButton(tr("co4e.stop"))
|
||||
self.stop_btn = bind_text(QPushButton(), "co4e.stop")
|
||||
self.stop_btn.setIcon(icon("stop"))
|
||||
self.stop_btn.setObjectName("danger")
|
||||
self.stop_btn.setToolTip(tr("co4e.tt_stop_run"))
|
||||
bind_tip(self.stop_btn, "co4e.tt_stop_run")
|
||||
# KHONG noi .clicked o day: cung ly do nhu back_btn o tren.
|
||||
self.rename_btn = QPushButton(tr("co4e.rename_run"))
|
||||
self.rename_btn = bind_text(QPushButton(), "co4e.rename_run")
|
||||
self.rename_btn.setIcon(icon("edit"))
|
||||
self.rename_btn.setToolTip(tr("co4e.tt_rename_run"))
|
||||
bind_tip(self.rename_btn, "co4e.tt_rename_run")
|
||||
# KHONG noi .clicked o day: cung ly do nhu back_btn o tren.
|
||||
self.del_btn = QPushButton(tr("co4e.delete_run"))
|
||||
self.del_btn = bind_text(QPushButton(), "co4e.delete_run")
|
||||
self.del_btn.setIcon(icon("trash"))
|
||||
self.del_btn.setToolTip(tr("co4e.tt_delete_run"))
|
||||
bind_tip(self.del_btn, "co4e.tt_delete_run")
|
||||
# KHONG noi .clicked o day: cung ly do nhu back_btn o tren.
|
||||
self.clear_btn = QPushButton(tr("co4e.clear_done"))
|
||||
self.clear_btn.setToolTip(tr("co4e.tt_clear_runs"))
|
||||
self.clear_btn = bind_text(QPushButton(), "co4e.clear_done")
|
||||
bind_tip(self.clear_btn, "co4e.tt_clear_runs")
|
||||
# KHONG noi .clicked o day: cung ly do nhu back_btn o tren. (Ban goc
|
||||
# noi thang toi lambda: self.manager.clear_finished(), khong qua mot
|
||||
# method rieng - Co4ETab van giu dung quirk do khi noi lai signal nay.)
|
||||
@@ -113,7 +115,7 @@ class RunsPagePanel(QWidget):
|
||||
self.table.verticalHeader().setVisible(False)
|
||||
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
|
||||
self.table.setSelectionBehavior(QTableWidget.SelectRows)
|
||||
self.table.setToolTip(tr("co4e.tt_runs_list"))
|
||||
bind_tip(self.table, "co4e.tt_runs_list")
|
||||
# KHONG noi .itemDoubleClicked o day: cung ly do nhu back_btn o tren.
|
||||
# Right-click a run → Open / Delete (delete a single old run from history).
|
||||
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
|
||||
@@ -13,10 +13,11 @@ import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtWidgets import QInputDialog, QMenu, QMessageBox, QTableWidget, QTableWidgetItem
|
||||
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:
|
||||
@@ -155,7 +156,14 @@ class Co4ERunsMixin:
|
||||
t = ev.get("type")
|
||||
if t == "node_status":
|
||||
if shown:
|
||||
self.canvas.update_node_status(ev.get("node_id"), ev.get("status"))
|
||||
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)
|
||||
elif t == "node_output":
|
||||
if run_wf is not None:
|
||||
self._outputs_for(run_wf)[ev["node_id"]] = ev.get("output", "")
|
||||
@@ -329,9 +337,9 @@ class Co4ERunsMixin:
|
||||
h = self.manager.get(run_id)
|
||||
if h is None:
|
||||
return
|
||||
from PySide6.QtWidgets import QInputDialog
|
||||
new, ok = QInputDialog.getText(self, tr("co4e.rename_run"),
|
||||
tr("co4e.rename_run_label"), text=h.name)
|
||||
from ...ui.dialog_buttons import ask_text
|
||||
new, ok = ask_text(self, tr("co4e.rename_run"),
|
||||
tr("co4e.rename_run_label"), text=h.name)
|
||||
new = (new or "").strip()
|
||||
if not ok or not new or new == h.name:
|
||||
return
|
||||
|
||||
@@ -11,14 +11,42 @@ from typing import List
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtWidgets import QHBoxLayout, QListWidget, QListWidgetItem, QPushButton, QSplitter, QVBoxLayout, QWidget
|
||||
from ...core import co4e, skills as skills_mod
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_dynamic, bind_text, bind_tip, tr
|
||||
from ...ui.icons import icon
|
||||
from ...presentation.co4e.agent_list_panel import AgentListPanel
|
||||
from ...presentation.co4e.co4e_chat_view import _skill_names
|
||||
from ...presentation.co4e.palette_list import _PaletteList
|
||||
from ...presentation.co4e.skills_list_panel import SkillsListPanel
|
||||
|
||||
|
||||
def _skill_prefix_lookup(all_skills):
|
||||
"""Answer ``skills.skill_prefix_for`` from an ALREADY-LOADED skill list.
|
||||
|
||||
``skill_prefix_for`` re-reads the whole skill folder on every call, so
|
||||
asking it once per skill made a sidebar reload cost one full disk scan per
|
||||
skill — measured at ~3.8s of frozen GUI thread on a 121-skill library, and
|
||||
that reload runs on every language switch.
|
||||
|
||||
The scan order and the blank-instructions rule are copied from
|
||||
``skill_prefix_for`` deliberately: a namesake with no instructions must NOT
|
||||
end the search, or a skill's text silently becomes empty in an agent prompt.
|
||||
"""
|
||||
cache: dict = {}
|
||||
|
||||
def lookup(name: str) -> str:
|
||||
"""The ``## Skill: <name>\\n<instructions>`` block for one name, or ''."""
|
||||
if not name:
|
||||
return ""
|
||||
low = name.strip().lower()
|
||||
if low not in cache:
|
||||
cache[low] = next(
|
||||
(f"## Skill: {s.name}\n{s.instructions.strip()}" for s in all_skills
|
||||
if (s.slug == low or s.name.lower() == low) and s.instructions.strip()),
|
||||
"")
|
||||
return cache[low]
|
||||
|
||||
return lookup
|
||||
|
||||
|
||||
class Co4ESidebarMixin:
|
||||
"""Cột trái của Co4E Studio: Workflows, Agents, Skills và Flow Status."""
|
||||
def _build_sidebar(self) -> QWidget:
|
||||
@@ -66,9 +94,12 @@ class Co4ESidebarMixin:
|
||||
col = _Col(self.side_split)
|
||||
|
||||
# --- WORKFLOWS ---------------------------------------------------
|
||||
self.wf_new_btn = QPushButton(tr("co4e.new"))
|
||||
# Bound, not set once: Co4ETab._retranslate reloads the sidebar's LIST
|
||||
# CONTENTS, but these headings, buttons and tooltips are built here and
|
||||
# nothing re-applied them — they stayed in the language of app start-up.
|
||||
self.wf_new_btn = bind_text(QPushButton(), "co4e.new")
|
||||
self.wf_new_btn.setIcon(icon("plus"))
|
||||
self.wf_new_btn.setToolTip(tr("co4e.tt_new_wf"))
|
||||
bind_tip(self.wf_new_btn, "co4e.tt_new_wf")
|
||||
self.wf_new_btn.setObjectName("co4eSectionAction")
|
||||
self.wf_new_btn.setFlat(True)
|
||||
self.wf_new_btn.setCursor(Qt.PointingHandCursor)
|
||||
@@ -78,7 +109,7 @@ class Co4ESidebarMixin:
|
||||
# Draggable: drag a flow onto the canvas to merge it in (Nova-style);
|
||||
# double-click loads it onto the canvas.
|
||||
self.wf_list = _PaletteList(payload_role=Qt.UserRole + 2)
|
||||
self.wf_list.setToolTip(tr("co4e.drag_hint"))
|
||||
bind_tip(self.wf_list, "co4e.drag_hint")
|
||||
self.wf_list.itemDoubleClicked.connect(self._load_selected_workflow)
|
||||
self.wf_list.setContextMenuPolicy(Qt.CustomContextMenu)
|
||||
self.wf_list.customContextMenuRequested.connect(self._wf_context_menu)
|
||||
@@ -93,8 +124,9 @@ class Co4ESidebarMixin:
|
||||
wl.addLayout(wf_btns)
|
||||
# Its own row: sharing one line with the three icon buttons cut "Chạy
|
||||
# nền" down to "Chạ" as soon as the sidebar hit its narrow width.
|
||||
self.wf_runbg_btn = QPushButton(tr("co4e.run_bg")); self.wf_runbg_btn.setIcon(icon("play"))
|
||||
self.wf_runbg_btn.setToolTip(tr("co4e.tt_run_bg"))
|
||||
self.wf_runbg_btn = bind_text(QPushButton(), "co4e.run_bg")
|
||||
self.wf_runbg_btn.setIcon(icon("play"))
|
||||
bind_tip(self.wf_runbg_btn, "co4e.tt_run_bg")
|
||||
self.wf_runbg_btn.clicked.connect(self._run_selected_in_background)
|
||||
wl.addWidget(self.wf_runbg_btn)
|
||||
col.addWidget(self._section("co4e.tab_workflows", wf_body, self.wf_new_btn), 3)
|
||||
@@ -135,12 +167,12 @@ class Co4ESidebarMixin:
|
||||
self.runs_more_btn.setIcon(icon("chevron-right"))
|
||||
self.runs_more_btn.setFixedWidth(30)
|
||||
self.runs_more_btn.setFlat(True)
|
||||
self.runs_more_btn.setToolTip(tr("co4e.tt_runs_tab"))
|
||||
bind_tip(self.runs_more_btn, "co4e.tt_runs_tab")
|
||||
self.runs_more_btn.clicked.connect(lambda: self._show_runs(True))
|
||||
runs_body = QWidget(); rl = QVBoxLayout(runs_body)
|
||||
rl.setContentsMargins(0, 0, 0, 0); rl.setSpacing(4)
|
||||
self.runs_side_list = QListWidget()
|
||||
self.runs_side_list.setToolTip(tr("co4e.tt_runs_tab"))
|
||||
bind_tip(self.runs_side_list, "co4e.tt_runs_tab")
|
||||
self.runs_side_list.itemClicked.connect(self._on_side_run_clicked)
|
||||
rl.addWidget(self.runs_side_list, 1)
|
||||
col.addWidget(self._section("co4e.runs_tab", runs_body, self.runs_more_btn), 2)
|
||||
@@ -202,7 +234,10 @@ class Co4ESidebarMixin:
|
||||
v.addWidget(body, 1)
|
||||
|
||||
self._sections[key] = (head, body, stretch)
|
||||
self._sync_section_arrow(key)
|
||||
# bind_dynamic, not bind_text: the heading is the fold arrow plus the
|
||||
# translated name in caps, so re-applying it means re-running the whole
|
||||
# line rather than pushing one key into setText.
|
||||
bind_dynamic(head, lambda k=key: self._sync_section_arrow(k))
|
||||
return box
|
||||
def _fold_section(self, key: str, body: QWidget, box: QWidget, on: bool) -> None:
|
||||
"""Fold/unfold a section AND give its height back to the others.
|
||||
@@ -223,7 +258,7 @@ class Co4ESidebarMixin:
|
||||
head.setText(("▾ " if head.isChecked() else "▸ ") + tr(key).upper())
|
||||
def _icon_btn(self, icon_name: str, tip_key: str, slot) -> QPushButton:
|
||||
"""Dựng một nút icon nhỏ (rộng 34px) kèm tooltip cho hàng công cụ của mục."""
|
||||
b = QPushButton(); b.setIcon(icon(icon_name)); b.setToolTip(tr(tip_key))
|
||||
b = QPushButton(); b.setIcon(icon(icon_name)); bind_tip(b, tip_key)
|
||||
b.setFixedWidth(34)
|
||||
b.clicked.connect(slot)
|
||||
return b
|
||||
@@ -254,13 +289,16 @@ class Co4ESidebarMixin:
|
||||
co4e._step_dict(step))
|
||||
it.setData(Qt.UserRole + 1, ca.id)
|
||||
self.agent_list.addItem(it)
|
||||
# Skills
|
||||
# Skills — the library is read ONCE here and both the names and the
|
||||
# instructions come out of that one read (see _skill_prefix_lookup).
|
||||
self.skill_list.clear()
|
||||
for name in _skill_names():
|
||||
content = skills_mod.skill_prefix_for(name)
|
||||
all_skills = skills_mod.list_skills() + skills_mod.builtin_skills()
|
||||
skill_prefix = _skill_prefix_lookup(all_skills)
|
||||
for skill in all_skills:
|
||||
name = skill.name
|
||||
payload = co4e._step_dict(co4e.Step(
|
||||
label=name, agent_slug=co4e.slugify(name), role="SKILL", icon="sparkle",
|
||||
instructions=content, skills=[name]))
|
||||
instructions=skill_prefix(name), skills=[name]))
|
||||
self.skill_list.addItem(self._palette_item(name, "sparkle", payload))
|
||||
@staticmethod
|
||||
def _palette_item(text: str, icon_name: str, payload: dict) -> QListWidgetItem:
|
||||
|
||||
@@ -8,12 +8,16 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import List, Optional
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtWidgets import QInputDialog, QMenu
|
||||
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.
|
||||
@@ -115,8 +119,8 @@ class Co4EWorkflowCrudMixin:
|
||||
wf = co4e.get_workflow(ident)
|
||||
if wf is None:
|
||||
return
|
||||
name, ok = QInputDialog.getText(self, tr("co4e.rename"), tr("co4e.rename_prompt"),
|
||||
text=wf.name)
|
||||
name, ok = ask_text(self, tr("co4e.rename"), tr("co4e.rename_prompt"),
|
||||
text=wf.name)
|
||||
name = (name or "").strip()
|
||||
if not ok or not name:
|
||||
return
|
||||
@@ -163,10 +167,15 @@ 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ọ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.
|
||||
"""
|
||||
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
|
||||
|
||||
@@ -24,20 +24,21 @@ thứ tự kế thừa không ảnh hưởng hành vi (khác trường hợp
|
||||
``co4e_canvas_widget.py``, nơi thứ tự mixin-trước-Qt-base là bắt buộc vì có
|
||||
override trùng tên).
|
||||
|
||||
Import trong từng method giữ nguyên y hệt bản gốc (kể cả các import cục bộ có
|
||||
vẻ thừa như ``from PySide6.QtWidgets import QInputDialog`` lặp lại bên trong
|
||||
``_add_subagent``/``_edit_subagent`` dù đã có ở top-level) — chỉ số cấp `..`
|
||||
được nâng lên `...` cho khớp việc file dời từ ``ui/`` (cách gốc 2 cấp) sang
|
||||
``presentation/co4e/`` (cách gốc 3 cấp).
|
||||
Import trong từng method giữ nguyên y hệt bản gốc — chỉ số cấp `..` được nâng
|
||||
lên `...` cho khớp việc file dời từ ``ui/`` (cách gốc 2 cấp) sang
|
||||
``presentation/co4e/`` (cách gốc 3 cấp). Riêng các lời gọi ``QInputDialog``
|
||||
đã chuyển sang ``ui.dialog_buttons``: hàm tĩnh của Qt tự dựng hộp thoại bên
|
||||
trong nên nút "Cancel" của nó luôn là tiếng Anh.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List
|
||||
|
||||
from PySide6.QtWidgets import QInputDialog, QListWidgetItem
|
||||
from PySide6.QtWidgets import QListWidgetItem
|
||||
|
||||
from ...core.co4e import SubAgent
|
||||
from ...i18n import tr
|
||||
from ...ui.dialog_buttons import ask_item, ask_multiline, ask_text
|
||||
|
||||
|
||||
class _StepConfigActionsMixin:
|
||||
@@ -67,14 +68,12 @@ class _StepConfigActionsMixin:
|
||||
"""Thêm một sub-agent vào bước đang chọn (chạy song song trong bước đó)."""
|
||||
if self._step is None:
|
||||
return
|
||||
from PySide6.QtWidgets import QInputDialog
|
||||
|
||||
names = self._available_agent_names()
|
||||
if names:
|
||||
name, ok = QInputDialog.getItem(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"),
|
||||
names, 0, True) # editable: can type a new one
|
||||
name, ok = ask_item(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"),
|
||||
names, 0, True) # editable: can type a new one
|
||||
else:
|
||||
name, ok = QInputDialog.getText(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"))
|
||||
name, ok = ask_text(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"))
|
||||
name = (name or "").strip()
|
||||
if not ok or not name:
|
||||
return
|
||||
@@ -89,13 +88,11 @@ class _StepConfigActionsMixin:
|
||||
row = self.sub_list.row(item)
|
||||
if not (0 <= row < len(self._step.sub_agents)):
|
||||
return
|
||||
from PySide6.QtWidgets import QInputDialog
|
||||
|
||||
names = self._available_agent_names()
|
||||
cur = self._step.sub_agents[row].agent
|
||||
start = names.index(cur) if cur in names else 0
|
||||
name, ok = QInputDialog.getItem(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"),
|
||||
names or [cur], start, True)
|
||||
name, ok = ask_item(self, tr("co4e.pick_agent"), tr("co4e.pick_agent"),
|
||||
names or [cur], start, True)
|
||||
name = (name or "").strip()
|
||||
if ok and name:
|
||||
self._step.sub_agents[row].agent = name
|
||||
@@ -151,7 +148,7 @@ class _StepConfigActionsMixin:
|
||||
role = self.role_edit.text().strip()
|
||||
if not name and not role:
|
||||
return
|
||||
hint, ok = QInputDialog.getMultiLineText(
|
||||
hint, ok = ask_multiline(
|
||||
self, tr("co4e.ai_draft_hint_title"), tr("co4e.ai_draft_hint_label"))
|
||||
if not ok:
|
||||
return
|
||||
|
||||
@@ -38,8 +38,8 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from ...config import PROVIDER_LABELS
|
||||
from ...core.co4e import PERMISSION_PRESETS, Step
|
||||
from ...i18n import tr
|
||||
from ...core.co4e import PERMISSION_PRESETS, STEP_DONE, STEP_RUNNING, 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
|
||||
from .step_config_section import _add_section
|
||||
@@ -65,6 +65,8 @@ 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)
|
||||
@@ -77,30 +79,34 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
# (skills/files/sub-agents). No tabs/accordion: every group's border
|
||||
# and heading are what separate it from its neighbours, and all three
|
||||
# are on screen (or one scroll away) at once.
|
||||
form, _basic_card = _add_section(outer, tr("co4e.tab_basic"))
|
||||
form, _basic_card = _add_section(outer, "co4e.tab_basic")
|
||||
|
||||
self.label_edit = QLineEdit()
|
||||
self.label_edit.textChanged.connect(self._on_edit)
|
||||
form.addRow(tr("co4e.f_label"), self.label_edit)
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_label"), self.label_edit)
|
||||
|
||||
self.role_edit = QLineEdit()
|
||||
self.role_edit.textChanged.connect(self._on_edit)
|
||||
form.addRow(tr("co4e.f_role"), self.role_edit)
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_role"), self.role_edit)
|
||||
|
||||
# Dropdown of every icon in the registry (Monitoring's Icon Management
|
||||
# set + built-ins), each row previewing its actual glyph — still
|
||||
# editable so a not-yet-added custom name can be typed directly.
|
||||
self.icon_edit = icon_picker_combo()
|
||||
self.icon_edit.lineEdit().setPlaceholderText(tr("co4e.f_icon_placeholder"))
|
||||
# Kept on self because the combo's line edit belongs to C++: a binding
|
||||
# holds its widget weakly, so with no owner on this side the Python
|
||||
# wrapper could be collected and the binding silently dropped.
|
||||
self._icon_line = self.icon_edit.lineEdit()
|
||||
bind_placeholder(self._icon_line, "co4e.f_icon_placeholder")
|
||||
self.icon_edit.currentTextChanged.connect(self._on_edit)
|
||||
form.addRow(tr("co4e.f_icon"), self.icon_edit)
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_icon"), self.icon_edit)
|
||||
|
||||
self.instructions_edit = QPlainTextEdit()
|
||||
self.instructions_edit.setMaximumHeight(120)
|
||||
self.instructions_edit.textChanged.connect(self._on_edit)
|
||||
self.gen_btn = QPushButton(tr("co4e.ai_draft"))
|
||||
self.gen_btn = bind_text(QPushButton(), "co4e.ai_draft")
|
||||
self.gen_btn.setIcon(icon("sparkle"))
|
||||
self.gen_btn.setToolTip(tr("co4e.ai_draft_tooltip"))
|
||||
bind_tip(self.gen_btn, "co4e.ai_draft_tooltip")
|
||||
self.gen_btn.setEnabled(ctx is not None)
|
||||
self.gen_btn.clicked.connect(self._ai_draft)
|
||||
instr_box = QWidget()
|
||||
@@ -108,17 +114,17 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
ib.setContentsMargins(0, 0, 0, 0)
|
||||
ib.addWidget(self.instructions_edit)
|
||||
ib.addWidget(self.gen_btn, alignment=Qt.AlignRight)
|
||||
form.addRow(tr("co4e.f_instructions"), instr_box)
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_instructions"), instr_box)
|
||||
|
||||
# Extra context — free-text background/info fed to the step at run time
|
||||
# (in addition to instructions, attachments and upstream outputs).
|
||||
self.context_edit = QPlainTextEdit()
|
||||
self.context_edit.setMaximumHeight(90)
|
||||
self.context_edit.setPlaceholderText(tr("co4e.f_context_placeholder"))
|
||||
bind_placeholder(self.context_edit, "co4e.f_context_placeholder")
|
||||
self.context_edit.textChanged.connect(self._on_edit)
|
||||
form.addRow(tr("co4e.f_context"), self.context_edit)
|
||||
form.addRow(bind_text(QLabel(), "co4e.f_context"), self.context_edit)
|
||||
|
||||
form2, _model_card = _add_section(outer, tr("co4e.tab_model_perm"))
|
||||
form2, _model_card = _add_section(outer, "co4e.tab_model_perm")
|
||||
|
||||
model_row = QHBoxLayout()
|
||||
self.model_combo = QComboBox()
|
||||
@@ -126,48 +132,52 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
self.model_combo.editTextChanged.connect(self._on_edit)
|
||||
self.load_models_btn = QPushButton()
|
||||
self.load_models_btn.setIcon(icon("download"))
|
||||
self.load_models_btn.setToolTip(tr("co4e.load_models_tooltip"))
|
||||
bind_tip(self.load_models_btn, "co4e.load_models_tooltip")
|
||||
self.load_models_btn.clicked.connect(self._load_models)
|
||||
self.load_models_btn.setEnabled(ctx is not None)
|
||||
model_row.addWidget(self.model_combo, 1)
|
||||
model_row.addWidget(self.load_models_btn)
|
||||
mrow = QWidget(); mrow.setLayout(model_row)
|
||||
form2.addRow(tr("co4e.f_model"), mrow)
|
||||
form2.addRow(bind_text(QLabel(), "co4e.f_model"), mrow)
|
||||
|
||||
self.perm_combo = QComboBox()
|
||||
for preset in PERMISSION_PRESETS:
|
||||
self.perm_combo.addItem(tr(f"co4e.perm.{preset}"), preset)
|
||||
perm_keys = [f"co4e.perm.{preset}" for preset in PERMISSION_PRESETS]
|
||||
for preset, key in zip(PERMISSION_PRESETS, perm_keys):
|
||||
self.perm_combo.addItem(tr(key), preset)
|
||||
# Only the visible labels follow the language — the data column stays
|
||||
# the preset id that ``_on_edit`` persists onto the Step.
|
||||
bind_items(self.perm_combo, perm_keys)
|
||||
self.perm_combo.currentIndexChanged.connect(self._on_edit)
|
||||
form2.addRow(tr("co4e.f_permission"), self.perm_combo)
|
||||
form2.addRow(bind_text(QLabel(), "co4e.f_permission"), self.perm_combo)
|
||||
|
||||
verify_row = QHBoxLayout()
|
||||
self.verify_chk = QCheckBox(tr("co4e.f_self_verify"))
|
||||
self.verify_chk = bind_text(QCheckBox(), "co4e.f_self_verify")
|
||||
self.verify_chk.toggled.connect(self._on_edit)
|
||||
self.rounds_spin = QSpinBox()
|
||||
self.rounds_spin.setRange(1, 5)
|
||||
self.rounds_spin.valueChanged.connect(self._on_edit)
|
||||
verify_row.addWidget(self.verify_chk)
|
||||
verify_row.addWidget(QLabel(tr("co4e.f_verify_rounds")))
|
||||
verify_row.addWidget(bind_text(QLabel(), "co4e.f_verify_rounds"))
|
||||
verify_row.addWidget(self.rounds_spin)
|
||||
verify_row.addStretch(1)
|
||||
vrow = QWidget(); vrow.setLayout(verify_row)
|
||||
form2.addRow("", vrow)
|
||||
|
||||
form3, _skills_card = _add_section(outer, tr("co4e.tab_skills_files"))
|
||||
form3, _skills_card = _add_section(outer, "co4e.tab_skills_files")
|
||||
|
||||
# Skills checklist (registry skills)
|
||||
self.skills_list = QListWidget()
|
||||
self.skills_list.setMaximumHeight(110)
|
||||
self.skills_list.itemChanged.connect(self._on_edit)
|
||||
form3.addRow(tr("co4e.f_skills"), self.skills_list)
|
||||
form3.addRow(bind_text(QLabel(), "co4e.f_skills"), self.skills_list)
|
||||
|
||||
# Attachments — files whose extracted text is fed to this step at run time.
|
||||
self.attach_list = QListWidget()
|
||||
self.attach_list.setMaximumHeight(80)
|
||||
self.attach_add_btn = QPushButton(tr("co4e.attach_add"))
|
||||
self.attach_add_btn = bind_text(QPushButton(), "co4e.attach_add")
|
||||
self.attach_add_btn.setIcon(icon("plus"))
|
||||
self.attach_add_btn.clicked.connect(self._add_attachment)
|
||||
self.attach_del_btn = QPushButton(tr("co4e.attach_remove"))
|
||||
self.attach_del_btn = bind_text(QPushButton(), "co4e.attach_remove")
|
||||
self.attach_del_btn.setIcon(icon("trash"))
|
||||
self.attach_del_btn.clicked.connect(self._del_attachment)
|
||||
att_btns = QHBoxLayout()
|
||||
@@ -175,7 +185,7 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
att_btns.addWidget(self.attach_del_btn)
|
||||
att_btns.addStretch(1)
|
||||
abtn = QWidget(); abtn.setLayout(att_btns)
|
||||
form3.addRow(tr("co4e.f_attachments"), self.attach_list)
|
||||
form3.addRow(bind_text(QLabel(), "co4e.f_attachments"), self.attach_list)
|
||||
form3.addRow("", abtn)
|
||||
|
||||
# Parallel sub-agents get their OWN section — same header style as
|
||||
@@ -183,14 +193,14 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
# Skills & Tệp, since it's really a distinct group, just one that
|
||||
# only applies to parallel-variant steps. load_step() hides the whole
|
||||
# card for a non-parallel step (see is_par below).
|
||||
form4, self._parallel_card = _add_section(outer, tr("co4e.f_subagents"))
|
||||
form4, self._parallel_card = _add_section(outer, "co4e.f_subagents")
|
||||
self.sub_list = QListWidget()
|
||||
self.sub_list.setMaximumHeight(90)
|
||||
self.sub_list.itemDoubleClicked.connect(self._edit_subagent) # re-pick agent
|
||||
self.sub_add_btn = QPushButton(tr("co4e.add_subagent"))
|
||||
self.sub_add_btn = bind_text(QPushButton(), "co4e.add_subagent")
|
||||
self.sub_add_btn.setIcon(icon("plus"))
|
||||
self.sub_add_btn.clicked.connect(self._add_subagent)
|
||||
self.sub_del_btn = QPushButton(tr("co4e.del_subagent"))
|
||||
self.sub_del_btn = bind_text(QPushButton(), "co4e.del_subagent")
|
||||
self.sub_del_btn.setIcon(icon("trash"))
|
||||
self.sub_del_btn.clicked.connect(self._del_subagent)
|
||||
sub_btns = QHBoxLayout()
|
||||
@@ -203,17 +213,17 @@ class StepConfigPanel(_StepConfigActionsMixin, QScrollArea):
|
||||
|
||||
# Footer actions — one compact row (Run · Run from here · Delete),
|
||||
# kept below every section, not inside one of the cards.
|
||||
self.run_btn = QPushButton(tr("co4e.run"))
|
||||
self.run_btn = bind_text(QPushButton(), "co4e.run")
|
||||
self.run_btn.setIcon(icon("play"))
|
||||
self.run_btn.setToolTip(tr("co4e.run_this_step"))
|
||||
bind_tip(self.run_btn, "co4e.run_this_step")
|
||||
self.run_btn.clicked.connect(lambda: self.run_node.emit(self._node_id))
|
||||
self.run_from_btn = QPushButton(tr("co4e.run_from_here"))
|
||||
self.run_from_btn.setToolTip(tr("co4e.run_from_here"))
|
||||
self.run_from_btn = bind_text(QPushButton(), "co4e.run_from_here")
|
||||
bind_tip(self.run_from_btn, "co4e.run_from_here")
|
||||
self.run_from_btn.clicked.connect(lambda: self.run_from.emit(self._node_id))
|
||||
self.del_btn = QPushButton()
|
||||
self.del_btn.setIcon(icon("trash"))
|
||||
self.del_btn.setObjectName("danger")
|
||||
self.del_btn.setToolTip(tr("co4e.delete_step"))
|
||||
bind_tip(self.del_btn, "co4e.delete_step")
|
||||
self.del_btn.setFixedWidth(38)
|
||||
self.del_btn.clicked.connect(lambda: self.delete_node.emit(self._node_id))
|
||||
foot = QHBoxLayout()
|
||||
@@ -281,6 +291,27 @@ 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
|
||||
|
||||
@@ -29,7 +29,7 @@ from __future__ import annotations
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
from ...i18n import tr
|
||||
from ...i18n import bind_text, bind_tip
|
||||
from .palette_list import _PaletteList
|
||||
|
||||
|
||||
@@ -50,8 +50,10 @@ class SkillsListPanel(QWidget):
|
||||
cái gì.
|
||||
"""
|
||||
super().__init__(parent)
|
||||
self.manage_btn = QPushButton(tr("co4e.manage_skills"))
|
||||
self.manage_btn.setToolTip(tr("co4e.tt_manage_skills"))
|
||||
# Bound, like AgentListPanel's: the panel owns how its own button reads,
|
||||
# so no embedder has to remember it in a retranslate method.
|
||||
self.manage_btn = bind_text(QPushButton(), "co4e.manage_skills")
|
||||
bind_tip(self.manage_btn, "co4e.tt_manage_skills")
|
||||
self.manage_btn.setObjectName("co4eSectionAction")
|
||||
self.manage_btn.setFlat(True)
|
||||
self.manage_btn.setCursor(Qt.PointingHandCursor)
|
||||
|
||||
@@ -26,6 +26,7 @@ from __future__ import annotations
|
||||
from PySide6.QtCore import Qt, QEasingCurve, QPropertyAnimation, Signal
|
||||
from PySide6.QtWidgets import QFormLayout, QLabel, QVBoxLayout, QWidget
|
||||
|
||||
from ...i18n import bind_dynamic, tr
|
||||
from ...theme import current_palette
|
||||
|
||||
_SECTION_ANIM_MS = 180
|
||||
@@ -64,7 +65,7 @@ class _SectionHeader(QLabel):
|
||||
super().showEvent(event)
|
||||
|
||||
|
||||
def _add_section(outer: QVBoxLayout, title: str) -> tuple[QFormLayout, QWidget]:
|
||||
def _add_section(outer: QVBoxLayout, title_key: str) -> tuple[QFormLayout, QWidget]:
|
||||
"""One group of fields, collapsed to just its heading by default and
|
||||
independently expandable, so a long step config reads as a short list of
|
||||
group names until you open the one you need. Deliberately bare — no card
|
||||
@@ -74,7 +75,11 @@ def _add_section(outer: QVBoxLayout, title: str) -> tuple[QFormLayout, QWidget]:
|
||||
the group's rows to ``form``; ``card`` is the whole section (header +
|
||||
body) — hide it to remove the group entirely (e.g. for a section that
|
||||
only applies to some steps), rather than hiding individual rows inside
|
||||
an always-visible header."""
|
||||
an always-visible header.
|
||||
|
||||
Nhận KHOÁ dịch, không nhận chuỗi đã dịch: nhãn mục do hàm này tự dựng nên
|
||||
nơi gọi không giữ tham chiếu nào để áp lại: truyền ``tr(...)`` vào đây thì
|
||||
bốn tiêu đề đứng nguyên ở ngôn ngữ lúc dựng panel."""
|
||||
p = current_palette()
|
||||
card = QWidget()
|
||||
card_lay = QVBoxLayout(card)
|
||||
@@ -96,7 +101,6 @@ def _add_section(outer: QVBoxLayout, title: str) -> tuple[QFormLayout, QWidget]:
|
||||
# diacritics.
|
||||
header.ensurePolished()
|
||||
header.setFixedHeight(header.fontMetrics().height())
|
||||
header.setText(f"▶ {title}")
|
||||
card_lay.addWidget(header)
|
||||
|
||||
body = QWidget()
|
||||
@@ -112,6 +116,14 @@ def _add_section(outer: QVBoxLayout, title: str) -> tuple[QFormLayout, QWidget]:
|
||||
|
||||
is_open = False
|
||||
|
||||
def _sync_header() -> None:
|
||||
"""Nhãn mục: dấu gập/mở hiện tại + tiêu đề theo ngôn ngữ đang chọn."""
|
||||
header.setText(f"{'▼' if is_open else '▶'} {tr(title_key)}")
|
||||
|
||||
# Ràng buộc ĐỘNG chứ không bind cứng một chuỗi: nhãn này mang cả trạng thái
|
||||
# gập/mở, nên bind cứng sẽ trả nó về ▶ mỗi lần người dùng đổi ngôn ngữ.
|
||||
bind_dynamic(header, _sync_header)
|
||||
|
||||
def _on_finished() -> None:
|
||||
"""Hiệu ứng gập/mở chạy xong: bỏ trần chiều cao khi đang mở, để bước có nhiều
|
||||
trường không bị cắt cụt.
|
||||
@@ -130,7 +142,7 @@ def _add_section(outer: QVBoxLayout, title: str) -> tuple[QFormLayout, QWidget]:
|
||||
"""Lật trạng thái gập/mở của một mục và chạy hiệu ứng tương ứng."""
|
||||
nonlocal is_open
|
||||
is_open = not is_open
|
||||
header.setText(f"{'▼' if is_open else '▶'} {title}")
|
||||
_sync_header()
|
||||
anim.stop()
|
||||
if is_open:
|
||||
body.setVisible(True)
|
||||
|
||||
@@ -116,9 +116,9 @@ class HabitsWidget(QWidget):
|
||||
"""Apply an AI-suggested cost-saving strategy AFTER the user
|
||||
approves: turn on auto-compress and compress earlier (lower
|
||||
threshold) + compress content before sending it to the agent."""
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
if QMessageBox.question(self, tr("dashboard.strategy_title"),
|
||||
tr("dashboard.strategy_confirm")) != QMessageBox.Yes:
|
||||
from ...ui.dialog_buttons import confirm
|
||||
if not confirm(self, tr("dashboard.strategy_title"),
|
||||
tr("dashboard.strategy_confirm")):
|
||||
return
|
||||
cx = self.ctx.config.data.setdefault("context", {})
|
||||
cx["auto_compact"] = True
|
||||
|
||||
@@ -121,6 +121,13 @@ class UsageChartWidget(QWidget):
|
||||
|
||||
def retranslate(self) -> None:
|
||||
"""Áp lại chữ theo ngôn ngữ đang chọn cho nhãn và tooltip."""
|
||||
# setItemText, chứ không clear()+addItem(): cột data của hai combo này
|
||||
# là thứ quyết định kỳ và chỉ số đang xem, dựng lại danh sách sẽ reset cả
|
||||
# hai. Khoá dịch suy ra từ chính cột data nên không phải chép lại danh
|
||||
# sách giá trị ở hai nơi.
|
||||
for combo, prefix in ((self.gran_combo, "gran"), (self.metric_combo, "metric")):
|
||||
for i in range(combo.count()):
|
||||
combo.setItemText(i, tr(f"dashboard.{prefix}_{combo.itemData(i)}"))
|
||||
self.currency_lbl.setText(tr("monitoring.overview_currency"))
|
||||
self.currency_combo.setToolTip(tr("dashboard.currency_tooltip"))
|
||||
self._chart_title.setText(tr("dashboard.chart_title"))
|
||||
|
||||
@@ -290,9 +290,9 @@ class AiEditPipeline:
|
||||
self.pending = None
|
||||
self._owner.show_confirm_row(False)
|
||||
if p.get("image_gens"):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
if QMessageBox.question(self._owner, tr("folder.ai_image_confirm_title"),
|
||||
tr("folder.ai_image_confirm_gen")) != QMessageBox.Yes:
|
||||
from ...ui.dialog_buttons import confirm
|
||||
if not confirm(self._owner, tr("folder.ai_image_confirm_title"),
|
||||
tr("folder.ai_image_confirm_gen")):
|
||||
self._owner.status_message.emit(tr("folder.ai_image_declined"))
|
||||
return
|
||||
self._generate_then_finalize(p)
|
||||
|
||||
@@ -21,9 +21,9 @@ from __future__ import annotations
|
||||
from typing import List, Optional
|
||||
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox, QHBoxLayout, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget,
|
||||
QComboBox, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget,
|
||||
)
|
||||
from PySide6.QtCore import Signal
|
||||
from PySide6.QtCore import Qt, Signal
|
||||
|
||||
from cowork_local.i18n import on_language_changed, tr
|
||||
from cowork_local.presentation.folder.ai_edit_model_resolver import AiEditModelResolver
|
||||
@@ -32,6 +32,45 @@ 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/
|
||||
@@ -94,9 +133,9 @@ class AiFileEditorDialog(QWidget):
|
||||
ctx, self.ai_model_combo, self.ai_chat.add_status, self._confirm_routing_switch)
|
||||
|
||||
row = QHBoxLayout()
|
||||
self.ai_input = QLineEdit()
|
||||
self.ai_input = _AutoExpandInput()
|
||||
self.ai_input.setPlaceholderText(tr("folder.ai_placeholder"))
|
||||
self.ai_input.returnPressed.connect(self._ai_send)
|
||||
self.ai_input.submit.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")
|
||||
@@ -170,7 +209,7 @@ class AiFileEditorDialog(QWidget):
|
||||
if not self.preview.root:
|
||||
self.ai_chat.add_error(tr("folder.ai_no_file"))
|
||||
return
|
||||
instruction = self.ai_input.text().strip()
|
||||
instruction = self.ai_input.toPlainText().strip()
|
||||
if not instruction:
|
||||
return
|
||||
self.ai_input.clear()
|
||||
|
||||
@@ -110,7 +110,10 @@ 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
|
||||
@@ -276,10 +279,9 @@ class OfficeDocumentRenderer:
|
||||
from cowork_local.core import pptx_edit
|
||||
o = self._owner
|
||||
if not skip_confirm and pptx_edit.image_change_requested(content):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
ok = QMessageBox.question(o, tr("folder.ai_image_confirm_title"),
|
||||
tr("folder.ai_image_confirm"))
|
||||
if ok != QMessageBox.Yes:
|
||||
from cowork_local.ui.dialog_buttons import confirm
|
||||
if not confirm(o, tr("folder.ai_image_confirm_title"),
|
||||
tr("folder.ai_image_confirm")):
|
||||
o.status_message.emit(tr("folder.ai_image_declined"))
|
||||
return False
|
||||
pptx_edit.apply_text_to_pptx(o.current_file, content)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""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"]
|
||||
@@ -237,7 +237,7 @@ class GraphRenderer(QWidget):
|
||||
# ---- prewarm / scan lifecycle -------------------------------------------------- #
|
||||
def prewarm(self) -> None:
|
||||
"""Pay for the graph view before it is clicked on, not during."""
|
||||
if not HAS_WEB_ENGINE or self.web is not None:
|
||||
if self.web is not None:
|
||||
return
|
||||
self._ensure_web()
|
||||
if self._graph is None and self.path_edit.text().strip():
|
||||
|
||||
@@ -10,6 +10,7 @@ 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
|
||||
@@ -18,6 +19,7 @@ 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
|
||||
@@ -25,11 +27,25 @@ from .tabs.overview_tab import OverviewTab
|
||||
from .tabs.security_events_tab import SecurityEventsTab
|
||||
|
||||
_REFRESH_MS = 3000
|
||||
# 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).
|
||||
# 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.
|
||||
_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):
|
||||
@@ -259,14 +275,21 @@ 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
|
||||
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()
|
||||
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)
|
||||
|
||||
def _apply_events_to_event_tabs(self, events: List[dict]) -> None:
|
||||
"""Filters the ALREADY-LOADED event list (see ``_load_events`` — one
|
||||
|
||||
@@ -6,7 +6,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from PySide6.QtCore import QEvent, QObject, QRect, QSize, Qt
|
||||
from PySide6.QtCore import QEvent, QObject, QRect, QSize, Qt, Signal
|
||||
from PySide6.QtGui import QBrush, QColor
|
||||
from PySide6.QtWidgets import QHeaderView, QTableWidget, QTableWidgetItem, QWidget
|
||||
|
||||
@@ -17,7 +17,8 @@ from ....ui.icons import DOT_GREEN, DOT_RED, icon
|
||||
from .badges import action_label
|
||||
from .formatters import agent_avatar_icon, fmt_event_time
|
||||
|
||||
_MAX_ROWS = 300
|
||||
_DEFAULT_PAGE_SIZE = 20
|
||||
PAGE_SIZE_OPTIONS = (5, 10, 20, 50, 100)
|
||||
|
||||
|
||||
class _TimeItem(QTableWidgetItem):
|
||||
@@ -62,6 +63,12 @@ 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.
|
||||
@@ -70,6 +77,10 @@ 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)
|
||||
@@ -98,13 +109,60 @@ 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, cắt ở ``_MAX_ROWS``.
|
||||
"""Đổ 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.
|
||||
|
||||
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.
|
||||
"""
|
||||
events = sorted(events, key=lambda e: e.get("ts", ""), reverse=True)[:_MAX_ROWS]
|
||||
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]
|
||||
self.setSortingEnabled(False)
|
||||
self.setRowCount(len(events))
|
||||
for row, ev in enumerate(events):
|
||||
@@ -149,6 +207,7 @@ 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, QHBoxLayout, QLabel, QLineEdit, QPushButton, QSplitter,
|
||||
QTableWidget, QVBoxLayout, QWidget,
|
||||
QApplication, QComboBox, QHBoxLayout, QLabel, QLineEdit, QPushButton,
|
||||
QSplitter, QTableWidget, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from ....i18n import tr
|
||||
from ....i18n import bind_tip, tr
|
||||
from ....ui.icons import icon
|
||||
from .event_table import ClickOutsideCloser, EventTable
|
||||
from .event_table import PAGE_SIZE_OPTIONS, ClickOutsideCloser, EventTable
|
||||
from .event_detail_panel import EventDetailPanel
|
||||
|
||||
|
||||
@@ -47,11 +47,12 @@ 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_detail: bool = False, with_page_size: 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 và panel chi tiết.
|
||||
nút lọc bằng AI, control "Số dòng/trang" (nếu ``with_page_size``) 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.
|
||||
@@ -82,12 +83,64 @@ def build_filter_scaffold(
|
||||
search.textChanged.connect(table.apply_filter)
|
||||
ai_btn = QPushButton(tr("monitoring.ai_filter_btn"))
|
||||
ai_btn.setIcon(icon("sparkle"))
|
||||
ai_btn.setToolTip(tr("monitoring.ai_filter_tooltip"))
|
||||
# Bound rather than set once: this scaffold builds the button for all
|
||||
# three event tabs, and none of their retranslate() methods can reach a
|
||||
# tooltip that was applied here.
|
||||
bind_tip(ai_btn, "monitoring.ai_filter_tooltip")
|
||||
ai_btn.setCursor(Qt.PointingHandCursor)
|
||||
if on_ai_filter is not None:
|
||||
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,13 +25,16 @@ 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, on_ai_filter=self._start_ai_filter)
|
||||
with_search=True, with_detail=True, with_page_size=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."""
|
||||
@@ -44,6 +47,8 @@ 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."""
|
||||
|
||||
@@ -20,6 +20,7 @@ from ....core import admin_agents, preview_ai
|
||||
from ....core.worker import AgentWorker
|
||||
from ....i18n import on_language_changed, tr
|
||||
from ....state import AppContext
|
||||
from ....ui.dialog_buttons import dialog_buttons
|
||||
from ....ui.icons import icon
|
||||
from ....ui.widgets import ToggleSwitch, badge_pill_widget
|
||||
|
||||
@@ -95,7 +96,7 @@ class AgentEditDialog(QDialog):
|
||||
self.enabled_chk = QCheckBox(tr("agents_admin.f_enabled"))
|
||||
self.enabled_chk.setChecked(agent.enabled if agent else True)
|
||||
form.addRow("", self.enabled_chk)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
|
||||
buttons = dialog_buttons(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
form.addRow(buttons)
|
||||
|
||||
@@ -26,7 +26,7 @@ from typing import Dict, List
|
||||
|
||||
from PySide6.QtCore import QSize, Qt
|
||||
from PySide6.QtWidgets import (
|
||||
QHBoxLayout, QHeaderView, QLabel, QMessageBox, QPushButton,
|
||||
QHBoxLayout, QHeaderView, QLabel, QPushButton,
|
||||
QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
@@ -35,6 +35,7 @@ from ....core import admin_agents
|
||||
from ....core.worker import AgentWorker
|
||||
from ....i18n import on_language_changed, tr
|
||||
from ....state import AppContext
|
||||
from ....ui.dialog_buttons import confirm
|
||||
from ....ui.icons import icon
|
||||
from ....ui.widgets import ToggleSwitch, badge_pill_widget
|
||||
from .agent_edit_dialog import AgentEditDialog
|
||||
@@ -189,9 +190,8 @@ class AgentsAdminTab(QWidget):
|
||||
agent = admin_agents.load_agent(agent_id, self._dir())
|
||||
if agent is None:
|
||||
return
|
||||
if QMessageBox.question(
|
||||
self, tr("agents_admin.delete_title"),
|
||||
tr("agents_admin.delete_confirm", name=agent.name)) != QMessageBox.Yes:
|
||||
if not confirm(self, tr("agents_admin.delete_title"),
|
||||
tr("agents_admin.delete_confirm", name=agent.name)):
|
||||
return
|
||||
admin_agents.delete_agent(agent.agent_id, self._dir())
|
||||
self.refresh()
|
||||
|
||||
@@ -25,13 +25,16 @@ 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, on_ai_filter=self._start_ai_filter)
|
||||
with_search=True, with_detail=True, with_page_size=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."""
|
||||
@@ -44,6 +47,8 @@ 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."""
|
||||
|
||||
@@ -139,11 +139,11 @@ class PricingPanel(QGroupBox):
|
||||
|
||||
def _add_pricing_row(self) -> None:
|
||||
"""Thêm một dòng đơn giá trống để người dùng điền tay."""
|
||||
from PySide6.QtWidgets import QInputDialog
|
||||
from ....ui.dialog_buttons import ask_text
|
||||
|
||||
from ....core import model_pricing as mp
|
||||
name, ok = QInputDialog.getText(self, tr("monitoring.pricing_add"),
|
||||
tr("monitoring.pricing_add_prompt"))
|
||||
name, ok = ask_text(self, tr("monitoring.pricing_add"),
|
||||
tr("monitoring.pricing_add_prompt"))
|
||||
name = (name or "").strip()
|
||||
if not ok or not name:
|
||||
return
|
||||
|
||||
@@ -31,13 +31,16 @@ 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, on_ai_filter=self._start_ai_filter)
|
||||
with_search=True, with_detail=True, with_page_size=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."""
|
||||
@@ -50,6 +53,8 @@ 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."""
|
||||
|
||||
@@ -179,9 +179,12 @@ class ToolsAdminTab(QWidget):
|
||||
hdr.addWidget(sw)
|
||||
lay.addLayout(hdr)
|
||||
|
||||
desc = QLabel(spec.description)
|
||||
# spec.description là mô tả gửi cho mô hình (schema function-calling),
|
||||
# luôn tiếng Anh và viết cho máy đọc — thẻ này dùng bản dịch riêng.
|
||||
desc_text = tr(f"tools_admin.desc.{spec.name}")
|
||||
desc = QLabel(desc_text)
|
||||
desc.setWordWrap(True)
|
||||
desc.setToolTip(spec.description)
|
||||
desc.setToolTip(desc_text)
|
||||
desc.setObjectName("hint")
|
||||
desc.setStyleSheet("border: none;")
|
||||
lay.addWidget(desc)
|
||||
@@ -213,7 +216,8 @@ 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 not bool(self.ctx.config.agent_security.get("allow_url_fetch", True))
|
||||
or bool(self.ctx.config.agent_security.get("block_network", False)))
|
||||
if disabled:
|
||||
self.test_internet_status.setText(tr("tools_admin.internet_disabled"))
|
||||
self.test_internet_status.setStyleSheet("color: #c00;")
|
||||
|
||||
@@ -32,6 +32,7 @@ from cowork_local.core.worker import AgentWorker
|
||||
from cowork_local.i18n import tr
|
||||
from cowork_local.presentation.scheduling.ai_task_import_dialog import ImportTaskPanel
|
||||
from cowork_local.state import AppContext
|
||||
from cowork_local.ui.dialog_buttons import dialog_buttons
|
||||
from cowork_local.ui.icons import icon
|
||||
|
||||
|
||||
@@ -79,8 +80,8 @@ class AiTaskCreatorDialog(QDialog):
|
||||
self.import_panel.tasks_changed.connect(self._on_import_tasks_changed)
|
||||
self.tabs.addTab(self.import_panel, tr("schedtask.tab_import"))
|
||||
|
||||
self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
|
||||
self.buttons.button(QDialogButtonBox.Ok).setText(tr("schedtask.ai_confirm"))
|
||||
self.buttons = dialog_buttons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
|
||||
ok="schedtask.ai_confirm")
|
||||
self.buttons.button(QDialogButtonBox.Ok).setEnabled(False)
|
||||
self.buttons.accepted.connect(self._confirm)
|
||||
self.buttons.rejected.connect(self.reject)
|
||||
|
||||
@@ -38,6 +38,7 @@ from cowork_local.infrastructure.persistence.json.task_repository_impl import (
|
||||
)
|
||||
from cowork_local.presentation.scheduling.run_history_dialog import RunHistoryDialog
|
||||
from cowork_local.theme import current_palette
|
||||
from cowork_local.ui.dialog_buttons import confirm
|
||||
from cowork_local.ui.osutil import open_path
|
||||
|
||||
# Priority shown as a plain text tag (no colored-emoji squares). Only the
|
||||
@@ -317,9 +318,8 @@ class KanbanBoardWidget(QWidget):
|
||||
elif chosen == next_act:
|
||||
self._create_next_from_output(task)
|
||||
elif chosen == del_act:
|
||||
if QMessageBox.question(self, tr("schedtask.menu_delete"),
|
||||
tr("schedtask.delete_confirm", title=task.get("title", ""))
|
||||
) == QMessageBox.Yes:
|
||||
if confirm(self, tr("schedtask.menu_delete"),
|
||||
tr("schedtask.delete_confirm", title=task.get("title", ""))):
|
||||
self._service.delete(tid)
|
||||
self.refresh()
|
||||
|
||||
@@ -335,9 +335,8 @@ class KanbanBoardWidget(QWidget):
|
||||
"""Confirm, then delete every task in ``selected``. Split out of
|
||||
_bulk_delete_menu so tests can drive it directly without having to
|
||||
fake a real (modal, event-loop-blocking) QMenu popup."""
|
||||
if QMessageBox.question(
|
||||
self, tr("schedtask.menu_delete"),
|
||||
tr("schedtask.delete_multi_confirm", n=len(selected))) != QMessageBox.Yes:
|
||||
if not confirm(self, tr("schedtask.menu_delete"),
|
||||
tr("schedtask.delete_multi_confirm", n=len(selected))):
|
||||
return False
|
||||
ids = [it.data(Qt.UserRole) for it in selected if it.data(Qt.UserRole)]
|
||||
self._service.bulk_delete(ids)
|
||||
@@ -381,7 +380,7 @@ class KanbanBoardWidget(QWidget):
|
||||
nxt["dependency"]["previous_task_id"] = task["task_id"]
|
||||
err = chain_error(self._repo.list() + [nxt], task["task_id"], nxt["task_id"])
|
||||
if err:
|
||||
QMessageBox.warning(self, tr("schedtask.g_dependency"), err)
|
||||
QMessageBox.warning(self, tr("schedtask.g_dependency"), tr(err))
|
||||
return
|
||||
self._repo.save(nxt)
|
||||
task["dependency"]["next_task_id"] = nxt["task_id"]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user