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>
191 lines
8.2 KiB
Python
191 lines
8.2 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 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
|
|
|
|
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 _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"
|
|
|
|
|
|
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()}")
|