Compare commits

..
Author SHA1 Message Date
thanhnv 202925e6ed feat(mcp): scaffold three project context tools
CI / test (pull_request) Canceled after 0s
2026-08-20 20:50:37 +07:00
thanhnv 3827552909 fix(security): remove shared unlock defaults 2026-08-20 20:20:04 +07:00
1419587401 Feature/fsg gamma team ui fix (#3)
CI / test (push) Canceled after 0s
## Summary

What changed and why?

## Change Type

- [ ] Cowork feature
- [ ] Bug fix
- [x] Core AI contribution
- [ ] Test / hardening
- [ ] 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?

What is intentionally NOT included?

## Validation

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

Commands / evidence:

## Security Impact

Permission / credential / network / customer data impact:

## Compatibility

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

## Reviewer Notes

Anything Cowork reviewers should pay attention to.

---------

Co-authored-by: Hiep Ha Van <hiephv3@fpt.com>
Co-authored-by: Nam Pham Dinh Thanh <nampdt@fpt.com>
Co-authored-by: Lam Hoang Van <lamhv7@fpt.com>
Co-authored-by: NamPDT <minhanhpkpro@gmail.com>
Reviewed-on: #3
2026-08-20 12:12:56 +00:00
160 changed files with 24281 additions and 3985 deletions
+29
View File
@@ -0,0 +1,29 @@
# Normalise line endings so a Windows checkout and a Linux CI runner see the
# same bytes. Without this, committing from Windows records CRLF and every file
# shows as fully rewritten to anyone (or any CI job) on Linux.
* text=auto eol=lf
# Windows-only scripts must keep CRLF or cmd.exe mis-parses them.
*.bat text eol=crlf
*.cmd text eol=crlf
*.ps1 text eol=crlf
# Binary: never touch, never try to diff as text.
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.pdf binary
*.pptx binary
*.xlsx binary
*.docx binary
*.7z binary
*.zip binary
*.ttf binary
*.woff binary
*.woff2 binary
# The audit page is a single 8 MB file with base64 images inlined — a textual
# diff of it is noise, and merging it by hand is never the right move.
docs/ui-audit.html -diff -merge
+108 -25
View File
@@ -1,39 +1,122 @@
# Python bytecode and test/tool caches
# =============================================================================
# Dependencies
# =============================================================================
node_modules/
.pnpm-store/
__pycache__/
*.py[cod]
*$py.class
.pytest_cache/
.ruff_cache/
.mypy_cache/
.coverage
htmlcov/
# Local environments and packaging output
*.pyc
*.pyo
*.pyd
.venv/
venv/
env/
build/
dist/
.env.venv/
pip-wheel-metadata/
*.egg-info/
*.egg
.eggs/
bower_components/
# Local configuration, credentials, and runtime data
# =============================================================================
# Environment & Secrets
# =============================================================================
.env
.env.*
!.env.example
.cowork_local/
ms365_token_cache.bin
*.log
*.sqlite
*.sqlite3
*.db
.env.local
.env.*.local
.env.production
.env.development
.env.preview
*.pem
*.key
*.p12
*.pfx
secrets/
credentials.json
.npmrc
.yarnrc
# Editors and operating systems
.DS_Store
# =============================================================================
# Build & Distribution
# =============================================================================
dist/
build/
out/
.next/
.nuxt/
.output/
# =============================================================================
# IDE & Editor
# =============================================================================
.idea/
.vscode/
*.swp
*.swo
*~
.project
.classpath
.settings/
*.sublime-project
*.sublime-workspace
# =============================================================================
# OS Files
# =============================================================================
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
desktop.ini
# =============================================================================
# Logs & Debug
# =============================================================================
*.log
logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# =============================================================================
# Testing & Coverage
# =============================================================================
.coverage
.coverage.*
htmlcov/
.pytest_cache/
.tox/
.nox/
coverage/
*.cover
*.py,cover
.hypothesis/
.nyc_output/
test-results/
playwright-report/
# =============================================================================
# AI & Agent Workspace
# =============================================================================
vibeflow.json
.claude/
.cursor/
.aider/
.continue/
.copilot/
# =============================================================================
# Temporary & Cache
# =============================================================================
*.tmp
*.temp
.cache/
.parcel-cache/
.turbo/
*.tsbuildinfo
# Runtime data the app writes next to itself when it is run from the repo.
# A chat transcript got committed and pushed this way.
.cowork_history/
.cowork_local/
+99
View File
@@ -0,0 +1,99 @@
#!/bin/sh
# Boot the Cowork-Local PySide6 desktop app on Qt's built-in VNC server, then
# expose the live GUI to the browser through noVNC + websockify on :6080.
#
# This entrypoint is intended to be run from a `python:3.11-slim-bookworm`
# container via podman-compose. All setup (Qt runtime libs, noVNC, PySide6
# wheels) happens here so we don't need a custom image / Dockerfile.
# Idempotent: reruns are fast (apt reuses debs, pip uses the named cache vol).
set -e
log() { printf '[entrypoint] %s\n' "$*"; }
# ---------------------------------------------------------------------------
# 1. System runtime libraries: Qt6 needs EGL/GL/XCB; noVNC needs websockify.
# ---------------------------------------------------------------------------
if [ ! -f /var/cache/cowork_setup.stamp ]; then
log "installing apt packages (first run only)…"
apt-get update -qq
apt-get install -y --no-install-recommends \
libegl1 libgl1 libglib2.0-0 libdbus-1-3 libfontconfig1 \
libxkbcommon0 libxkbcommon-x11-0 libxcb-cursor0 \
libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-randr0 \
libxcb-render-util0 libxcb-shape0 libxcb-sync1 \
libxcb-xfixes0 libxcb-xinerama0 libxcb-xkb1 libxcb-util1 \
libxcomposite1 libxdamage1 libxrandr2 libxss1 libxtst6 \
libxi6 libxrender1 libfreetype6 \
fonts-dejavu fonts-noto-cjk \
netcat-openbsd ca-certificates >/dev/null
rm -rf /var/lib/apt/lists/*
touch /var/cache/cowork_setup.stamp
log "apt setup done."
else
log "apt setup already done (skipping)."
fi
# ---------------------------------------------------------------------------
# 2. Python dependencies (cached in the named `pip-cache` volume).
# `websockify` is shipped as a pip wheel and bundles the noVNC web
# assets under its package `web/` directory, so we don't need the
# (unavailable on slim-bookworm) apt `novnc` / `websockify` packages.
# ---------------------------------------------------------------------------
log "ensuring python deps…"
pip install --no-cache-dir --quiet \
"PySide6>=6.6" "pydantic>=2" requests psutil websockify numpy
log "python deps OK."
# ---------------------------------------------------------------------------
# 3. Make the workspace importable as `cowork_local` (the package name that
# `python -m cowork_local` and the test suite expect). Compose mounts the
# live repo at /workspace; we add a thin symlink at /opt/cowork_local.
# ---------------------------------------------------------------------------
ln -sfn /workspace /opt/cowork_local
export PYTHONPATH=/opt
# ---------------------------------------------------------------------------
# 4. Launch the app on Qt's built-in VNC platform (no Xvfb needed).
# Qt VNC listens on QT_QPA_VNC_HOST:QT_QPA_VNC_PORT (127.0.0.1:5900).
# ---------------------------------------------------------------------------
: > /var/log/app.log
log "launching app on Qt VNC platform…"
python -m cowork_local >/var/log/app.log 2>&1 &
APP_PID=$!
# Wait until the VNC socket accepts a connection (or give up after 60s).
for i in $(seq 1 120); do
if nc -z 127.0.0.1 "${QT_QPA_VNC_PORT:-5900}" 2>/dev/null; then
log "VNC server up on 127.0.0.1:${QT_QPA_VNC_PORT:-5900} (pid ${APP_PID})."
break
fi
if ! kill -0 "${APP_PID}" 2>/dev/null; then
log "app process died before VNC was up; log tail:"
tail -n 60 /var/log/app.log >&2 || true
exit 1
fi
sleep 0.5
done
if ! nc -z 127.0.0.1 "${QT_QPA_VNC_PORT:-5900}" 2>/dev/null; then
log "VNC never came up; log tail:"
tail -n 60 /var/log/app.log >&2 || true
exit 1
fi
# ---------------------------------------------------------------------------
# 5. Bridge browser -> VNC. websockify serves the noVNC web client on :6080
# and proxies WebSocket connections to the raw VNC server. The noVNC web
# assets are bundled inside the websockify pip wheel.
# ---------------------------------------------------------------------------
NOVNC_WEB="$(python - <<'PY'
import os, websockify
print(os.path.join(os.path.dirname(websockify.__file__), "web"))
PY
)"
[ -f "${NOVNC_WEB}/vnc.html" ] || { log "noVNC web assets not found at ${NOVNC_WEB}, aborting."; exit 1; }
log "noVNC web assets: ${NOVNC_WEB}"
log "starting noVNC bridge on 0.0.0.0:6080 -> 127.0.0.1:${QT_QPA_VNC_PORT:-5900}"
exec websockify --web="${NOVNC_WEB}" 0.0.0.0:6080 "127.0.0.1:${QT_QPA_VNC_PORT:-5900}"
+4 -7
View File
@@ -6,23 +6,20 @@ The Cowork Team owns this product and its stable branch. The FSG AI Core Team co
## Quick start
Install the Python/PySide6 desktop application into an isolated environment:
The imported application is a Python/PySide6 package. Run it from the directory that contains `cowork_local`:
```bash
./scripts/install_local.sh
./scripts/run_local.sh
python -m cowork_local
```
The installer also creates `~/.local/bin/cowork-local` when that path is available. See [docs/installation.md](docs/installation.md) for prerequisites, configuration, verification, optional document tooling, and platform limitations.
The reliable automated test surface checked by CI is:
The source snapshot does not include a complete runtime dependency manifest. Use the Cowork Team's supported runtime environment until that packaging contract is documented. The reliable automated test surface currently checked by CI is:
```bash
python -m pip install -r cowork_local/requirements-test.txt
python -m pytest cowork_local/tests -q
```
When already inside this repository, run `.venv/bin/python -m pytest tests -q`.
When already inside this repository, run `python -m pytest tests -q`.
Configuration and runtime data live under `~/.cowork_local/`. Provider keys and local unlock codes must be supplied through environment variables or an approved secret manager; see `.env.example`.
+18 -2
View File
@@ -1,13 +1,29 @@
"""Entry point: ``python -m cowork_local``."""
"""Entry point: ``python -m cowork_local``.
Also works when run directly as ``python __main__.py`` — see main().
"""
from __future__ import annotations
import os
import sys
def main() -> int:
# Imported lazily so that ``-h`` style tooling and tests can import the
# package without spinning up a full Qt application.
from .app import run
#
# `from .app import run` requires this file to be loaded as part of the
# `cowork_local` package (i.e. via `python -m cowork_local`). When run as
# a plain script (`python __main__.py`), `__package__` is empty so the
# relative import fails — in that case put the package root (the parent
# of this file's directory) on sys.path and use an absolute import.
if __package__:
from .app import run
else:
parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if parent not in sys.path:
sys.path.insert(0, parent)
from cowork_local.app import run
return run(sys.argv)
+623 -140
View File
@@ -7,18 +7,21 @@ from pathlib import Path
from typing import List
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QGuiApplication, QIcon
from PySide6.QtGui import QColor, QGuiApplication, QIcon
from PySide6.QtWidgets import (
QStyledItemDelegate,
QApplication, QComboBox, QHBoxLayout, QLabel, QMainWindow, QMenu,
QPushButton, QSizePolicy, QSplitter, QStackedWidget, QSystemTrayIcon,
QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget,
QPushButton, QScrollArea, QSizePolicy, QSplitter, QStackedWidget,
QSystemTrayIcon, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout,
QWidget,
)
from . import APP_NAME, DISPLAY_NAME, __version__
from .config import PROVIDER_LABELS, AppConfig
from .i18n import LANGUAGE_SHORT, LANGUAGES, get_language, on_language_changed, set_language, tr
from .state import AppContext
from .theme import ACCENT, stylesheet
from .ui.widgets import tidy_popup
from .theme import current_palette, set_active_theme, stylesheet
from .core.task_scheduler import TaskScheduler
from .ui.cowork_tab import CoworkTab
from .ui.dashboard_tab import DashboardTab
@@ -35,6 +38,23 @@ ASSETS = Path(__file__).resolve().parent / "assets"
# shows icon-only (still fully clickable, just narrower).
_NAV_EXPANDED_WIDTH = 150
_NAV_COLLAPSED_WIDTH = 54
# The splitter between rail and content draws a drag handle. It only means
# something if the rail can actually take a width from it, so the expanded rail
# is a range rather than one number; long project and thread names in RECENTS
# are the reason someone would widen it.
#
# The ceiling is a SHARE of the window, not a pixel count: 360px is a quarter
# of a 1440 screen and more than a quarter of a 1280 one, where it left the
# seven Kanban lanes 920px of the 1067 they need. A share behaves the same on
# every monitor.
# Where a rail row starts, and how much air sits between its icon and its
# label. The tree rows get these from the style; anything laid out by hand
# beside them has to use the same two numbers or it will not line up.
_NAV_ROW_INSET = 4
_NAV_ROW_GAP = 6
_NAV_MIN_WIDTH = 132
_NAV_MAX_SHARE = 0.22
_NAV_MAX_CEILING = 360
def app_icon() -> QIcon:
@@ -64,10 +84,12 @@ class _Toast(QLabel):
self._timer.timeout.connect(self.hide)
def show_message(self, text: str, ok: bool = True, ms: int = 4500) -> None:
bg = "#1f9d63" if ok else "#e5484d"
p = current_palette()
bg = p.success_soft if ok else p.danger_soft
fg = p.success if ok else p.danger
self.setStyleSheet(
f"#toast {{ background:{bg}; color:white; border-radius:12px;"
f" padding:10px 16px; font-weight:600; }}")
f"#toast {{ background:{bg}; color:{fg}; border:1px solid {fg};"
f" border-radius:{p.radius}px; padding:10px 16px; font-weight:600; }}")
self.setText(text)
self.adjustSize()
self.move(14, 14) # top-left of the window
@@ -76,6 +98,23 @@ class _Toast(QLabel):
self._timer.start(ms)
class _NavItemDelegate(QStyledItemDelegate):
"""Keep a rail row's icon on the left edge, whatever the column is doing.
QStyledItemDelegate hands the style decorationAlignment = AlignHCenter, so
a row with no label — every row once the rail collapses to 54px — has its
icon centred inside whatever box the column happens to give it. That box
tracks the column width, which is not stable: stretched to the viewport the
icons land in the middle of the rail, while a column left wider than the
view leaves them at the left. Same code, two different pictures, which is
why a test render disagreed with the running app.
"""
def initStyleOption(self, option, index):
super().initStyleOption(option, index)
option.decorationAlignment = Qt.AlignLeft | Qt.AlignVCenter
class MainWindow(QMainWindow):
# Nav rows (Dashboard/Schedule/Monitoring are lazy; Workspace is the eager home page).
_ROW_DASHBOARD, _ROW_SCHEDULE, _ROW_WORKSPACE, _ROW_MONITORING = 0, 1, 2, 3
@@ -155,8 +194,6 @@ class MainWindow(QMainWindow):
("app.tab.workspace", "workspaces", None, self.workspace),
("app.tab.monitoring", "monitoring", self._build_monitoring, None),
]
# Container pages whose sub-tabs become expandable nav children.
self._nav_parents = {self._ROW_WORKSPACE, self._ROW_MONITORING}
self._page_widgets = [] # page index → widget (placeholder until lazily built)
self._built = []
for _key, _icon_name, _builder, widget in self._nav_defs:
@@ -165,48 +202,37 @@ class MainWindow(QMainWindow):
self._page_widgets.append(page)
self._built.append(widget is not None)
# Left nav rail as a parent→child accordion (Claude-style): the container
# pages (Workspaces, Monitoring) expand to list their sub-views as
# children, and their in-content tab strips are hidden — so the content
# area is as large as possible.
from .ui.icons import icon as _icon
self.nav = QTreeWidget()
self.nav.setObjectName("navrail")
self.nav.setHeaderHidden(True)
self.nav.setIndentation(14)
self.nav.setRootIsDecorated(True)
self.nav.setExpandsOnDoubleClick(False)
self._nav_items = [] # page index → top-level QTreeWidgetItem
for page, (key, icon_name, _b, _w) in enumerate(self._nav_defs):
it = QTreeWidgetItem([tr(key)])
it.setIcon(0, _icon(icon_name))
it.setData(0, Qt.UserRole, {"page": page, "sub": None,
"parent": page in self._nav_parents, "key": key})
# A container (Monitoring/Workspace) always shows the dropdown arrow —
# even before its page/children are lazily built — so it's obvious it
# holds multiple sub-views. It stays collapsed until first expanded.
if page in self._nav_parents:
it.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator)
self.nav.addTopLevelItem(it)
self._nav_items.append(it)
# Left nav rail — ONE FLAT LIST, no accordion. Every screen the user
# works in is one click away: the Workspace sub-views are listed
# directly instead of hiding behind an expandable parent. The two
# occasional admin destinations sit in a second, bottom-pinned list.
#
# Monitoring is the exception that keeps its sub-views OUT of the rail:
# it has eight, which would double the rail's length for screens opened
# once a week. Its own tab strip is left visible instead (it was hidden
# while the rail carried its children), so all eight stay reachable.
self.nav = self._new_nav_tree("navrail")
self.nav_bottom = self._new_nav_tree("navrailBottom")
self._nav_building = False # guards the rebuild → select → rebuild loop
self.workspace.hide_tab_bar()
self._reload_nav_children(self._ROW_WORKSPACE) # Workspace is eager
self.workspace.subtabs_changed.connect(
lambda: self._reload_nav_children(self._ROW_WORKSPACE))
self.nav.currentItemChanged.connect(lambda cur, _prev: self._navigate(cur))
self.nav.itemClicked.connect(self._on_nav_click)
self.nav.itemExpanded.connect(self._on_nav_expanded) # build children lazily
self._rebuild_nav()
self.workspace.subtabs_changed.connect(self._rebuild_nav)
for tree in (self.nav, self.nav_bottom):
tree.currentItemChanged.connect(
lambda cur, _prev, t=tree: self._on_nav_current(t, cur))
rlay.addWidget(self.pages, 1)
# Nav rail wrapper: a small toggle button ABOVE the page list so the
# whole rail can collapse to icon-only (still fully clickable). Same
# collapse/expand chevron iconography as every other collapsible panel.
from .ui.icons import collapse_left_icon, collapse_right_icon
from .ui.icons import icon as _icon
self._collapse_left_icon = collapse_left_icon
self._collapse_right_icon = collapse_right_icon
self._nav_wrap = QWidget()
self._nav_wrap.setObjectName("navWrap")
self._nav_wrap.setFixedWidth(_NAV_EXPANDED_WIDTH)
self._nav_width = _NAV_EXPANDED_WIDTH # remembered across collapses
self._set_nav_width_range(_NAV_MIN_WIDTH, self._nav_max_width())
nvl = QVBoxLayout(self._nav_wrap)
nvl.setContentsMargins(0, 0, 0, 0)
nvl.setSpacing(0)
@@ -228,7 +254,107 @@ class MainWindow(QMainWindow):
toggle_row.addWidget(self._nav_toggle_btn, 0, Qt.AlignLeft)
toggle_row.addStretch(1)
nvl.addLayout(toggle_row)
nvl.addWidget(self.nav, 1)
# Primary action at the top of the rail, with the project it will land
# in named right above it. Before, starting a chat in another project
# meant leaving Cowork → Project tab → click a row → come back.
self.nav_project = QComboBox()
self.nav_project.setObjectName("navProjectPick")
self.nav_project.setToolTip(tr("app.nav.project_pick"))
self.nav_project.currentIndexChanged.connect(self._on_rail_project_pick)
tidy_popup(self.nav_project)
self.nav_new_chat = QPushButton(tr("cowork.new_chat"))
self.nav_new_chat.setObjectName("navNewChatBtn")
self.nav_new_chat.setIcon(_icon("plus"))
self.nav_new_chat.setCursor(Qt.PointingHandCursor)
self.nav_new_chat.clicked.connect(self._on_rail_new_chat)
# At 54px the picker cannot show a name, but dropping it altogether left
# the collapsed rail with no way to change project at all. This stands in
# for it: same list, same handler, just the folder icon and a tooltip.
self.nav_project_btn = QToolButton()
self.nav_project_btn.setObjectName("navProjectPickMini")
self.nav_project_btn.setIcon(_icon("folder"))
self.nav_project_btn.setCursor(Qt.PointingHandCursor)
self.nav_project_btn.setPopupMode(QToolButton.InstantPopup)
self.nav_project_btn.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.nav_project_btn.setMenu(QMenu(self.nav_project_btn))
self.nav_project_btn.menu().aboutToShow.connect(self._fill_rail_project_menu)
self.nav_project_btn.setVisible(False)
head = QVBoxLayout()
head.setContentsMargins(6, 0, 6, 6)
head.setSpacing(6)
head.addWidget(self.nav_project)
head.addWidget(self.nav_project_btn)
head.addWidget(self.nav_new_chat)
nvl.addLayout(head)
self.workspace.project_selected.connect(self._sync_rail_project)
self.workspace.projects_changed.connect(self._sync_rail_project)
self._syncing_rail_project = False
self._sync_rail_project()
# The destinations and RECENTS scroll together; the bottom group, the
# Settings button and the account row stay pinned below them.
#
# Without this the rail simply ran out of room on a short window (a
# 1280×720 laptop leaves ~570px here): nav and the bottom group have
# fixed heights, so the squeeze fell entirely on RECENTS, and once that
# hit zero the layout drew the "GẦN ĐÂY" heading straight over the last
# nav row.
self._nav_scroll = QScrollArea()
self._nav_scroll.setObjectName("navScroll")
self._nav_scroll.setWidgetResizable(True)
self._nav_scroll.setFrameShape(QScrollArea.NoFrame)
self._nav_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scroll_body = QWidget()
sv = QVBoxLayout(scroll_body)
sv.setContentsMargins(0, 0, 0, 0)
sv.setSpacing(0)
sv.addWidget(self.nav, 0)
# RECENTS — the threads of the project named in the picker above, right
# where Claude puts them. A shortcut only: the full History panel (search,
# filters, pin, bulk delete, context menu) stays exactly where it is, and
# "all projects…" at the end of this list opens it.
self.nav_recents_hdr = QLabel(tr("app.nav.recents"))
self.nav_recents_hdr.setObjectName("navSectionHdr")
sv.addWidget(self.nav_recents_hdr)
self.nav_recents = self._new_nav_tree("navRecents")
self.nav_recents.itemClicked.connect(self._on_rail_recent)
sv.addWidget(self.nav_recents, 1)
# Collapsing hides RECENTS, and with it the only item carrying a stretch
# factor. A box layout with nothing left to expand centres what remains,
# so the destinations dropped ~300px down the rail — "thu gọn menu lại
# ra giữa". This spacer takes the slack instead, and takes none of it
# while RECENTS is visible (stretch 0 against its 1).
sv.addStretch(0)
self._nav_scroll.setWidget(scroll_body)
nvl.addWidget(self._nav_scroll, 1)
# Bottom-pinned group: the places you visit occasionally, kept out of the
# way of the ones you live in. A hairline (styled via #navrailBottom in
# theme.py) separates the two lists.
nvl.addWidget(self.nav_bottom, 0)
# Settings reads as one more row under Dashboard / Giám sát, so its icon
# and label must start exactly where theirs do. Letting QPushButton place
# them does not achieve that: the gap it leaves between icon and text is
# the platform style's, and on macOS it is visibly tighter than the tree
# rows above — a Windows-tuned nudge only moved the mismatch. So the row
# is laid out here, in the same two numbers the tree uses: 4px in, 6px
# between.
self._nav_settings_btn = QPushButton()
self._nav_settings_btn.setObjectName("navSettingsBtn")
self._nav_settings_btn.setFlat(True)
self._nav_settings_btn.setCursor(Qt.PointingHandCursor)
self._nav_settings_btn.clicked.connect(self._open_settings)
srow = QHBoxLayout(self._nav_settings_btn)
srow.setContentsMargins(_NAV_ROW_INSET, 6, 8, 6)
srow.setSpacing(_NAV_ROW_GAP)
self._nav_settings_icon = QLabel()
self._nav_settings_icon.setPixmap(_icon("settings").pixmap(16, 16))
self._nav_settings_icon.setFixedSize(16, 16)
self._nav_settings_text = QLabel(tr("app.settings"))
srow.addWidget(self._nav_settings_icon)
srow.addWidget(self._nav_settings_text)
srow.addStretch(1)
nvl.addWidget(self._nav_settings_btn)
self._account_row = self._build_account_row()
nvl.addWidget(self._account_row)
self.split = QSplitter(Qt.Horizontal)
self.split.addWidget(self._nav_wrap)
@@ -236,10 +362,12 @@ class MainWindow(QMainWindow):
self.split.setStretchFactor(0, 0)
self.split.setStretchFactor(1, 1)
self.split.setSizes([_NAV_EXPANDED_WIDTH, 1000])
self.split.splitterMoved.connect(self._on_split_moved)
self.setCentralWidget(self.split)
# Workspace = landing/home (expand it and select its first sub-view).
self._nav_items[self._ROW_WORKSPACE].setExpanded(True)
self.nav.setCurrentItem(self._nav_items[self._ROW_WORKSPACE])
# Landing stays Workspace ▸ Project, exactly as before. Go through _goto
# so the page is actually shown — selecting the row alone only moves the
# highlight (its signals are blocked to avoid rebuild loops).
self._goto(self._ROW_WORKSPACE, self.workspace.current_subtab())
self.toast = _Toast(self) # top-left "task done" popup
# Floating in-app Help assistant — a robot icon pinned bottom-right on
# every screen; expands into a small help-only chat (see
@@ -253,8 +381,8 @@ class MainWindow(QMainWindow):
# widget sits at the right end and is never cleared by showMessage (which
# writes on the left).
self._credit = QLabel(tr("app.credit"))
self._credit.setObjectName("hint")
self._credit.setStyleSheet("color: rgba(140,146,152,0.85); padding: 0 10px;")
self._credit.setObjectName("faint")
self._credit.setStyleSheet("padding: 0 10px;")
self.statusBar().addPermanentWidget(self._credit)
self._restore_sessions()
self._setup_tray()
@@ -273,6 +401,11 @@ class MainWindow(QMainWindow):
def resizeEvent(self, event): # noqa: N802 - Qt override
super().resizeEvent(event)
# The rail's ceiling is a share of the window, so it moves with the
# window. Computed once at construction it was read off a not-yet-sized
# window and stuck at 162px on every monitor.
if getattr(self, "_nav_wrap", None) is not None and not self._nav_collapsed:
self._set_nav_width_range(_NAV_MIN_WIDTH, self._nav_max_width())
# Keep the floating Help assistant pinned to the bottom-right corner.
if getattr(self, "help_agent", None) is not None:
self.help_agent.reposition()
@@ -280,8 +413,24 @@ class MainWindow(QMainWindow):
def showEvent(self, event): # noqa: N802 - Qt override
super().showEvent(event)
if getattr(self, "help_agent", None) is not None:
self._update_dock_guard()
self.help_agent.reposition()
self.help_agent.raise_()
# Build GraphRAG's browser view and first graph once the window is up
# and idle, so clicking GraphRAG does not sit on an empty view while
# both happen. 3s is after the first paint and any startup refresh.
if not getattr(self, "_graph_prewarmed", False):
self._graph_prewarmed = True
QTimer.singleShot(3000, self._prewarm_graph)
def _prewarm_graph(self) -> None:
view = getattr(self, "structure", None)
if view is None or not hasattr(view, "prewarm"):
return
try:
view.prewarm()
except Exception: # noqa: BLE001 — a warm-up must never break the app
pass
# ---- i18n ----------------------------------------------------------
def _retranslate(self) -> None:
@@ -368,12 +517,9 @@ class MainWindow(QMainWindow):
placeholder.deleteLater()
self._page_widgets[row] = real
self._built[row] = True
# Container pages: hide their in-content tab strip + list their sub-views
# as children in the nav rail now that the real widget exists.
if hasattr(real, "hide_tab_bar"):
real.hide_tab_bar()
if row in self._nav_parents:
self._reload_nav_children(row)
# Monitoring KEEPS its own tab strip: its eight sub-views live in the
# page, not in the rail. Workspace is the one that hides its strip,
# because the rail lists its sub-views directly.
def _page_index(self, widget) -> int:
if widget is self.workspace:
@@ -386,28 +532,311 @@ class MainWindow(QMainWindow):
return self._ROW_MONITORING
return self.pages.indexOf(widget)
# ---- nav rail collapse (icon-only) --------------------------------
# ---- flat nav rail -------------------------------------------------
def _new_nav_tree(self, name: str) -> QTreeWidget:
"""One flat, single-column list. No indentation and no expand arrows —
every row is a destination, nothing is a container."""
tree = QTreeWidget()
tree.setObjectName(name)
tree.setHeaderHidden(True)
tree.setIndentation(0)
tree.setRootIsDecorated(False)
tree.setUniformRowHeights(True)
# The column follows the viewport instead of the widest label. Left
# to size itself it stayed ~100px wide inside the 54px collapsed
# rail, so a horizontal scrollbar appeared and slid the icons out of
# the position they hold while the rail is open.
from PySide6.QtWidgets import QHeaderView
tree.header().setSectionResizeMode(0, QHeaderView.Stretch)
tree.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
tree.setItemDelegate(_NavItemDelegate(tree))
return tree
def _nav_rows(self):
"""(tree, page, sub, label, icon, enabled) for every row, rail order.
Workspace contributes all five of its sub-views — including the two the
project gate currently disables — so the rail never changes shape while
the user is looking at it.
"""
rows = [(self.nav, self._ROW_WORKSPACE, sub, label, ic, on)
for label, sub, ic, on in self.workspace.nav_entries()]
rows.append((self.nav, self._ROW_SCHEDULE, None,
tr("app.tab.schedule"), "schedule", True))
rows.append((self.nav_bottom, self._ROW_DASHBOARD, None,
tr("app.tab.dashboard"), "dashboard", True))
rows.append((self.nav_bottom, self._ROW_MONITORING, None,
tr("app.tab.monitoring"), "monitoring", True))
return rows
def _rebuild_nav(self, force: bool = False) -> None:
"""Re-fill both lists from _nav_rows(), keeping the current selection.
Rebuilding changes the current item, which would fire navigation and can
loop back here via subtabs_changed — hence the guard and the blocked
signals.
"""
if self._nav_building:
return
spec = self._nav_rows()
# Rebuilding deletes the QTreeWidgetItems, including the one a signal is
# currently being delivered for. subtabs_changed fires on every visit to
# Workspace, so skip the rebuild unless the rows really differ.
sig = [(label, page, sub, enabled)
for _t, page, sub, label, _ic, enabled in spec]
if not force and sig == getattr(self, "_nav_sig", None):
return
self._nav_sig = sig
self._nav_building = True
try:
from .ui.icons import icon as _icon
keep = self._current_nav_key()
for tree in (self.nav, self.nav_bottom):
blocked = tree.blockSignals(True)
tree.clear()
tree.blockSignals(blocked)
for tree, page, sub, label, icon_name, enabled in spec:
it = QTreeWidgetItem([""] if self._nav_collapsed else [label])
it.setIcon(0, _icon(icon_name))
it.setData(0, Qt.UserRole, {"page": page, "sub": sub})
if not enabled:
# Same gate as before, shown instead of hidden: the row stays
# in place, greyed, and says why it cannot be opened.
it.setDisabled(True)
it.setToolTip(0, tr("app.nav.needs_project"))
elif self._nav_collapsed:
it.setToolTip(0, label)
blocked = tree.blockSignals(True)
tree.addTopLevelItem(it)
tree.blockSignals(blocked)
# Both destination lists are exactly as tall as their rows; the
# stretch in between belongs to RECENTS.
for tree in (self.nav, self.nav_bottom):
n = tree.topLevelItemCount()
row_h = tree.sizeHintForRow(0) if n else 0
tree.setFixedHeight(n * row_h + 8)
if keep:
self._select_nav_row(*keep)
finally:
self._nav_building = False
def _current_nav_key(self):
"""(page, sub) of the highlighted row, or None."""
for tree in (self.nav, self.nav_bottom):
it = tree.currentItem()
if it is not None and it.isSelected():
data = it.data(0, Qt.UserRole) or {}
if "page" in data:
return data["page"], data.get("sub")
return None
def _select_nav_row(self, page: int, sub) -> None:
"""Highlight the row for (page, sub) without triggering navigation.
Called both when the user clicks (to keep the two lists mutually
exclusive) and from _goto, so programmatic navigation moves the
highlight too — it used to stay behind on whatever was clicked last.
"""
for tree in (self.nav, self.nav_bottom):
blocked = tree.blockSignals(True)
match = None
for i in range(tree.topLevelItemCount()):
it = tree.topLevelItem(i)
data = it.data(0, Qt.UserRole) or {}
if data.get("page") == page and (
data.get("sub") == sub or data.get("sub") is None):
match = it
break
if match is not None:
tree.setCurrentItem(match)
else:
tree.setCurrentItem(None)
tree.clearSelection()
tree.blockSignals(blocked)
def _on_nav_current(self, tree: QTreeWidget, item) -> None:
"""A row was picked: clear the other list so only one row looks active."""
if item is None or self._nav_building:
return
data = item.data(0, Qt.UserRole) or {}
other = self.nav_bottom if tree is self.nav else self.nav
blocked = other.blockSignals(True)
other.setCurrentItem(None)
other.clearSelection()
other.blockSignals(blocked)
self._goto(data.get("page", 0), data.get("sub"))
# ---- rail header: project picker + new chat ------------------------
def _sync_rail_project(self, *_a) -> None:
"""Mirror the workspace's project list/selection into the rail picker.
One-way on purpose: the project list stays the source of truth, this is
only a second place to see and change it.
"""
if self._syncing_rail_project:
return
self._syncing_rail_project = True
try:
choices = self.workspace.project_choices()
current = self.workspace.selected_project_id()
self.nav_project.clear()
for name, pid in choices:
self.nav_project.addItem(f"📁 {name}", pid)
if not choices:
# No project yet: say so, and say what to do about it, instead of
# leaving an empty box and a button that silently does nothing.
self.nav_project.addItem(tr("app.nav.no_project"), "")
idx = self.nav_project.findData(current)
if idx >= 0:
self.nav_project.setCurrentIndex(idx)
has = bool(choices)
tidy_popup(self.nav_project)
self.nav_project.setEnabled(has)
self.nav_project_btn.setEnabled(has)
self.nav_project_btn.setToolTip(
self.nav_project.currentText().replace("📁 ", "")
if has else tr("app.nav.create_project_first"))
self.nav_new_chat.setEnabled(has)
self.nav_new_chat.setToolTip(
"" if has else tr("app.nav.create_project_first"))
finally:
self._syncing_rail_project = False
def _fill_rail_project_menu(self) -> None:
"""Mirror the picker's items. Choosing one moves the picker, which runs
_on_rail_project_pick — the collapsed rail adds no second code path."""
menu = self.nav_project_btn.menu()
menu.clear()
for i in range(self.nav_project.count()):
act = menu.addAction(self.nav_project.itemText(i))
act.setCheckable(True)
act.setChecked(i == self.nav_project.currentIndex())
act.triggered.connect(
lambda _checked=False, row=i: self.nav_project.setCurrentIndex(row))
def _on_rail_project_pick(self, _idx: int) -> None:
if self._syncing_rail_project:
return
pid = self.nav_project.currentData()
if pid:
self.workspace.choose_project(pid)
# ---- rail RECENTS --------------------------------------------------
_RAIL_RECENTS = 5
def _refresh_rail_recents(self) -> None:
"""Re-fill the rail's recents from the active project's history."""
from .ui.icons import DOT_BLUE, dot_icon
from .ui.icons import icon as _icon
tree = self.nav_recents
blocked = tree.blockSignals(True)
tree.clear()
running = self._running_session_ids()
threads = self.workspace.recent_threads(self._RAIL_RECENTS)
for t in threads:
it = QTreeWidgetItem([t["title"]])
it.setToolTip(0, t["title"])
if t["session_id"] in running:
it.setIcon(0, dot_icon(DOT_BLUE)) # same marker as History
elif t["pinned"]:
it.setIcon(0, _icon("pin"))
it.setData(0, Qt.UserRole, {"path": t["path"], "kind": t["kind"]})
tree.addTopLevelItem(it)
if not threads:
it = QTreeWidgetItem([tr("sidebar.empty")])
it.setDisabled(True)
tree.addTopLevelItem(it)
# The way back to everything the rail cannot show — styled as a link
# (italic, accent-colored) so it reads as "go elsewhere", not another row.
more = QTreeWidgetItem([tr("app.nav.all_projects")])
more.setData(0, Qt.UserRole, {"all": True})
more_font = more.font(0)
more_font.setItalic(True)
more.setFont(0, more_font)
more.setForeground(0, QColor(current_palette().accent))
tree.addTopLevelItem(more)
tree.blockSignals(blocked)
self.nav_recents_hdr.setVisible(not self._nav_collapsed)
self.nav_recents.setVisible(not self._nav_collapsed)
def _on_rail_recent(self, item, _col: int = 0) -> None:
data = item.data(0, Qt.UserRole) or {}
if data.get("all"):
self._goto(self._ROW_WORKSPACE, self.workspace._cowork_tab_idx)
self.workspace.show_history_pane()
return
path = data.get("path")
if path:
self._goto(self._ROW_WORKSPACE, self.workspace._cowork_tab_idx)
self.workspace.open_thread(path, data.get("kind", "cowork"))
def _on_rail_new_chat(self) -> None:
"""Start a new chat, from any screen.
Same call the Cowork toolbar button makes — that button stays exactly
where it was; this is a second entry point, not a replacement.
"""
self._goto(self._ROW_WORKSPACE, None)
self.workspace.start_new_chat()
self._select_nav_row(self._ROW_WORKSPACE, self.workspace.current_subtab())
def _apply_nav_labels(self) -> None:
"""Set each top-level nav item's text for the current language AND
collapse state: collapsed shows icon-only (label → tooltip) and folds
the accordion so only the top-level icons show."""
for page, item in enumerate(self._nav_items):
key = self._nav_defs[page][0]
label = tr(key)
item.setText(0, "" if self._nav_collapsed else label)
item.setToolTip(0, label if self._nav_collapsed else "")
if self._nav_collapsed:
item.setExpanded(False)
# Refresh child labels (language-aware, from each container's tabText).
"""Re-label every row for the current language and collapse state
(collapsed = icon only, label moves to the tooltip)."""
# force: collapsing leaves the row spec identical, only the text changes.
self._rebuild_nav(force=True)
self._nav_settings_text.setText(tr("app.settings"))
self._nav_settings_text.setVisible(not self._nav_collapsed)
self._nav_settings_btn.setToolTip(tr("app.settings"))
# Collapsed to 54px there is no room for either control's label; the
# picker would be a stub of a name, so it steps aside entirely and the
# button keeps just its + icon.
self.nav_project.setVisible(not self._nav_collapsed)
self.nav_project_btn.setVisible(self._nav_collapsed)
self._refresh_rail_recents()
# Collapsed to 54px only the theme toggle still fits; the rest of the
# account row would be clipped, so it steps aside (Settings, which opens
# the same values in a dialog, stays reachable as an icon).
self.account_lbl.setVisible(not self._nav_collapsed)
self.language_combo.setVisible(not self._nav_collapsed)
self.provider_combo.setVisible(not self._nav_collapsed)
self.nav_new_chat.setText("" if self._nav_collapsed else tr("cowork.new_chat"))
if self._nav_new_chat_enabled():
self.nav_new_chat.setToolTip(
tr("cowork.new_chat") if self._nav_collapsed else "")
self._sync_rail_project()
def _nav_new_chat_enabled(self) -> bool:
return bool(self.workspace.project_choices())
def _nav_max_width(self) -> int:
"""The rail's ceiling for THIS window, as a share of it."""
return max(_NAV_MIN_WIDTH,
min(_NAV_MAX_CEILING, int(self.width() * _NAV_MAX_SHARE)))
def _set_nav_width_range(self, lo: int, hi: int) -> None:
"""setFixedWidth would leave the splitter handle inert — visible, and
doing nothing when dragged."""
self._nav_wrap.setMinimumWidth(lo)
self._nav_wrap.setMaximumWidth(hi)
def _on_split_moved(self, _pos: int, _index: int) -> None:
if not self._nav_collapsed:
for page in self._nav_parents:
if self._built[page]:
self._reload_nav_children(page)
self._nav_width = max(_NAV_MIN_WIDTH,
min(self._nav_max_width(), self._nav_wrap.width()))
def _toggle_nav(self) -> None:
if not self._nav_collapsed:
self._nav_width = max(_NAV_MIN_WIDTH,
min(self._nav_max_width(), self._nav_wrap.width()))
self._nav_collapsed = not self._nav_collapsed
width = _NAV_COLLAPSED_WIDTH if self._nav_collapsed else _NAV_EXPANDED_WIDTH
self._nav_wrap.setFixedWidth(width)
if self._nav_collapsed:
width = _NAV_COLLAPSED_WIDTH
self._set_nav_width_range(width, width)
else:
width = self._nav_width
self._set_nav_width_range(_NAV_MIN_WIDTH, self._nav_max_width())
self._apply_nav_labels()
# Same chevron convention as every other collapsible panel: right-
# pointing (fill-right) means "click to expand", left means "collapse".
@@ -444,6 +873,7 @@ class MainWindow(QMainWindow):
current = self.cowork.session_id
self.sidebar.set_view_state(current, self._running_session_ids())
self.sidebar.refresh()
self._refresh_rail_recents() # the rail shortcut follows the panel
QTimer.singleShot(0, _do)
@@ -531,9 +961,8 @@ class MainWindow(QMainWindow):
def _build_topbar(self) -> QWidget:
bar = QWidget()
bar.setObjectName("topbar")
# Transparent: the logo/provider/language text sits directly on the
# window background, no separate card box behind it.
bar.setStyleSheet("#topbar { background: transparent; border: none; }")
# Styled centrally (see theme._TEMPLATE): flat, with a single hairline
# separating it from the content below — no card box behind it.
h = QHBoxLayout(bar)
h.setContentsMargins(16, 10, 12, 10)
h.setSpacing(10)
@@ -548,22 +977,32 @@ class MainWindow(QMainWindow):
self.logo_img.setVisible(False)
h.addWidget(self.logo_img)
self.logo_lbl = QLabel(tr("app.logo"))
self.logo_lbl.setStyleSheet(f"font-weight:800; font-size:16px; color:{ACCENT};")
self.logo_lbl.setObjectName("brand") # styled centrally — see theme._TEMPLATE
h.addWidget(self.logo_lbl)
h.addStretch(1)
# Provider / language / theme / Settings used to live here, five controls
# wide across the top of every screen. They are per-account settings, not
# per-screen ones, so they moved to the account row at the foot of the
# rail (_build_account_row) — same widgets, same handlers, new home.
return bar
self.provider_lbl = QLabel(tr("app.provider"))
self.provider_lbl.setObjectName("hint")
h.addWidget(self.provider_lbl)
self.provider_combo = QComboBox()
for key, label in PROVIDER_LABELS.items():
self.provider_combo.addItem(label, key)
idx = self.provider_combo.findData(self.ctx.config.active_provider)
if idx >= 0:
self.provider_combo.setCurrentIndex(idx)
self.provider_combo.currentIndexChanged.connect(self._on_provider_changed)
h.addWidget(self.provider_combo)
def _build_account_row(self) -> QWidget:
"""The rail's foot: who you are, and the settings that follow you.
Nothing new is introduced here — these are the exact widgets the top bar
used to hold, moved as-is so every existing signal still lands.
"""
box = QWidget()
box.setObjectName("navAccount")
v = QVBoxLayout(box)
v.setContentsMargins(6, 4, 6, 4)
v.setSpacing(4)
who = QHBoxLayout()
who.setSpacing(4)
self.account_lbl = QLabel(f"👤 {self._user_name}" if self._user_name else "👤")
self.account_lbl.setObjectName("hint")
who.addWidget(self.account_lbl, 1)
self.language_combo = QComboBox()
for key in LANGUAGES:
self.language_combo.addItem(LANGUAGE_SHORT.get(key, key.upper()), key)
@@ -572,22 +1011,28 @@ class MainWindow(QMainWindow):
idx = self.language_combo.findData(get_language())
if idx >= 0:
self.language_combo.setCurrentIndex(idx)
tidy_popup(self.language_combo)
self.language_combo.currentIndexChanged.connect(self._on_language_changed)
h.addWidget(self.language_combo)
who.addWidget(self.language_combo)
self.theme_btn = self._build_theme_button()
h.addWidget(self.theme_btn)
who.addWidget(self.theme_btn)
v.addLayout(who)
if self._user_name:
user_lbl = QLabel(f"👤 {self._user_name}")
user_lbl.setObjectName("hint")
h.addWidget(user_lbl)
self.settings_btn = QPushButton(tr("app.settings"))
from .ui.icons import icon as _icon
self.settings_btn.setIcon(_icon("settings"))
self.settings_btn.clicked.connect(self._open_settings)
h.addWidget(self.settings_btn)
return bar
self.provider_lbl = QLabel(tr("app.provider"))
self.provider_lbl.setObjectName("hint")
self.provider_lbl.setVisible(False) # the combo names itself in the rail
self.provider_combo = QComboBox()
self.provider_combo.setToolTip(tr("app.provider"))
for key, label in PROVIDER_LABELS.items():
self.provider_combo.addItem(label, key)
tidy_popup(self.provider_combo)
idx = self.provider_combo.findData(self.ctx.config.active_provider)
if idx >= 0:
self.provider_combo.setCurrentIndex(idx)
self.provider_combo.currentIndexChanged.connect(self._on_provider_changed)
v.addWidget(self.provider_lbl)
v.addWidget(self.provider_combo)
return box
_BRAND_LOGO_NAMES = ("fpt_logo.png", "fpt-logo.png", "logo_fpt.png", "fpt_logo.jpg")
_BRAND_LOGO_HEIGHT = 22
@@ -661,6 +1106,11 @@ class MainWindow(QMainWindow):
dlg = SettingsDialog(self.ctx, self)
if dlg.exec():
self._apply_theme()
# Settings can change the theme too — keep the rail's toggle icon
# showing the value that is actually in effect.
from .ui.icons import icon as _theme_icon
self.theme_btn.setIcon(
_theme_icon(self._THEME_ICONS.get(self.ctx.config.theme, "monitor")))
set_language(self.ctx.config.language) # apply if changed in Settings
# reflect provider/theme/language changes
i = self.provider_combo.findData(self.ctx.config.active_provider)
@@ -679,46 +1129,6 @@ class MainWindow(QMainWindow):
self.sidebar.refresh()
self.statusBar().showMessage(tr("app.status.settings_saved"))
def _reload_nav_children(self, page: int) -> None:
"""(Re)build the nav children of a container page from its current
sub-views. Called when the page is built, when Workspace sub-tab
visibility changes, and on language change."""
if not (0 <= page < len(self._nav_items)):
return
item = self._nav_items[page]
expanded = item.isExpanded()
item.takeChildren()
widget = self._page_widgets[page]
if not hasattr(widget, "nav_subtabs"):
return
from .ui.icons import icon as _icon
for label, sub, icon_name in widget.nav_subtabs():
child = QTreeWidgetItem([label])
child.setIcon(0, _icon(icon_name))
child.setData(0, Qt.UserRole, {"page": page, "sub": sub, "parent": False})
item.addChild(child)
item.setExpanded(True)
def _on_nav_click(self, item, _col: int = 0) -> None:
# Clicking a parent toggles its expansion (its page is still shown).
data = item.data(0, Qt.UserRole) or {}
if data.get("parent"):
item.setExpanded(not item.isExpanded())
def _on_nav_expanded(self, item) -> None:
# Expanding a container whose children aren't built yet (e.g. Monitoring
# on first open, shown via its always-on dropdown arrow) builds its page
# so the sub-views appear.
data = item.data(0, Qt.UserRole) or {}
if data.get("parent") and item.childCount() == 0:
self._ensure_page(data.get("page", 0))
def _navigate(self, item) -> None:
if item is None:
return
data = item.data(0, Qt.UserRole) or {}
self._goto(data.get("page", 0), data.get("sub"))
def _goto(self, page: int, sub) -> None:
self._ensure_page(page) # build lazy page on first visit
self.pages.setCurrentIndex(page)
@@ -726,10 +1136,52 @@ class MainWindow(QMainWindow):
self.workspace.refresh() # re-list projects + threads on entry
widget = self._page_widgets[page]
if sub is not None and hasattr(widget, "select_subtab"):
widget.select_subtab(sub)
# Enforce the project gate here rather than at each entry point. A
# greyed rail row cannot be clicked, but _goto is also reached from
# RECENTS and from startup restore, and it used to open a sub-tab
# the gate was holding shut — page shown, tab strip still hiding it.
if hasattr(widget, "subtab_available") and not widget.subtab_available(sub):
self.statusBar().showMessage(tr("app.nav.needs_project"), 4000)
else:
widget.select_subtab(sub)
# Move the highlight with the content, however navigation was triggered —
# a programmatic _goto used to leave it on whatever was clicked last.
if not self._nav_building:
self._select_nav_row(page, sub)
self._update_dock_guard()
# Switching pages updates which conversation is "current".
self._refresh_history()
def _update_dock_guard(self) -> None:
"""Keep the floating assistant clear of a screen's own bottom bar.
Only Cowork has one (the composer). Everywhere else the dock sits in
the corner as before.
"""
dock = getattr(self, "help_agent", None)
if dock is None:
return
guard = 0
on_cowork = (self.pages.currentIndex() == self._ROW_WORKSPACE
and self.workspace.current_subtab() == self.workspace._cowork_tab_idx)
if on_cowork:
comp = getattr(self.cowork, "composer", None)
if comp is not None and not comp.isHidden():
# Measured from the composer's TOP edge in window coordinates:
# its own height misses the extra row of controls laid out under
# it, which left the dot still overlapping by ~25px.
origin = comp.mapTo(self, comp.rect().topLeft())
# ...but only lift the dot if the composer is actually beneath
# it. The composer stops at the chat column's right edge, well
# short of the dot, so lifting it there raised the dot 156px for
# nothing — on Cowork alone it sat off the corner every other
# screen keeps it in.
dock_left = dock.x() - self.mapToGlobal(self.rect().topLeft()).x()
dock_right = dock_left + dock.width()
if dock_right > origin.x() and dock_left < origin.x() + comp.width():
guard = max(0, self.height() - origin.y() + 8)
dock.set_bottom_guard(guard)
def _on_projects_changed(self) -> None:
self.sidebar.refresh() # History regroups by project
self.cowork._apply_output_folder_label() # project may have been renamed
@@ -738,6 +1190,7 @@ class MainWindow(QMainWindow):
def _apply_theme(self) -> None:
app = QApplication.instance()
if app:
set_active_theme(self.ctx.config.theme)
app.setStyleSheet(stylesheet(self.ctx.config.theme))
# Re-apply theme styles to chat bubbles so they adapt to the new theme.
self.cowork.apply_theme()
@@ -745,6 +1198,11 @@ class MainWindow(QMainWindow):
self.help_agent.apply_theme() # chat body follows theme (header stays fixed)
# ---- sizing ------------------------------------------------------
# Share of the available screen the window takes when it has room to. Fixed
# pixels do not travel: 1180×760 fills a laptop and looks lost on a 4K
# panel. `want_*` stays the floor so a small screen behaves as before.
_SCREEN_SHARE_W, _SCREEN_SHARE_H = 0.80, 0.85
def _fit_to_screen(self, want_w: int, want_h: int) -> None:
screen = self.screen() or QGuiApplication.primaryScreen()
avail = screen.availableGeometry() if screen else None
@@ -752,8 +1210,12 @@ class MainWindow(QMainWindow):
self.resize(want_w, want_h)
return
margin = 60
w = min(want_w, avail.width() - margin)
h = min(want_h, avail.height() - margin)
# Take a share of the screen, never less than the asked-for size and
# never more than the screen can show.
w = min(max(want_w, int(avail.width() * self._SCREEN_SHARE_W)),
avail.width() - margin)
h = min(max(want_h, int(avail.height() * self._SCREEN_SHARE_H)),
avail.height() - margin)
# minimum must never exceed what the screen can show
self.setMinimumSize(min(820, avail.width() - margin), min(520, avail.height() - margin))
self.resize(max(w, 1), max(h, 1))
@@ -761,6 +1223,25 @@ class MainWindow(QMainWindow):
frame.moveCenter(avail.center())
self.move(frame.topLeft())
def moveEvent(self, event): # noqa: N802 - Qt override
super().moveEvent(event)
# Dragged to another monitor: its work area (and scaling) may differ, so
# the floating assistant re-pins and the panes re-decide if they fit.
self._on_screen_maybe_changed()
def _on_screen_maybe_changed(self) -> None:
screen = self.screen()
if screen is getattr(self, "_last_screen", None):
return
self._last_screen = screen
avail = screen.availableGeometry() if screen else None
if avail is not None:
self.setMinimumSize(min(820, avail.width() - 60),
min(520, avail.height() - 60))
if getattr(self, "help_agent", None) is not None:
self._update_dock_guard()
self.help_agent.reposition()
# ---- lifecycle ---------------------------------------------------
def closeEvent(self, event) -> None: # noqa: N802
keep = (self.tray is not None
@@ -843,6 +1324,7 @@ def run(argv: List[str] | None = None) -> int:
ctx.config.save()
except Exception: # noqa: BLE001 - seeding must never block startup
pass
set_active_theme(ctx.config.theme)
app.setStyleSheet(stylesheet(ctx.config.theme))
# Follow the OS light/dark scheme live when theme is "Auto (System)".
@@ -858,6 +1340,7 @@ def run(argv: List[str] | None = None) -> int:
def _reapply_system_theme(*_a):
if ctx.config.theme == "system":
set_active_theme("system")
app.setStyleSheet(stylesheet("system"))
win.cowork.apply_theme()
try:
+2 -4
View File
@@ -105,8 +105,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
# sandboxes agent-run shell commands) — reading a URL for info is safe and
# useful, so this defaults ON. Toggle in Settings → Security.
"allow_url_fetch": True,
# Set with COWORK_SANDBOX_PASSWORD. Never ship a shared unlock secret.
"sandbox_pw": "",
"sandbox_pw": "", # set through COWORK_SANDBOX_PASSWORD
"rulebase_path": "", # custom RULEBASE.md — attached to every agent execution
},
# Legacy generic-MCP-server list. MERGED into ext_connectors["other"] as of
@@ -174,8 +173,7 @@ DEFAULT_CONFIG: Dict[str, Any] = {
# Microsoft. Real Outlook/Teams/OneDrive/SharePoint access still requires a
# proper OAuth sign-in (not implemented yet) using tenant_id/client_id below.
"ms365": {
# Set with COWORK_MS365_UNLOCK_CODE. Never ship a shared unlock secret.
"unlock_code": "",
"unlock_code": "", # set through COWORK_MS365_UNLOCK_CODE
"unlocked": False, # runtime-only — never persisted as True, see save()
# Auto-connect MS365/OneDrive/SharePoint: the built-in MS365 MCP server
# launches automatically once the user is signed in (OAuth tenant/client
Binary file not shown.
+327
View File
@@ -0,0 +1,327 @@
<!doctype html>
<html lang="vi" data-theme="auto">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cấu trúc hệ thống · Cowork Local</title>
<style>
:root{
--bg:#f6f7f9; --surface:#ffffff; --surface-2:#eef1f4; --border:#dbe0e7;
--ink:#131a22; --ink-2:#4b5663; --ink-3:#7c8794;
--accent:#0e7c86; --accent-ink:#0a5b63; --accent-soft:#e2f2f2;
--ok:#157f4a; --warn:#9a5a0e; --crit:#b5322c;
--ok-soft:#e4f4ea; --warn-soft:#f8efdd; --crit-soft:#f7e5e3;
--mono-bg:#eef2f6; --shadow:0 1px 2px rgba(16,24,32,.06),0 8px 24px -12px rgba(16,24,32,.18);
--font-display:"Segoe UI Variable Display","Segoe UI Semibold","Segoe UI",system-ui,-apple-system,sans-serif;
--font-body:"Segoe UI Variable Text","Segoe UI",system-ui,-apple-system,sans-serif;
--font-mono:"Cascadia Code","Cascadia Mono",Consolas,"SF Mono",ui-monospace,monospace;
--maxw:920px;
}
@media (prefers-color-scheme:dark){
:root{
--bg:#0d1218; --surface:#141c25; --surface-2:#1b2530; --border:#28343f;
--ink:#e7edf4; --ink-2:#a2b2c2; --ink-3:#6c7d8e;
--accent:#46cfc8; --accent-ink:#8fe9e3; --accent-soft:#14312f;
--ok:#47c97e; --warn:#e0a33a; --crit:#f0726b;
--ok-soft:#12281c; --warn-soft:#2c2410; --crit-soft:#2e1614;
--mono-bg:#0f1720; --shadow:0 1px 2px rgba(0,0,0,.4),0 10px 30px -16px rgba(0,0,0,.7);
}
}
:root[data-theme="light"]{
--bg:#f6f7f9; --surface:#ffffff; --surface-2:#eef1f4; --border:#dbe0e7;
--ink:#131a22; --ink-2:#4b5663; --ink-3:#7c8794;
--accent:#0e7c86; --accent-ink:#0a5b63; --accent-soft:#e2f2f2;
--ok:#157f4a; --warn:#9a5a0e; --crit:#b5322c;
--ok-soft:#e4f4ea; --warn-soft:#f8efdd; --crit-soft:#f7e5e3; --mono-bg:#eef2f6;
--shadow:0 1px 2px rgba(16,24,32,.06),0 8px 24px -12px rgba(16,24,32,.18);
}
:root[data-theme="dark"]{
--bg:#0d1218; --surface:#141c25; --surface-2:#1b2530; --border:#28343f;
--ink:#e7edf4; --ink-2:#a2b2c2; --ink-3:#6c7d8e;
--accent:#46cfc8; --accent-ink:#8fe9e3; --accent-soft:#14312f;
--ok:#47c97e; --warn:#e0a33a; --crit:#f0726b;
--ok-soft:#12281c; --warn-soft:#2c2410; --crit-soft:#2e1614; --mono-bg:#0f1720;
--shadow:0 1px 2px rgba(0,0,0,.4),0 10px 30px -16px rgba(0,0,0,.7);
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--font-body);
font-size:16.5px;line-height:1.62;-webkit-font-smoothing:antialiased;}
.wrap{max-width:var(--maxw);margin:0 auto;padding:0 24px}
/* top bar */
header.top{position:sticky;top:0;z-index:20;background:color-mix(in srgb,var(--surface) 88%,transparent);
backdrop-filter:saturate(1.4) blur(10px);border-bottom:1px solid var(--border)}
.top .wrap{display:flex;align-items:center;gap:18px;height:58px}
.brand{font-family:var(--font-mono);font-weight:600;font-size:14px;letter-spacing:.02em;
color:var(--ink);display:flex;align-items:center;gap:9px;white-space:nowrap}
.brand .dot{width:10px;height:10px;border-radius:2px;background:var(--accent);
box-shadow:0 0 0 3px var(--accent-soft)}
nav.doc{display:flex;gap:4px;margin-left:auto;flex-wrap:wrap}
nav.doc a{font-size:13.5px;color:var(--ink-2);text-decoration:none;padding:7px 12px;border-radius:8px;
font-weight:550;white-space:nowrap}
nav.doc a:hover{background:var(--surface-2);color:var(--ink)}
nav.doc a[aria-current="page"]{background:var(--accent-soft);color:var(--accent-ink)}
.toggle{border:1px solid var(--border);background:var(--surface);color:var(--ink-2);
width:36px;height:34px;border-radius:9px;cursor:pointer;font-size:15px;display:grid;place-items:center}
.toggle:hover{color:var(--ink);border-color:var(--accent)}
.toggle:focus-visible,nav.doc a:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
/* hero */
.hero{padding:64px 0 34px}
.eyebrow{font-family:var(--font-mono);font-size:12px;letter-spacing:.18em;text-transform:uppercase;
color:var(--accent-ink);font-weight:600;margin:0 0 14px}
h1{font-family:var(--font-display);font-weight:700;font-size:clamp(2.1rem,5vw,3.1rem);line-height:1.06;
letter-spacing:-.02em;margin:0 0 18px;text-wrap:balance}
.lead{font-size:1.16rem;color:var(--ink-2);max-width:64ch;margin:0}
.meta{display:flex;gap:10px;flex-wrap:wrap;margin-top:26px}
.tag{font-family:var(--font-mono);font-size:12px;padding:5px 11px;border-radius:999px;
background:var(--surface-2);border:1px solid var(--border);color:var(--ink-2)}
section{padding:34px 0;border-top:1px solid var(--border)}
h2{font-family:var(--font-display);font-weight:650;font-size:1.6rem;letter-spacing:-.01em;margin:0 0 6px;
display:flex;align-items:baseline;gap:12px;text-wrap:balance}
h2 .num{font-family:var(--font-mono);font-size:.85rem;color:var(--accent-ink);font-weight:600}
h3{font-family:var(--font-display);font-weight:600;font-size:1.13rem;margin:26px 0 8px;letter-spacing:-.01em}
p{margin:.6em 0}
.sub{color:var(--ink-2);margin:2px 0 20px;max-width:66ch}
a{color:var(--accent-ink);text-underline-offset:3px}
strong{font-weight:650;color:var(--ink)}
code,.k{font-family:var(--font-mono);font-size:.86em;background:var(--mono-bg);
padding:2px 6px;border-radius:6px;border:1px solid var(--border);color:var(--ink)}
/* layer stack diagram */
.stack{display:flex;flex-direction:column;gap:0;margin:24px 0}
.layer{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:16px 18px;
box-shadow:var(--shadow);position:relative}
.layer + .layer{margin-top:26px}
.layer + .layer::before{content:"";position:absolute;top:-20px;left:50%;width:2px;height:14px;
background:var(--border);transform:translateX(-50%)}
.layer + .layer::after{content:"▾";position:absolute;top:-14px;left:50%;transform:translateX(-50%);
color:var(--ink-3);font-size:13px}
.layer .lh{display:flex;align-items:center;gap:10px;margin-bottom:12px}
.layer .lh .tier{font-family:var(--font-mono);font-size:11px;letter-spacing:.12em;text-transform:uppercase;
color:#fff;background:var(--accent);padding:3px 8px;border-radius:6px;font-weight:600}
.layer .lh h4{margin:0;font-family:var(--font-display);font-weight:600;font-size:1.02rem}
.layer .lh small{color:var(--ink-3);margin-left:auto;font-size:12.5px}
.chips{display:flex;flex-wrap:wrap;gap:8px}
.chip{font-family:var(--font-mono);font-size:12.5px;background:var(--surface-2);border:1px solid var(--border);
border-radius:8px;padding:6px 10px;color:var(--ink-2)}
.chip b{color:var(--ink);font-weight:600}
/* cards */
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:16px;margin-top:8px}
.card{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:18px 18px;
box-shadow:var(--shadow)}
.card h4{margin:0 0 6px;font-family:var(--font-display);font-size:1.04rem;font-weight:600;
display:flex;align-items:center;gap:9px}
.card h4 .ic{width:26px;height:26px;border-radius:7px;background:var(--accent-soft);color:var(--accent-ink);
display:grid;place-items:center;font-size:14px;flex:none}
.card p{margin:0;color:var(--ink-2);font-size:14.5px}
.card .files{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px}
.card .files code{font-size:11.5px}
/* flow steps */
.flow{display:flex;flex-direction:column;gap:10px;margin:18px 0;counter-reset:fl}
.flow li{list-style:none;display:flex;gap:14px;align-items:flex-start;background:var(--surface);
border:1px solid var(--border);border-radius:12px;padding:13px 15px}
.flow li::before{counter-increment:fl;content:counter(fl);font-family:var(--font-mono);font-weight:600;
font-size:13px;color:var(--accent-ink);background:var(--accent-soft);border-radius:8px;
width:28px;height:28px;display:grid;place-items:center;flex:none}
.flow b{color:var(--ink)}
.flow small{color:var(--ink-3);display:block;font-size:13px}
.note{border:1px solid var(--border);border-left:3px solid var(--accent);background:var(--surface);
border-radius:0 12px 12px 0;padding:14px 16px;margin:18px 0;font-size:14.5px;color:var(--ink-2)}
.note b{color:var(--ink)}
footer{border-top:1px solid var(--border);padding:34px 0 60px;color:var(--ink-3);font-size:13.5px}
footer .wrap{display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;align-items:center}
footer a{color:var(--ink-2)}
@media (max-width:560px){.brand span.full{display:none}.hero{padding:40px 0 24px}}
</style>
</head>
<body>
<header class="top"><div class="wrap">
<span class="brand"><span class="dot"></span>cowork_local<span class="full">&nbsp;· docs</span></span>
<nav class="doc" aria-label="Tài liệu">
<a href="architecture.html" aria-current="page">Cấu trúc</a>
<a href="security.html">Bảo mật</a>
<a href="usage.html">Cách dùng</a>
</nav>
<button class="toggle" id="themeBtn" title="Đổi giao diện sáng/tối" aria-label="Đổi giao diện">◐</button>
</div></header>
<main>
<div class="wrap hero">
<p class="eyebrow">Cowork Local · Tài liệu kỹ thuật</p>
<h1>Cấu trúc hệ thống</h1>
<p class="lead">Trợ lý AI dạng agent chạy <strong>cục bộ trên máy</strong> (desktop, ưu tiên Windows). Người dùng trò chuyện, chạy luồng nhiều bước, thao tác tệp và lên lịch tác vụ — mọi thứ được bọc trong một khung bảo mật nhiều lớp.</p>
<div class="meta">
<span class="tag">PySide6 / Qt6</span>
<span class="tag">Local-first</span>
<span class="tag">Provider-agnostic</span>
<span class="tag">~53K dòng Python</span>
<span class="tag">Windows · macOS · Linux</span>
</div>
</div>
<section class="wrap">
<h2><span class="num">01</span> Tổng quan &amp; nguyên tắc</h2>
<p class="sub">Bốn nguyên tắc định hình toàn bộ kiến trúc.</p>
<div class="grid">
<div class="card"><h4><span class="ic">▤</span>Local-first</h4><p>Cấu hình, lịch sử hội thoại, workspace và nhật ký đều nằm trên máy người dùng. Chỉ lệnh gọi mô hình mới ra ngoài.</p></div>
<div class="card"><h4><span class="ic">⛨</span>Bảo mật nhiều lớp</h4><p>Mọi tool có tác động (chạy lệnh, ghi tệp, tải URL) đi qua chuỗi kiểm soát fail-closed; xem tài liệu <a href="security.html">Bảo mật</a>.</p></div>
<div class="card"><h4><span class="ic">⧉</span>Đa workspace</h4><p>Nhiều project chạy song song, mỗi project nhiều hội thoại Cowork và nhiều luồng Co4E — không cái nào chặn cái nào.</p></div>
<div class="card"><h4><span class="ic">⇄</span>Provider-agnostic</h4><p>Nhiều nhà cung cấp mô hình (OpenAI-compatible…), tự động định tuyến chọn mô hình phù hợp trong số các model được bật.</p></div>
</div>
</section>
<section class="wrap">
<h2><span class="num">02</span> Ngăn xếp công nghệ</h2>
<p class="sub">Những thư viện/thành phần chủ chốt và vai trò của chúng.</p>
<div class="chips">
<span class="chip"><b>PySide6/Qt6</b> · toàn bộ giao diện, đa luồng QThread</span>
<span class="chip"><b>FastAPI + uvicorn</b> · Routing API (chỉ localhost)</span>
<span class="chip"><b>MCP</b> · kết nối công cụ ngoài (Model Context Protocol)</span>
<span class="chip"><b>MSAL</b> · đăng nhập Microsoft 365</span>
<span class="chip"><b>openpyxl / python-pptx</b> · đọc Office</span>
<span class="chip"><b>opendataloader-pdf</b> · trích xuất PDF</span>
<span class="chip"><b>networkx</b> · đồ thị cấu trúc (GraphRAG)</span>
<span class="chip"><b>keyring</b> · lưu bí mật qua OS</span>
<span class="chip"><b>ctypes / Win32</b> · sandbox AppContainer &amp; Job Object</span>
<span class="chip"><b>Pygments</b> · tô màu mã nguồn</span>
</div>
</section>
<section class="wrap">
<h2><span class="num">03</span> Kiến trúc phân lớp</h2>
<p class="sub">Một yêu cầu đi từ giao diện xuống lớp thực thi rồi ra ngoài — mỗi lớp có trách nhiệm rõ ràng.</p>
<div class="stack">
<div class="layer">
<div class="lh"><span class="tier">UI</span><h4>Lớp giao diện — PySide6</h4><small>người dùng thao tác</small></div>
<div class="chips">
<span class="chip">MainWindow</span><span class="chip">WorkspaceTab / WorkspacePane</span>
<span class="chip">CoworkTab (chat)</span><span class="chip">Co4ETab (flow canvas)</span>
<span class="chip">FolderTab</span><span class="chip">ScheduleTaskTab</span>
<span class="chip">MonitoringTab → Security</span><span class="chip">SettingsDialog</span>
</div>
</div>
<div class="layer">
<div class="lh"><span class="tier">Agent</span><h4>Lớp agent / lõi thực thi</h4><small>điều phối lượt chạy</small></div>
<div class="chips">
<span class="chip"><b>chat_agent</b> · run_cowork</span>
<span class="chip"><b>code_agent</b> · run_code</span>
<span class="chip"><b>co4e_runner</b> · run_workflow</span>
<span class="chip"><b>task_executors</b> · tác vụ theo lịch</span>
<span class="chip"><b>model_routing</b> · assess &amp; chọn model</span>
<span class="chip"><b>agent_security</b> · guardrail</span>
</div>
</div>
<div class="layer">
<div class="lh"><span class="tier">Tool</span><h4>Lớp công cụ &amp; sandbox</h4><small>ranh giới tin cậy</small></div>
<div class="chips">
<span class="chip"><b>ToolContext</b> · confine đường dẫn + scope</span>
<span class="chip">execute_tool</span>
<span class="chip">read/write/edit/list_dir</span>
<span class="chip">run_command · install_package</span>
<span class="chip">fetch_url · jira</span>
<span class="chip"><b>SandboxManager</b> + backends</span>
</div>
</div>
<div class="layer">
<div class="lh"><span class="tier">Provider</span><h4>Lớp nhà cung cấp mô hình</h4><small>gọi ra mạng an toàn</small></div>
<div class="chips">
<span class="chip">providers/* (OpenAI-compatible…)</span>
<span class="chip"><b>tls_trust</b> · phục hồi TLS gateway</span>
<span class="chip">usage_tracker · đo token/chi phí</span>
</div>
</div>
<div class="layer">
<div class="lh"><span class="tier">Ngoài</span><h4>Dịch vụ bên ngoài</h4><small>không tin cậy mặc định</small></div>
<div class="chips">
<span class="chip">LLM APIs</span><span class="chip">MCP servers</span>
<span class="chip">Microsoft 365</span><span class="chip">Jira</span><span class="chip">Web (fetch_url)</span>
</div>
</div>
</div>
</section>
<section class="wrap">
<h2><span class="num">04</span> Các subsystem chính</h2>
<p class="sub">Mỗi khối là một tính năng lớn người dùng thấy được, ánh xạ tới module tương ứng.</p>
<div class="grid">
<div class="card"><h4><span class="ic">▦</span>Workspaces &amp; Projects</h4><p>Nhiều project song song, mỗi cái một pane riêng với sandbox bật/tắt để tiết kiệm tài nguyên.</p><div class="files"><code>workspace_tab.py</code><code>workspace_pane.py</code></div></div>
<div class="card"><h4><span class="ic">💬</span>Cowork · đa hội thoại</h4><p>Nhiều hội thoại trong một project; lượt chạy nền giữ đúng hội thoại gốc kể cả khi bạn chuyển tab.</p><div class="files"><code>chat_panel.py</code><code>cowork_tab.py</code></div></div>
<div class="card"><h4><span class="ic">◈</span>Co4E flows</h4><p>Canvas nhiều bước, agent tùy biến, chế độ auto/plan/manual, chạy song song &amp; theo dõi ở Flow Status.</p><div class="files"><code>co4e_tab.py</code><code>co4e_runner.py</code></div></div>
<div class="card"><h4><span class="ic">⇉</span>Model routing</h4><p>Tự đánh giá &amp; chọn mô hình tốt nhất trong số model được bật theo policy (chất lượng/chi phí/độ trễ).</p><div class="files"><code>core/routing/*</code></div></div>
<div class="card"><h4><span class="ic">⛨</span>Sandbox</h4><p>Chọn backend theo mức rủi ro: best-effort → AppContainer → Windows Sandbox VM.</p><div class="files"><code>sandbox_manager.py</code><code>appcontainer_sandbox.py</code></div></div>
<div class="card"><h4><span class="ic">⏱</span>Scheduler</h4><p>Tác vụ theo lịch (Cowork/Code/Flow), phụ thuộc chuỗi, opt-in chạy lệnh.</p><div class="files"><code>task_scheduler.py</code><code>task_executors.py</code></div></div>
<div class="card"><h4><span class="ic">📊</span>Monitoring</h4><p>Tổng quan chi phí, nhật ký sự kiện/bảo mật, quản trị Tool/Agent, trang Security.</p><div class="files"><code>monitoring_tab.py</code></div></div>
<div class="card"><h4><span class="ic">🗄</span>Lưu trữ</h4><p>Cấu hình + lịch sử theo project + workspace + audit log, tất cả trên máy.</p><div class="files"><code>config.py</code><code>core/history.py</code></div></div>
</div>
</section>
<section class="wrap">
<h2><span class="num">05</span> Mô hình đồng thời</h2>
<p class="sub">Vì sao nhiều lượt chạy song song không giẫm chân nhau.</p>
<h3>Cô lập theo lượt (per-turn)</h3>
<p>Mỗi lượt chat chạy trong một <code>AgentWorker</code> (QThread) riêng. Tại thời điểm bắt đầu, lượt chụp lại bối cảnh <span class="k">home_*</span> (id hội thoại, thư mục làm việc, project) — nên dù người dùng chuyển sang hội thoại khác, lượt nền vẫn ghi kết quả về <strong>đúng hội thoại gốc</strong> và quét đúng thư mục của nó.</p>
<h3>Quản lý luồng Co4E dùng chung</h3>
<p>Một <code>Co4ERunManager</code> duy nhất phục vụ mọi pane, mỗi run gắn <span class="k">project_id</span> để lọc. Khi dừng một worker bị treo, nó được "park" giữ tham chiếu (không GC luồng đang chạy → tránh crash <em>QThread destroyed while running</em>).</p>
<div class="note"><b>Cách ly dừng (Stop):</b> nút Stop chỉ tác động lên các worker của <em>chính</em> hội thoại đó và xóa hàng đợi của riêng nó — dừng ở hội thoại này không ảnh hưởng hội thoại khác.</div>
</section>
<section class="wrap">
<h2><span class="num">06</span> Luồng dữ liệu một lượt chat</h2>
<p class="sub">Từ tin nhắn người dùng đến kết quả — mỗi bước là một điểm kiểm soát.</p>
<ol class="flow">
<li><div><b>Tin nhắn + đính kèm</b><small>Người dùng gửi; tệp/thư mục workspace được nạp qua <code>_augment</code>.</small></div></li>
<li><div><b>Bọc nội dung không tin cậy</b><small>Nội dung tệp/web/tool được rào trong khối <span class="k">UNTRUSTED DATA</span> — model coi là dữ liệu, không phải mệnh lệnh.</small></div></li>
<li><div><b>Định tuyến mô hình</b><small>Auto Routing có thể chọn mô hình phù hợp trong số model được bật.</small></div></li>
<li><div><b>Gọi provider</b><small><code>provider.chat()</code> qua <code>tls_trust</code>; usage_tracker ghi token/chi phí theo hội thoại gốc.</small></div></li>
<li><div><b>Model gọi tool</b><small>Mỗi tool qua: kiểm scope ở executor → human-gate (nếu bật) → classifier → sandbox.</small></div></li>
<li><div><b>Kết quả &amp; lưu</b><small>Văn bản/diff hiện realtime; hội thoại lưu vào <code>.cowork_history</code> của project.</small></div></li>
</ol>
</section>
<section class="wrap">
<h2><span class="num">07</span> Lưu trữ trên máy</h2>
<p class="sub">Dữ liệu nằm ở đâu.</p>
<div class="chips">
<span class="chip"><b>~/.cowork_local/config.json</b> · cấu hình (perm 0o600)</span>
<span class="chip"><b>&lt;project&gt;/.cowork_history</b> · hội thoại theo project</span>
<span class="chip"><b>workspaces/</b> · thư mục làm việc mỗi project</span>
<span class="chip"><b>audit log</b> · mọi tool-call &amp; quyết định quyền (lưu hash lệnh)</span>
<span class="chip"><b>trusted_certs/</b> · cert gateway đã pin</span>
<span class="chip"><b>appcontainer_grants.json</b> · cache cấp quyền sandbox</span>
</div>
<div class="note">Vị trí lịch sử có thể trỏ vào thư mục đồng bộ OneDrive — tiện chia sẻ, nhưng lưu ý dữ liệu tệp đã nạp sẽ được sao lên cloud dạng plaintext. Xem khuyến nghị ở tài liệu <a href="security.html">Bảo mật</a>.</div>
</section>
</main>
<footer><div class="wrap">
<span>Cowork Local — tài liệu nội bộ · Cấu trúc hệ thống</span>
<span><a href="security.html">Bảo mật →</a> &nbsp; <a href="usage.html">Cách dùng →</a></span>
</div></footer>
<script>
(function(){
var root=document.documentElement, key="cowork_docs_theme";
var saved=null; try{saved=localStorage.getItem(key)}catch(e){}
if(saved==="dark"||saved==="light") root.setAttribute("data-theme",saved);
else root.removeAttribute("data-theme");
document.getElementById("themeBtn").addEventListener("click",function(){
var cur=root.getAttribute("data-theme");
if(!cur){ // currently following OS → flip to opposite of OS
cur=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";
}
var next=cur==="dark"?"light":"dark";
root.setAttribute("data-theme",next);
try{localStorage.setItem(key,next)}catch(e){}
});
})();
</script>
</body>
</html>
+473
View File
@@ -0,0 +1,473 @@
# 📋 COWORK-LOCAL BamBOO — Danh Sách Chức Năng Chi Tiết Theo Navigation Bar
---
## 🔹 1. 📊 DASHBOARD (Bảng Điều Khiển)
### 1.1 Token Usage & Cost — Thống Kê Token & Chi Phí
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 1.1.1 | `_refresh_cards()` | Làm mới các thẻ thống kê (Total, Input, Output, Cache tokens + Cost) |
| 1.1.2 | `_refresh_chart()` | Vẽ biểu đồ spline theo chu kỳ (week/month/year) và metric (cost/tokens) |
| 1.1.3 | `_chart_prev()` / `_chart_next()` | Chuyển đến chu kỳ trước/sau trên biểu đồ |
| 1.1.4 | `_on_gran_changed()` | Thay đổi đơn vị thời gian (week/month/year) |
| 1.1.5 | `_refresh_budget()` | Cập nhật ngân sách (budget card — còn lại / đã dùng / cảnh báo >85%) |
| 1.1.6 | `_apply_budget()` | Lưu giá trị budget mới |
| 1.1.7 | `_refresh_habits()` | Hiển thị thói quen sử dụng (task tốn nhiều token nhất, trung bình/prompt, ngày/giờ bận nhất) |
| 1.1.8 | `_ai_analyze()` | ✨ AI phân tích thói quen dùng token và gợi ý tiết kiệm |
| 1.1.9 | `_apply_saving_strategy()` | Áp dụng chiến lược tiết kiệm AI (tự nén context, nén sớm hơn) |
| 1.1.10 | Currency Picker | Chọn đơn vị tiền tệ hiển thị (USD, VND, JPY, …) |
---
## 🔹 2. 📅 SCHEDULE TASK (Lên Lịch Nhiệm Vụ)
### 2.1 Kanban Board
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 2.1.1 | `_build_kanban()` | Xây dựng board Kanban với 7 cột: Backlog, Scheduled, Running, Waiting Input, Done, Failed, Paused |
| 2.1.2 | `_render_kanban()` | Render các thẻ task vào từng cột |
| 2.1.3 | `_on_task_dropped(task_id, new_status)` | Kéo thả task giữa các cột (thay đổi status) |
| 2.1.4 | `_on_card_double_click()` | Mở Task Editor khi double-click |
| 2.1.5 | `_on_card_right_click()` | Menu ngữ cảnh: Run now, Edit, Duplicate, Pause, Delete, View logs, Create-next-from-output |
| 2.1.6 | `_bulk_delete_menu()` | Xóa hàng loạt (chọn nhiều thẻ → right-click → Delete N selected) |
| 2.1.7 | `_run_now(task_id)` | Chạy task ngay lập tức |
| 2.1.8 | `_duplicate_task(task_id)` | Sao chép task |
| 2.1.9 | `_pause_task(task_id)` | Tạm dừng task |
| 2.1.10 | `_delete_task(task_id)` | Xóa task |
| 2.1.11 | `_view_logs(task_id)` | Xem log của task |
| 2.1.12 | `_search_tasks()` | Tìm kiếm task theo tên |
| 2.1.13 | `_filter_by_type()` | Lọc task theo loại (cowork/co4e/code/…) |
### 2.2 Calendar View
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 2.2.1 | `_build_calendar()` | Xây dựng chế độ xem lịch |
| 2.2.2 | `_shift(direction)` | Chuyển tháng/tuần trước/sau |
| 2.2.3 | `add_task_on_date(date)` | Thêm task vào ngày cụ thể |
| 2.2.4 | `edit_task(task_id)` | Sửa task từ lịch |
### 2.3 Add / AI Create Task
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 2.3.1 | `_open_add_dialog()` | Mở dialog thêm task thủ công |
| 2.3.2 | `_ai_create_task()` | Mở dialog AI tạo task tự động |
| 2.3.3 | `_ai_pick_files()` | Chọn file đính kèm cho AI planner |
| 2.3.4 | `_generate()` | AI tạo kế hoạch tasks từ mô tả |
| 2.3.5 | `_on_planned(result)` | Hiển thị preview các task AI đề xuất |
| 2.3.6 | `_confirm()` | Xác nhận và tạo các task từ AI plan |
### 2.4 AI Import Tasks
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 2.4.1 | `_ai_import()` | AI nhập task từ file/link |
| 2.4.2 | `_ai_pick_import_files()` | Chọn file để import |
| 2.4.3 | `_generate_import()` | AI phân tích file và tạo tasks |
| 2.4.4 | `_on_import_planned()` | Hiển thị preview import |
---
## 🔹 3. 🏠 WORKSPACE (Không Gian Làm Việc)
### 3.1 Projects — Quản Lý Dự Án (Tab 0)
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.1.1 | `_create()` | Tạo dự án mới |
| 3.1.2 | `_delete()` | Xóa dự án (có xác nhận) |
| 3.1.3 | `_save()` | Lưu thông tin dự án (name, description, instructions, folder) |
| 3.1.4 | `_pick_folder()` | Chọn workspace folder cho dự án |
| 3.1.5 | `_open_workspace()` | Mở folder workspace trong file explorer |
| 3.1.6 | `_select_project_row(project_id)` | Chọn dự án trong danh sách |
| 3.1.7 | `_refresh_sandbox_toggle()` | Bật/tắt sandbox cho dự án |
| 3.1.8 | `refresh()` | Làm mới danh sách dự án |
### 3.2 Workspace Pane — Mỗi Dự Án Mở (Tab 1..N)
#### 3.2.1 🤖 COWORK — Chat Với AI Agent
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.1.1 | `new_session()` | Tạo phiên chat mới |
| 3.2.1.2 | `send_message()` | Gửi tin nhắn đến AI agent |
| 3.2.1.3 | `_build_job()` | Xây dựng job cho AgentWorker (gọi `run_cowork`) |
| 3.2.1.4 | `_cleanup_turn(ctx, ok)` | Dọn dẹp sau khi turn kết thúc (promote files, xóa sandbox) |
| 3.2.1.5 | `_promote_turn_outputs()` | Di chuyển file đầu ra từ sandbox lên session output |
| 3.2.1.6 | `_refresh_outputs_from_disk()` | Làm mới danh sách output files |
| 3.2.1.7 | `_pick_output_folder()` | Chọn thư mục output |
| 3.2.1.8 | `_open_skills_manager()` | Mở Skill Manager |
| 3.2.1.9 | `refresh_header()` | Làm mới header (project name, model info) |
| 3.2.1.10 | `refresh_agents()` | Làm mới danh sách agents trong combo |
| 3.2.1.11 | `admin_agent_prompt()` | Lấy prompt từ agent preset đã chọn |
| 3.2.1.12 | `build_provider()` | Xây dựng provider từ cấu hình agent/model |
| 3.2.1.13 | `workspace_dir()` | Trả về workspace directory hiện tại |
| 3.2.1.14 | `_start_watching(dir)` | Giám sát folder output (file watcher) |
| 3.2.1.15 | `_on_file_changed()` | Xử lý khi file output thay đổi |
**ChatPanel (Class cha của CoworkTab):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.1.16 | `_submit_message()` | Gửi tin nhắn (kiểm tra queue, parallel limit) |
| 3.2.1.17 | `_on_turn_started()` | Khi turn bắt đầu (show thinking indicator) |
| 3.2.1.18 | `_on_turn_finished()` | Khi turn kết thúc (update UI, queue next) |
| 3.2.1.19 | `_on_event(ev)` | Xử lý streaming events (text delta, tool calls, plan) |
| 3.2.1.20 | `_compress_messages()` | Nén tin nhắn cũ để giảm token |
| 3.2.1.21 | `_on_agent_changed()` | Khi thay đổi agent trong combo |
| 3.2.1.22 | `_apply_routing()` | Áp dụng model routing (Auto/Manual/Off) |
| 3.2.1.23 | `_note_agent_switch()` | Ghi chú khi agent thay đổi giữa các turn |
| 3.2.1.24 | `_ensure_conversation()` | Đảm bảo conversation tab tồn tại |
| 3.2.1.25 | `load_conversation()` | Load hội thoại từ disk |
| 3.2.1.26 | `running_session_ids()` | Trả về danh sách session đang chạy |
| 3.2.1.27 | `active_workers()` | Trả về danh sách worker đang hoạt động |
| 3.2.1.28 | `_save_conversation()` | Tự động lưu hội thoại |
**Composer (Composer input box):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.1.29 | `send()` | Gửi tin nhắn |
| 3.2.1.30 | `attach_files()` | Đính kèm file |
| 3.2.1.31 | `attach_links()` | Đính kèm link URL |
| 3.2.1.32 | `has_any_queue()` | Kiểm tra queue có tin nhắn chờ |
| 3.2.1.33 | `_parse_directives()` | Phân tích directives inline (`/agent:name`, `/skill:name`) |
| 3.2.1.34 | `_show_autocomplete()` | Hiển thị gợi ý tự động |
#### 3.2.2 ⚡ CO4E — Node-Graph Workflow Studio
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.1 | `_build_sidebar()` | Xây dựng sidebar (Workflows / Agents / Skills tabs) |
| 3.2.2.2 | `_build_canvas()` | Xây dựng canvas node-graph |
| 3.2.2.3 | `_build_config_panel()` | Xây dựng config panel bên phải |
| 3.2.2.4 | `_toggle_config()` | Thu/mở config panel |
| 3.2.2.5 | `_build_canvas_overlay()` | Zoom +/− và Fit buttons trên canvas |
**Workflows (Sidebar):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.6 | `_refresh_flows_list()` | Làm mới danh sách flows |
| 3.2.2.7 | `_create_flow()` | Tạo flow mới |
| 3.2.2.8 | `_delete_flow()` | Xóa flow |
| 3.2.2.9 | `_duplicate_flow()` | Sao chép flow |
| 3.2.2.10 | `_import_flow()` | Import flow từ file |
| 3.2.2.11 | `_export_flow()` | Export flow ra file |
| 3.2.2.12 | `_run_flow()` | Chạy flow (foreground/background) |
| 3.2.2.13 | `_stop_flow()` | Dừng flow đang chạy |
| 3.2.2.14 | `_open_flow()` | Mở flow trên canvas |
**Agents (Sidebar):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.15 | `_refresh_agents_list()` | Làm mới danh sách agents |
| 3.2.2.16 | `_create_agent()` | Tạo agent mới (dialog) |
| 3.2.2.17 | `_edit_agent()` | Sửa agent |
| 3.2.2.18 | `_delete_agent()` | Xóa agent |
| 3.2.2.19 | `_toggle_agent_enabled()` | Bật/tắt agent |
**Skills (Sidebar):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.20 | `_refresh_skills_list()` | Làm mới danh sách skills |
**Canvas (Node-Graph):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.21 | `zoom_in()` / `zoom_out()` | Zoom canvas |
| 3.2.2.22 | `fit_view()` | Auto-fit canvas |
| 3.2.2.23 | `_add_node()` | Thêm node lên canvas |
| 3.2.2.24 | `_delete_node()` | Xóa node |
| 3.2.2.25 | `_connect_nodes()` | Kết nối 2 nodes |
| 3.2.2.26 | `_drag_node()` | Kéo thả node |
| 3.2.2.27 | `_select_node()` | Chọn node (→ config panel) |
| 3.2.2.28 | `_activate_node()` | Double-click node |
**Run Modes:**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.29 | `_set_run_mode("auto")` | Auto mode: agent tự plan rồi execute |
| 3.2.2.30 | `_set_run_mode("plan")` | Plan mode: chỉ tạo kế hoạch |
| 3.2.2.31 | `_set_run_mode("manual")` | Manual mode: từng bước, bấm "Next step" |
| 3.2.2.32 | `_run_step()` | Chạy bước tiếp theo (manual mode) |
| 3.2.2.33 | `_on_step_finished()` | Xử lý khi bước hoàn thành |
| 3.2.2.34 | `_render_plan()` | Render plan checklist |
**Chat/Output (Bottom):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.2.35 | `_get_flow_chat(flow_id)` | Lấy ChatView cho flow (tạo mới nếu chưa có) |
| 3.2.2.36 | `_on_chat_event()` | Xử lý event từ chat |
#### 3.2.3 📁 FOLDER — File Explorer
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.3.1 | `set_root(path)` | Đặt thư mục gốc |
| 3.2.3.2 | `_build_tree_view()` | Xây dựng cây thư mục (QFileSystemModel) |
| 3.2.3.3 | `_open_file(path)` | Mở file được chọn |
| 3.2.3.4 | `_view_source()` | Xem source code (syntax highlighting) |
| 3.2.3.5 | `_view_html_preview()` | Preview HTML (WebEngine/rich text) |
| 3.2.3.6 | `_view_office_doc()` | Xem Office doc (docx/pdf/xlsx/…) |
| 3.2.3.7 | `_view_image()` | Hiển thị ảnh inline |
| 3.2.3.8 | `_edit_file()` | Chỉnh sửa file (code editor) |
| 3.2.3.9 | `_save_file()` | Lưu file |
| 3.2.3.10 | `_preview_toggle()` | Chuyển đổi Preview ⇄ Edit |
| 3.2.3.11 | `_create_new_file()` | Tạo file mới |
| 3.2.3.12 | `_create_new_folder()` | Tạo folder mới |
| 3.2.3.13 | `_rename_item()` | Đổi tên file/folder |
| 3.2.3.14 | `_delete_item()` | Xóa file/folder |
| 3.2.3.15 | `_copy_item()` | Sao chép file/folder |
| 3.2.3.16 | `_paste_item()` | Dán file/folder |
| 3.2.3.17 | `refresh_ai_models()` | Làm mới danh sách AI models cho AI Edit |
**AI Edit (Chỉnh Sửa File Bằng AI):**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.3.18 | `_ai_send()` | Gửi yêu cầu AI edit |
| 3.2.3.19 | `_ai_apply()` | Áp dụng thay đổi AI |
| 3.2.3.20 | `_ai_discard()` | Hủy thay đổi AI |
| 3.2.3.21 | `_reset_ai_conversation()` | Xóa hội thoại AI edit |
| 3.2.3.22 | `_ai_apply_routing()` | Áp dụng routing cho AI edit |
#### 3.2.4 🧠 GRAPH RAG — Knowledge Graph
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.4.1 | `_build_graph()` | Xây dựng knowledge graph từ code/documents |
| 3.2.4.2 | `_render_d3_graph()` | Render graph bằng D3.js (WebEngine) |
| 3.2.4.3 | `_render_native_graph()` | Render graph bằng QGraphicsView (fallback) |
| 3.2.4.4 | `_auto_rotate()` | Tự xoay graph khi idle |
| 3.2.4.5 | `_on_node_click()` | Xử lý click node (mở folder) |
| 3.2.4.6 | `_open_node_path()` | Mở folder chứa node |
| 3.2.4.7 | `_refresh_graph()` | Tự cập nhật graph khi có output mới |
| 3.2.4.8 | `_search_graph()` | Tìm kiếm trong graph |
| 3.2.4.9 | `_filter_by_kind()` | Lọc node theo loại |
| 3.2.4.10 | `_zoom_graph()` | Zoom graph |
**Graph-RAG Q&A:**
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 3.2.4.11 | `_ask_question()` | Hỏi AI về graph |
| 3.2.4.12 | `_on_ask_event()` | Xử lý streaming answer |
| 3.2.4.13 | `_on_ask_done()` | Khi AI trả lời xong |
| 3.2.4.14 | `_candidate_file_paths()` | Lấy danh sách file để extract |
| 3.2.4.15 | `_extract_tmp_dir()` | Tạo thư mục tạm cho extraction |
| 3.2.4.16 | `_clear_extracts()` | Xóa dữ liệu extract tạm |
---
## 🔹 4. 📊 MONITORING (Giám Sát)
### 4.1 Overview — Tổng Quan
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.1.1 | `_refresh_overview()` | Làm mới tất cả cards overview |
| 4.1.2 | `_refresh_usage_cards()` | Token Usage & Cost cards (Total, Input, Output, Cache) |
| 4.1.3 | `_refresh_resource_usage()` | Resource usage (CPU, RAM, Disk) |
| 4.1.4 | `_refresh_recent_activity()` | Hoạt động gần đây |
| 4.1.5 | `_refresh_sandbox_details()` | Chi tiết sandbox (PID, uptime, limits) |
| 4.1.6 | `_refresh_permissions()` | Hiển thị permissions hiện tại |
| 4.1.7 | `_refresh_audit_log()` | Audit log gần đây |
| 4.1.8 | `_refresh_budget()` | Budget card (còn lại / đã dùng) |
| 4.1.9 | `_apply_budget()` | Lưu budget mới |
### 4.2 Security Events — Sự Kiện Bảo Mật
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.2.1 | `_refresh_security_events()` | Làm mới bảng security events (audit log `kind="security_block"`) |
| 4.2.2 | `_filter_security_events()` | Lọc sự kiện bảo mật |
| 4.2.3 | `_sort_events()` | Sắp xếp bảng events |
### 4.3 MCP Call History — Lịch Sử Gọi MCP
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.3.1 | `_refresh_mcp_calls()` | Làm mới bảng MCP calls (audit log `kind="mcp_call"`) |
| 4.3.2 | `_filter_mcp_calls()` | Lọc MCP calls |
### 4.4 Action Logs — Nhật Ký Hành Động
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.4.1 | `_refresh_action_logs()` | Làm mới bảng action logs (toàn bộ audit log) |
| 4.4.2 | `_filter_action_logs()` | Lọc action logs |
| 4.4.3 | `_sort_action_logs()` | Sắp xếp action logs |
### 4.5 Agent Status — Trạng Thái Agent
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.5.1 | `_refresh_agent_status()` | Làm mới trạng thái các agent (Cowork, Co4E, Schedule, GraphRAG) |
### 4.6 Security Settings — Cài Đặt Bảo Mật
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 4.6.1 | `_toggle_sandbox()` | Bật/tắt sandbox |
| 4.6.2 | `_toggle_network_block()` | Chặn kết nối mạng |
| 4.6.3 | `_set_resource_limits()` | Đặt giới hạn tài nguyên (CPU/RAM/Disk) |
| 4.6.4 | `_toggle_command_confirm()` | Xác nhận trước khi chạy lệnh |
| 4.6.5 | `_manage_permissions()` | Quản lý quyền truy cập |
---
## 🔹 5. ⚙️ SETTINGS (Cài Đặt)
### 5.1 AI Provider — Nhà Cung Cấp AI
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 5.1.1 | `_on_provider_changed()` | Khi thay đổi provider |
| 5.1.2 | `_load_models(provider)` | Load danh sách models của provider |
| 5.1.3 | `_test_connection(provider)` | Kiểm tra kết nối provider |
| 5.1.4 | `_stash_provider_fields()` | Lưu tạm các trường cấu hình provider |
| 5.1.5 | `_apply_provider_fields()` | Áp dụng các trường cấu hình provider |
| 5.1.6 | Model List Widget | Hiển thị danh sách models (enable/disable, chọn default) |
### 5.2 Connectors (MCP) — Kết Nối
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 5.2.1 | `_add_mcp_server()` | Thêm MCP server mới |
| 5.2.2 | `_edit_mcp_server()` | Sửa MCP server |
| 5.2.3 | `_delete_mcp_server()` | Xóa MCP server |
| 5.2.4 | `_test_mcp_connection()` | Kiểm tra kết nối MCP |
| 5.2.5 | MS365 Connector | Kết nối Microsoft 365 (tự động khi đăng nhập) |
| 5.2.6 | CAD/CAE Connectors | Kết nối CAD/CAE tools |
### 5.3 Parameters — Tham Số
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 5.3.1 | `attach_tokens` | Giới hạn token cho attachments |
| 5.3.2 | `attach_files` | Giới hạn số file attachments |
| 5.3.3 | `struct_nodes` | Giới hạn nodes cho GraphRAG |
| 5.3.4 | `struct_edges` | Giới hạn edges cho GraphRAG |
### 5.4 Model Routing — Định Tuyến Model
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 5.4.1 | `routing_mode` | Chế độ routing (Off/Auto/Manual) |
| 5.4.2 | `routing_policy` | Chính sách routing |
| 5.4.3 | `routing_min_gain` | Threshold tối thiểu để chuyển model |
| 5.4.4 | `routing_timeout` | Timeout xác nhận routing |
| 5.4.5 | `routing_interval` | Khoảng thời gian đánh giá lại |
| 5.4.6 | `routing_concurrency` | Số lượng request đồng thời per provider |
| 5.4.7 | `routing_judge` | Model dùng để đánh giá routing |
### 5.5 General — Chung
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 5.5.1 | Language Picker | Chọn ngôn ngữ (EN/VI/JP) |
| 5.5.2 | `tray_chk` | Minimize to tray thay vì đóng |
| 5.5.3 | `notify_chk` | Thông báo khi task hoàn thành |
| 5.5.4 | `_save()` | Lưu tất cả cài đặt |
---
## 🔹 6. 📜 HISTORY SIDEBAR (Thanh Lịch Sử Bên Trái)
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 6.0.1 | `refresh()` | Làm mới danh sách hội thoại |
| 6.0.2 | `set_view_state(session_id, running_ids)` | Đánh dấu hội thoại hiện tại + đang chạy |
| 6.0.3 | `set_project_filter(project_id)` | Lọc theo dự án |
| 6.0.4 | `_open_chat()` | Mở hội thoại khi click |
| 6.0.5 | `_context_menu()` | Menu chuột phải (Pin/Unpin, Rename, Delete) |
| 6.0.6 | `_bulk_delete_menu()` | Menu xóa hàng loạt |
| 6.0.7 | `_confirm_and_delete_selected()` | Xác nhận và xóa các hội thoại đã chọn |
| 6.0.8 | `new_chat(kind)` | Tạo hội thoại mới |
| 6.0.9 | `collapse_requested()` | Thu nhỏ sidebar |
| 6.0.10 | `expand_requested()` | Mở rộng sidebar |
---
## 🔹 7. 🧩 CÁC CHỨC NĂNG TOÀN CẦU (Global)
### 7.1 MainWindow (app.py)
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 7.1.1 | `_build_topbar()` | Xây dựng thanh trên cùng (User name, Settings, Language) |
| 7.1.2 | `_build_nav_rail()` | Xây dựng thanh điều hướng bên trái |
| 7.1.3 | `_toggle_nav()` | Thu/mở nav rail (icon-only ↔ full) |
| 7.1.4 | `_apply_nav_labels()` | Áp dụng labels cho nav items |
| 7.1.5 | `_ensure_page(row)` | Xây dựng page lười (lazy loading) |
| 7.1.6 | `_refresh_history()` | Làm mới history của tất cả panes |
| 7.1.7 | `_on_scheduled_task_done()` | Thông báo khi scheduled task hoàn thành |
| 7.1.8 | `_notify_task()` | Thông báo khi task hoàn thành |
| 7.1.9 | `_on_projects_changed()` | Khi danh sách dự án thay đổi |
| 7.1.10 | `_on_pane_turn_finished()` | Khi turn trong pane hoàn thành |
| 7.1.11 | `_open_settings()` | Mở dialog cài đặt |
| 7.1.12 | `_fit_to_screen()` | Tự động fit cửa sổ theo màn hình |
| 7.1.13 | Toast notifications | Hiển thị thông báo toast |
| 7.1.14 | System Tray | Minimize to tray, tray notifications |
### 7.2 Skills Manager
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 7.2.1 | `_open_skills_manager()` | Mở Skill Manager |
| 7.2.2 | `seed_library_skills()` | Gieo skills mặc định |
| 7.2.3 | `prune_seeded_builtins()` | Dọn dẹp skills built-in |
### 7.3 Welcome Dialog
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 7.3.1 | `maybe_show_welcome()` | Hiển thị dialog chào mừng lần đầu |
### 7.4 i18n (Đa Ngôn Ngữ)
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 7.4.1 | `tr(key)` | Dịch chuỗi theo ngôn ngữ hiện tại |
| 7.4.2 | `set_language(lang)` | Đặt ngôn ngữ |
| 7.4.3 | `get_language()` | Lấy ngôn ngữ hiện tại |
| 7.4.4 | `on_language_changed(callback)` | Đăng ký callback khi ngôn ngữ thay đổi |
### 7.5 Task Scheduler (Nền)
| # | Tên Hàm / Chức Năng | Mô Tả |
|---|---------------------|--------|
| 7.5.1 | `task_finished` signal | Khi scheduled task hoàn thành |
| 7.5.2 | `history_ready` signal | Khi session của task sẵn sàng |
| 7.5.3 | `running_session_ids()` | Lấy danh sách session đang chạy |
---
## 📌 TỔNG KẾT
| Navigation Item | Số Hàm/Chức Năng |
|----------------|:-:|
| 📊 Dashboard | ~10 |
| 📅 Schedule Task | ~25 |
| 🏠 Workspace → Projects | ~8 |
| 🏠 Workspace → Cowork | ~34 |
| 🏠 Workspace → Co4E | ~36 |
| 🏠 Workspace → Folder | ~22 |
| 🏠 Workspace → Graph RAG | ~16 |
| 📊 Monitoring | ~20 |
| ⚙️ Settings | ~25 |
| 📜 History Sidebar | ~10 |
| 🌐 Global Functions | ~15 |
| **TỔNG CỘNG** | **~221** |
> **Lưu ý:** Đây là danh sách các hàm/chức năng ở cấp UI và business logic chính. Các hàm core (providers, MCP, worker, security…) nằm ở tầng dưới và được gọi bởi các hàm UI ở trên.
-71
View File
@@ -1,71 +0,0 @@
# Installation Record — 2026-08-11
This record captures the successful local source installation performed on an Apple Silicon macOS host. It contains no credentials or machine-specific home-directory path.
## Environment
```text
Architecture: arm64
Python: 3.11.15
Installer: uv 0.11.8
Virtual environment: <repository>/.venv
Launcher: ~/.local/bin/cowork-local
Installed size: approximately 1.3 GB
```
## Steps executed
From the repository root:
```bash
git switch -c chore/local-installation
./scripts/install_local.sh
```
The installer selected Homebrew Python 3.11, created `.venv`, installed the runtime and test requirement sets, and created the user launcher without replacing any existing path.
Key resolved packages:
```text
PySide6==6.11.1
anyio==4.14.2
holidays==0.102
keyring==25.7.0
mcp==1.29.0
msal==1.37.0
networkx==3.6.1
openpyxl==3.1.5
psutil==7.2.2
pydantic==2.13.4
Pygments==2.20.0
python-pptx==1.0.2
requests==2.34.2
pytest==9.1.1
```
## Verification executed
```bash
.venv/bin/python -m pytest tests -q
.venv/bin/python -c "import PySide6, pydantic, requests"
```
Additional verification imported every module under `cowork_local` with `QT_QPA_PLATFORM=offscreen`, then started the real application entry point with a 1.5-second automatic Qt shutdown.
Results:
```text
Tests: 81 passed
Runtime dependency imports: PASS
Application module imports: 0 failures
Headless startup: exit 0
Launcher in PATH: PASS
```
Qt emitted one non-fatal warning while populating the fallback alias for the missing `Sans Serif` family. It did not affect application startup.
## Optional capabilities
`pypdf` and `opendataloader-pdf` were intentionally not installed in the baseline environment. Install `requirements-optional.txt` when advanced PDF extraction is required. A `soffice` command was detected on the installation host, but LibreOffice availability remains an external host prerequisite rather than a Python dependency.
No provider credential, unlock code, token, or application state was written to the repository during installation or verification.
-92
View File
@@ -1,92 +0,0 @@
# Local Installation
This guide installs the source checkout into an isolated virtual environment. It does not modify the system Python and does not store provider credentials in the repository.
## Supported baseline
- Python 3.11 or newer; CI and this installation use Python 3.11.
- macOS, Linux, or Windows for the cross-platform desktop UI.
- Windows-only integrations such as AppContainer, Windows Sandbox, Outlook COM, and Office COM conversion remain unavailable on macOS/Linux and degrade gracefully.
## Automated installation
From the repository root:
```bash
./scripts/install_local.sh
```
The installer:
1. selects `python3.11` when available;
2. creates `.venv/` inside the repository;
3. installs `requirements.txt` and `requirements-test.txt` with `uv` when available, otherwise `pip`;
4. creates `~/.local/bin/cowork-local` when that path is free;
5. never replaces an existing launcher or global Python package.
Override the interpreter when necessary:
```bash
COWORK_PYTHON=/path/to/python3.11 ./scripts/install_local.sh
```
## Run
Use the repository launcher:
```bash
./scripts/run_local.sh
```
If `~/.local/bin` is in `PATH`, use:
```bash
cowork-local
```
The launcher changes to the package's parent directory and runs `python -m cowork_local`, which is required by the current source layout.
## Configure credentials
Application state is stored outside Git under `~/.cowork_local/`. Export only the variables you need; `.env.example` documents the supported names. For example:
```bash
export OPENAI_API_KEY="..."
export OPENAI_BASE_URL="https://your-approved-gateway/v1"
export COWORK_SANDBOX_PASSWORD="..."
export COWORK_MS365_UNLOCK_CODE="..."
cowork-local
```
Do not put real values in `.env.example` or any tracked file.
## Verify
```bash
.venv/bin/python -m pytest tests -q
.venv/bin/python -c "import PySide6, pydantic, requests; print('runtime imports OK')"
```
A headless startup smoke test suitable for CI or remote shells is documented in the verification section below:
```bash
cd ..
QT_QPA_PLATFORM=offscreen cowork_local/.venv/bin/python -c \
"from PySide6.QtCore import QTimer; from PySide6.QtWidgets import QApplication; app=QApplication([]); QTimer.singleShot(1000, app.quit); from cowork_local.app import run; raise SystemExit(run([]))"
```
## Optional document tooling
Install PDF extraction helpers when needed:
```bash
uv pip install --python .venv/bin/python -r requirements-optional.txt
```
LibreOffice is an external application, not a Python package. Install it separately if headless Office-to-PDF conversion is required. Microsoft Office/Outlook COM integration and `pywin32` are Windows-only.
## Update or repair
Pull the desired reviewed revision and rerun `./scripts/install_local.sh`. The operation is idempotent: it reuses `.venv`, reconciles declared packages, and keeps the existing launcher when it already points to this checkout.
The first verified macOS installation is recorded in [installation-log-2026-08-11.md](installation-log-2026-08-11.md).
+58
View File
@@ -0,0 +1,58 @@
# Project Context MCP — hướng dẫn làm song song
Mục tiêu: hoàn thiện ba tool trên **cùng một server** `project_context`. Không tạo server, registry,
policy hay error envelope mới. Shared skeleton đã khóa sẵn thứ tự an toàn:
```text
validate input → policy ALLOW → resolve provider → gọi upstream → validate output
```
## Chia việc
| Người | Tool | Chỉ sửa | Branch đề xuất |
|---|---|---|---|
| Member A | `get_project_issue_context` | `tools/issue_context.py`, `providers/issue.py`, test riêng | `feat/mcp-issue-context` |
| Member B | `search_project_knowledge` | `tools/knowledge_search.py`, `providers/knowledge.py`, test riêng | `feat/mcp-knowledge-search` |
| Member C | `get_project_change_context` | `tools/change_context.py`, `providers/change.py`, test riêng | `feat/mcp-change-context` |
Trước khi gửi task, thay `Member A/B/C` bằng username thật trên ba issue. Mỗi người **không sửa**
`foundation.py`, `registry.py`, `runtime.py`, `server.py` hoặc file của người khác. Nếu shared contract
cần đổi, mở một PR nhỏ riêng và để cả ba người rebase sau khi PR đó merge.
## Bắt đầu trong 5 phút
1. Chạy `python --version` và xác nhận Python 3.11+ như baseline trong `requirements.txt`.
2. Tạo branch từ commit template chứa tài liệu này sau khi PR template merge.
3. Đọc input/output model trong module tool được giao; không thêm field riêng của Gitea/Jira/Redmine.
4. Implement provider read-only trong module `providers/<tool>.py`; credential chỉ lấy sau policy ALLOW.
5. Thêm test happy, invalid, not-found, timeout, DENIED với `resolver.calls == 0`, output sai schema,
truncation/cursor và source mở được có `revision`.
6. Chạy:
```bash
python -m pytest tests/test_project_context_mcp_template.py tests/test_project_context_<tool>.py -q
```
Lệnh trên chạy trực tiếp từ root repo `cowork_local`; `tests/conftest.py` đã thiết lập import path.
## Definition of Done của từng người
- Tool trả đúng schema, có `project_id` và source gồm `system`, `url`, `revision`, `retrieved_at`.
- Provider-neutral: đổi Gitea sang GitHub/Jira/Redmine không đổi schema hay tool name.
- Sai project bị `DENIED` trước khi resolve credential và trước mọi upstream call.
- Không log/return token; lỗi ngoài dự kiến không lộ exception; read không có side effect.
- Output lớn có `truncated`, `returned`, `remaining`, `next_cursor`; không cắt im lặng.
- Test riêng pass, test shared pass, PR chỉ chạm đúng vùng sở hữu trong bảng trên.
## Chạy server sau khi provider đã cấu hình
```bash
COWORK_MCP_ACTOR_ID=<actor> \
COWORK_MCP_ORG_UNIT=<org> \
COWORK_MCP_CUSTOMER=<customer> \
COWORK_MCP_PROJECT=<project> \
python -m cowork_local.mcp_servers.project_context_server
```
Không commit giá trị môi trường hoặc credential. Cowork kết nối bằng stdio với command Python và
args `-m cowork_local.mcp_servers.project_context_server`.
+540
View File
@@ -0,0 +1,540 @@
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Tìm hiểu RAG — Hỏi &amp; Đáp</title>
<style>
:root{
--navy:#1B3C87; --blue:#0A4EA3; --acc:#1565C0; --acc2:#4A90D9;
--bg:#fff; --sf:#F7F9FC; --card:#fff; --bd:#E3E8EF; --bds:#CBD5E1;
--tx:#2B3542; --mut:#5A6675; --fnt:#8A94A3;
--ok:#1B7A3D; --okbg:#E8F5EC; --warn:#B26A00; --warnbg:#FDF3E3;
--bad:#C0392B; --badbg:#FCEDEC; --r:10px;
}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--tx);
font:15px/1.6 "Segoe UI Variable Text","Segoe UI",system-ui,sans-serif}
.bar{background:var(--navy);color:#fff;padding:12px 28px;font-weight:700;font-size:16px;
display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:9}
.bar .sub{font-weight:400;opacity:.85;font-size:13px}
.wrap{max-width:1060px;margin:0 auto;padding:28px 28px 80px}
h1{color:var(--blue);font-size:30px;margin:14px 0 6px;letter-spacing:-.02em}
h2{color:var(--blue);font-size:20px;margin:40px 0 4px;padding-top:18px;
border-top:2px solid var(--bd)}
.lead{color:var(--mut);margin:0 0 8px}
.qa{border:1px solid var(--bd);border-radius:var(--r);margin:14px 0;background:var(--card);
box-shadow:0 1px 2px rgba(16,32,64,.04)}
.q{padding:13px 18px;font-weight:700;color:var(--blue);font-size:15.5px;
display:flex;gap:10px;align-items:flex-start}
.q .n{background:var(--acc);color:#fff;border-radius:5px;min-width:26px;height:22px;
display:inline-flex;align-items:center;justify-content:center;font-size:12px;flex:none}
.a{padding:0 18px 15px 54px;color:var(--tx)}
.a p{margin:0 0 8px}
.a ul{margin:6px 0;padding-left:20px}.a li{margin:3px 0}
b{color:var(--blue)}
code{font:13px "Cascadia Code",Consolas,monospace;background:var(--sf);
border:1px solid var(--bd);border-radius:4px;padding:1px 5px;color:#0F3D6E}
.note{border-left:4px solid var(--acc);background:#EAF2FC;border-radius:6px;
padding:10px 14px;margin:10px 0}
.note.ok{border-left-color:var(--ok);background:var(--okbg)}
.note.warn{border-left-color:var(--warn);background:var(--warnbg)}
.note.bad{border-left-color:var(--bad);background:var(--badbg)}
figure{margin:12px 0;padding:14px;background:var(--sf);border:1px solid var(--bd);
border-radius:var(--r)}
figure svg{display:block;width:100%;height:auto}
figcaption{color:var(--fnt);font-size:12.5px;margin-top:8px;text-align:center}
table{width:100%;border-collapse:collapse;margin:10px 0;font-size:14px}
th,td{text-align:left;padding:7px 11px;border-bottom:1px solid var(--bd);vertical-align:top}
th{color:var(--mut);font-size:12px;text-transform:uppercase;letter-spacing:.05em}
.toc{background:var(--sf);border:1px solid var(--bd);border-radius:var(--r);padding:14px 20px}
.toc ol{margin:6px 0;padding-left:20px;columns:2;column-gap:32px;font-size:14px}
.toc a{color:var(--tx);text-decoration:none}.toc a:hover{color:var(--acc)}
@media(max-width:820px){.toc ol{columns:1}.a{padding-left:18px}}
</style>
</head>
<body>
<div class="bar"><span>Tìm hiểu RAG — Hỏi &amp; Đáp</span>
<span class="sub">Chuẩn bị cho phần Q&amp;A sau buổi trình bày</span></div>
<div class="wrap">
<h1>Những câu hay được hỏi nhất</h1>
<p class="lead">20 câu, xếp từ dễ tới khó. Năm câu cuối là về chính dự án Cowork-Local —
nhóm câu này gần như chắc chắn sẽ có người hỏi.</p>
<div class="toc"><b>Nội dung</b>
<ol>
<li><a href="#q1">RAG là gì, nói gọn trong một câu?</a></li>
<li><a href="#q2">RAG khác fine-tuning thế nào?</a></li>
<li><a href="#q3">RAG có xoá hết bịa đặt không?</a></li>
<li><a href="#q4">Vector là gì mà so sánh được nghĩa?</a></li>
<li><a href="#q5">Chia đoạn bao nhiêu chữ là đúng?</a></li>
<li><a href="#q6">Overlap để làm gì?</a></li>
<li><a href="#q7">top-K nên đặt bao nhiêu?</a></li>
<li><a href="#q8">Chọn mô hình embedding thế nào? Tiếng Việt thì sao?</a></li>
<li><a href="#q9">Bắt buộc phải có Vector DB không?</a></li>
<li><a href="#q10">Chỉ tìm theo vector đã đủ chưa?</a></li>
<li><a href="#q11">Câu hỏi cần nối nhiều tài liệu thì sao?</a></li>
<li><a href="#q12">Context window đã 1 triệu token, còn cần RAG?</a></li>
<li><a href="#q13">Chi phí thực tế bao nhiêu?</a></li>
<li><a href="#q14">RAG làm chậm bao nhiêu?</a></li>
<li><a href="#q15">Tài liệu sửa thì cập nhật thế nào?</a></li>
<li><a href="#q16">Đo chất lượng RAG bằng gì?</a></li>
<li><a href="#q17">Phân quyền tài liệu xử lý ra sao?</a></li>
<li><a href="#q18">Cowork-Local đã có RAG chưa?</a></li>
<li><a href="#q19">GraphRAG của dự án có phải GraphRAG của Microsoft?</a></li>
<li><a href="#q20">Muốn nâng lên RAG đầy đủ cần làm gì?</a></li>
</ol></div>
<h2>Nhóm 1 — Khái niệm</h2>
<div class="qa" id="q1"><div class="q"><span class="n">1</span>
RAG là gì, nói gọn trong một câu?</div>
<div class="a">
<p><b>Tìm tài liệu liên quan trước, rồi đưa cho LLM đọc và trả lời dựa trên đó</b> — thay vì
để LLM trả lời bằng trí nhớ có sẵn.</p>
<p>Ví von: thay vì bắt thí sinh làm bài từ trí nhớ, ta cho <i>thi mở sách</i> — nhưng có
thủ thư lật sẵn đúng trang cần đọc.</p>
</div></div>
<div class="qa" id="q2"><div class="q"><span class="n">2</span>
RAG khác fine-tuning thế nào? Khi nào dùng cái nào?</div>
<div class="a">
<figure>
<svg viewBox="0 0 720 190" role="img" aria-label="So sánh RAG và fine-tuning">
<rect x="8" y="14" width="340" height="162" rx="8" fill="#EAF2FC" stroke="#1565C0"/>
<text x="26" y="40" font-size="15" font-weight="700" fill="#0A4EA3">RAG — đưa thêm tài liệu</text>
<rect x="26" y="56" width="86" height="34" rx="5" fill="#fff" stroke="#4A90D9"/>
<text x="69" y="77" font-size="12" text-anchor="middle" fill="#2B3542">Câu hỏi</text>
<path d="M116 73 h22" stroke="#5A6675" stroke-width="1.6" marker-end="url(#ar)"/>
<rect x="142" y="56" width="94" height="34" rx="5" fill="#fff" stroke="#4A90D9"/>
<text x="189" y="72" font-size="11" text-anchor="middle" fill="#2B3542">Tìm tài liệu</text>
<text x="189" y="84" font-size="10" text-anchor="middle" fill="#5A6675">top-K đoạn</text>
<path d="M240 73 h22" stroke="#5A6675" stroke-width="1.6" marker-end="url(#ar)"/>
<rect x="266" y="56" width="66" height="34" rx="5" fill="#1565C0"/>
<text x="299" y="77" font-size="12" text-anchor="middle" fill="#fff">LLM</text>
<text x="26" y="116" font-size="12" fill="#2B3542">✔ Cập nhật tức thì — chỉ re-index</text>
<text x="26" y="136" font-size="12" fill="#2B3542">✔ Trích được nguồn</text>
<text x="26" y="156" font-size="12" fill="#2B3542">✔ Rẻ, không cần GPU train</text>
<rect x="372" y="14" width="340" height="162" rx="8" fill="#FDF3E3" stroke="#B26A00"/>
<text x="390" y="40" font-size="15" font-weight="700" fill="#8A5000">Fine-tune — dạy lại mô hình</text>
<rect x="390" y="56" width="96" height="34" rx="5" fill="#fff" stroke="#D9A24A"/>
<text x="438" y="72" font-size="11" text-anchor="middle" fill="#2B3542">Dữ liệu mẫu</text>
<text x="438" y="84" font-size="10" text-anchor="middle" fill="#5A6675">hàng nghìn cặp</text>
<path d="M490 73 h22" stroke="#5A6675" stroke-width="1.6" marker-end="url(#ar)"/>
<rect x="516" y="56" width="80" height="34" rx="5" fill="#fff" stroke="#D9A24A"/>
<text x="556" y="77" font-size="12" text-anchor="middle" fill="#2B3542">Huấn luyện</text>
<path d="M600 73 h22" stroke="#5A6675" stroke-width="1.6" marker-end="url(#ar)"/>
<rect x="626" y="56" width="70" height="34" rx="5" fill="#B26A00"/>
<text x="661" y="77" font-size="12" text-anchor="middle" fill="#fff">Model mới</text>
<text x="390" y="116" font-size="12" fill="#2B3542">✔ Dạy được <i>văn phong</i>, định dạng</text>
<text x="390" y="136" font-size="12" fill="#2B3542">✔ Dạy được kỹ năng chuyên ngành</text>
<text x="390" y="156" font-size="12" fill="#2B3542">✘ Kiến thức mới → phải train lại</text>
<defs><marker id="ar" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto">
<path d="M0 0 L7 3.5 L0 7 z" fill="#5A6675"/></marker></defs>
</svg>
<figcaption>RAG thêm <i>kiến thức</i>. Fine-tune thay đổi <i>hành vi</i>.</figcaption>
</figure>
<p><b>Quy tắc chọn:</b> câu trả lời phụ thuộc <i>nội dung tài liệu</i> → RAG.
Phụ thuộc <i>cách nói / định dạng / kỹ năng</i> → fine-tune. Cần cả hai thì làm cả hai.</p>
<div class="note">Đa số bài toán doanh nghiệp là loại thứ nhất, nên RAG hầu như luôn là
bước làm trước.</div>
</div></div>
<div class="qa" id="q3"><div class="q"><span class="n">3</span>
RAG có xoá hết bịa đặt (hallucination) không?</div>
<div class="a">
<p><b>Không. Chỉ giảm mạnh.</b> Đây là câu dễ bị hỏi vặn nhất, nên trả lời thẳng.</p>
<p>RAG vẫn sai được ở bốn chỗ:</p>
<ul>
<li><b>Tra sai đoạn</b> — lấy nhầm tài liệu, LLM trả lời trung thực trên tài liệu sai.</li>
<li><b>Không có trong kho</b> — LLM vẫn cố trả lời thay vì nói "không tìm thấy".</li>
<li><b>Đọc đúng nhưng suy diễn thêm</b> — thêm chi tiết không có trong đoạn trích.</li>
<li><b>Tài liệu gốc đã sai</b> — RAG không kiểm chứng nội dung.</li>
</ul>
<div class="note warn">Cách khắc phục thực dụng: bắt LLM <b>trích dẫn đoạn nguồn</b> cho từng ý,
và cho phép trả lời <b>"không tìm thấy trong tài liệu"</b>. Slide "Ưu điểm" nên nói
<i>giảm</i> hallucination, không nói <i>hết</i>.</div>
</div></div>
<div class="qa" id="q4"><div class="q"><span class="n">4</span>
Vector là gì mà so sánh được "nghĩa giống nhau"?</div>
<div class="a">
<figure>
<svg viewBox="0 0 720 210" role="img" aria-label="Không gian vector, các câu gần nghĩa nằm gần nhau">
<rect x="40" y="14" width="640" height="164" rx="8" fill="#fff" stroke="var(--bds)"/>
<line x1="70" y1="160" x2="660" y2="160" stroke="#CBD5E1"/>
<line x1="70" y1="160" x2="70" y2="30" stroke="#CBD5E1"/>
<circle cx="180" cy="70" r="6" fill="#1565C0"/><text x="192" y="74" font-size="12">"Xe hơi"</text>
<circle cx="214" cy="88" r="6" fill="#1565C0"/><text x="226" y="92" font-size="12">"Ô tô"</text>
<circle cx="196" cy="52" r="6" fill="#1565C0"/><text x="208" y="56" font-size="12">"Xe bốn bánh"</text>
<ellipse cx="200" cy="70" rx="86" ry="46" fill="none" stroke="#1565C0"
stroke-dasharray="4 3" opacity=".6"/>
<circle cx="520" cy="120" r="6" fill="#B26A00"/><text x="532" y="124" font-size="12">"Nấu phở"</text>
<circle cx="556" cy="98" r="6" fill="#B26A00"/><text x="568" y="102" font-size="12">"Công thức bún"</text>
<ellipse cx="540" cy="110" rx="70" ry="38" fill="none" stroke="#B26A00"
stroke-dasharray="4 3" opacity=".6"/>
<circle cx="300" cy="118" r="7" fill="#C0392B"/>
<text x="252" y="140" font-size="12" fill="#C0392B">câu hỏi của user</text>
<line x1="300" y1="118" x2="214" y2="88" stroke="#C0392B" stroke-width="1.4"/>
<text x="236" y="112" font-size="10.5" fill="#C0392B">gần → lấy</text>
<line x1="300" y1="118" x2="520" y2="120" stroke="#CBD5E1" stroke-width="1.2"
stroke-dasharray="3 3"/>
<text x="386" y="134" font-size="10.5" fill="#8A94A3">xa → bỏ qua</text>
</svg>
<figcaption>Mỗi đoạn chữ thành một điểm trong không gian nhiều chiều.
Gần nhau = gần nghĩa.</figcaption>
</figure>
<p>Mô hình embedding biến một đoạn chữ thành dãy số (768 – 4096 chiều). Nó được huấn luyện
sao cho <b>hai đoạn cùng nghĩa cho ra hai điểm gần nhau</b>, kể cả khi không trùng một chữ nào.</p>
<p>Máy đo "gần" bằng <b>cosine similarity</b> — góc giữa hai vector. Nhờ vậy hỏi "xe hơi"
vẫn tìm ra tài liệu viết "ô tô".</p>
<div class="note">Đây chính là điểm RAG hơn tìm kiếm từ khoá: từ khoá cần <i>trùng chữ</i>,
vector chỉ cần <i>trùng nghĩa</i>.</div>
</div></div>
<h2>Nhóm 2 — Tham số kỹ thuật</h2>
<div class="qa" id="q5"><div class="q"><span class="n">5</span>
Chia đoạn bao nhiêu chữ là đúng?</div>
<div class="a">
<p><b>Không có con số đúng chung</b> — phụ thuộc loại tài liệu. Nhưng có nguyên tắc:</p>
<table>
<tr><th>Loại tài liệu</th><th>Cỡ đoạn gợi ý</th><th>Vì sao</th></tr>
<tr><td>FAQ, hỏi đáp ngắn</td><td>100 – 300 chữ</td><td>Mỗi mục vốn đã độc lập</td></tr>
<tr><td>Chính sách, quy trình</td><td>300 – 600 chữ</td><td>Giữ trọn một điều khoản</td></tr>
<tr><td>Sách, báo cáo dài</td><td>500 – 1000 chữ</td><td>Cần đủ ngữ cảnh xung quanh</td></tr>
<tr><td>Mã nguồn</td><td>theo hàm / lớp</td><td>Cắt giữa hàm là hỏng nghĩa</td></tr>
</table>
<div class="note warn"><b>Đoạn quá nhỏ</b> → mất ngữ cảnh, tra ra mảnh vụn vô nghĩa.
<b>Đoạn quá lớn</b> → một đoạn chứa nhiều chủ đề, vector bị "trung bình hoá" nên tra kém chính xác,
lại tốn token.</div>
<p>Thực tế nên <b>cắt theo cấu trúc trước</b> (theo mục, theo điều, theo hàm) rồi mới giới hạn
độ dài — cắt cứng theo số chữ là phương án cuối.</p>
</div></div>
<div class="qa" id="q6"><div class="q"><span class="n">6</span>
Overlap 10–20% để làm gì?</div>
<div class="a">
<figure>
<svg viewBox="0 0 720 150" role="img" aria-label="Chia đoạn có phần chồng lấn">
<text x="20" y="26" font-size="12.5" font-weight="700" fill="#C0392B">Không overlap — câu bị cắt đôi</text>
<rect x="20" y="36" width="200" height="30" rx="4" fill="#EAF2FC" stroke="#4A90D9"/>
<rect x="222" y="36" width="200" height="30" rx="4" fill="#EAF2FC" stroke="#4A90D9"/>
<rect x="424" y="36" width="200" height="30" rx="4" fill="#EAF2FC" stroke="#4A90D9"/>
<text x="120" y="55" font-size="11" text-anchor="middle">đoạn 1</text>
<text x="322" y="55" font-size="11" text-anchor="middle">đoạn 2</text>
<text x="524" y="55" font-size="11" text-anchor="middle">đoạn 3</text>
<line x1="221" y1="30" x2="221" y2="72" stroke="#C0392B" stroke-width="2"/>
<text x="228" y="82" font-size="10.5" fill="#C0392B">"Mức phụ cấp là | 2 triệu/tháng" — mất vế sau</text>
<text x="20" y="110" font-size="12.5" font-weight="700" fill="#1B7A3D">Có overlap — câu nào cũng trọn ở ít nhất 1 đoạn</text>
<rect x="20" y="118" width="210" height="26" rx="4" fill="#E8F5EC" stroke="#1B7A3D"/>
<rect x="196" y="118" width="210" height="26" rx="4" fill="#E8F5EC" stroke="#1B7A3D"
opacity=".75"/>
<rect x="372" y="118" width="210" height="26" rx="4" fill="#E8F5EC" stroke="#1B7A3D"
opacity=".55"/>
<rect x="196" y="118" width="34" height="26" fill="#1B7A3D" opacity=".2"/>
<rect x="372" y="118" width="34" height="26" fill="#1B7A3D" opacity=".2"/>
<text x="600" y="136" font-size="10.5" fill="#1B7A3D">phần tô đậm = chồng lấn</text>
</svg>
<figcaption>Overlap là bảo hiểm cho những câu nằm vắt ngang ranh giới đoạn.</figcaption>
</figure>
<p>Cắt cứng theo số chữ sẽ có lúc cắt <b>giữa một câu hoặc giữa một ý</b>. Đoạn nào cũng
lặp lại một phần đoạn trước thì thông tin ở ranh giới luôn còn nguyên vẹn ở ít nhất một đoạn.</p>
<p>Giá phải trả: kho phình thêm đúng bằng tỉ lệ overlap. 20% overlap → nhiều hơn ~20% vector.</p>
</div></div>
<div class="qa" id="q7"><div class="q"><span class="n">7</span>
top-K nên đặt bao nhiêu?</div>
<div class="a">
<p>Thường <b>3 – 10</b>. Cách chọn:</p>
<ul>
<li><b>K nhỏ (3–5)</b> — câu hỏi tra cứu một dữ kiện. Ít nhiễu, rẻ, nhanh.</li>
<li><b>K lớn (8–15)</b> — câu hỏi tổng hợp, cần gom nhiều nguồn.</li>
</ul>
<div class="note warn">K càng lớn <b>không</b> đồng nghĩa càng chính xác. Đoạn thứ 15 thường
đã lạc đề, và nó <i>làm loãng</i> ngữ cảnh khiến LLM trả lời kém đi — hiện tượng
"lạc giữa đống tài liệu".</div>
<p>Thực dụng hơn: đặt <b>ngưỡng điểm tương đồng</b> thay vì K cố định — lấy mọi đoạn trên
ngưỡng, không có đoạn nào đạt thì trả lời "không tìm thấy".</p>
</div></div>
<div class="qa" id="q8"><div class="q"><span class="n">8</span>
Chọn mô hình embedding thế nào? Tiếng Việt có ổn không?</div>
<div class="a">
<p>Ba tiêu chí: <b>hỗ trợ tiếng Việt</b>, <b>số chiều</b>, <b>chạy nội bộ hay gọi API</b>.</p>
<table>
<tr><th>Nhóm</th><th>Ví dụ</th><th>Ghi chú</th></tr>
<tr><td>API thương mại</td><td>OpenAI <code>text-embedding-3</code>, Cohere</td>
<td>Chất lượng tốt, nhưng <b>tài liệu phải gửi ra ngoài</b></td></tr>
<tr><td>Đa ngữ, chạy nội bộ</td><td>multilingual-e5, BGE-M3</td>
<td>Tiếng Việt khá tốt, chạy được trên máy công ty</td></tr>
<tr><td>Chuyên tiếng Việt</td><td>PhoBERT và các bản fine-tune</td>
<td>Cần đánh giá lại trên chính dữ liệu của mình</td></tr>
</table>
<div class="note bad"><b>Lưu ý bắt buộc:</b> đổi mô hình embedding thì
<b>phải index lại toàn bộ kho</b>. Vector của mô hình này không so sánh được với vector của
mô hình khác. Nên chọn kỹ ngay từ đầu.</div>
<p>Với dữ liệu nội bộ nhạy cảm, nhóm "chạy nội bộ" thường là lựa chọn duy nhất khả thi.</p>
</div></div>
<div class="qa" id="q9"><div class="q"><span class="n">9</span>
Bắt buộc phải có Vector DB riêng không?</div>
<div class="a">
<p><b>Không.</b> Chọn theo quy mô:</p>
<table>
<tr><th>Quy mô</th><th>Giải pháp</th><th>Ghi chú</th></tr>
<tr><td>&lt; 100k vector</td><td>FAISS, Chroma, hoặc file numpy</td>
<td>Không cần dựng thêm dịch vụ</td></tr>
<tr><td>Đã có PostgreSQL</td><td><code>pgvector</code></td>
<td>Dùng luôn DB sẵn có — thường là lựa chọn tốt nhất</td></tr>
<tr><td>Triệu vector trở lên</td><td>Milvus, Qdrant, Weaviate</td>
<td>Cần index ANN chuyên dụng</td></tr>
<tr><td>Không muốn tự vận hành</td><td>Pinecone</td>
<td>Dịch vụ đám mây, dữ liệu ra ngoài</td></tr>
</table>
<p>Ví dụ trong slide — 100 file PDF ra 20.000 vector — <b>hoàn toàn không cần</b> Vector DB
chuyên dụng. FAISS trên một máy là đủ và nhanh.</p>
</div></div>
<h2>Nhóm 3 — Chất lượng truy hồi</h2>
<div class="qa" id="q10"><div class="q"><span class="n">10</span>
Chỉ tìm theo vector đã đủ chưa?</div>
<div class="a">
<figure>
<svg viewBox="0 0 720 168" role="img" aria-label="Hybrid search và rerank">
<rect x="14" y="52" width="98" height="42" rx="6" fill="#fff" stroke="#4A90D9"/>
<text x="63" y="70" font-size="12" text-anchor="middle">Câu hỏi</text>
<text x="63" y="85" font-size="10" text-anchor="middle" fill="#5A6675">của user</text>
<path d="M116 73 h26" stroke="#5A6675" stroke-width="1.6" marker-end="url(#a2)"/>
<rect x="146" y="20" width="128" height="42" rx="6" fill="#EAF2FC" stroke="#1565C0"/>
<text x="210" y="38" font-size="12" text-anchor="middle" fill="#0A4EA3">Tìm theo vector</text>
<text x="210" y="52" font-size="10" text-anchor="middle" fill="#5A6675">bắt được ý nghĩa</text>
<rect x="146" y="84" width="128" height="42" rx="6" fill="#FDF3E3" stroke="#B26A00"/>
<text x="210" y="102" font-size="12" text-anchor="middle" fill="#8A5000">Tìm theo từ khoá</text>
<text x="210" y="116" font-size="10" text-anchor="middle" fill="#5A6675">bắt mã, tên riêng</text>
<path d="M278 41 h20 v32" stroke="#5A6675" stroke-width="1.6" fill="none"/>
<path d="M278 105 h20 v-32" stroke="#5A6675" stroke-width="1.6" fill="none"
marker-end="url(#a2)"/>
<rect x="318" y="52" width="104" height="42" rx="6" fill="#fff" stroke="#4A90D9"/>
<text x="370" y="70" font-size="12" text-anchor="middle">Gộp kết quả</text>
<text x="370" y="85" font-size="10" text-anchor="middle" fill="#5A6675">~30 đoạn</text>
<path d="M426 73 h26" stroke="#5A6675" stroke-width="1.6" marker-end="url(#a2)"/>
<rect x="456" y="52" width="110" height="42" rx="6" fill="#1565C0"/>
<text x="511" y="70" font-size="12" text-anchor="middle" fill="#fff">Rerank</text>
<text x="511" y="85" font-size="10" text-anchor="middle" fill="#D6E7F8">chấm lại điểm</text>
<path d="M570 73 h26" stroke="#5A6675" stroke-width="1.6" marker-end="url(#a2)"/>
<rect x="600" y="52" width="104" height="42" rx="6" fill="#E8F5EC" stroke="#1B7A3D"/>
<text x="652" y="70" font-size="12" text-anchor="middle" fill="#14612F">Top 5 tinh</text>
<text x="652" y="85" font-size="10" text-anchor="middle" fill="#5A6675">đưa cho LLM</text>
<defs><marker id="a2" markerWidth="7" markerHeight="7" refX="6" refY="3.5" orient="auto">
<path d="M0 0 L7 3.5 L0 7 z" fill="#5A6675"/></marker></defs>
</svg>
<figcaption>Hai cách tìm bù khuyết cho nhau, rồi lọc lại một lần nữa.</figcaption>
</figure>
<p><b>Chưa đủ.</b> Vector giỏi bắt ý nghĩa nhưng <b>dở với mã số, tên riêng, ký hiệu</b> —
hỏi "điều 7.5.3" hay "mã lỗi FN0101" thì tìm từ khoá lại chính xác hơn hẳn.</p>
<p>Hai cải tiến gần như luôn đáng làm:</p>
<ul>
<li><b>Hybrid search</b> — chạy song song vector + từ khoá (BM25), gộp kết quả.</li>
<li><b>Rerank</b> — lấy ~30 đoạn rồi dùng mô hình cross-encoder chấm lại, giữ 5 đoạn tốt nhất.
Đây thường là <b>cải thiện lớn nhất</b> với chi phí nhỏ nhất.</li>
</ul>
</div></div>
<div class="qa" id="q11"><div class="q"><span class="n">11</span>
Câu hỏi cần nối nhiều tài liệu (multi-hop) thì sao?</div>
<div class="a">
<p>Slide đã nêu đúng đây là điểm yếu. Ví dụ: <i>"Nhân viên nào ký hợp đồng với nhà cung cấp
có doanh số cao nhất năm ngoái?"</i> — cần tra bảng doanh số trước, rồi mới tra hợp đồng.</p>
<p>RAG một lượt sẽ hỏng, vì một lần tra không thể ra cả hai. Ba hướng xử lý:</p>
<ul>
<li><b>Tra nhiều vòng (agentic RAG)</b> — cho LLM tự quyết định tra tiếp, dùng kết quả vòng
trước làm câu truy vấn vòng sau.</li>
<li><b>Tách câu hỏi</b> — chia thành các câu con, tra từng câu, rồi tổng hợp.</li>
<li><b>Knowledge graph</b> — dựng sẵn quan hệ giữa các thực thể để đi theo liên kết thay vì
tra lại từ đầu. Đây chính là ý tưởng của GraphRAG.</li>
</ul>
</div></div>
<h2>Nhóm 4 — Vận hành</h2>
<div class="qa" id="q12"><div class="q"><span class="n">12</span>
Context window đã tới 1 triệu token — còn cần RAG không?</div>
<div class="a">
<p><b>Vẫn cần</b>, vì ba lý do:</p>
<ul>
<li><b>Chi phí</b> — nhét 500k token vào mỗi câu hỏi thì mỗi lượt hỏi tốn gấp hàng trăm lần
so với nhét 5 đoạn. Nhân với số lượt hỏi mỗi ngày.</li>
<li><b>Độ trễ</b> — đọc 500k token mất hàng chục giây.</li>
<li><b>Quy mô</b> — kho tài liệu doanh nghiệp thường vài chục triệu token, vượt xa mọi
context window.</li>
</ul>
<div class="note">Thêm nữa, độ chính xác <b>giảm khi ngữ cảnh quá dài</b> — mô hình hay bỏ sót
thông tin nằm ở giữa. Đưa 5 đoạn đúng thường cho kết quả tốt hơn đưa cả cuốn sách.</div>
<p>Context dài <i>có</i> chỗ dùng: khi tổng tài liệu nhỏ (vài chục trang) và bạn muốn giải pháp
đơn giản nhất — lúc đó bỏ RAG cho gọn là hợp lý.</p>
</div></div>
<div class="qa" id="q13"><div class="q"><span class="n">13</span>
Chi phí thực tế bao nhiêu?</div>
<div class="a">
<p>Tách làm hai phần, và phần đắt <b>không</b> phải phần người ta hay lo:</p>
<table>
<tr><th>Khoản</th><th>Khi nào phát sinh</th><th>Mức độ</th></tr>
<tr><td>Embedding tài liệu</td><td>Một lần lúc index + khi tài liệu đổi</td>
<td><b>Rẻ</b> — embedding rẻ hơn LLM hàng chục lần</td></tr>
<tr><td>Lưu trữ vector</td><td>Liên tục</td><td>Nhỏ, trừ khi kho cực lớn</td></tr>
<tr><td>Embedding câu hỏi</td><td>Mỗi lượt hỏi</td><td>Không đáng kể</td></tr>
<tr><td><b>LLM sinh câu trả lời</b></td><td>Mỗi lượt hỏi</td>
<td><b>Chiếm phần lớn chi phí</b></td></tr>
</table>
<p>Vì vậy giảm chi phí RAG thực chất là <b>giảm số token đưa vào LLM</b> — tức chọn top-K
gọn và đoạn sạch, chứ không phải tiết kiệm ở khâu embedding.</p>
</div></div>
<div class="qa" id="q14"><div class="q"><span class="n">14</span>
RAG làm chậm thêm bao nhiêu?</div>
<div class="a">
<p>Bước tra thường tốn <b>vài chục tới vài trăm mili-giây</b>: embedding câu hỏi + tìm trong
vector DB. Có rerank thì cộng thêm chút nữa.</p>
<p>So với thời gian LLM sinh câu trả lời (thường vài giây), phần này <b>gần như không đáng kể</b>.</p>
<div class="note warn">Slide ghi "ứng dụng real-time cần &lt; 100ms" thì nên cẩn trọng —
đúng, nhưng lúc đó nút thắt là <b>LLM</b>, không phải bước tra. Nếu cần dưới 100ms thì
bản thân việc gọi LLM đã không khả thi rồi.</div>
</div></div>
<div class="qa" id="q15"><div class="q"><span class="n">15</span>
Tài liệu sửa thì cập nhật thế nào?</div>
<div class="a">
<p>Chỉ cần <b>index lại phần thay đổi</b>, không đụng tới mô hình:</p>
<ul>
<li>File sửa → xoá vector cũ của file đó, embedding lại, ghi vector mới.</li>
<li>File xoá → xoá vector tương ứng.</li>
<li>File mới → embedding và thêm vào.</li>
</ul>
<p>Cách làm thực dụng: lưu kèm <b>hash nội dung</b> mỗi file, chạy định kỳ, chỉ xử lý file
có hash đổi. Vài giây cho một lần cập nhật thông thường.</p>
<div class="note bad">Ngoại lệ duy nhất phải làm lại toàn bộ: <b>đổi mô hình embedding</b>
hoặc <b>đổi cách chia đoạn</b>.</div>
</div></div>
<div class="qa" id="q16"><div class="q"><span class="n">16</span>
Đo chất lượng RAG bằng gì? Làm sao biết là tốt?</div>
<div class="a">
<p>Điểm mấu chốt: <b>đo tách hai khâu</b>, vì hỏng ở đâu thì sửa ở đó khác nhau.</p>
<table>
<tr><th>Khâu</th><th>Đo gì</th><th>Hỏng thì sửa gì</th></tr>
<tr><td><b>Truy hồi</b></td><td>Đoạn đúng có nằm trong top-K không?</td>
<td>Chia đoạn, mô hình embedding, hybrid, rerank</td></tr>
<tr><td><b>Sinh câu trả lời</b></td><td>Câu trả lời có bám vào đoạn đã lấy không?</td>
<td>Prompt, model, yêu cầu trích nguồn</td></tr>
</table>
<p>Cách làm tối thiểu mà hiệu quả: dựng <b>bộ 50–100 câu hỏi mẫu có đáp án đúng</b> lấy từ
người dùng thật. Mỗi lần chỉnh tham số thì chạy lại bộ đó và so điểm.</p>
<div class="note">Không có bộ câu hỏi mẫu thì mọi tinh chỉnh chỉ là cảm tính — đây là việc
nên làm ngay từ đầu, trước cả khi tối ưu.</div>
</div></div>
<div class="qa" id="q17"><div class="q"><span class="n">17</span>
Phân quyền tài liệu xử lý ra sao? Người A không được xem tài liệu của phòng B.</div>
<div class="a">
<p>Đây là câu hay bị bỏ quên tới lúc triển khai thật mới lộ ra.</p>
<p><b>Nguyên tắc: lọc quyền ở bước truy hồi, không phải ở bước trả lời.</b> Tuyệt đối không
dựa vào việc nhắc LLM "đừng nói về tài liệu này" — không đáng tin.</p>
<ul>
<li>Mỗi vector lưu kèm <b>metadata quyền</b> (phòng ban, mức mật, danh sách người xem).</li>
<li>Khi tra, lọc theo quyền của người hỏi <b>ngay trong truy vấn</b>.</li>
<li>Tài liệu ngoài quyền thì không bao giờ vào được ngữ cảnh của LLM.</li>
</ul>
<div class="note bad">Rủi ro thường gặp: một đoạn trích chứa thông tin mật lọt vào ngữ cảnh,
LLM tóm tắt lại và <b>rò rỉ gián tiếp</b> dù không trích nguyên văn.</div>
</div></div>
<h2>Nhóm 5 — Về dự án Cowork-Local</h2>
<p class="lead">Nhóm này gần như chắc chắn được hỏi, vì slide 17 đã tự nêu ra.</p>
<div class="qa" id="q18"><div class="q"><span class="n">18</span>
Vậy Cowork-Local đã có RAG chưa?</div>
<div class="a">
<p>Trả lời thẳng như slide 17 đã viết: <b>chưa có RAG theo nghĩa đầy đủ.</b></p>
<figure>
<svg viewBox="0 0 720 150" role="img" aria-label="Ba mức nạp ngữ cảnh">
<rect x="10" y="24" width="222" height="104" rx="8" fill="#FDF3E3" stroke="#B26A00"/>
<text x="121" y="48" font-size="13" font-weight="700" text-anchor="middle" fill="#8A5000">
Mức 1 — Nạp thủ công</text>
<text x="121" y="70" font-size="11.5" text-anchor="middle" fill="#2B3542">Đính kèm file, dán link,</text>
<text x="121" y="86" font-size="11.5" text-anchor="middle" fill="#2B3542">Instructions của project</text>
<text x="121" y="110" font-size="11" text-anchor="middle" fill="#8A5000">Người dùng tự chọn</text>
<rect x="248" y="24" width="222" height="104" rx="8" fill="#EAF2FC" stroke="#1565C0"/>
<text x="359" y="48" font-size="13" font-weight="700" text-anchor="middle" fill="#0A4EA3">
Mức 2 — Tra theo cấu trúc</text>
<text x="359" y="70" font-size="11.5" text-anchor="middle" fill="#2B3542">GraphRAG: sơ đồ file,</text>
<text x="359" y="86" font-size="11.5" text-anchor="middle" fill="#2B3542">lớp, hàm, quan hệ</text>
<text x="359" y="110" font-size="11" text-anchor="middle" fill="#0A4EA3">AI tự tra — đang ở đây</text>
<rect x="486" y="24" width="224" height="104" rx="8" fill="#F2F4F7" stroke="#CBD5E1"
stroke-dasharray="5 4"/>
<text x="598" y="48" font-size="13" font-weight="700" text-anchor="middle" fill="#5A6675">
Mức 3 — Tra theo ngữ nghĩa</text>
<text x="598" y="70" font-size="11.5" text-anchor="middle" fill="#5A6675">Embedding + Vector DB</text>
<text x="598" y="86" font-size="11.5" text-anchor="middle" fill="#5A6675">tìm theo nghĩa</text>
<text x="598" y="110" font-size="11" text-anchor="middle" fill="#8A94A3">chưa có</text>
</svg>
<figcaption>Dự án đang ở mức 2. Mức 3 mới là RAG như trình bày ở phần đầu.</figcaption>
</figure>
<p>Cách nói an toàn khi bị hỏi vặn: <i>"Hiện tại là truy xuất theo cấu trúc, chưa phải truy xuất
theo ngữ nghĩa. Phần trình bày hôm nay là kiến thức nền cho bước tiếp theo."</i></p>
</div></div>
<div class="qa" id="q19"><div class="q"><span class="n">19</span>
"GraphRAG" của dự án có phải GraphRAG của Microsoft không?</div>
<div class="a">
<div class="note warn"><b>Câu này rất dễ bị hỏi và dễ gây hiểu nhầm — nên chủ động làm rõ trước.</b></div>
<table>
<tr><th></th><th>GraphRAG (Microsoft)</th><th>GraphRAG trong Cowork-Local</th></tr>
<tr><td>Đồ thị chứa gì</td><td>Thực thể và quan hệ do <b>LLM trích</b> từ nội dung</td>
<td>File, lớp, hàm và liên kết import</td></tr>
<tr><td>Dựng bằng gì</td><td>Gọi LLM nhiều lượt, tốn chi phí</td>
<td>Phân tích cú pháp mã nguồn, <b>không tốn phí gọi AI</b></td></tr>
<tr><td>Trả lời câu hỏi</td><td>Đi theo quan hệ + tóm tắt theo cụm</td>
<td>Đọc sơ đồ và nội dung file liên quan</td></tr>
</table>
<p><b>Cùng tên, khác bản chất.</b> Slide của bạn mô tả đúng cái thứ hai — "quét file, ghi nhận
mỗi file có class/hàm gì và liên kết với file nào".</p>
<p>Nói rõ điểm này lại là <b>lợi thế</b>: cách của dự án <i>rẻ và nhanh hơn nhiều</i> vì không
phải gọi LLM để dựng đồ thị.</p>
</div></div>
<div class="qa" id="q20"><div class="q"><span class="n">20</span>
Muốn nâng lên RAG đầy đủ thì cần làm gì?</div>
<div class="a">
<p>Bốn việc, xếp theo thứ tự nên làm:</p>
<table>
<tr><th>#</th><th>Việc</th><th>Quyết định phải chốt</th></tr>
<tr><td>1</td><td>Chọn mô hình embedding</td>
<td>Chạy nội bộ hay gọi API — quyết định này ràng buộc mọi thứ sau, và
<b>đổi về sau là phải index lại toàn bộ</b></td></tr>
<tr><td>2</td><td>Chia đoạn tài liệu</td>
<td>Cắt theo cấu trúc (mục, điều, hàm) trước khi cắt theo độ dài</td></tr>
<tr><td>3</td><td>Chọn nơi lưu vector</td>
<td>Quy mô hiện tại chỉ cần FAISS hoặc <code>pgvector</code></td></tr>
<tr><td>4</td><td>Dựng bộ câu hỏi đánh giá</td>
<td>50–100 câu có đáp án đúng — <b>làm trước khi tối ưu</b></td></tr>
</table>
<div class="note ok"><b>Điểm mạnh sẵn có:</b> dự án đã có sẵn khái niệm <i>project</i> với
thư mục riêng và phân tách dữ liệu theo project. Đó chính là ranh giới phân quyền tự nhiên
cho câu 17 — thứ mà nhiều dự án phải làm lại từ đầu.</div>
</div></div>
<h2>Ba câu nên chuẩn bị sẵn câu trả lời</h2>
<div class="note bad"><b>1. "RAG có hết bịa không?"</b> → Không, chỉ giảm. Nói thẳng và nêu
cách giảm: bắt trích nguồn, cho phép trả lời "không tìm thấy".</div>
<div class="note bad"><b>2. "GraphRAG này có phải GraphRAG kia không?"</b> → Không, cùng tên
khác bản chất. Chủ động nói trước khi bị hỏi.</div>
<div class="note bad"><b>3. "Vậy dự án đã có RAG chưa?"</b> → Chưa đủ. Đang ở mức truy xuất
theo cấu trúc, chưa có truy xuất theo ngữ nghĩa.</div>
</div>
</body>
</html>
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+542
View File
@@ -0,0 +1,542 @@
[
{
"slug": "dashboard",
"title": "Dashboard",
"theme": "dark",
"note": "ui/dashboard_tab.py:35",
"file": "screens/dashboard-dark.png",
"error": "",
"nav": "Dashboard",
"nav_expected": "Dashboard"
},
{
"slug": "schedule-kanban",
"title": "Schedule Task — Kanban",
"theme": "dark",
"note": "ui/schedule_task_tab.py:70",
"file": "screens/schedule-kanban-dark.png",
"error": "",
"nav": "Schedule Task",
"nav_expected": "Schedule Task"
},
{
"slug": "schedule-calendar",
"title": "Schedule Task — Calendar",
"theme": "dark",
"note": "ui/calendar_view.py:88",
"file": "screens/schedule-calendar-dark.png",
"error": "",
"nav": "Schedule Task",
"nav_expected": "Schedule Task"
},
{
"slug": "workspace-project",
"title": "Workspace ▸ Project",
"theme": "dark",
"note": "ui/workspace_tab.py:188",
"file": "screens/workspace-project-dark.png",
"error": "",
"nav": "Workspace",
"nav_expected": "Workspace"
},
{
"slug": "workspace-cowork",
"title": "Workspace ▸ Cowork",
"theme": "dark",
"note": "ui/cowork_tab.py:21",
"file": "screens/workspace-cowork-dark.png",
"error": "",
"nav": "Cowork",
"nav_expected": "Cowork"
},
{
"slug": "workspace-co4e",
"title": "Workspace ▸ Co4E",
"theme": "dark",
"note": "ui/co4e_tab.py:228",
"file": "screens/workspace-co4e-dark.png",
"error": "",
"nav": "Co4E",
"nav_expected": "Co4E"
},
{
"slug": "workspace-folder",
"title": "Workspace ▸ Folder",
"theme": "dark",
"note": "ui/folder_tab.py:238",
"file": "screens/workspace-folder-dark.png",
"error": "",
"nav": "Thư mục",
"nav_expected": "Thư mục"
},
{
"slug": "workspace-graphrag",
"title": "Workspace ▸ GraphRAG",
"theme": "dark",
"note": "ui/structure_graph_view.py:188",
"file": "screens/workspace-graphrag-dark.png",
"error": "",
"nav": "GraphRAG",
"nav_expected": "GraphRAG"
},
{
"slug": "monitoring-tổng-quan",
"title": "Monitoring ▸ Tổng quan",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-tổng-quan-dark.png",
"error": "",
"nav": "Tổng quan",
"nav_expected": "Tổng quan"
},
{
"slug": "monitoring-sự-kiện-bảo-mật",
"title": "Monitoring ▸ Sự kiện bảo mật",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-sự-kiện-bảo-mật-dark.png",
"error": "",
"nav": "Sự kiện bảo mật",
"nav_expected": "Sự kiện bảo mật"
},
{
"slug": "monitoring-lịch-sử-gọi-mcp",
"title": "Monitoring ▸ Lịch sử gọi MCP",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-lịch-sử-gọi-mcp-dark.png",
"error": "",
"nav": "Lịch sử gọi MCP",
"nav_expected": "Lịch sử gọi MCP"
},
{
"slug": "monitoring-nhật-ký-hành-động",
"title": "Monitoring ▸ Nhật ký hành động",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-nhật-ký-hành-động-dark.png",
"error": "",
"nav": "Nhật ký hành động",
"nav_expected": "Nhật ký hành động"
},
{
"slug": "monitoring-trạng-thái-agent",
"title": "Monitoring ▸ Trạng thái Agent",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-trạng-thái-agent-dark.png",
"error": "",
"nav": "Trạng thái Agent",
"nav_expected": "Trạng thái Agent"
},
{
"slug": "monitoring-agents-admin",
"title": "Monitoring ▸ Agents Admin",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-agents-admin-dark.png",
"error": "",
"nav": "Agents Admin",
"nav_expected": "Agents Admin"
},
{
"slug": "monitoring-công-cụ",
"title": "Monitoring ▸ Công cụ",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-công-cụ-dark.png",
"error": "",
"nav": "Công cụ",
"nav_expected": "Công cụ"
},
{
"slug": "monitoring-icon",
"title": "Monitoring ▸ Icon",
"theme": "dark",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-icon-dark.png",
"error": "",
"nav": "Icon",
"nav_expected": "Icon"
},
{
"slug": "dialog-settings",
"title": "Settings",
"theme": "dark",
"note": "ui/settings_dialog.py:26",
"file": "screens/dialog-settings-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-task-editor",
"title": "Task Editor",
"theme": "dark",
"note": "ui/task_editor_dialog.py:55",
"file": "screens/dialog-task-editor-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-skills",
"title": "Skills manager",
"theme": "dark",
"note": "ui/skills_dialog.py:108",
"file": "screens/dialog-skills-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-skill-edit",
"title": "Skill editor",
"theme": "dark",
"note": "ui/skills_dialog.py:23",
"file": "screens/dialog-skill-edit-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-file-edit",
"title": "File view & AI edit",
"theme": "dark",
"note": "ui/file_edit_dialog.py:50",
"file": "screens/dialog-file-edit-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-co4e-agent",
"title": "Co4E agent editor",
"theme": "dark",
"note": "ui/co4e_agent_dialog.py:23",
"file": "screens/dialog-co4e-agent-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-ext-connector",
"title": "External connector",
"theme": "dark",
"note": "ui/ext_connector_dialog.py:23",
"file": "screens/dialog-ext-connector-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-permission",
"title": "Permission request",
"theme": "dark",
"note": "ui/permission_dialog.py:13",
"file": "screens/dialog-permission-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-agent-edit",
"title": "Admin agent editor",
"theme": "dark",
"note": "ui/agents_admin_tab.py:35",
"file": "screens/dialog-agent-edit-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-login",
"title": "Login (dead screen — not wired)",
"theme": "dark",
"note": "ui/login_dialog.py:57",
"file": "screens/dialog-login-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "overlay-help-panel",
"title": "Help dock — expanded panel",
"theme": "dark",
"note": "ui/help_agent_widget.py:79",
"file": "screens/overlay-help-panel-dark.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dashboard",
"title": "Dashboard",
"theme": "light",
"note": "ui/dashboard_tab.py:35",
"file": "screens/dashboard-light.png",
"error": "",
"nav": "Dashboard",
"nav_expected": "Dashboard"
},
{
"slug": "schedule-kanban",
"title": "Schedule Task — Kanban",
"theme": "light",
"note": "ui/schedule_task_tab.py:70",
"file": "screens/schedule-kanban-light.png",
"error": "",
"nav": "Schedule Task",
"nav_expected": "Schedule Task"
},
{
"slug": "schedule-calendar",
"title": "Schedule Task — Calendar",
"theme": "light",
"note": "ui/calendar_view.py:88",
"file": "screens/schedule-calendar-light.png",
"error": "",
"nav": "Schedule Task",
"nav_expected": "Schedule Task"
},
{
"slug": "workspace-project",
"title": "Workspace ▸ Project",
"theme": "light",
"note": "ui/workspace_tab.py:188",
"file": "screens/workspace-project-light.png",
"error": "",
"nav": "Workspace",
"nav_expected": "Workspace"
},
{
"slug": "workspace-cowork",
"title": "Workspace ▸ Cowork",
"theme": "light",
"note": "ui/cowork_tab.py:21",
"file": "screens/workspace-cowork-light.png",
"error": "",
"nav": "Cowork",
"nav_expected": "Cowork"
},
{
"slug": "workspace-co4e",
"title": "Workspace ▸ Co4E",
"theme": "light",
"note": "ui/co4e_tab.py:228",
"file": "screens/workspace-co4e-light.png",
"error": "",
"nav": "Co4E",
"nav_expected": "Co4E"
},
{
"slug": "workspace-folder",
"title": "Workspace ▸ Folder",
"theme": "light",
"note": "ui/folder_tab.py:238",
"file": "screens/workspace-folder-light.png",
"error": "",
"nav": "Thư mục",
"nav_expected": "Thư mục"
},
{
"slug": "workspace-graphrag",
"title": "Workspace ▸ GraphRAG",
"theme": "light",
"note": "ui/structure_graph_view.py:188",
"file": "screens/workspace-graphrag-light.png",
"error": "",
"nav": "GraphRAG",
"nav_expected": "GraphRAG"
},
{
"slug": "monitoring-tổng-quan",
"title": "Monitoring ▸ Tổng quan",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-tổng-quan-light.png",
"error": "",
"nav": "Tổng quan",
"nav_expected": "Tổng quan"
},
{
"slug": "monitoring-sự-kiện-bảo-mật",
"title": "Monitoring ▸ Sự kiện bảo mật",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-sự-kiện-bảo-mật-light.png",
"error": "",
"nav": "Sự kiện bảo mật",
"nav_expected": "Sự kiện bảo mật"
},
{
"slug": "monitoring-lịch-sử-gọi-mcp",
"title": "Monitoring ▸ Lịch sử gọi MCP",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-lịch-sử-gọi-mcp-light.png",
"error": "",
"nav": "Lịch sử gọi MCP",
"nav_expected": "Lịch sử gọi MCP"
},
{
"slug": "monitoring-nhật-ký-hành-động",
"title": "Monitoring ▸ Nhật ký hành động",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-nhật-ký-hành-động-light.png",
"error": "",
"nav": "Nhật ký hành động",
"nav_expected": "Nhật ký hành động"
},
{
"slug": "monitoring-trạng-thái-agent",
"title": "Monitoring ▸ Trạng thái Agent",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-trạng-thái-agent-light.png",
"error": "",
"nav": "Trạng thái Agent",
"nav_expected": "Trạng thái Agent"
},
{
"slug": "monitoring-agents-admin",
"title": "Monitoring ▸ Agents Admin",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-agents-admin-light.png",
"error": "",
"nav": "Agents Admin",
"nav_expected": "Agents Admin"
},
{
"slug": "monitoring-công-cụ",
"title": "Monitoring ▸ Công cụ",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-công-cụ-light.png",
"error": "",
"nav": "Công cụ",
"nav_expected": "Công cụ"
},
{
"slug": "monitoring-icon",
"title": "Monitoring ▸ Icon",
"theme": "light",
"note": "ui/monitoring_tab.py:132",
"file": "screens/monitoring-icon-light.png",
"error": "",
"nav": "Icon",
"nav_expected": "Icon"
},
{
"slug": "dialog-settings",
"title": "Settings",
"theme": "light",
"note": "ui/settings_dialog.py:26",
"file": "screens/dialog-settings-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-task-editor",
"title": "Task Editor",
"theme": "light",
"note": "ui/task_editor_dialog.py:55",
"file": "screens/dialog-task-editor-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-skills",
"title": "Skills manager",
"theme": "light",
"note": "ui/skills_dialog.py:108",
"file": "screens/dialog-skills-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-skill-edit",
"title": "Skill editor",
"theme": "light",
"note": "ui/skills_dialog.py:23",
"file": "screens/dialog-skill-edit-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-file-edit",
"title": "File view & AI edit",
"theme": "light",
"note": "ui/file_edit_dialog.py:50",
"file": "screens/dialog-file-edit-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-co4e-agent",
"title": "Co4E agent editor",
"theme": "light",
"note": "ui/co4e_agent_dialog.py:23",
"file": "screens/dialog-co4e-agent-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-ext-connector",
"title": "External connector",
"theme": "light",
"note": "ui/ext_connector_dialog.py:23",
"file": "screens/dialog-ext-connector-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-permission",
"title": "Permission request",
"theme": "light",
"note": "ui/permission_dialog.py:13",
"file": "screens/dialog-permission-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-agent-edit",
"title": "Admin agent editor",
"theme": "light",
"note": "ui/agents_admin_tab.py:35",
"file": "screens/dialog-agent-edit-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "dialog-login",
"title": "Login (dead screen — not wired)",
"theme": "light",
"note": "ui/login_dialog.py:57",
"file": "screens/dialog-login-light.png",
"error": "",
"nav": "",
"nav_expected": ""
},
{
"slug": "overlay-help-panel",
"title": "Help dock — expanded panel",
"theme": "light",
"note": "ui/help_agent_widget.py:79",
"file": "screens/overlay-help-panel-light.png",
"error": "",
"nav": "",
"nav_expected": ""
}
]
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

+1175
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+166 -33
View File
@@ -178,9 +178,27 @@ STRINGS: Dict[str, Dict[str, str]] = {
"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"},
# 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": {
"en": "Select a project first", "ja": "先にプロジェクトを選択してください",
"vi": "Chọn project trước"},
# Rail header: the project a new chat will be created in, and what to do
# when there is no project yet.
"app.nav.project_pick": {
"en": "Project for new chats", "ja": "新しいチャットのプロジェクト",
"vi": "Project cho đoạn chat mới"},
"app.nav.no_project": {
"en": "No project yet", "ja": "プロジェクトなし", "vi": "Chưa có project"},
"app.nav.recents": {"en": "RECENTS", "ja": "最近", "vi": "GẦN ĐÂY"},
"app.nav.all_projects": {
"en": "All projects…", "ja": "すべてのプロジェクト…", "vi": "Tất cả project…"},
"app.nav.create_project_first": {
"en": "Create a project first", "ja": "先にプロジェクトを作成してください",
"vi": "Tạo project trước"},
# ---- workspace_tab.py (Projects — Claude-Projects style) -----------
"workspace.header": {"en": "Workspace — Projects", "ja": "ワークスペース — プロジェクト", "vi": "Workspace — Projects"},
"workspace.header": {"en": "Manage projects", "ja": "プロジェクト管理", "vi": "Quản lý project"},
"workspace.tab_cowork": {"en": "Cowork", "ja": "Cowork", "vi": "Cowork"},
"workspace.tab_graphrag": {"en": "GraphRAG", "ja": "GraphRAG", "vi": "GraphRAG"},
"workspace.tab_project": {"en": "Project", "ja": "プロジェクト", "vi": "Project"},
@@ -360,6 +378,12 @@ STRINGS: Dict[str, Dict[str, str]] = {
"các file đặt ở gốc thư mục đó (project knowledge)."),
},
"workspace.new_project": {"en": "New project", "ja": "新規プロジェクト", "vi": "Project mới"},
"workspace.projects_heading": {"en": "PROJECTS", "ja": "プロジェクト", "vi": "PROJECT"},
"workspace.folder_label": {"en": "Workspace folder", "ja": "作業フォルダ", "vi": "Thư mục làm việc"},
"workspace.counts": {
"en": "{chats} chats · {tasks} tasks",
"ja": "チャット {chats} · タスク {tasks}",
"vi": "{chats} đoạn chat · {tasks} task"},
"workspace.delete": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"workspace.delete_confirm": {
"en": "Delete project “{name}”? Its conversations and files are kept (threads move to General).",
@@ -373,19 +397,19 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Project của hội thoại này không còn tồn tại — không thể mở."},
"workspace.name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"workspace.description": {"en": "Description", "ja": "説明", "vi": "Mô tả"},
"workspace.instructions": {"en": "Instructions (shared project context)", "ja": "指示(プロジェクト共有コンテキスト)", "vi": "Instructions (ngữ cảnh chung của project)"},
"workspace.instructions": {"en": "Instructions", "ja": "Instructions", "vi": "Instructions"},
"workspace.instructions_placeholder": {
"en": "e.g. \"All answers in Vietnamese. We are building the X reporting tool; always follow the naming rules …\"",
"ja": "例:「回答はすべて日本語で。X レポートツールを開発中。命名規則に従うこと …」",
"vi": "vd: \"Trả lời bằng tiếng Việt. Team đang xây tool báo cáo X; luôn theo quy tắc đặt tên …\"",
},
"workspace.browse": {"en": "Change folder…", "ja": "フォルダ変更…", "vi": "Đổi thư mục…"},
"workspace.browse": {"en": "Change", "ja": "変更", "vi": "Đổi"},
"workspace.browse_tooltip": {
"en": "Choose the project's workspace folder (agent sandbox + shared knowledge root)",
"ja": "プロジェクトのワークスペースフォルダを選択(エージェントのサンドボックス+共有ナレッジのルート)",
"vi": "Chọn thư mục workspace của project (sandbox của agent + gốc chứa knowledge chung)",
},
"workspace.open_folder": {"en": "Open folder", "ja": "フォルダを開く", "vi": "Mở thư mục"},
"workspace.open_folder": {"en": "Open", "ja": "開く", "vi": "Mở"},
"workspace.save": {"en": "Save project", "ja": "プロジェクトを保存", "vi": "Lưu project"},
"workspace.saved": {"en": "Saved project {name}.", "ja": "プロジェクト {name} を保存しました。", "vi": "Đã lưu project {name}."},
"workspace.threads": {"en": "Conversations in this project", "ja": "このプロジェクトの会話", "vi": "Hội thoại trong project này"},
@@ -468,7 +492,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
"chat.assistant": {"en": "Assistant", "ja": "アシスタント", "vi": "Assistant"},
"chat.error": {"en": "Error", "ja": "エラー", "vi": "Lỗi"},
"help_agent.title": {
"en": "App Assistant", "ja": "アプリアシスタント", "vi": "Trợ lý App"},
# The audit page names this AI Assistant, and keeps it the same in every
# language — it is a product name, not a description.
"en": "AI Assistant", "ja": "AI Assistant", "vi": "AI Assistant"},
"help_agent.greeting": {
"en": "Hello {name}, have a great working day! How can I help you use the app?",
"ja": "こんにちは {name} さん、良い一日を!アプリの使い方について何かお手伝いできますか?",
@@ -478,16 +504,27 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Ask how to use the app…", "ja": "アプリの使い方を質問…",
"vi": "Hỏi cách sử dụng app…"},
"help_agent.open_tooltip": {
"en": "App Assistant — help using the app",
"ja": "アプリアシスタント — アプリの使い方をサポート",
"vi": "Trợ lý App — hỗ trợ sử dụng app"},
"en": "AI Assistant — help using the app",
"ja": "AI Assistant — アプリの使い方をサポート",
"vi": "AI Assistant — hỗ trợ sử dụng app"},
"help_agent.collapse_tooltip": {
"en": "Minimize", "ja": "最小化", "vi": "Thu nhỏ"},
"help_agent.hide_tooltip": {
"en": "Hide to the edge", "ja": "端に隠す", "vi": "Ẩn vào cạnh phải"},
"help_agent.dot_hint": {
"en": "right-click to hide",
"ja": "右クリックで非表示",
"vi": "chuột phải để ẩn"},
# The name on the launcher pill. Deliberately the same in every language —
# it is a product name, and it only shows on hover, so length is not a
# constraint the way it was on a permanently visible badge.
"help_agent.badge": {
"en": "AI Assistant", "ja": "AI Assistant", "vi": "AI Assistant"},
"help_agent.more_tooltip": {
"en": "More", "ja": "その他", "vi": "Thêm"},
"help_agent.show_tooltip": {
"en": "Show the App Assistant", "ja": "アプリアシスタントを表示",
"vi": "Hiện App Assistant"},
"en": "Show the AI Assistant", "ja": "AI Assistant を表示",
"vi": "Hiện AI Assistant"},
"help_agent.empty_reply": {
"en": "(no answer)", "ja": "(回答なし)", "vi": "(không có phản hồi)"},
"help_agent.error": {
@@ -886,6 +923,14 @@ STRINGS: Dict[str, Dict[str, str]] = {
"schedtask.script_placeholder": {
"en": "(script tasks only) e.g. python report.py", "ja": "(Scriptタスクのみ)例: python report.py",
"vi": "(chỉ task Script) vd: python report.py"},
# The title/description block at the top of the Task editor had no name
# either — needed once the index had to list it.
"schedtask.g_basic": {"en": "Basics", "ja": "基本", "vi": "Thông tin chung"},
# The three steps the editor is split into: what to do, when, and what it
# connects to. Each holds the same group boxes as before.
"schedtask.step_content": {"en": "Content", "ja": "内容", "vi": "Nội dung"},
"schedtask.step_schedule": {"en": "Schedule", "ja": "スケジュール", "vi": "Lịch chạy"},
"schedtask.step_link": {"en": "Links", "ja": "連携", "vi": "Liên kết"},
"schedtask.g_schedule": {"en": "Schedule Setup", "ja": "スケジュール設定", "vi": "Thiết lập lịch chạy"},
"schedtask.sched_enable": {"en": "Enable schedule", "ja": "スケジュールを有効化", "vi": "Bật lịch chạy"},
"schedtask.f_run_at": {"en": "Run at", "ja": "実行日時", "vi": "Chạy lúc"},
@@ -1241,7 +1286,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
"dashboard.card_in": {"en": "Input", "ja": "入力", "vi": "Input"},
"dashboard.card_out": {"en": "Output", "ja": "出力", "vi": "Output"},
"dashboard.card_cache": {"en": "Cache", "ja": "キャッシュ", "vi": "Cache"},
"dashboard.card_cost": {"en": "Total cost", "ja": "合計コスト", "vi": "Tổng chi phí"},
"dashboard.card_cost": {"en": "Cost", "ja": "コスト", "vi": "Chi phí"},
"dashboard.card_turns": {"en": "{n} turns", "ja": "{n} ターン", "vi": "{n} lượt"},
"dashboard.prices_label": {
"en": "Unit price (USD / 1M tokens):", "ja": "単価 (USD / 100万トークン):",
@@ -1276,7 +1321,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
"dashboard.ref_last_week": {"en": "Last week", "ja": "先週", "vi": "Tuần trước"},
"dashboard.ref_last_month": {"en": "Last month", "ja": "先月", "vi": "Tháng trước"},
"dashboard.ref_last_year": {"en": "Last year", "ja": "昨年", "vi": "Năm trước"},
"usage.budget_title": {"en": "Budget", "ja": "予算", "vi": "Budget"},
"usage.budget_title": {"en": "Budget", "ja": "予算", "vi": "Ngân sách"},
"usage.budget_no_budget": {"en": "No budget set", "ja": "予算未設定", "vi": "Chưa đặt Budget"},
"usage.budget_used_pct": {"en": "{pct}% used", "ja": "{pct}% 使用済み", "vi": "Đã dùng {pct}%"},
"usage.budget_over_warning": {"en": "⚠ Over 85% of budget used",
@@ -1441,6 +1486,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Hiện thông báo khay hệ thống khi tác vụ xong hoặc lỗi"},
"settings.group.openai": {"en": "OpenAI-compatible (Internal Gateway)", "ja": "OpenAI 互換(社内ゲートウェイ)", "vi": "OpenAI-compatible (Gateway nội bộ)"},
"settings.group.anthropic": {"en": "Anthropic Claude", "ja": "Anthropic Claude", "vi": "Anthropic Claude"},
# Name for the language/tray block at the top of Settings — it had none,
# 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.param_section_pricing": {
@@ -1751,6 +1799,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Xóa connector \"{name}\"?"},
"ext.add_title": {"en": "Add connector", "ja": "コネクタを追加", "vi": "Thêm connector"},
"ext.edit_title": {"en": "Edit connector", "ja": "コネクタを編集", "vi": "Sửa connector"},
"ext.category_label": {"en": "Category", "ja": "カテゴリ", "vi": "Nhóm"},
"ext.preset_label": {"en": "App", "ja": "アプリ", "vi": "Ứng dụng"},
"ext.preset_custom": {"en": "(Custom…)", "ja": "(カスタム…)", "vi": "(Tuỳ chỉnh…)"},
"ext.name_label": {"en": "Display name", "ja": "表示名", "vi": "Tên hiển thị"},
@@ -2338,22 +2387,36 @@ STRINGS: Dict[str, Dict[str, str]] = {
# ---- monitoring_tab.py (📊 Monitoring Dashboard) --------------------
"monitoring.title": {"en": "Monitoring Dashboard", "ja": "モニタリングダッシュボード", "vi": "Bảng giám sát"},
"monitoring.refresh": {"en": "Refresh", "ja": "更新", "vi": "Làm mới"},
"monitoring.tab_security": {"en": "Security Events", "ja": "セキュリティイベント", "vi": "Sự kiện bảo mật"},
"monitoring.tab_mcp": {"en": "MCP Call History", "ja": "MCP 呼び出し履歴", "vi": "Lịch sử gọi MCP"},
"monitoring.tab_actions": {"en": "Action Logs", "ja": "アクションログ", "vi": "Nhật ký hành động"},
"monitoring.tab_agents": {"en": "Agent Status", "ja": "エージェント状態", "vi": "Trạng thái Agent"},
"monitoring.tab_security": {"en": "Security", "ja": "セキュリティ", "vi": "Bảo mật"},
"monitoring.tab_mcp": {"en": "MCP", "ja": "MCP", "vi": "MCP"},
"monitoring.tab_actions": {"en": "Actions", "ja": "アクション", "vi": "Hành động"},
"monitoring.tab_agents": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
"monitoring.tab_accounts": {"en": "Accounts", "ja": "アカウント", "vi": "Tài khoản"},
"monitoring.col_time": {"en": "Time", "ja": "時刻", "vi": "Thời gian"},
"monitoring.col_role": {"en": "Agent Role", "ja": "エージェント役割", "vi": "Vai trò Agent"},
"monitoring.col_name": {"en": "Action", "ja": "アクション", "vi": "Hành động"},
"monitoring.col_result": {"en": "Result", "ja": "結果", "vi": "Kết quả"},
# Security Events shows WHICH rule fired instead of a result that is always
# the same — every security_block is recorded with ok=False.
"monitoring.col_action": {"en": "Action", "ja": "アクション", "vi": "Hành động"},
# The fourth KPI tile on Overview, as the wireframe labels it.
"monitoring.overview_calls": {"en": "Calls", "ja": "呼び出し", "vi": "Lượt gọi"},
# The fold under the Sandbox summary line — the wireframe shows only the
# summary, so the ID / created / uptime / limits rows live behind this.
"monitoring.overview_disk_free": {
"en": "{size} free", "ja": "空き {size}", "vi": "{size} trống"},
"monitoring.overview_disk_label": {"en": "Disk", "ja": "ディスク", "vi": "Đĩa"},
"monitoring.overview_sbx_detail": {
"en": "Details", "ja": "詳細", "vi": "Chi tiết"},
"monitoring.col_detail": {"en": "Detail", "ja": "詳細", "vi": "Chi tiết"},
"monitoring.col_account": {"en": "Account", "ja": "アカウント", "vi": "Tài khoản"},
"monitoring.col_machine": {"en": "Machine", "ja": "マシン", "vi": "Máy"},
"monitoring.col_agent": {"en": "Agent", "ja": "エージェント", "vi": "Agent"},
"monitoring.col_active": {"en": "Active", "ja": "稼働中", "vi": "Đang chạy"},
"monitoring.col_source": {"en": "Source", "ja": "ソース", "vi": "Nguồn"},
"monitoring.active_n": {"en": "{n} running", "ja": "{n} 件実行中", "vi": "{n} đang chạy"},
"monitoring.idle": {"en": "Idle", "ja": "アイドル", "vi": "Rảnh"},
"monitoring.agent_status_title": {
"en": "Agent Status", "ja": "エージェント状態", "vi": "Trạng thái Agent"},
"monitoring.source_cowork": {
"en": "Cowork tab's active turns", "ja": "Cowork タブの実行中ターン",
"vi": "Lượt đang chạy của tab Cowork"},
@@ -2384,7 +2447,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
# ---- monitoring_tab.py — Overview card dashboard ---------------------
"monitoring.tab_overview": {"en": "Overview", "ja": "概要", "vi": "Tổng quan"},
"monitoring.overview_usage_title": {
"en": "Token Usage & Cost", "ja": "トークン使用量とコスト", "vi": "Sử dụng token & Chi phí"},
"en": "Token & Cost", "ja": "トークンとコスト", "vi": "Token & Chi phí"},
"monitoring.overview_currency": {"en": "Currency:", "ja": "通貨:", "vi": "Tiền tệ:"},
"monitoring.tab_agents_admin": {
"en": "Agents Admin", "ja": "エージェント管理", "vi": "Agents Admin"},
@@ -2418,8 +2481,8 @@ STRINGS: Dict[str, Dict[str, str]] = {
"下から独自のSVGアイコンを追加でき、名前ですぐ使えます。",
"vi": "Các icon dùng cho agent và flow. Gõ tên vào ô Icon của step/agent để dùng. Thêm icon SVG "
"của bạn ở dưới — dùng được ngay bằng tên."},
"icons_admin.search": {"en": "Search built-in icons…", "ja": "組込みアイコンを検索…", "vi": "Tìm icon có sẵn…"},
"icons_admin.builtin": {"en": "Built-in icons", "ja": "組込みアイコン", "vi": "Icon có sẵn"},
"icons_admin.search": {"en": "Search icons by name…", "ja": "名前でアイコンを検索…", "vi": "Tìm icon theo tên…"},
"icons_admin.builtin": {"en": "Built-in icons", "ja": "組込みアイコン", "vi": "Icon tích hợp"},
"icons_admin.custom": {"en": "Custom icons", "ja": "カスタムアイコン", "vi": "Icon tùy chỉnh"},
"icons_admin.add": {"en": "Add SVG file", "ja": "SVGファイルを追加", "vi": "Thêm tệp SVG"},
"icons_admin.paste": {"en": "Paste SVG", "ja": "SVGを貼付", "vi": "Dán SVG"},
@@ -2431,9 +2494,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"icons_admin.select_custom": {"en": "Select a custom icon to delete.",
"ja": "削除するカスタムアイコンを選択してください。",
"vi": "Hãy chọn một icon tùy chỉnh để xóa."},
"tools_admin.col_name": {"en": "Tool", "ja": "ツール", "vi": "Tool"},
"tools_admin.col_desc": {"en": "Description", "ja": "説明", "vi": "Mô tả"},
"tools_admin.col_enabled": {"en": "Enabled", "ja": "有効", "vi": "Bật"},
"tools_admin.jira_note": {
"en": "Jira connection setup moved to the Connector tab → set it up there; here you only turn "
"the jira_search / jira_get_issue tools on or off.",
@@ -2468,10 +2528,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Double-click to connect Jira (paste any Jira link — no per-request setup after that).",
"ja": "ダブルクリックで Jira に接続(Jira リンクを貼るだけ、以降は設定不要)。",
"vi": "Nhấp đúp để kết nối Jira (dán bất kỳ link Jira nào — sau đó không cần thiết lập gì thêm)."},
"connectors.dbl_configure": {
"en": "Double-click a connector to configure it.",
"ja": "コネクタをダブルクリックして設定します。",
"vi": "Nhấp đúp vào một connector để thiết lập."},
"connectors.builtin_auto": {
"en": "Built-in, connects automatically", "ja": "組み込み、自動接続",
"vi": "Tích hợp, tự kết nối"},
"connectors.connect_external": {
"en": "Connect to external connectors",
"ja": "外部コネクタに接続する",
@@ -2624,6 +2683,19 @@ STRINGS: Dict[str, Dict[str, str]] = {
"vi": "Chạy flow đã chọn ở nền — nhiều flow chạy song song"},
"co4e.running_flows": {"en": "Running flows", "ja": "実行中のフロー", "vi": "Flow đang chạy"},
"co4e.runs_tab": {"en": "Flow Status", "ja": "フロー状態", "vi": "Flow Status"},
# The flow tab strip was removed, so its pinned Flow Status tab became a
# toggle in the flow toolbar — and that page needs its own way back.
"co4e.tt_runs_tab": {
"en": "Show every flow run", "ja": "すべてのフロー実行を表示",
"vi": "Xem toàn bộ lần chạy flow"},
"co4e.back_to_flow": {"en": "Back to flow", "ja": "フローに戻る", "vi": "Về flow"},
"co4e.new_flow_ready": {
"en": "New flow — type a name, then drag agents onto the canvas",
"ja": "新しいフロー — 名前を入力し、エージェントをキャンバスへ",
"vi": "Flow mới — đặt tên rồi kéo agent vào canvas"},
"co4e.tt_back_to_flow": {
"en": "Back to the flow editor", "ja": "フローエディタに戻る",
"vi": "Quay lại màn dựng flow"},
"co4e.runs_tab_n": {"en": "Flow Status ({n})", "ja": "フロー状態 ({n})", "vi": "Flow Status ({n})"},
"co4e.runs_col_flow": {"en": "Flow", "ja": "フロー", "vi": "Flow"},
"co4e.runs_col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
@@ -2693,6 +2765,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
"ja": "フローとチャット — /agent:<name> または /skill:<name>",
"vi": "Chat với flow — dùng /agent:<name> hoặc /skill:<name>"},
"co4e.send": {"en": "Send", "ja": "送信", "vi": "Gửi"},
"co4e.tab_basic": {"en": "Basic", "ja": "基本", "vi": "Cơ bản"},
"co4e.tab_model_perm": {"en": "Model & Permission", "ja": "モデルと権限", "vi": "Model & Quyền"},
"co4e.tab_skills_files": {"en": "Skills & Files", "ja": "スキルとファイル", "vi": "Skills & Tệp"},
"co4e.f_label": {"en": "Label", "ja": "ラベル", "vi": "Nhãn"},
"co4e.f_role": {"en": "Role", "ja": "ロール", "vi": "Vai trò"},
"co4e.f_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
@@ -2743,6 +2818,9 @@ 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.edit_row_tooltip": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"agents_admin.delete_row_tooltip": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"agents_admin.hint": {
"en": "System-management agents shared across every machine (stored in the shared accounts folder): the help agent and Schedule Task executors. These are NOT the agents you pick in Cowork or Co4E.",
"ja": "全マシンで共有されるシステム管理用エージェント(共有フォルダーに保存):ヘルプエージェントやスケジュールタスクの実行エージェントなど。CoworkやCo4Eで選択するエージェントではありません。",
@@ -2754,8 +2832,6 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "Delete agent \"{name}\"?", "ja": "エージェント「{name}」を削除しますか?",
"vi": "Xóa agent \"{name}\"?"},
"agents_admin.add_btn": {"en": "Add", "ja": "追加", "vi": "Thêm"},
"agents_admin.edit_btn": {"en": "Edit", "ja": "編集", "vi": "Sửa"},
"agents_admin.delete_btn": {"en": "Delete", "ja": "削除", "vi": "Xóa"},
"agents_admin.f_name": {"en": "Name", "ja": "名前", "vi": "Tên"},
"agents_admin.f_kind": {"en": "App function", "ja": "アプリ機能", "vi": "Chức năng App"},
"agents_admin.f_prompt": {"en": "Instructions", "ja": "指示", "vi": "Chỉ dẫn"},
@@ -2787,7 +2863,7 @@ STRINGS: Dict[str, Dict[str, str]] = {
"agents_admin.col_enabled": {"en": "Enabled", "ja": "有効", "vi": "Kích hoạt"},
"agents_admin.col_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"agents_admin.col_updated": {"en": "Updated", "ja": "更新", "vi": "Cập nhật"},
"agents_admin.check_btn": {"en": "Check", "ja": "チェック", "vi": "Kiểm tra"},
"agents_admin.check_btn": {"en": "Check all", "ja": "すべてチェック", "vi": "Kiểm tra tất cả"},
"agents_admin.check_tooltip": {
"en": "Check each agent's effective provider/model connectivity",
"ja": "各エージェントの実効プロバイダ/モデルの接続性を確認",
@@ -2835,12 +2911,67 @@ STRINGS: Dict[str, Dict[str, str]] = {
"en": "AI turns your question into a filter keyword (e.g. \"which commands failed today?\").",
"ja": "質問をAIがフィルターキーワードに変換します。",
"vi": "AI chuyển câu hỏi thành từ khóa lọc (vd: \"hôm nay lệnh nào bị lỗi?\")."},
"monitoring.security_detail_title": {
"en": "Event details", "ja": "イベント詳細", "vi": "Chi tiết sự kiện"},
"monitoring.security_detail_close": {
"en": "Close", "ja": "閉じる", "vi": "Đóng"},
"monitoring.security_events_title": {
"en": "Security Events", "ja": "セキュリティイベント", "vi": "Sự kiện bảo mật"},
"monitoring.mcp_history_title": {
"en": "MCP Call History", "ja": "MCP 呼び出し履歴", "vi": "Lịch sử gọi MCP"},
"monitoring.action_logs_title": {
"en": "Action Logs", "ja": "アクションログ", "vi": "Nhật ký hành động"},
"monitoring.col_detail_block": {
"en": "Block detail", "ja": "ブロック詳細", "vi": "Chi tiết chặn"},
# ---- event-detail panel (ui-audit_v2.html openDetail()) --------------
"monitoring.detail_section_general": {
"en": "General info", "ja": "基本情報", "vi": "Thông tin chung"},
"monitoring.detail_section_action": {
"en": "Action", "ja": "アクション", "vi": "Hành động"},
"monitoring.detail_section_metadata": {
"en": "Metadata", "ja": "メタデータ", "vi": "Metadata"},
"monitoring.detail_type": {"en": "Type", "ja": "種類", "vi": "Loại"},
"monitoring.detail_status": {"en": "Status", "ja": "ステータス", "vi": "Trạng thái"},
"monitoring.detail_event_id": {"en": "Event ID", "ja": "イベントID", "vi": "Event ID"},
"monitoring.detail_policy": {"en": "Policy", "ja": "ポリシー", "vi": "Policy"},
"monitoring.detail_severity": {"en": "Severity", "ja": "重大度", "vi": "Severity"},
"monitoring.detail_copy": {"en": "Copy", "ja": "コピー", "vi": "Copy"},
"monitoring.detail_copied": {"en": "Copied", "ja": "コピー済み", "vi": "Đã copy"},
# Trạng thái pill — which rule fired, phrased as the enforcement outcome
# (distinct wording from the Loại/action_* labels below, matching
# ui-audit_v2.html's statusInfo() vs actionLabel).
"monitoring.status_blocked": {"en": "Blocked", "ja": "ブロック済み", "vi": "Đã chặn"},
"monitoring.status_path": {"en": "Path blocked", "ja": "パスをブロック", "vi": "Path chặn"},
"monitoring.status_network": {"en": "Network blocked", "ja": "ネットワークをブロック", "vi": "Mạng chặn"},
"monitoring.status_secret": {"en": "Secret leaked", "ja": "シークレット漏洩", "vi": "Bí mật lộ"},
"monitoring.status_ok": {"en": "Succeeded", "ja": "成功", "vi": "Thành công"},
"monitoring.status_failed": {"en": "Failed", "ja": "失敗", "vi": "Thất bại"},
"monitoring.severity_critical": {"en": "CRITICAL", "ja": "CRITICAL", "vi": "CRITICAL"},
"monitoring.severity_medium": {"en": "MEDIUM", "ja": "MEDIUM", "vi": "MEDIUM"},
"monitoring.severity_info": {"en": "INFO", "ja": "INFO", "vi": "INFO"},
# Loại field — a human label for the raw event name (audit_log ``name``).
"monitoring.action_prompt": {"en": "Risky prompt", "ja": "危険なプロンプト", "vi": "Prompt rủi ro"},
"monitoring.action_dangerous_command": {
"en": "Dangerous command", "ja": "危険なコマンド", "vi": "Lệnh nguy hiểm"},
"monitoring.action_install_package": {
"en": "Package install", "ja": "パッケージインストール", "vi": "Cài đặt gói"},
"monitoring.action_path_outside_sandbox": {
"en": "Path outside sandbox", "ja": "サンドボックス外のパス", "vi": "Path ngoài sandbox"},
"monitoring.action_network_blocked": {
"en": "Network blocked", "ja": "ネットワークブロック", "vi": "Mạng bị chặn"},
"monitoring.action_secret_in_output": {
"en": "Secret disclosed", "ja": "シークレット漏洩", "vi": "Tiết lộ bí mật"},
"monitoring.overview_activity_title": {
"en": "Recent Activity", "ja": "最近のアクティビティ", "vi": "Hoạt động gần đây"},
"en": "Recent log", "ja": "最近のログ", "vi": "Nhật ký gần đây"},
"monitoring.overview_no_activity": {
"en": "No activity yet.", "ja": "まだアクティビティはありません。", "vi": "Chưa có hoạt động nào."},
"monitoring.overview_resource_title": {
"en": "Resource Usage", "ja": "リソース使用状況", "vi": "Sử dụng tài nguyên"},
"en": "Resources", "ja": "リソース", "vi": "Tài nguyên"},
"monitoring.overview_res_cpu": {"en": "CPU", "ja": "CPU", "vi": "CPU"},
"monitoring.overview_res_mem": {"en": "Memory", "ja": "メモリ", "vi": "Bộ nhớ"},
"monitoring.overview_res_disk": {"en": "Disk I/O", "ja": "ディスク I/O", "vi": "Disk I/O"},
@@ -2867,7 +2998,9 @@ STRINGS: Dict[str, Dict[str, str]] = {
"monitoring.pricing_col_input": {"en": "Input price", "ja": "入力単価", "vi": "Giá input"},
"monitoring.pricing_col_output": {"en": "Output price", "ja": "出力単価", "vi": "Giá output"},
"monitoring.overview_sandbox_details_title": {
"en": "Sandbox Details", "ja": "サンドボックス詳細", "vi": "Chi tiết Sandbox"},
# One section now, holding both the sandbox facts and the permissions.
"en": "Sandbox & Permissions", "ja": "サンドボックスと権限",
"vi": "Sandbox & Quyền"},
"monitoring.overview_sandbox_id": {"en": "Sandbox ID", "ja": "サンドボックス ID", "vi": "Sandbox ID"},
"monitoring.overview_status": {"en": "Status", "ja": "状態", "vi": "Trạng thái"},
"monitoring.overview_status_running": {"en": "Running", "ja": "実行中", "vi": "Đang chạy"},
+5
View File
@@ -0,0 +1,5 @@
"""Provider-neutral Project Context MCP server template."""
from .server import build_server, dispatch
__all__ = ["build_server", "dispatch"]
+106
View File
@@ -0,0 +1,106 @@
"""Shared, stable boundary used by all Project Context tool work packages."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Protocol
from pydantic import AnyUrl, BaseModel, ConfigDict, Field
class ContractModel(BaseModel):
"""Strict immutable model so provider-specific fields cannot leak to the Agent."""
model_config = ConfigDict(extra="forbid", frozen=True)
class IdentityContext(ContractModel):
actor_id: str = Field(min_length=1, max_length=256)
org_unit: str = Field(min_length=1, max_length=128)
customer: str = Field(min_length=1, max_length=128)
project: str = Field(min_length=1, max_length=128)
granted_scopes: frozenset[str]
class SourceCitation(ContractModel):
system: str = Field(min_length=1, max_length=64)
url: AnyUrl
revision: str = Field(min_length=1, max_length=256)
retrieved_at: datetime
@dataclass(frozen=True)
class DispatchResult:
ok: bool
payload: dict[str, Any]
class PolicyDecisionPoint(Protocol):
def decide(self, identity: IdentityContext, tool_name: str, project_id: str) -> bool: ...
class CredentialResolver(Protocol):
def resolve(self, identity: IdentityContext, tool_name: str) -> Any: ...
@dataclass(frozen=True)
class ProjectContextRuntime:
identity: IdentityContext
policy: PolicyDecisionPoint
credential_resolver: CredentialResolver
class ProviderError(RuntimeError):
"""A provider failure with a caller-safe message and retry classification."""
def __init__(self, code: str, message: str, *, retryable: bool) -> None:
super().__init__(message)
self.code = code
self.safe_message = message
self.retryable = retryable
ToolHandler = Callable[[ContractModel, Any], dict[str, Any]]
@dataclass(frozen=True)
class ToolTemplate:
name: str
description: str
input_model: type[ContractModel]
output_model: type[ContractModel]
handler: ToolHandler
def declaration(self) -> dict[str, Any]:
return {
"name": self.name,
"description": self.description,
"inputSchema": self.input_model.model_json_schema(),
"outputSchema": self.output_model.model_json_schema(),
}
def error_result(
code: str,
*,
category: str,
retryable: bool,
message: str,
suggested_action: str,
correlation_id: str,
) -> DispatchResult:
return DispatchResult(
ok=False,
payload={
"error": {
"code": code,
"category": category,
"retryable": retryable,
"message": message,
"suggested_action": suggested_action,
"correlation_id": correlation_id,
}
},
)
@@ -0,0 +1 @@
"""One provider module per member-owned tool work package."""
@@ -0,0 +1,25 @@
"""Provider boundary owned with get_project_change_context."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class ChangeProvider(Protocol):
def get_change_context(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredChangeProvider:
def get_change_context(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The change provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> ChangeProvider:
"""Replace only this factory when wiring the approved read-only Git adapter."""
return UnconfiguredChangeProvider()
@@ -0,0 +1,25 @@
"""Provider boundary owned with get_project_issue_context."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class IssueProvider(Protocol):
def get_issue_context(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredIssueProvider:
def get_issue_context(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The issue provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> IssueProvider:
"""Replace only this factory when wiring the approved read-only issue adapter."""
return UnconfiguredIssueProvider()
@@ -0,0 +1,25 @@
"""Provider boundary owned with search_project_knowledge."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class KnowledgeProvider(Protocol):
def search_knowledge(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredKnowledgeProvider:
def search_knowledge(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The knowledge provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> KnowledgeProvider:
"""Replace only this factory when wiring approved project retrieval."""
return UnconfiguredKnowledgeProvider()
+23
View File
@@ -0,0 +1,23 @@
"""Immutable registry composed before member work starts to prevent merge conflicts."""
from __future__ import annotations
from types import MappingProxyType
from typing import Any
from .foundation import ToolTemplate
from .tools.change_context import TOOL as CHANGE_CONTEXT_TOOL
from .tools.issue_context import TOOL as ISSUE_CONTEXT_TOOL
from .tools.knowledge_search import TOOL as KNOWLEDGE_SEARCH_TOOL
TOOLS: tuple[ToolTemplate, ...] = (
ISSUE_CONTEXT_TOOL,
KNOWLEDGE_SEARCH_TOOL,
CHANGE_CONTEXT_TOOL,
)
TOOLS_BY_NAME = MappingProxyType({tool.name: tool for tool in TOOLS})
TOOL_NAMES = tuple(tool.name for tool in TOOLS)
def tool_declarations() -> list[dict[str, Any]]:
return [tool.declaration() for tool in TOOLS]
+74
View File
@@ -0,0 +1,74 @@
"""Fail-closed identity, policy, and provider resolution for the template server."""
from __future__ import annotations
import os
import sys
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from .foundation import IdentityContext, ProjectContextRuntime, ProviderError
from .providers.change import build_provider as build_change_provider
from .providers.issue import build_provider as build_issue_provider
from .providers.knowledge import build_provider as build_knowledge_provider
MINIMUM_PYTHON = (3, 11)
def require_supported_python(version_info: tuple[int, ...] | None = None) -> None:
"""Fail with an actionable message before the MCP server starts."""
current = version_info or tuple(sys.version_info[:3])
if current[:2] < MINIMUM_PYTHON:
raise RuntimeError(
"Project Context MCP requires Python 3.11 or newer; "
f"current runtime is {current[0]}.{current[1]}"
)
@dataclass(frozen=True)
class ProjectScopePolicy:
"""Pilot policy: read scope and exact identity-bound project are both mandatory."""
def decide(self, identity: IdentityContext, tool_name: str, project_id: str) -> bool:
return "read" in identity.granted_scopes and project_id == identity.project
PROVIDER_FACTORIES: dict[str, Callable[[IdentityContext], Any]] = {
"get_project_issue_context": build_issue_provider,
"search_project_knowledge": build_knowledge_provider,
"get_project_change_context": build_change_provider,
}
@dataclass(frozen=True)
class ProjectProviderResolver:
def resolve(self, identity: IdentityContext, tool_name: str) -> Any:
factory = PROVIDER_FACTORIES.get(tool_name)
if factory is None:
raise ProviderError("NOT_FOUND", "The requested tool is not registered.", retryable=False)
return factory(identity)
def _required_environment(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Project Context MCP cannot start: required setting {name} is missing")
return value
def default_runtime() -> ProjectContextRuntime:
"""Build immutable runtime state; missing identity configuration fails at boot."""
require_supported_python()
identity = IdentityContext(
actor_id=_required_environment("COWORK_MCP_ACTOR_ID"),
org_unit=_required_environment("COWORK_MCP_ORG_UNIT"),
customer=_required_environment("COWORK_MCP_CUSTOMER"),
project=_required_environment("COWORK_MCP_PROJECT"),
granted_scopes=frozenset({"read"}),
)
return ProjectContextRuntime(
identity=identity,
policy=ProjectScopePolicy(),
credential_resolver=ProjectProviderResolver(),
)
+142
View File
@@ -0,0 +1,142 @@
"""Low-level MCP stdio adapter around the transport-agnostic Project Context core."""
# ruff: noqa: UP045 -- Optional keeps the template importable with Pydantic on Python 3.9.
from __future__ import annotations
import json
from typing import Any, Optional
from uuid import uuid4
from pydantic import ValidationError
from .foundation import (
DispatchResult,
ProjectContextRuntime,
ProviderError,
error_result,
)
from .registry import TOOLS_BY_NAME, tool_declarations
from .runtime import default_runtime, require_supported_python
def dispatch(
name: str,
arguments: dict[str, Any],
runtime: ProjectContextRuntime,
) -> DispatchResult:
"""Validate → authorize → resolve provider → execute → validate output."""
correlation_id = str(uuid4())
tool = TOOLS_BY_NAME.get(name)
if tool is None:
return error_result(
"NOT_FOUND",
category="NOT_FOUND",
retryable=False,
message="The requested MCP tool is not registered.",
suggested_action="Refresh the tool list and choose one of the advertised tools.",
correlation_id=correlation_id,
)
try:
validated_input = tool.input_model.model_validate(arguments or {})
except ValidationError:
return error_result(
"INVALID_INPUT",
category="INVALID_INPUT",
retryable=False,
message="The tool arguments do not match the published input contract.",
suggested_action="Correct the required fields and value bounds, then call again.",
correlation_id=correlation_id,
)
project_id = str(validated_input.project_id)
if not runtime.policy.decide(runtime.identity, name, project_id):
return error_result(
"DENIED",
category="DENIED",
retryable=False,
message="The project is outside the caller's approved scope.",
suggested_action="Use an approved project or ask the project owner for access.",
correlation_id=correlation_id,
)
try:
provider = runtime.credential_resolver.resolve(runtime.identity, name)
raw_output = tool.handler(validated_input, provider)
except ProviderError as exc:
return error_result(
exc.code,
category=exc.code,
retryable=exc.retryable,
message=exc.safe_message,
suggested_action="Check the approved provider configuration and retry if allowed.",
correlation_id=correlation_id,
)
except Exception: # noqa: BLE001 - provider failures must not crash or leak into the agent turn
return error_result(
"UPSTREAM_ERROR",
category="UPSTREAM_ERROR",
retryable=False,
message="The approved provider could not complete the request.",
suggested_action="Check the correlation ID in server logs; do not resend credentials.",
correlation_id=correlation_id,
)
try:
output_with_trace = {**raw_output, "correlation_id": correlation_id}
validated_output = tool.output_model.model_validate(output_with_trace)
except ValidationError:
return error_result(
"UPSTREAM_ERROR",
category="UPSTREAM_ERROR",
retryable=False,
message="The provider response did not match the published output contract.",
suggested_action="Fix the provider mapping before retrying the request.",
correlation_id=correlation_id,
)
return DispatchResult(ok=True, payload=validated_output.model_dump(mode="json"))
def build_server(runtime: Optional[ProjectContextRuntime] = None):
from mcp import types
from mcp.server.lowlevel import Server
require_supported_python()
app_runtime = runtime or default_runtime()
app = Server("project_context")
@app.list_tools()
async def list_tools() -> list[types.Tool]:
return [types.Tool(**declaration) for declaration in tool_declarations()]
@app.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> types.CallToolResult:
result = dispatch(name, arguments or {}, app_runtime)
return types.CallToolResult(
content=[types.TextContent(
type="text",
text=json.dumps(result.payload, ensure_ascii=False, separators=(",", ":")),
)],
structuredContent=result.payload if result.ok else None,
isError=not result.ok,
)
return app
def main() -> None:
import anyio
from mcp.server.stdio import stdio_server
app = build_server()
async def _run() -> None:
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())
anyio.run(_run)
if __name__ == "__main__":
main()
@@ -0,0 +1 @@
"""Independent tool modules; ownership is documented in the team guide."""
@@ -0,0 +1,55 @@
"""Member C work package: get_project_change_context."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class ChangeContextInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
change_id: str = Field(min_length=1, max_length=128)
detail: Literal["summary", "standard", "full"] = "standard"
cursor: Optional[str] = Field(default=None, max_length=2048)
class ChangeContextOutput(ContractModel):
correlation_id: str
project_id: str
change_id: str
change_type: Literal["commit", "pull-request", "merge-request"]
title: str
state: str
summary: str
authors: tuple[str, ...]
files: tuple[str, ...]
commits: tuple[str, ...]
related_issues: tuple[str, ...]
source: SourceCitation
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = ChangeContextInput.model_validate(arguments)
return provider.get_change_context(**request.model_dump())
TOOL = ToolTemplate(
name="get_project_change_context",
description=(
"Returns provider-neutral context for one authorized commit, pull request, or merge request "
"with changed files, commits, related issues, and a pinned source. Use when an exact change "
"identifier is known. Do not use for issue details or free-text document search."
),
input_model=ChangeContextInput,
output_model=ChangeContextOutput,
handler=_handle,
)
@@ -0,0 +1,59 @@
"""Member A work package: get_project_issue_context."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class IssueContextInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
issue_key: str = Field(min_length=1, max_length=128)
detail: Literal["summary", "standard", "full"] = "standard"
cursor: Optional[str] = Field(default=None, max_length=2048)
class RelatedItem(ContractModel):
item_id: str
relation: str
title: str
url: str
class IssueContextOutput(ContractModel):
correlation_id: str
project_id: str
issue_key: str
title: str
status: str
description: str
acceptance_criteria: tuple[str, ...]
related: tuple[RelatedItem, ...]
source: SourceCitation
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = IssueContextInput.model_validate(arguments)
return provider.get_issue_context(**request.model_dump())
TOOL = ToolTemplate(
name="get_project_issue_context",
description=(
"Returns one authorized work item's title, state, description, acceptance criteria, "
"related items, and pinned source. Use when an exact issue key is known. Do not use for "
"free-text knowledge search or Git change review."
),
input_model=IssueContextInput,
output_model=IssueContextOutput,
handler=_handle,
)
@@ -0,0 +1,58 @@
"""Member B work package: search_project_knowledge."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class KnowledgeSearchInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
query: str = Field(min_length=2, max_length=1000)
detail: Literal["summary", "standard", "full"] = "standard"
top_k: int = Field(default=5, ge=1, le=20)
language: Optional[Literal["en", "ja", "vi"]] = None
cursor: Optional[str] = Field(default=None, max_length=2048)
class KnowledgeItem(ContractModel):
document_id: str
chunk_id: str
title: str
excerpt: str
score: float = Field(ge=0, le=1)
source: SourceCitation
class KnowledgeSearchOutput(ContractModel):
correlation_id: str
project_id: str
query: str
items: tuple[KnowledgeItem, ...]
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = KnowledgeSearchInput.model_validate(arguments)
return provider.search_knowledge(**request.model_dump())
TOOL = ToolTemplate(
name="search_project_knowledge",
description=(
"Searches approved knowledge for one authorized project and returns ranked excerpts with "
"pinned citations. Use for requirements, design notes, or runbooks when no exact issue is "
"known. Do not use for issue details or Git change review."
),
input_model=KnowledgeSearchInput,
output_model=KnowledgeSearchOutput,
handler=_handle,
)
+9
View File
@@ -0,0 +1,9 @@
"""Stable module entry point for ``python -m cowork_local.mcp_servers.project_context_server``."""
from .project_context.server import build_server, dispatch, main
__all__ = ["build_server", "dispatch", "main"]
if __name__ == "__main__":
main()
+23
View File
@@ -0,0 +1,23 @@
services:
cowork-desktop:
image: python:3.11-slim-bookworm
container_name: cowork-local-desktop-preview
working_dir: /workspace
volumes:
- /workspace:/workspace:Z
- pip-cache:/root/.cache/pip:Z
ports:
- "6080:6080"
environment:
PYTHONUNBUFFERED: "1"
QT_QPA_PLATFORM: "vnc:size=1280x800:depth=32"
QT_QPA_VNC_HOST: "127.0.0.1"
QT_QPA_VNC_PORT: "5900"
QSG_RHI_BACKEND: "software"
PYTHONPATH: "/opt"
entrypoint: ["/bin/sh", "/workspace/.vibeflow-preview/entrypoint.sh"]
command: []
restart: unless-stopped
volumes:
pip-cache: {}
View File
+9
View File
@@ -0,0 +1,9 @@
PySide6>=6.6
pydantic>=2
requests
psutil
pygments
openpyxl
python-pptx
networkx
pytest
-4
View File
@@ -1,4 +0,0 @@
# Optional document/PDF extraction helpers. The application degrades
# gracefully or can install these on demand when they are not present.
pypdf>=4,<7
opendataloader-pdf
+24 -16
View File
@@ -1,16 +1,24 @@
# Cowork Local desktop runtime (Python 3.11).
# Keep optional/heavy document tooling out of this baseline; see
# requirements-optional.txt and docs/installation.md.
PySide6>=6.7,<7
anyio>=4,<5
holidays>=0.40,<1
keyring>=24,<26
mcp>=1,<2
msal>=1.28,<2
networkx>=3.2,<4
openpyxl>=3.1,<4
psutil>=5.9,<8
pydantic>=2,<3
Pygments>=2.17,<3
python-pptx>=1,<2
requests>=2.31,<3
# Cowork-Local BamBOO — dependencies
# Install: pip install -r requirements.txt
# --- Core UI framework ---
PySide6>=6.6.0
# --- HTTP client ---
requests>=2.31.0
# --- Process & resource monitoring ---
psutil>=5.9.0
# --- Document handling ---
openpyxl>=3.1.0 # Excel (.xlsx) creation & reading
python-pptx>=0.6.0 # PowerPoint (.pptx) editing
pypdf>=4.0.0 # PDF text extraction (preferred)
# PyPDF2>=3.0.0 # PDF fallback (optional, pypdf preferred)
# --- Microsoft 365 integration ---
msal>=1.24.0 # OAuth device-code flow for MS365
keyring>=24.0.0 # OS credential store (token cache)
# --- MCP (Model Context Protocol) ---
mcp>=1.0.0 # MCP client SDK (stdio transport)
-52
View File
@@ -1,52 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo_dir=$(cd "$script_dir/.." && pwd)
venv_dir="$repo_dir/.venv"
launcher_dir="$HOME/.local/bin"
launcher_link="$launcher_dir/cowork-local"
launcher_target="$repo_dir/scripts/run_local.sh"
if [[ -n "${COWORK_PYTHON:-}" ]]; then
python_bin="$COWORK_PYTHON"
elif command -v python3.11 >/dev/null 2>&1; then
python_bin=$(command -v python3.11)
else
python_bin=$(command -v python3)
fi
"$python_bin" -c 'import sys; assert sys.version_info >= (3, 11), "Cowork Local requires Python 3.11+"'
if [[ ! -x "$venv_dir/bin/python" ]]; then
if command -v uv >/dev/null 2>&1; then
uv venv --python "$python_bin" "$venv_dir"
else
"$python_bin" -m venv "$venv_dir"
fi
fi
if command -v uv >/dev/null 2>&1; then
uv pip install --python "$venv_dir/bin/python" \
-r "$repo_dir/requirements.txt" \
-r "$repo_dir/requirements-test.txt"
else
"$venv_dir/bin/python" -m pip install --disable-pip-version-check \
-r "$repo_dir/requirements.txt" \
-r "$repo_dir/requirements-test.txt"
fi
mkdir -p "$launcher_dir"
if [[ ! -e "$launcher_link" && ! -L "$launcher_link" ]]; then
ln -s "$launcher_target" "$launcher_link"
echo "Installed launcher: $launcher_link"
elif [[ -L "$launcher_link" && "$(readlink "$launcher_link")" == "$launcher_target" ]]; then
echo "Launcher already installed: $launcher_link"
else
echo "Not replacing existing path: $launcher_link" >&2
echo "Run Cowork Local with: $launcher_target" >&2
fi
echo "Cowork Local environment: $venv_dir"
echo "Run: $launcher_target"
echo "Or add $launcher_dir to PATH and run: cowork-local"
-25
View File
@@ -1,25 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
launcher_source=${BASH_SOURCE[0]}
while [[ -L "$launcher_source" ]]; do
launcher_dir=$(cd "$(dirname "$launcher_source")" && pwd)
launcher_target=$(readlink "$launcher_source")
if [[ "$launcher_target" = /* ]]; then
launcher_source="$launcher_target"
else
launcher_source="$launcher_dir/$launcher_target"
fi
done
script_dir=$(cd "$(dirname "$launcher_source")" && pwd)
repo_dir=$(cd "$script_dir/.." && pwd)
python_bin="$repo_dir/.venv/bin/python"
if [[ ! -x "$python_bin" ]]; then
echo "Cowork Local is not installed. Run $repo_dir/scripts/install_local.sh first." >&2
exit 1
fi
cd "$(dirname "$repo_dir")"
exec "$python_bin" -m cowork_local "$@"
+677
View File
@@ -0,0 +1,677 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Cowork-Local BamBOO</title>
<style>
:root{
--bg:#f8faff;--surface:#fff;--surface-2:rgba(255,255,255,0.95);
--text:#1a202c;--muted:#6b7280;
--accent:#003087;--accent2:#0072CE;--accent3:#FF6B00;
--border:#e2e8f0;--border-strong:#cbd5e1;
--gradient1:linear-gradient(135deg,#003087 0%,#0072CE 100%);
--gradient-hero:linear-gradient(160deg,#001a4d 0%,#003087 45%,#0072CE 100%);
--shadow:0 2px 12px rgba(0,0,0,.07);
}
[data-theme="dark"]{
--bg:#0a0e1a;--surface:#111827;--surface-2:rgba(17,24,39,0.92);
--text:#e2e8f0;--muted:#9ca3af;
--border:#374151;--border-strong:#4b5563;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{
font-family:"Meiryo UI","Yu Gothic","Meiryo","Hiragino Sans","Noto Sans CJK JP",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
background:var(--bg);color:var(--text);
font-size:20px;line-height:1.55;
transition:background .3s,color .3s;
}
.deck{display:flex;flex-direction:column;align-items:center}
/* Scaled wrapper so .slide (1920×1080) fits viewport */
.slide-wrap{width:var(--scaled-w,1920px);height:var(--scaled-h,1080px);position:relative;overflow:hidden;border-bottom:1px solid var(--border)}
.slide-wrap > .slide{transform:scale(var(--scale,1));transform-origin:top left;border-bottom:0}
.slide{
position:relative;
width:1920px;height:1080px;min-height:1080px;max-height:1080px;
padding:72px 96px 92px;
display:flex;flex-direction:column;
background:var(--bg);overflow:hidden;
}
.slide.cover{align-items:center;justify-content:center;text-align:center;background:var(--gradient-hero);color:white;padding:96px}
.slide.section-divider{align-items:center;justify-content:center;text-align:center;background:var(--gradient1);color:white}
h1,h2,h3{font-weight:700;line-height:1.2}
.slide h1{font-size:3.2em;margin-bottom:.3em}
.slide h2{font-size:2.2em;color:var(--accent);margin-bottom:.4em}
.slide h3{font-size:1.2em;color:var(--accent2);margin-bottom:.3em}
.slide.section-divider h2{color:white!important;font-size:2.8em}
.slide.section-divider p{color:rgba(255,255,255,.88);font-size:1.2em;margin-top:.6em}
.slide.cover h1{color:white;font-size:3.4em}
.slide p{font-size:1.1em;color:var(--muted);margin-bottom:1rem}
.slide ul{padding-left:1.4em;margin-top:.4rem}
.slide ul li{font-size:clamp(1.1em,1.5vw,1.3em);margin:.5em 0;line-height:1.45}
.card-grid{display:grid;gap:1.2rem;margin-top:.6rem}
.grid2{grid-template-columns:1fr 1fr}
.grid3{grid-template-columns:1fr 1fr 1fr}
.grid4{grid-template-columns:1fr 1fr 1fr 1fr}
.card{background:var(--surface-2);border:1px solid var(--border);border-radius:16px;padding:1.5rem 1.8rem;box-shadow:var(--shadow);overflow-wrap:break-word;word-break:break-word}
.card-title{font-weight:700;font-size:1.35em;color:var(--accent);margin-bottom:.5em}
.badge{display:inline-block;padding:6px 16px;border-radius:20px;font-size:.9em;font-weight:600;margin-bottom:.6rem}
.badge-blue{background:#dbeafe;color:#1e40af}
.badge-orange{background:#fed7aa;color:#c2410c}
.badge-green{background:#d1fae5;color:#065f46}
.badge-purple{background:#ede9fe;color:#5b21b6}
.badge-red{background:#fee2e2;color:#991b1b}
.flow-row{display:flex;align-items:center;justify-content:center;gap:1rem;flex-wrap:wrap;margin:.6em 0}
.flow-node{background:var(--surface-2);border:2px solid var(--accent2);border-radius:12px;padding:.8rem 1.4rem;text-align:center;font-size:clamp(.9em,1.3vw,1.1em);font-weight:600;color:var(--text);min-width:140px;box-shadow:var(--shadow)}
.flow-node.accent{background:var(--gradient1);color:white;border-color:var(--accent)}
.flow-node.warm{background:linear-gradient(135deg,#FF6B00,#FF8F3A);color:white;border-color:#FF6B00}
.flow-node.orange{background:linear-gradient(135deg,#ff6b00,#ff9500);color:white;border-color:#ff6b00}
.flow-node.green{background:#065f46;color:white;border-color:#065f46}
.flow-arrow{font-size:1.6em;color:var(--accent2);font-weight:700}
.flow-label{font-size:1em;color:var(--muted);text-align:center;margin:.3em 0;font-weight:600}
.arrow{font-size:1.3em;color:var(--accent2);font-weight:700}
.gantt-wrap{overflow-x:auto;width:100%;margin-top:.6rem;display:grid;grid-template-columns:max-content 1fr;column-gap:.6rem;row-gap:.22rem;align-items:center;font-size:clamp(.85em,1.2vw,1em)}
.gantt-row{display:contents}
.gantt-label{min-width:0;width:auto;color:var(--text);font-weight:500}
.gantt-track{background:var(--border);border-radius:4px;height:22px;position:relative;min-width:240px}
.gantt-bar{position:absolute;height:100%;border-radius:4px}
.gantt-row.gantt-sep > .gantt-label,.gantt-row.gantt-sep > .gantt-track{margin-top:.4rem}
.highlight-box{background:linear-gradient(135deg,#e5eaf4,#e5f1fa);border-left:4px solid var(--accent2);border-radius:10px;padding:1.3rem 1.8rem;margin-top:1.5rem;font-size:1.1em}
.accent-box{background:linear-gradient(135deg,#ffe2cc,#fff4ea);border-left:4px solid var(--accent3);border-radius:10px;padding:1.3rem 1.8rem;margin-top:1rem;font-size:1.1em}
table{width:100%;border-collapse:collapse;font-size:clamp(.9em,1.3vw,1.05em);margin-top:.6rem}
th{background:var(--gradient1);color:white;padding:12px 16px;text-align:left;font-weight:600}
td{padding:10px 16px;border-bottom:1px solid var(--border)}
tr:nth-child(even) td{background:#f1f4fa}
.big-number{font-size:clamp(3em,6vw,5em);font-weight:900;color:var(--accent2);line-height:1}
.big-label{font-size:1.1em;color:var(--muted);margin-top:.3em}
/* ── Sparse-slide modifiers (2026-05-03) ───────────────────────────────
* The base font-sizes assume a content-dense slide (close to the per-slide
* cap). Slides with little content (1 short table, 1 small flow-row,
* ≤6 bullets, etc.) end up using only ~50% of the 1920×1080 canvas with
* tiny text. These two modifier classes bump the in-slide typography so
* the visible content fills more of the frame. The min font-sizes stay
* intact for content-dense slides — only sparse slides opt in.
*
* Heuristic for the agent (see "Slide Density Sizing" in the prompt):
* slide--sparse — ~1.3× bump : ≤8 short bullets, OR 1 small table
* (≤6 rows), OR 1 flow-row + ≤6 bullets, OR ≤2
* cards in card-grid.
* slide--very-sparse — ~1.5× bump : ≤4 short bullets, OR a single
* small table (≤4 rows), OR 1 flow-row only, OR
* a single highlight-box/accent-box, OR a single
* big-number metric.
* Header/footer chrome (slide-number, attribution, badge) intentionally
* unchanged so the visual baseline of the deck stays consistent.
*/
.slide.slide--sparse h2{font-size:2.6em}
.slide.slide--sparse h3{font-size:1.5em}
.slide.slide--sparse p{font-size:1.35em}
.slide.slide--sparse ul li{font-size:1.5em;margin:.7em 0}
.slide.slide--sparse table{font-size:1.2em}
.slide.slide--sparse th,.slide.slide--sparse td{padding:14px 18px}
.slide.slide--sparse .flow-node{font-size:1.3em;padding:1rem 1.6rem;min-width:170px}
.slide.slide--sparse .flow-arrow{font-size:1.9em}
.slide.slide--sparse .card-title{font-size:1.55em}
.slide.slide--sparse .card{padding:1.7rem 2rem}
.slide.slide--sparse .highlight-box,.slide.slide--sparse .accent-box{font-size:1.3em;padding:1.5rem 2rem}
.slide.slide--sparse .gantt-wrap{font-size:1.15em}
.slide.slide--very-sparse h2{font-size:3em}
.slide.slide--very-sparse h3{font-size:1.7em}
.slide.slide--very-sparse p{font-size:1.55em}
.slide.slide--very-sparse ul li{font-size:1.7em;margin:.85em 0}
.slide.slide--very-sparse table{font-size:1.4em}
.slide.slide--very-sparse th,.slide.slide--very-sparse td{padding:16px 22px}
.slide.slide--very-sparse .flow-node{font-size:1.55em;padding:1.2rem 1.9rem;min-width:200px}
.slide.slide--very-sparse .flow-arrow{font-size:2.2em}
.slide.slide--very-sparse .card-title{font-size:1.8em}
.slide.slide--very-sparse .card{padding:1.9rem 2.3rem}
.slide.slide--very-sparse .highlight-box,.slide.slide--very-sparse .accent-box{font-size:1.55em;padding:1.8rem 2.4rem}
.slide.slide--very-sparse .gantt-wrap{font-size:1.3em}
/* ── Dense-doc modifier (文字多め / Japanese document-style) ──────────────
* The OPPOSITE of slide--sparse. For "read-as-document" decks (提案書・
* 報告書 / RFP where slides double as standalone reading material) you want
* MORE text per slide, not bigger text. This modifier keeps fonts AT the
* floor (never below — critical rule #2 still holds) but tightens
* line-height / margins / gaps and enables 2-column body prose so a slide
* holds full sentences + many bullets without overflowing 1080px. Used by
* "dense-doc" mode ONLY — never auto-applied, and the sparse-bump heuristic
* does NOT run in this mode (see §Slide Density Sizing dense-doc note).
*/
.slide.slide--dense{padding:56px 80px 80px}
.slide.slide--dense .lead{font-size:1.5em;font-weight:700;color:var(--accent);line-height:1.35;margin-bottom:.5em;border-left:6px solid var(--accent2);padding-left:.55em;padding-right:120px}/* padding-right clears the top-right brand-mark (right:32px+96px wide) so the lead's first line never runs under the logo */
.slide.slide--dense h2{font-size:1.9em;margin-bottom:.25em}
.slide.slide--dense h3{font-size:1.15em;margin:.45em 0 .2em}
.slide.slide--dense p{font-size:1.05em;line-height:1.5;margin-bottom:.55rem;color:var(--text)}
.slide.slide--dense ul{margin-top:.2rem}
.slide.slide--dense ul li{font-size:1.1em;margin:.28em 0;line-height:1.45}
.slide.slide--dense .body-2col{column-count:2;column-gap:2.4rem}
.slide.slide--dense .body-2col li{break-inside:avoid}
.slide.slide--dense .card-grid{gap:.8rem;margin-top:.4rem}
.slide.slide--dense .card{padding:1rem 1.2rem;border-radius:12px}
.slide.slide--dense .card-title{font-size:1.15em;margin-bottom:.3em}
.slide.slide--dense table{font-size:.95em;margin-top:.4rem}
.slide.slide--dense th,.slide.slide--dense td{padding:7px 12px}
.slide.slide--dense .highlight-box,.slide.slide--dense .accent-box{padding:.9rem 1.3rem;margin-top:.7rem;font-size:1.05em}
.slide.slide--dense .footnote{font-size:.8em;color:var(--muted);margin-top:.6rem;line-height:1.4}
.attribution{position:absolute;bottom:14px;left:24px;font-size:12px;color:var(--muted);opacity:.6;pointer-events:none}
.slide.cover .attribution,.slide.section-divider .attribution{color:rgba(255,255,255,.55)}
.slide-number{position:absolute;bottom:14px;right:24px;font-size:14px;color:var(--muted);opacity:.7}
.slide.cover .slide-number,.slide.section-divider .slide-number{color:rgba(255,255,255,.7)}
.brand-mark{position:absolute;top:22px;right:32px;width:96px;height:auto;pointer-events:none;z-index:5}
#slide-nav{position:fixed;top:0;left:0;right:0;background:rgba(0,48,135,.97);color:white;padding:10px 20px;display:flex;align-items:center;justify-content:space-between;z-index:1000;gap:1rem;font-size:.95em}
#slide-nav button{background:rgba(255,255,255,.15);color:white;border:1px solid rgba(255,255,255,.3);border-radius:6px;padding:6px 14px;cursor:pointer;font-size:1em}
.theme-toggle{position:fixed;top:64px;right:20px;z-index:999;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:6px 12px;cursor:pointer;font-size:1.1em;box-shadow:var(--shadow)}
body{padding-top:54px}
.thumb-nav{position:fixed;left:0;top:54px;bottom:0;width:220px;background:var(--surface);border-right:1px solid var(--border);overflow-y:auto;padding:12px 10px;z-index:998;display:none}
.thumb-nav.open{display:block}
body.thumbs-open{padding-left:220px}
body.thumbs-open .theme-toggle{left:240px;right:auto}
.thumb{width:200px;height:112px;margin-bottom:10px;border:2px solid var(--border);border-radius:4px;overflow:hidden;cursor:pointer;position:relative;background:#fff}
.thumb:hover{border-color:var(--accent2)}
.thumb.active{border-color:var(--accent3);box-shadow:0 0 0 2px rgba(255,107,0,.3)}
.thumb-inner{width:1920px;height:1080px;transform:scale(0.1042);transform-origin:top left;pointer-events:none}
.thumb-num{position:absolute;top:3px;left:4px;font-size:10px;font-weight:600;background:rgba(0,0,0,.65);color:#fff;padding:1px 5px;border-radius:3px;z-index:2}
.thumb-toggle{position:fixed;top:64px;left:20px;z-index:999;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:6px 12px;cursor:pointer;font-size:1.1em;box-shadow:var(--shadow)}
/* ── Architecture diagram patterns (redraw source Mermaid into these; NEVER
* embed Mermaid/SVG — dom-to-pptx rasterises it → not editable). See
* /usr/local/share/vibeflow/skills/slide-craft/patterns/arch-diagrams.html for ready HTML.
* Shared node colours are used by arch-node / .proj / .tnode. ───────────── */
/* shared coloured box */
.arch-node,.proj,.tnode{border:1px solid var(--border-strong);border-radius:8px;padding:.45rem .6rem;font-weight:600;font-size:.88em;line-height:1.25;background:#fff;color:var(--text)}
.arch-node small,.proj small,.tnode small{display:block;font-weight:500;color:var(--muted);font-size:.82em}
.arch-node.blue,.proj.blue,.tnode.blue{background:#dbeafe;border-color:#93c5fd;color:#1e40af}
.arch-node.green,.proj.green,.tnode.green{background:#d1fae5;border-color:#6ee7b7;color:#065f46}
.arch-node.orange,.proj.orange,.tnode.orange{background:#fed7aa;border-color:#fdba74;color:#c2410c}
.arch-node.purple,.proj.purple,.tnode.purple{background:#ede9fe;border-color:#c4b5fd;color:#5b21b6}
.arch-node.red,.proj.red,.tnode.red{background:#fee2e2;border-color:#fca5a5;color:#991b1b}
.arch-node.cyan,.proj.cyan,.tnode.cyan{background:#cffafe;border-color:#67e8f9;color:#0e7490}
.proj.muted,.tnode.muted{background:#f1f5f9;border-style:dashed;color:var(--muted)}
/* (1) LAYERED — tiers as columns with titles (Mermaid flowchart LR/TB with parallel layers) */
.arch-wrap{display:grid;gap:.5rem;margin-top:.6rem;align-items:start}
.arch-layer{background:var(--surface-2);border:1px solid var(--border);border-radius:10px;padding:.8rem;text-align:center}
.arch-layer-title{font-weight:700;font-size:.95em;color:var(--accent);margin-bottom:.4rem;border-bottom:2px solid var(--accent2);padding-bottom:.3rem}
.arch-layer .arch-node{margin:.25rem 0}
/* (2) GROUPED CLUSTER — bordered groups + nested sub-clusters + ⇄ connectors
* (Mermaid subgraph / nested topology: VPC, multi-cloud) */
.cloud-flow{display:flex;align-items:stretch;justify-content:center;gap:.55rem;margin-top:.7rem}
.cloud-flow .flow-arrow{align-self:center;flex:0 0 auto}
.zone-col{display:flex;flex-direction:column;gap:.55rem}
.arch-group{border:2px solid var(--border-strong);border-radius:12px;padding:.6rem .7rem;background:var(--surface-2);display:flex;flex-direction:column}
.arch-group-title{font-weight:700;font-size:.88em;color:var(--accent);text-align:center;margin-bottom:.45rem;padding-bottom:.3rem;border-bottom:2px solid var(--accent2)}
.arch-group>.arch-node{margin:.2rem 0}
.arch-sub{border:1px dashed var(--border-strong);border-radius:8px;padding:.4rem;margin-top:.4rem}
.arch-sub-title{font-size:.74em;font-weight:700;color:var(--muted);text-align:center;margin-bottom:.3rem}
.ngrid{display:grid;grid-template-columns:1fr 1fr;gap:.4rem}
.ngrid.three{grid-template-columns:1fr 1fr 1fr}
/* (3) HIERARCHY via nested containment — Org wraps Folders wrap Projects
* (Mermaid tree / org-chart). Containment shows parent→child, no fragile lines. */
.org{border:2.5px solid var(--accent);border-radius:16px;margin-top:1rem;padding:0 1.2rem 1.2rem}
.org-title{display:inline-block;transform:translateY(-50%);background:var(--gradient1);color:#fff;font-weight:700;padding:.5rem 1.4rem;border-radius:10px;font-size:1.05em}
.org-title small{font-weight:500;opacity:.85;margin-left:.5rem;color:#fff}
.folder-row{display:flex;gap:1rem;align-items:flex-start;margin-top:-.4rem}
.folder{flex:1;border:2px solid var(--border-strong);border-radius:12px;padding:0 .8rem .9rem;background:var(--surface-2)}
.folder-title{display:inline-block;transform:translateY(-50%);font-weight:700;padding:.35rem 1rem;border-radius:8px;font-size:.92em;background:#dbeafe;color:#1e40af}
.folder .proj{margin:.4rem 0;display:flex;justify-content:space-between;align-items:center}
.folder .proj small{display:inline}
</style>
</head>
<body>
<div id="slide-nav">
<div><strong>Cowork-Local BamBOO</strong></div>
<div><button onclick="prevSlide()">◀</button> <span id="nav-pos">1 / N</span> <button onclick="nextSlide()">▶</button></div>
</div>
<button class="thumb-toggle" onclick="toggleThumbs()" title="Slides">☰</button>
<button class="theme-toggle" onclick="toggleTheme()">🌙</button>
<aside class="thumb-nav" id="thumb-nav"></aside>
<div class="deck">
<section class="slide cover" id="s1">
<svg width="188" height="116" viewBox="0 0 34 21" xmlns="http://www.w3.org/2000/svg" style="display:block;margin:0 auto 1.8rem;filter:drop-shadow(0 2px 8px rgba(0,0,0,.25))">
<path d="M6.68439 3.50089C4.75756 3.50089 3.12259 4.75793 2.55021 6.5013C2.53888 6.54111 2.52471 6.58093 2.51338 6.6179L2.41703 6.99331L0 17.499H6.08934C7.90849 17.499 9.45845 16.3415 10.0478 14.7204L10.2774 13.7193L12.6292 3.49805H6.68439V3.50089Z" fill="#08509F"/>
<path d="M18.1691 0C16.18 0 14.5025 1.34236 13.984 3.17389C13.9443 3.3104 13.9131 3.44976 13.8876 3.59196L9.88379 21H15.8286C17.866 21 19.5746 19.5951 20.0506 17.6981H20.0535L24.1196 0H18.1691Z" fill="#F27123"/>
<path d="M28.0555 3.50098C26.1967 3.50098 24.6099 4.6727 23.9865 6.31937C23.9553 6.40469 23.8448 6.75165 23.8448 6.75165L21.3711 17.5019H27.3159C29.3589 17.5019 31.0732 16.0885 31.5408 14.183L33.9975 3.50382H28.0555V3.50098Z" fill="#51B748"/>
<path d="M4.03217 7.37699C3.69781 7.6557 3.48246 7.99413 3.41728 8.26431L2.15918 13.9637H2.23002C2.62105 13.9637 2.98942 13.8243 3.32378 13.5484C3.66097 13.2726 3.87349 12.9341 3.95566 12.5445L4.27869 11.0969H6.97908C7.37011 11.0969 7.74131 10.9576 8.07851 10.6817C8.4157 10.4058 8.63105 10.0646 8.71606 9.67208L8.73023 9.60098H4.61305L4.86524 8.46055H8.76706C9.1581 8.46055 9.52646 8.32119 9.86366 8.04817C10.198 7.7723 10.4049 7.42818 10.4955 7.03855L10.5125 6.96745H5.12593C4.73489 6.96176 4.36653 7.10112 4.03217 7.37699Z" fill="white"/>
<path d="M31.52 7.30069C31.3047 7.08455 31.0213 6.97363 30.6813 6.97363H25.2975L25.289 7.02198C25.2691 7.12721 25.2578 7.22675 25.2578 7.3206C25.2578 7.6505 25.3683 7.92637 25.5837 8.14535C25.8019 8.3615 26.0824 8.47241 26.4252 8.47241H27.587L26.4196 13.9642H26.4932C26.8843 13.9642 27.2498 13.8248 27.5842 13.5518C27.9185 13.2759 28.1254 12.9375 28.2076 12.545L29.0718 8.46957H31.809L31.8175 8.42122C31.8374 8.32168 31.8487 8.21645 31.8487 8.11407C31.8459 7.78986 31.7354 7.51683 31.52 7.30069Z" fill="white"/>
<path d="M19.7101 6.96223H16.0718L16.0747 6.95654H14.5785L13.0938 13.9641H13.1646C13.5556 13.9641 13.924 13.8248 14.2555 13.5489C14.587 13.273 14.7967 12.9346 14.8789 12.545L15.1821 11.1059H18.8544C19.2454 11.1059 19.611 10.9666 19.9453 10.6935C20.2768 10.4205 20.4894 10.0792 20.5772 9.68108L20.8521 8.41551C20.8719 8.31597 20.8832 8.21359 20.8832 8.10836C20.8832 7.78414 20.7727 7.51112 20.5517 7.29213C20.3364 7.07315 20.0502 6.96223 19.7101 6.96223ZM15.7488 8.46101H19.3531L19.1038 9.60714H15.4995L15.7488 8.46101Z" fill="white"/>
</svg>
<h1 style="font-size:3.2em;margin-bottom:0.4em">Cowork-Local BamBOO</h1>
<p style="font-size:1.6em;opacity:.85">Enterprise AI Business Assistant</p>
<span class="slide-number">Slide 1 / 11</span>
</section><section class="slide slide--very-sparse" id="s2">
<h2>Mục đích ứng dụng</h2>
<div class="card-grid grid2">
<div class="card">
<div class="card-title">Vấn đề</div>
<ul>
<li>Nhân viên văn phòng cần AI hỗ trợ tác vụ hàng ngày: tổng hợp báo cáo, phân tích dữ liệu, tạo tài liệu.</li>
<li>Giải pháp hiện tại quá đơn giản (chat thuần túy) hoặc quá phức tạp (cần kiến thức lập trình).</li>
<li>Thiếu công cụ AI <strong>doanh nghiệp</strong>: bảo mật, quản lý tài khoản, tích hợp hệ thống văn phòng.</li>
</ul>
</div>
<div class="card">
<div class="card-title">Giải pháp — Cowork-Local BamBOO</div>
<ul>
<li>Ứng dụng desktop AI đa năng cho doanh nghiệp.</li>
<li>Hỗ trợ 3 ngôn ngữ: Việt, Anh, Nhật.</li>
<li>Tích hợp Microsoft 365 (OneDrive, SharePoint).</li>
<li>Quản lý tài khoản (Admin/Sub-admin/User), phân quyền, giám sát chi phí.</li>
<li><strong>Không cần kiến thức lập trình</strong> — dùng như chat, kết quả là file thực tế.</li>
</ul>
</div>
</div>
<span class="slide-number">Slide 2 / 13</span>
</section><section class="slide slide--very-sparse" id="s3">
<h2>Kiến trúc tổng quan</h2>
<div class="arch-wrap" style="grid-template-columns:repeat(4,1fr)">
<div class="arch-layer">
<div class="arch-layer-title">UI Layer (PySide6/Qt)</div>
<div class="arch-node blue">Dashboard<small>thống kê chi phí</small></div>
<div class="arch-node blue">Schedule<small>Kanban board</small></div>
<div class="arch-node blue">Workspace<small>5 sub-tabs</small></div>
<div class="arch-node blue">Monitoring<small>Security · MCP · Logs</small></div>
<div class="arch-node blue">Settings · Login · Help</div>
</div>
<div class="arch-layer">
<div class="arch-layer-title">Core Business Logic</div>
<div class="arch-node green">Chat Agent<small>Cowork</small></div>
<div class="arch-node green">Code Agent</div>
<div class="arch-node green">Co4E Workflow<small>DAG multi-agent</small></div>
<div class="arch-node green">Schedule Task<small>cron + chaining</small></div>
<div class="arch-node green">Projects · Accounts · Skills</div>
<div class="arch-node green">Doc Extract · PPTX · XLSX</div>
</div>
<div class="arch-layer">
<div class="arch-layer-title">Routing &amp; Providers</div>
<div class="arch-node purple">Auto Model Routing<small>classify → score → select</small></div>
<div class="arch-node purple">OpenAI Compatible</div>
<div class="arch-node purple">Anthropic · Ollama</div>
<div class="arch-node purple">Copilot · Codex</div>
<div class="arch-node purple">Model Pricing · Benchmark</div>
</div>
<div class="arch-layer">
<div class="arch-layer-title">Security &amp; Integration</div>
<div class="arch-node orange">Agent Security<small>3 lớp bảo mật</small></div>
<div class="arch-node orange">Sandbox Manager<small>risk-based</small></div>
<div class="arch-node orange">MCP Client + Servers</div>
<div class="arch-node orange">MS365 · Jira · Ext</div>
<div class="arch-node orange">Audit Log · Usage Tracker</div>
<div class="arch-node orange">Doc Extract · Image Gen</div>
</div>
</div>
<div class="highlight-box"><strong>Bảo mật xuyên suốt:</strong> Risk Classifier → Backend Selector → Execution (Direct / Integrity Job / AppContainer / Win Sandbox).</div>
<div class="footnote">Kiến trúc 4 lớp: UI → Core → Routing/Providers → Security/Integration. Mỗi layer có thể mở rộng độc lập. Tổng cộng 50+ module trong core/, 30+ UI components. Hỗ trợ Windows, macOS, Linux. I18n: Tiếng Việt, English, 日本語. Dark/Light theme tích hợp sẵn.</div>
<div class="accent-box" style="margin-top:0.6rem"><strong>Thiết kế modular:</strong> mỗi layer giao tiếp qua interface rõ ràng, dễ dàng thay thế hoặc mở rộng thành phần.</div>
<span class="slide-number">Slide 3 / 13</span>
</section><section class="slide slide--very-sparse" id="s4">
<h2>Luồng xử lý chính: Chat Cowork</h2>
<div class="flow-row">
<div class="flow-node">User Input + file</div>
<span class="flow-arrow">→</span>
<div class="flow-node accent">Chat Agent<small>apply skills · rules · project ctx</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node">Auto Model Routing<small>classify → rank → switch</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node">Agent Security L1<small>prompt validate</small></div>
</div>
<div class="flow-row">
<div class="flow-node">Provider Chat Loop<small>streaming response</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node accent">Tool Calling<small>file / command / MCP / MS365</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node">Security L2+L3<small>attachment + command check</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node green">Output Files<small>.xlsx · .pptx · .docx · .md</small></div>
</div>
<div class="highlight-box"><strong>Kết quả là file thực tế</strong> — không chỉ là câu trả lời chat, AI tạo ra tài liệu/báo cáo có thể dùng ngay.</div>
<div class="footnote">Tool calling hỗ trợ: file I/O, command execution, MCP connectors, MS365 Graph API, Jira, và external connectors framework.</div>
<div class="accent-box" style="margin-top:1rem"><strong>Đa provider:</strong> OpenAI, Anthropic, Ollama, GitHub Copilot, Codex — tự động chọn model phù hợp.</div>
<span class="slide-number">Slide 4 / 13</span>
</section>
<section class="slide slide--very-sparse" id="s5">
<h2>Luồng xử lý: Co4E Workflow</h2>
<div class="flow-row">
<div class="flow-node">Wave 0<small>Step A</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node accent">Wave 1 (parallel)<small>Sub 1 + Sub 2 chạy đồng thời</small></div>
<span class="flow-arrow">→</span>
<div class="flow-node">Wave 2 (join)<small>Coordinator tổng hợp</small></div>
</div>
<div class="card-grid grid3">
<div class="card">
<div class="card-title">Mỗi step</div>
<ul>
<li>Agent persona (built-in / custom)</li>
<li>Model riêng</li>
<li>Permission preset</li>
<li>Self-verify (quality gate)</li>
<li>Skills đính kèm</li>
</ul>
</div>
<div class="card">
<div class="card-title">Run modes</div>
<ul>
<li><strong>Auto</strong> — AI tự thực hiện</li>
<li><strong>Plan</strong> — read-only</li>
<li><strong>Manual</strong> — step-by-step</li>
</ul>
</div>
<div class="card">
<div class="card-title">Lưu ý</div>
<ul>
<li>Workflow là DAG — không có retry/loop/condition/branch tự động.</li>
<li>Parallel node chạy sub-agent đồng thời + join stage.</li>
</ul>
</div>
</div>
<span class="slide-number">Slide 5 / 13</span>
</section>
<section class="slide slide--very-sparse" id="s6">
<h2>Luồng xử lý: Schedule Task</h2>
<div class="flow-row">
<div class="flow-node">Backlog</div>
<span class="flow-arrow">→</span>
<div class="flow-node accent">Scheduled</div>
<span class="flow-arrow">→</span>
<div class="flow-node">Running</div>
<span class="flow-arrow">→</span>
<div class="flow-node green">Done</div>
</div>
<div class="card-grid grid3">
<div class="card">
<div class="card-title">Trạng thái phụ</div>
<ul>
<li>Paused</li>
<li>Failed</li>
<li>Waiting Input</li>
</ul>
</div>
<div class="card">
<div class="card-title">Lập lịch</div>
<ul>
<li>One-shot · Daily · Weekly · Monthly · Cron</li>
<li>Skip: working days + holiday calendar</li>
<li>Task chaining (fan-in depends_on)</li>
</ul>
</div>
<div class="card">
<div class="card-title">Kiểm soát</div>
<ul>
<li>Retry: max_retry</li>
<li>Timeout: per-task (600s)</li>
<li>Notify: Teams webhook / Outlook desktop</li>
</ul>
</div>
</div>
<div class="footnote">Hỗ trợ import task từ CSV/Excel, tự động chain theo thứ tự, và lịch nghỉ lễ (VN/JP/US/KR…).</div>
<span class="slide-number">Slide 6 / 13</span>
</section><section class="slide" id="s7">
<h2>Chức năng hiện tại (1/4)</h2>
<h3>Chat &amp; Agent</h3>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Cowork Chat</strong></td><td>Chat với AI, đính kèm file, nhận output file thực tế</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Code Agent</strong></td><td>Agent chuyên biệt cho task phát triển phần mềm</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>AI Edit</strong></td><td>Chỉnh sửa file bằng AI, hỗ trợ tạo ảnh minh họa</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Help Agent</strong></td><td>Trợ lý hỗ trợ sử dụng app, luôn sẵn sàng</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Multi-provider</strong></td><td>OpenAI, Anthropic, Ollama, GitHub Copilot, Codex</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<h3>Workspace &amp; Project</h3>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Projects</strong></td><td>Mỗi project có instructions + sandbox riêng</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Structure Graph</strong></td><td>Đồ thị cấu trúc từ code/tài liệu (AST-based)</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Folder Viewer</strong></td><td>Xem &amp; chỉnh sửa file (PDF/DOCX/XLSX)</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Terminal</strong></td><td>Terminal tích hợp trong app</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<div class="footnote">Tổng cộng 9 tính năng trong nhóm Chat & Agent và Workspace & Project, tất cả đã hoàn chỉnh và sẵn sàng sử dụng. Multi-provider hỗ trợ OpenAI, Anthropic, Ollama, GitHub Copilot, Codex.</div>
<span class="slide-number">Slide 7 / 13</span>
</section>
<section class="slide slide--sparse" id="s8">
<h2>Chức năng hiện tại (2/4) — Automation · Integration</h2>
<h3>Automation</h3>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Co4E Workflow</strong></td><td>DAG workflow đa bước, multi-agent, chạy song song</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Schedule Task</strong></td><td>Lên lịch task tự động, Kanban board, cron, chaining</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Skills</strong></td><td>Thư viện skill tích hợp sẵn (5 skills), Skill Manager</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Plan Checklist</strong></td><td>Agent tự động tạo &amp; theo dõi checklist công việc</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<h3>Integration</h3>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Microsoft 365</strong></td><td>OneDrive (đọc/ghi), SharePoint (đọc) — auto-connect</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>MCP Connectors</strong></td><td>Kết nối external tools qua Model Context Protocol</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Jira</strong></td><td>Read-only: search issues, get issue details</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Ext Connectors</strong></td><td>Framework CAD/CAE/MS365/Other</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<span class="slide-number">Slide 8 / 13</span>
</section>
<section class="slide slide--very-sparse" id="s9">
<h2>Chức năng hiện tại (3/4) — Administration</h2>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Tài khoản &amp; RBAC</strong></td><td>Admin / Sub-admin / User, import/export Excel</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Groups</strong></td><td>Nhóm tài khoản để phân quyền theo nhóm</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Dashboard</strong></td><td>Thống kê token usage &amp; chi phí, biểu đồ spline</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Auto Model Routing</strong></td><td>Benchmark model, tự động định tuyến (Auto/Manual/Off)</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Agent Security</strong></td><td>3 lớp bảo mật: prompt, attachment, command</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Sandbox</strong></td><td>Risk-based: Direct/Integrity/AppContainer/Win Sandbox</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Monitoring</strong></td><td>Overview, Security, MCP, Logs, Agent Status</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Audit Log</strong></td><td>tool_call, permission, security_block, mcp_call</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Model Pricing</strong></td><td>Bảng giá model, tùy chỉnh USD/token</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<span class="slide-number">Slide 9 / 13</span>
</section>
<section class="slide slide--very-sparse" id="s10">
<h2>Chức năng hiện tại (4/4) — Document &amp; File</h2>
<table>
<thead><tr><th>Chức năng</th><th>Mô tả</th><th>Trạng thái</th></tr></thead>
<tbody>
<tr><td><strong>Doc Extract</strong></td><td>Trích xuất text từ PDF/DOCX/XLSX/PPTX/images</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>PPTX Edit</strong></td><td>Tạo và chỉnh sửa PowerPoint files</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>XLSX Write</strong></td><td>Tạo Excel files với styling</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Image Gen</strong></td><td>Tạo ảnh bằng AI</td><td>✅ Hoàn chỉnh</td></tr>
<tr><td><strong>Link Fetch</strong></td><td>Fetch URL preview cho task attachments</td><td>✅ Hoàn chỉnh</td></tr>
</tbody>
</table>
<div class="highlight-box"><strong>Tổng cộng:</strong> 30+ tính năng đã hoàn chỉnh, sẵn sàng dùng trong doanh nghiệp.</div>
<div class="footnote">Doc Extract hỗ trợ PDF, DOCX, XLSX, PPTX, images. PPTX Edit tạo và chỉnh sửa slide với font/styling. XLSX Write tạo Excel có màu sắc, border.</div>
<div class="accent-box" style="margin-top:1rem"><strong>AI tạo file trực tiếp</strong> — từ câu lệnh chat, AI sinh ra tài liệu/báo cáo/ảnh dùng ngay được.</div>
<span class="slide-number">Slide 10 / 13</span>
</section><section class="slide slide--sparse" id="s11">
<h2>Hướng dẫn build &amp; chạy ứng dụng</h2>
<div class="card-grid grid2">
<div class="card">
<div class="card-title">Yêu cầu hệ thống</div>
<ul>
<li>Python 3.10+ (khuyến nghị 3.11/3.12)</li>
<li>OS: Windows 10/11, macOS, Linux</li>
<li>Network: cần internet để cài dependencies &amp; gọi API AI</li>
</ul>
<div class="card-title" style="margin-top:1rem">Cài &amp; chạy</div>
<ul>
<li><code>pip install -r requirements.txt</code></li>
<li><code>python -m cowork_local</code> hoặc <code>python __main__.py</code></li>
</ul>
</div>
<div class="card">
<div class="card-title">Cấu hình API key</div>
<ul>
<li>Settings (⚙) → chọn provider → nhập API key &amp; base URL.</li>
<li>Hoặc đặt qua environment variables: <code>OPENAI_API_KEY</code>, <code>OPENAI_BASE_URL</code>…</li>
</ul>
<div class="card-title" style="margin-top:1rem">Lưu ý</div>
<ul>
<li>Cấu hình lưu tại <code>~/.cowork_local/config.json</code></li>
<li>Một số package (như <code>opendataloader-pdf</code>) tự cài khi cần lần đầu.</li>
<li>Lỗi <code>No module named cowork_local</code> → chạy <code>python __main__.py</code>.</li>
</ul>
</div>
</div>
<span class="slide-number">Slide 11 / 13</span>
</section>
<section class="slide slide--sparse" id="s12">
<h2>Kịch bản Demo</h2>
<div class="card-grid grid3">
<div class="card">
<div class="card-title">Demo 1 — File → AI → Báo cáo + OneDrive</div>
<ul>
<li>Mở Cowork Chat, đính kèm file báo cáo doanh thu (.xlsx/.pdf).</li>
<li>Gõ: phân tích số liệu, tạo báo cáo .xlsx có màu + viết .md lên OneDrive.</li>
<li>AI: đọc → phân tích → tạo Excel → upload text lên OneDrive → trả link.</li>
</ul>
<div class="footnote">Demo 1: OneDrive write chỉ hỗ trợ text files (.md, .txt). Demo 2: Teams webhook + Outlook desktop notification. Demo 3: Auto mode chạy toàn bộ workflow tự động.</div>
</div>
<div class="card">
<div class="card-title">Demo 2 — Schedule Task tự động</div>
<ul>
<li>Vào Schedule → tạo task, đặt lịch "8h sáng thứ 2 hàng tuần".</li>
<li>Nội dung: đọc file doanh thu, phân tích, tạo báo cáo .xlsx.</li>
<li>Bật <code>working_days_only</code> + <code>skip_holidays</code>.</li>
<li>Task tự chạy, kết quả lưu trong task artifacts.</li>
</ul>
</div>
<div class="card">
<div class="card-title">Demo 3 — Co4E Workflow phân tích dự án</div>
<ul>
<li>Step 1 (Research): đọc code, phân tích kiến trúc.</li>
<li>Step 2 (Implement - parallel): 2 sub-agent cùng chạy (unit test + docs).</li>
<li>Step 3 (Join + Review): tổng hợp, kiểm tra chất lượng.</li>
<li>Chạy Auto mode → AI tự thực hiện từng bước.</li>
</ul>
</div>
</div>
<span class="slide-number">Slide 12 / 13</span>
</section>
<section class="slide slide--very-sparse" id="s13">
<h2>Tóm tắt</h2>
<div class="card-grid grid3">
<div class="card">
<div class="card-title">Dễ dùng &amp; Đa năng</div>
<ul>
<li>Giao diện chat, không cần code.</li>
<li>Chat, workflow, schedule, code, Structure Graph, skills.</li>
</ul>
</div>
<div class="card">
<div class="card-title">Bảo mật &amp; Tiết kiệm</div>
<ul>
<li>3 lớp Agent Security + Sandbox risk-based.</li>
<li>Auto Model Routing, theo dõi chi phí.</li>
</ul>
</div>
<div class="card">
<div class="card-title">Tích hợp &amp; Quản trị</div>
<ul>
<li>MS365 (OneDrive/SharePoint), MCP, Jira.</li>
<li>RBAC, Dashboard, Audit Log, Groups.</li>
</ul>
</div>
</div>
<div class="highlight-box"><strong>Cowork-Local BamBOO</strong> — công cụ AI doanh nghiệp toàn diện: dễ dùng, bảo mật, tiết kiệm, tích hợp, quản trị, đa năng.</div>
<div class="accent-box" style="margin-top:1rem"><strong>30+ tính năng đã hoàn chỉnh</strong> — sẵn sàng triển khai trong doanh nghiệp ngay hôm nay.</div>
<span class="slide-number">Slide 13 / 13</span>
</section></div>
<script>
function toggleTheme(){
const h=document.documentElement,b=document.querySelector('.theme-toggle'),d=h.getAttribute('data-theme')==='dark';
h.setAttribute('data-theme',d?'light':'dark');b.textContent=d?'🌙':'☀️';
}
if(window.matchMedia&&window.matchMedia('(prefers-color-scheme: dark)').matches){
document.documentElement.setAttribute('data-theme','dark');
document.querySelector('.theme-toggle').textContent='☀️';
}
// Inject FPT brand mark (default) into every slide — see "Brand Logo" section for SVG constant
const BRAND_SVG='<svg class="brand-mark" viewBox="0 0 34 21" xmlns="http://www.w3.org/2000/svg"><path d="M6.68439 3.50089C4.75756 3.50089 3.12259 4.75793 2.55021 6.5013C2.53888 6.54111 2.52471 6.58093 2.51338 6.6179L2.41703 6.99331L0 17.499H6.08934C7.90849 17.499 9.45845 16.3415 10.0478 14.7204L10.2774 13.7193L12.6292 3.49805H6.68439V3.50089Z" fill="#08509F"/><path d="M18.1691 0C16.18 0 14.5025 1.34236 13.984 3.17389C13.9443 3.3104 13.9131 3.44976 13.8876 3.59196L9.88379 21H15.8286C17.866 21 19.5746 19.5951 20.0506 17.6981H20.0535L24.1196 0H18.1691Z" fill="#F27123"/><path d="M28.0555 3.50098C26.1967 3.50098 24.6099 4.6727 23.9865 6.31937C23.9553 6.40469 23.8448 6.75165 23.8448 6.75165L21.3711 17.5019H27.3159C29.3589 17.5019 31.0732 16.0885 31.5408 14.183L33.9975 3.50382H28.0555V3.50098Z" fill="#51B748"/><path d="M4.03217 7.37699C3.69781 7.6557 3.48246 7.99413 3.41728 8.26431L2.15918 13.9637H2.23002C2.62105 13.9637 2.98942 13.8243 3.32378 13.5484C3.66097 13.2726 3.87349 12.9341 3.95566 12.5445L4.27869 11.0969H6.97908C7.37011 11.0969 7.74131 10.9576 8.07851 10.6817C8.4157 10.4058 8.63105 10.0646 8.71606 9.67208L8.73023 9.60098H4.61305L4.86524 8.46055H8.76706C9.1581 8.46055 9.52646 8.32119 9.86366 8.04817C10.198 7.7723 10.4049 7.42818 10.4955 7.03855L10.5125 6.96745H5.12593C4.73489 6.96176 4.36653 7.10112 4.03217 7.37699Z" fill="white"/><path d="M31.52 7.30069C31.3047 7.08455 31.0213 6.97363 30.6813 6.97363H25.2975L25.289 7.02198C25.2691 7.12721 25.2578 7.22675 25.2578 7.3206C25.2578 7.6505 25.3683 7.92637 25.5837 8.14535C25.8019 8.3615 26.0824 8.47241 26.4252 8.47241H27.587L26.4196 13.9642H26.4932C26.8843 13.9642 27.2498 13.8248 27.5842 13.5518C27.9185 13.2759 28.1254 12.9375 28.2076 12.545L29.0718 8.46957H31.809L31.8175 8.42122C31.8374 8.32168 31.8487 8.21645 31.8487 8.11407C31.8459 7.78986 31.7354 7.51683 31.52 7.30069Z" fill="white"/><path d="M19.7101 6.96223H16.0718L16.0747 6.95654H14.5785L13.0938 13.9641H13.1646C13.5556 13.9641 13.924 13.8248 14.2555 13.5489C14.587 13.273 14.7967 12.9346 14.8789 12.545L15.1821 11.1059H18.8544C19.2454 11.1059 19.611 10.9666 19.9453 10.6935C20.2768 10.4205 20.4894 10.0792 20.5772 9.68108L20.8521 8.41551C20.8719 8.31597 20.8832 8.21359 20.8832 8.10836C20.8832 7.78414 20.7727 7.51112 20.5517 7.29213C20.3364 7.07315 20.0502 6.96223 19.7101 6.96223ZM15.7488 8.46101H19.3531L19.1038 9.60714H15.4995L15.7488 8.46101Z" fill="white"/></svg>';
document.querySelectorAll('.slide').forEach(s=>{if(!s.querySelector('.brand-mark'))s.insertAdjacentHTML('beforeend',BRAND_SVG);});
// Wrap each slide for viewport scaling
document.querySelectorAll('.slide').forEach(s=>{
const w=document.createElement('div');w.className='slide-wrap';
s.parentNode.insertBefore(w,s);w.appendChild(s);
});
// Build thumbnail sidebar (cloned slides at 0.1x)
const thumbNav=document.getElementById('thumb-nav');
const slides=document.querySelectorAll('.slide');
slides.forEach((s,i)=>{
const t=document.createElement('div');t.className='thumb';t.dataset.idx=i;
t.innerHTML='<span class="thumb-num">'+(i+1)+'</span>';
const inner=document.createElement('div');inner.className='thumb-inner';
inner.appendChild(s.cloneNode(true));
t.appendChild(inner);
t.onclick=()=>slides[i].scrollIntoView({behavior:'smooth',block:'start'});
thumbNav.appendChild(t);
});
const thumbs=thumbNav.querySelectorAll('.thumb');
function toggleThumbs(){document.body.classList.toggle('thumbs-open');thumbNav.classList.toggle('open');setTimeout(applyScale,0);}
function highlightThumb(){
const i=currentIndex();thumbs.forEach((t,j)=>t.classList.toggle('active',j===i));
const a=thumbs[i];if(a&&thumbNav.classList.contains('open')){
const r=a.getBoundingClientRect(),nr=thumbNav.getBoundingClientRect();
if(r.top<nr.top||r.bottom>nr.bottom)a.scrollIntoView({block:'nearest'});
}
}
function applyScale(){
const navH=54,sideW=document.body.classList.contains('thumbs-open')?220:0;
const vw=window.innerWidth-sideW,vh=window.innerHeight-navH;
const scale=Math.min(vw/1920,vh/1080,1);
document.documentElement.style.setProperty('--scale',scale);
document.documentElement.style.setProperty('--scaled-w',(1920*scale)+'px');
document.documentElement.style.setProperty('--scaled-h',(1080*scale)+'px');
}
applyScale();window.addEventListener('resize',applyScale);
function currentIndex(){
const y=window.scrollY+window.innerHeight/2;
for(let i=0;i<slides.length;i++){
const r=slides[i].getBoundingClientRect();
if(r.top+window.scrollY<=y&&r.bottom+window.scrollY>=y)return i;
}
return 0;
}
function updateNav(){const p=document.getElementById('nav-pos');if(p)p.textContent=(currentIndex()+1)+' / '+slides.length;highlightThumb();}
function prevSlide(){const i=currentIndex();if(i>0)slides[i-1].scrollIntoView({behavior:'smooth'});}
function nextSlide(){const i=currentIndex();if(i<slides.length-1)slides[i+1].scrollIntoView({behavior:'smooth'});}
window.addEventListener('scroll',updateNav);
document.addEventListener('keydown',e=>{if(e.key==='ArrowRight'||e.key==='ArrowDown')nextSlide();if(e.key==='ArrowLeft'||e.key==='ArrowUp')prevSlide();});
updateNav();
</script>
</body>
</html>
Binary file not shown.
Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
"""Make the repository package importable when pytest runs from the repo root."""
from __future__ import annotations
import sys
from pathlib import Path
REPOSITORY_PARENT = Path(__file__).resolve().parents[2]
if str(REPOSITORY_PARENT) not in sys.path:
sys.path.insert(0, str(REPOSITORY_PARENT))
+245
View File
@@ -0,0 +1,245 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import pytest
from cowork_local.mcp_servers.project_context.foundation import (
IdentityContext,
ProjectContextRuntime,
)
from cowork_local.mcp_servers.project_context.registry import (
TOOL_NAMES,
tool_declarations,
)
from cowork_local.mcp_servers.project_context.runtime import require_supported_python
from cowork_local.mcp_servers.project_context.server import dispatch
from mcp import types
EXPECTED_TOOLS = {
"get_project_issue_context",
"search_project_knowledge",
"get_project_change_context",
}
@dataclass
class RecordingPolicy:
allowed: bool
calls: int = 0
def decide(self, identity: IdentityContext, tool_name: str, project_id: str) -> bool:
self.calls += 1
return self.allowed
@dataclass
class RecordingResolver:
provider: Any
calls: int = 0
def resolve(self, identity: IdentityContext, tool_name: str) -> Any:
self.calls += 1
return self.provider
@dataclass(frozen=True)
class FakeProvider:
response: dict[str, Any]
def get_issue_context(self, **_: Any) -> dict[str, Any]:
return dict(self.response)
def search_knowledge(self, **_: Any) -> dict[str, Any]:
return dict(self.response)
def get_change_context(self, **_: Any) -> dict[str, Any]:
return dict(self.response)
@pytest.fixture
def identity() -> IdentityContext:
return IdentityContext(
actor_id="member-a",
org_unit="fsg",
customer="internal",
project="cowork-local",
granted_scopes=frozenset({"read"}),
)
def runtime(identity: IdentityContext, response: dict[str, Any], *, allowed: bool = True):
policy = RecordingPolicy(allowed=allowed)
resolver = RecordingResolver(provider=FakeProvider(response))
return ProjectContextRuntime(
identity=identity,
policy=policy,
credential_resolver=resolver,
), policy, resolver
def source() -> dict[str, str]:
return {
"system": "gitea",
"url": "http://example.test/gitea-admin/cowork-local/issues/1",
"revision": "main@abc123",
"retrieved_at": "2026-08-20T10:00:00Z",
}
def test_template_exposes_exactly_three_provider_neutral_tools() -> None:
assert set(TOOL_NAMES) == EXPECTED_TOOLS
declarations = tool_declarations()
assert {item["name"] for item in declarations} == EXPECTED_TOOLS
assert all(item["inputSchema"]["additionalProperties"] is False for item in declarations)
assert all(item["outputSchema"]["additionalProperties"] is False for item in declarations)
assert all(types.Tool(**item).name in EXPECTED_TOOLS for item in declarations)
def test_runtime_fails_fast_below_python_311() -> None:
with pytest.raises(RuntimeError, match="requires Python 3.11"):
require_supported_python((3, 9, 0))
def test_denied_request_never_resolves_credentials_or_calls_provider(
identity: IdentityContext,
) -> None:
app, policy, resolver = runtime(identity, {}, allowed=False)
result = dispatch(
"get_project_issue_context",
{"project_id": "other-project", "issue_key": "1"},
app,
)
assert result.ok is False
assert result.payload["error"]["code"] == "DENIED"
assert policy.calls == 1
assert resolver.calls == 0
def test_invalid_input_is_rejected_before_policy(identity: IdentityContext) -> None:
app, policy, resolver = runtime(identity, {})
result = dispatch("get_project_issue_context", {"project_id": "cowork-local"}, app)
assert result.ok is False
assert result.payload["error"]["code"] == "INVALID_INPUT"
assert policy.calls == 0
assert resolver.calls == 0
@pytest.mark.parametrize(
("tool_name", "arguments", "response"),
[
(
"get_project_issue_context",
{"project_id": "cowork-local", "issue_key": "1"},
{
"project_id": "cowork-local",
"issue_key": "1",
"title": "MCP pilot",
"status": "open",
"description": "Build verifiable project context.",
"acceptance_criteria": ["Every result has a source."],
"related": [],
"source": source(),
"truncated": False,
"returned": 1,
"remaining": 0,
"next_cursor": None,
},
),
(
"search_project_knowledge",
{"project_id": "cowork-local", "query": "MCP setup"},
{
"project_id": "cowork-local",
"query": "MCP setup",
"items": [
{
"document_id": "README.md",
"chunk_id": "README.md#setup",
"title": "Setup",
"excerpt": "Install the approved dependencies.",
"score": 0.9,
"source": source(),
}
],
"truncated": False,
"returned": 1,
"remaining": 0,
"next_cursor": None,
},
),
(
"get_project_change_context",
{"project_id": "cowork-local", "change_id": "1"},
{
"project_id": "cowork-local",
"change_id": "1",
"change_type": "pull-request",
"title": "Add MCP contract",
"state": "merged",
"summary": "Introduces the project context contract.",
"authors": ["member-c"],
"files": ["mcp/contract.yaml"],
"commits": ["abc123"],
"related_issues": ["1"],
"source": source(),
"truncated": False,
"returned": 1,
"remaining": 0,
"next_cursor": None,
},
),
],
)
def test_each_member_template_has_a_valid_success_path(
identity: IdentityContext,
tool_name: str,
arguments: dict[str, Any],
response: dict[str, Any],
) -> None:
app, policy, resolver = runtime(identity, response)
result = dispatch(tool_name, arguments, app)
assert result.ok is True
assert result.payload["project_id"] == "cowork-local"
assert result.payload["correlation_id"]
assert policy.calls == 1
assert resolver.calls == 1
def test_provider_output_must_match_contract(identity: IdentityContext) -> None:
app, _, _ = runtime(identity, {"project_id": "cowork-local"})
result = dispatch(
"get_project_issue_context",
{"project_id": "cowork-local", "issue_key": "1"},
app,
)
assert result.ok is False
assert result.payload["error"]["code"] == "UPSTREAM_ERROR"
def test_unexpected_provider_error_does_not_leak_exception(identity: IdentityContext) -> None:
class LeakingProvider:
def get_issue_context(self, **_: Any) -> dict[str, Any]:
raise RuntimeError("secret provider-token-value")
policy = RecordingPolicy(allowed=True)
resolver = RecordingResolver(provider=LeakingProvider())
app = ProjectContextRuntime(identity=identity, policy=policy, credential_resolver=resolver)
result = dispatch(
"get_project_issue_context",
{"project_id": "cowork-local", "issue_key": "1"},
app,
)
assert result.ok is False
assert result.payload["error"]["code"] == "UPSTREAM_ERROR"
assert "secret" not in str(result.payload)

Some files were not shown because too many files have changed in this diff Show More