Files
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

311 lines
13 KiB
Python

"""Thin Microsoft Graph REST wrapper for the MS365 connectors.
Every function takes a bearer ``token`` (from ``ms365_auth.get_access_token``)
and returns plain dict/list data straight from Graph's JSON — the caller
(``ms365_tools.py``) is responsible for turning that into a tool result.
Raises :class:`Ms365GraphError` on any non-2xx response so callers can
surface the real Graph error message instead of a generic failure.
"""
from __future__ import annotations
import base64
import re
from typing import Any, Dict, List, Optional
from urllib.parse import parse_qs, quote, unquote, urlparse
import requests
from . import tls_trust
GRAPH_BASE = "https://graph.microsoft.com/v1.0"
TIMEOUT = 30
class Ms365GraphError(Exception):
"""Lỗi khi gọi Microsoft Graph API."""
pass
class TeamsLinkError(Exception):
"""Link Teams không phân giải được thành team/channel/chat hợp lệ."""
pass
def _headers(token: str, extra: Optional[dict] = None) -> Dict[str, str]:
"""Header cho một lượt gọi Graph: Bearer token cộng phần thêm (nếu có)."""
h = {"Authorization": f"Bearer {token}"}
if extra:
h.update(extra)
return h
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))
# Same TLS auto-recovery every other outbound HTTPS call in this app uses
# (see core/tls_trust.py): a corporate network that intercepts traffic to
# the internal AI gateway with a self-signed certificate typically
# intercepts graph.microsoft.com the same way, so Graph calls need the
# same trust-on-first-use handling instead of failing outright.
kwargs["verify"] = tls_trust.verify_for(url, None)
try:
resp = requests.request(method, url, headers=headers, timeout=TIMEOUT, **kwargs)
except requests.exceptions.SSLError as exc:
if not tls_trust.looks_like_cert_trust_error(exc):
raise
pinned = tls_trust.capture_and_trust(url)
if not pinned:
raise
kwargs["verify"] = pinned
resp = requests.request(method, url, headers=headers, timeout=TIMEOUT, **kwargs)
if resp.status_code >= 400:
try:
detail = resp.json().get("error", {}).get("message", resp.text)
except ValueError:
detail = resp.text
raise Ms365GraphError(f"Graph API error {resp.status_code}: {detail}")
return resp
def _path_segment(path: str) -> str:
"""Encode a OneDrive/SharePoint relative path for the ``root:/{path}:``
addressing form Graph uses."""
return quote(path.strip("/"), safe="/")
# ---- Outlook ---------------------------------------------------------------
def list_mail(token: str, top: int = 10, folder: str = "inbox") -> List[dict]:
"""Danh sách thư trong một thư mục hộp thư (mặc định Inbox)."""
resp = _request("GET", f"/me/mailFolders/{quote(folder)}/messages"
f"?$top={int(top)}&$select=subject,from,receivedDateTime,bodyPreview,webLink",
token)
return resp.json().get("value", [])
def send_mail(token: str, to: str, subject: str, body: str) -> None:
"""Gửi một email qua tài khoản đang đăng nhập."""
payload = {
"message": {
"subject": subject,
"body": {"contentType": "Text", "content": body},
"toRecipients": [{"emailAddress": {"address": a.strip()}} for a in to.split(",") if a.strip()],
}
}
_request("POST", "/me/sendMail", token, json=payload)
def list_calendar_events(token: str, top: int = 10) -> List[dict]:
"""Danh sách sự kiện lịch sắp tới, xếp theo thời gian bắt đầu."""
resp = _request("GET", f"/me/events?$top={int(top)}"
"&$select=subject,start,end,organizer,location&$orderby=start/dateTime",
token)
return resp.json().get("value", [])
# ---- Teams ------------------------------------------------------------------
def list_teams(token: str) -> List[dict]:
"""Các team mà người dùng đang tham gia."""
resp = _request("GET", "/me/joinedTeams", token)
return resp.json().get("value", [])
def list_channels(token: str, team_id: str) -> List[dict]:
"""Các kênh trong một team."""
resp = _request("GET", f"/teams/{quote(team_id)}/channels", token)
return resp.json().get("value", [])
def list_channel_messages(token: str, team_id: str, channel_id: str, top: int = 20) -> List[dict]:
"""Tin nhắn gần đây trong một kênh."""
resp = _request("GET", f"/teams/{quote(team_id)}/channels/{quote(channel_id)}/messages"
f"?$top={int(top)}", token)
return resp.json().get("value", [])
def send_channel_message(token: str, team_id: str, channel_id: str, text: str) -> None:
"""Gửi tin nhắn vào một kênh Teams."""
payload = {"body": {"content": text}}
_request("POST", f"/teams/{quote(team_id)}/channels/{quote(channel_id)}/messages", token,
json=payload)
def get_channel(token: str, team_id: str, channel_id: str) -> dict:
"""Thông tin một kênh Teams."""
resp = _request("GET", f"/teams/{quote(team_id)}/channels/{quote(channel_id)}", token)
return resp.json()
def get_chat(token: str, chat_id: str) -> dict:
"""Thông tin một cuộc trò chuyện Teams."""
resp = _request("GET", f"/chats/{quote(chat_id)}", token)
return resp.json()
def send_chat_message(token: str, chat_id: str, text: str) -> None:
"""Gửi tin nhắn vào một cuộc trò chuyện Teams."""
_request("POST", f"/chats/{quote(chat_id)}/messages", token, json={"body": {"content": text}})
# ---- "paste a Teams link" convenience -----------------------------------
_LINK_THREAD_RE = re.compile(r"/l/(?:channel|chat|message)/([^/?]+)")
def parse_teams_link(url: str) -> Dict[str, str]:
"""Parse a link copied from Teams ("Get link to channel" or a message's
"Copy link") into a Graph-addressable target:
``{"kind": "channel", "team_id": ..., "channel_id": ...}`` or
``{"kind": "chat", "chat_id": ...}``."""
url = (url or "").strip()
if not url:
raise TeamsLinkError("Empty link.")
match = _LINK_THREAD_RE.search(url)
if not match:
raise TeamsLinkError(
"Unrecognized Teams link — paste a channel link ('Get link to channel') "
"or a chat/message link copied from Teams.")
thread_id = unquote(match.group(1))
group_id = (parse_qs(urlparse(url).query).get("groupId") or [""])[0]
if group_id:
return {"kind": "channel", "team_id": group_id, "channel_id": thread_id}
return {"kind": "chat", "chat_id": thread_id}
# ---- OneDrive -----------------------------------------------------------
def list_onedrive_files(token: str, path: str = "") -> List[dict]:
"""Liệt kê tệp/thư mục trong OneDrive; ``path`` rỗng là thư mục gốc."""
url = "/me/drive/root/children" if not path else f"/me/drive/root:/{_path_segment(path)}:/children"
resp = _request("GET", url, token)
return resp.json().get("value", [])
def read_onedrive_file(token: str, path: str, max_chars: int = 50_000) -> str:
"""Đọc nội dung một tệp OneDrive dưới dạng văn bản, cắt ở ``max_chars``."""
resp = _request("GET", f"/me/drive/root:/{_path_segment(path)}:/content", token)
return resp.content.decode("utf-8", errors="replace")[:max_chars]
def write_onedrive_file(token: str, path: str, content: str) -> dict:
"""Ghi nội dung văn bản vào một tệp OneDrive (tạo mới hoặc ghi đè)."""
resp = _request("PUT", f"/me/drive/root:/{_path_segment(path)}:/content", token,
data=content.encode("utf-8"),
headers={"Content-Type": "text/plain"})
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)."""
b64 = base64.urlsafe_b64encode(url.strip().encode("utf-8")).decode("ascii").rstrip("=")
return f"u!{b64}"
def read_shared_file(token: str, share_url: str, max_chars: int = 50_000) -> str:
"""Read the content of an item shared via a OneDrive/SharePoint sharing
LINK (e.g. an admin's "Anyone with the link" rules document) — resolved
through Graph's ``/shares`` endpoint, so it works for a link into anyone's
drive, not just the signed-in user's own OneDrive (unlike
:func:`read_onedrive_file`, which only reads by path in ``/me/drive``)."""
share_id = _encode_share_url(share_url)
resp = _request("GET", f"/shares/{share_id}/driveItem/content", token)
return resp.content.decode("utf-8", errors="replace")[:max_chars]
# ---- SharePoint --------------------------------------------------------
def list_sharepoint_sites(token: str, query: str) -> List[dict]:
"""Tìm site SharePoint theo từ khoá."""
resp = _request("GET", f"/sites?search={quote(query)}", token)
return resp.json().get("value", [])
def list_sharepoint_files(token: str, site_id: str, path: str = "") -> List[dict]:
"""Liệt kê tệp/thư mục trong thư viện tài liệu của một site SharePoint."""
url = (f"/sites/{quote(site_id)}/drive/root/children" if not path
else f"/sites/{quote(site_id)}/drive/root:/{_path_segment(path)}:/children")
resp = _request("GET", url, token)
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."""
resp = _request("GET", f"/me/onlineMeetings?$filter=JoinWebUrl eq '{quote(join_url, safe='')}'",
token)
return resp.json().get("value", [])
def list_meeting_transcripts(token: str, meeting_id: str) -> List[dict]:
"""Danh sách bản ghi lời thoại của một cuộc họp."""
resp = _request("GET", f"/me/onlineMeetings/{quote(meeting_id)}/transcripts", token)
return resp.json().get("value", [])
def get_meeting_transcript_content(token: str, meeting_id: str, transcript_id: str,
max_chars: int = 50_000) -> str:
"""Nội dung một bản ghi lời thoại, cắt ở ``max_chars``."""
resp = _request(
"GET",
f"/me/onlineMeetings/{quote(meeting_id)}/transcripts/{quote(transcript_id)}/content"
"?$format=text/vtt",
token)
return resp.content.decode("utf-8", errors="replace")[:max_chars]