Files
cowork-local/core/windows_sandbox_vm.py
T
anhtnm1andClaude Opus 5 e29a0ccdbd refactor: vá 4 hồi quy, tách 4 file chạm trần LOC, docstring lên 100%
Hồi quy đã vá
-------------
F-12  Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
      `chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
      `composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
      tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
      là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
      gắn 1 tệp, khớp bản trước refactor.

F-01  Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
      `folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
      `ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
      tiên hỏng thì đổi provider chính là lúc phải thử lại.

F-07  Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
      lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
      người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
      theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
      mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
      `check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.

F-11  Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
      mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
      và không bao giờ chạy.

Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:

    graph_renderer.py         -> graph_scene_builder.py + graph_export.py
    co4e_workflow_service.py  -> co4e_run_history.py
    json_config_repository.py -> config_sections.py
    agents_admin_tab.py       -> shared/agent_kind_visuals.py

File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.

Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.

Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.

859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 10:41:45 +09:00

168 lines
5.8 KiB
Python

"""Windows Sandbox VM — high-risk execution in ephemeral VM isolation.
Uses .wsb configuration files to launch Windows Sandbox with:
- Full filesystem isolation
- Optional full network disablement
- Disabled clipboard, printer, audio input, video input, vGPU
- Mounts only approved workspace folder
- Captures stdout, stderr, exit code back to safe output files
"""
from __future__ import annotations
import os
import platform
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, Optional
_IS_WINDOWS = sys.platform == "win32"
def is_windows_sandbox_available() -> bool:
"""Check if Windows Sandbox is available (Win 10/11 Pro/Enterprise with virtualization)."""
if not _IS_WINDOWS:
return False
try:
import winreg
key = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
r"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Virtualization",
0,
winreg.KEY_READ,
)
val, _ = winreg.QueryValueEx(key, "VirtualizationEnabled")
winreg.CloseKey(key)
return val == 1
except Exception:
pass
return False
class WindowsSandboxVM:
"""Sandbox using Windows Sandbox VM for critical-risk execution."""
def run_command(
self,
command: str,
workdir: str = "",
block_network: bool = True,
memory_mb: int = 1024,
timeout_sec: int = 300,
) -> Dict[str, Any]:
"""Run command in Windows Sandbox VM.
Generates a temporary .wsb config, launches the sandbox, runs the
command inside, captures output, and cleans up.
"""
if not _IS_WINDOWS:
return self._error("Windows Sandbox is only available on Windows")
if not is_windows_sandbox_available():
return self._error(
"Windows Sandbox is not available or not enabled on this system"
)
# Create output capture files
stdout_file = Path(tempfile.gettempdir()) / f"wsb_stdout_{os.getpid()}.txt"
stderr_file = Path(tempfile.gettempdir()) / f"wsb_stderr_{os.getpid()}.txt"
exit_file = Path(tempfile.gettempdir()) / f"wsb_exit_{os.getpid()}.txt"
# Escape command for batch
safe_cmd = command.replace('"', '"^"')
# Build batch script to capture output
batch = (
f'cmd /c ("{safe_cmd}" > "{stdout_file}" 2> "{stderr_file}" && '
f'echo %errorlevel% > "{exit_file}" || echo %errorlevel% > "{exit_file}")'
)
# Build .wsb config
wsb_content = [
"<Configuration>",
f" <MemoryMB>{memory_mb}</MemoryMB>",
]
if block_network:
wsb_content.append(" <Networking>Disable</Networking>")
wsb_content.append(" <Clipboard>Disable</Clipboard>")
wsb_content.append(" <Printer>Disable</Printer>")
wsb_content.append(" <AudioInput>Disable</AudioInput>")
wsb_content.append(" <VideoInput>Disable</VideoInput>")
wsb_content.append(" <VGpu>Disable</VGpu>")
if workdir:
wsb_content.append(f" <Volume>{workdir}={workdir}</Volume>")
wsb_content.append(f' <LogonCommand>')
wsb_content.append(f' <Command>{batch}</Command>')
wsb_content.append(f" </LogonCommand>")
wsb_content.append("</Configuration>")
wsb_path = Path(tempfile.gettempdir()) / f"cowork_sandbox_{os.getpid()}.wsb"
try:
wsb_path.write_text("\n".join(wsb_content), encoding="utf-8")
# Launch Windows Sandbox
proc = subprocess.Popen(
[str(wsb_path)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# Wait for the sandbox to complete (it exits when logon command finishes)
try:
proc.wait(timeout=timeout_sec)
except subprocess.TimeoutExpired:
proc.kill()
return {
"ok": False,
"stdout": "",
"stderr": f"Timeout after {timeout_sec}s",
"returncode": -1,
"sandbox": "windows_sandbox",
}
# Read results
stdout_text = ""
stderr_text = ""
returncode = proc.returncode or 0
if stdout_file.exists():
stdout_text = stdout_file.read_text(encoding="utf-8", errors="replace")
if stderr_file.exists():
stderr_text = stderr_file.read_text(encoding="utf-8", errors="replace")
if exit_file.exists():
try:
returncode = int(exit_file.read_text().strip())
except ValueError:
pass
return {
"ok": returncode == 0,
"stdout": stdout_text,
"stderr": stderr_text,
"returncode": returncode,
"sandbox": "windows_sandbox",
}
except Exception as exc:
return self._error(str(exc))
finally:
# Cleanup temp files
for f in (wsb_path, stdout_file, stderr_file, exit_file):
try:
if f.exists():
f.unlink()
except OSError:
pass
def _error(self, message: str) -> Dict[str, Any]:
"""Kết quả lỗi theo đúng khuôn chung của bộ chạy sandbox."""
return {
"ok": False,
"stdout": "",
"stderr": message,
"returncode": -1,
"sandbox": "windows_sandbox",
}