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

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

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

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

## Change Type

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

## Related Work

Cowork Task:

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

Core AI Issue:

Core Task:

Related PR:

## Scope

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

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

## Validation

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

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

## Security Impact

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

## Compatibility

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

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

## Reviewer Notes

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

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

---------

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

256 lines
11 KiB
Python

"""Projects (workspaces) — Claude-Projects-style grouping for conversations.
A *project* groups chat threads that share one context, the way Claude's
Projects do:
* **Instructions** — free text injected into the system prompt of EVERY chat
in the project, so all threads follow the same project context.
* **Workspace (sandbox)** — each project owns its own folder; the AI agent's
file/command tools are confined to it (``ToolContext.resolve`` rejects any
path outside), so one project's agent can never touch another project's
files. Files placed at the workspace root are the project's *knowledge*:
every chat auto-reads them as input.
* **Threads** — conversations carry a ``project_id``; History and the
Workspace screen group them per project.
Stored one JSON file per project under ``~/.cowork_local/projects/``.
There is no longer a special, undeletable "General" project. Instead, a normal
**starter project** (id ``default`` for backward-compat, so pre-existing
conversations tagged ``default`` still attach to it) is seeded the first time
the projects folder is empty. It can be renamed and deleted like any other
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
from pathlib import Path
from typing import Dict, List, Optional
from ..config import CONFIG_DIR
PROJECTS_DIR = CONFIG_DIR / "projects"
WORKSPACES_DIR = CONFIG_DIR / "workspaces"
# The id of the auto-seeded starter project. It keeps the legacy value
# ``default`` only so conversations saved before Projects existed (they were
# tagged ``project_id="default"``) still land in it. It is NOT special —
# it can be renamed and deleted like any other project.
DEFAULT_PROJECT_ID = "default"
STARTER_PROJECT_NAME = "My Workspace"
@dataclass
class Project:
"""Một project: id, tên, mô tả, chỉ dẫn chung và thư mục sandbox.
Chỉ dẫn chung được chèn vào MỌI lượt chat thuộc project, nên đây là chỗ đặt
bối cảnh dùng lại thay vì gõ lại ở từng tin nhắn.
"""
project_id: str
name: str
description: str = ""
instructions: str = "" # shared context — injected into every chat's system prompt
output_dir: str = "" # optional custom workspace folder; empty → managed sandbox
created: str = ""
# ---- Per-workspace mode overrides (Auto Model Routing + Auto-run) --------
# Each workspace (project) remembers its OWN modes, independent of other
# workspaces, falling back to the global defaults when unset. See
# AppContext.project_routing_mode / project_confirm_commands.
# routing_modes: {surface: "off"|"auto"|"manual"}; missing/"" → follow the
# global routing.switch_mode. Surfaces: "cowork" | "co4e" | "ai_edit".
routing_modes: Dict[str, str] = field(default_factory=dict)
# 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
it (one sub-folder per session) and the agent's tools are confined to
it. Files at this root are the project's shared knowledge."""
if self.output_dir.strip():
return Path(self.output_dir).expanduser()
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."""
return Project(project_id=DEFAULT_PROJECT_ID, name=STARTER_PROJECT_NAME,
description="", instructions="",
created=datetime.now().isoformat(timespec="seconds"))
def ensure_starter_project(directory: Path = None) -> Project:
"""Guarantee at least one project exists. If the projects folder has no
project files yet, seed the starter project (id ``default``) and return it;
otherwise return the first existing project. Idempotent."""
directory = directory or PROJECTS_DIR
existing = list_projects(directory)
if existing:
return existing[0]
project = _starter_project()
save_project(project, directory)
return project
def _slugify(name: str) -> str:
"""Định danh an toàn cho tên file, suy từ tên project."""
s = "".join(c if (c.isalnum() or c in "-_") else "-" for c in name.strip().lower())
s = "-".join(filter(None, s.split("-")))
return s or "project"
#: Lich su hoi thoai cua mot project nam TRONG thu muc lam viec cua no, de chia
#: se thu muc do la chia se ca lich su (may khac xem va tiep tuc duoc).
HISTORY_SUBDIR = ".cowork_history"
def project_history_dir(project) -> Path:
"""Thư mục lịch sử hội thoại của một project."""
return project.workspace_dir() / HISTORY_SUBDIR
def new_project(name: str, description: str = "", instructions: str = "",
output_dir: str = "", directory: Path = None) -> Project:
"""Create + persist a new project with a unique id derived from the name."""
directory = directory or PROJECTS_DIR
base = _slugify(name)
pid, n = base, 2
while pid == DEFAULT_PROJECT_ID or (directory / f"{pid}.json").exists():
pid = f"{base}-{n}"
n += 1
project = Project(project_id=pid, name=name.strip() or pid,
description=description, instructions=instructions,
output_dir=output_dir,
created=datetime.now().isoformat(timespec="seconds"))
save_project(project, directory)
return project
def save_project(project: Project, directory: Path = None) -> Path:
"""Ghi một project ra ``<project_id>.json`` (ghi nguyên tử)."""
directory = directory or PROJECTS_DIR
path = directory / f"{project.project_id}.json"
# R06-T02: atomic write — a crash/kill between truncate and write used to
# leave a half-written project.json that load_project() then silently
# treats as "missing" (see infrastructure/persistence/json/atomic_write.py).
from ..infrastructure.persistence.json.atomic_write import write_json
write_json(path, asdict(project))
return path
def load_project(project_id: str, directory: Path = None) -> Optional[Project]:
"""Load one project from disk, or None if it does not exist. No project is
special-cased any more — a missing id simply returns None (callers treat
that as 'no project context')."""
directory = directory or PROJECTS_DIR
safe_id = re.sub(r"[^\w\-]", "", project_id or "")
path = directory / f"{safe_id}.json"
if path.exists():
try:
data = json.loads(path.read_text(encoding="utf-8"))
data.setdefault("project_id", path.stem)
known = {f for f in Project.__dataclass_fields__}
return Project(**{k: v for k, v in data.items() if k in known})
except (OSError, json.JSONDecodeError, TypeError):
return None
return None
def list_projects(directory: Path = None) -> List[Project]:
"""Every stored project, sorted by name. The starter project (id
``default``) is no longer forced to the top — it sorts like any other."""
directory = directory or PROJECTS_DIR
out: List[Project] = []
if directory.exists():
for path in sorted(directory.glob("*.json")):
p = load_project(path.stem, directory)
if p is not None:
out.append(p)
out.sort(key=lambda p: p.name.lower())
return out
def delete_project(project_id: str, directory: Path = None) -> bool:
"""Delete a project file (any project — nothing is undeletable now). The
project's conversations and workspace files are NOT deleted; its threads
just stop matching a project group in History until reassigned."""
directory = directory or PROJECTS_DIR
safe_id = re.sub(r"[^\w\-]", "", project_id or "")
if not safe_id:
return False
path = directory / f"{safe_id}.json"
try:
path.unlink()
return True
except OSError:
return False
def project_context_text(project: Optional[Project]) -> str:
"""The system-prompt block for a project's shared instructions ('' when
there is nothing to inject)."""
if project is None or not project.instructions.strip():
return ""
return (f"## Project context — {project.name}\n"
"Every conversation in this project follows these shared instructions:\n"
f"{project.instructions.strip()}")