Hồi quy đã vá
-------------
F-12 Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
`chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
`composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
gắn 1 tệp, khớp bản trước refactor.
F-01 Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
`folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
`ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
tiên hỏng thì đổi provider chính là lúc phải thử lại.
F-07 Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
`check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.
F-11 Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
và không bao giờ chạy.
Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:
graph_renderer.py -> graph_scene_builder.py + graph_export.py
co4e_workflow_service.py -> co4e_run_history.py
json_config_repository.py -> config_sections.py
agents_admin_tab.py -> shared/agent_kind_visuals.py
File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.
Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.
Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.
859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
175 lines
7.1 KiB
Python
175 lines
7.1 KiB
Python
"""Microsoft Teams notifications via Incoming Webhook / Power Automate Workflow.
|
|
|
|
The user pastes a webhook URL in Settings. We try the common payload formats in
|
|
order so it works with both classic Incoming Webhook connectors (MessageCard)
|
|
and the newer Workflows (Adaptive Card) URLs.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
import requests
|
|
|
|
from . import tls_trust
|
|
|
|
_TIMEOUT = 20
|
|
ACCENT = "F37021"
|
|
|
|
|
|
class TeamsNotifier:
|
|
"""Gửi thông báo lên Microsoft Teams qua webhook.
|
|
|
|
Tự thử hai khuôn thẻ: Adaptive Card (webhook Workflows mới) rồi tới
|
|
MessageCard (webhook Connector cũ) — hai loại webhook không nhận chung một khuôn.
|
|
"""
|
|
def __init__(self, webhook_url: str = "", ca_bundle: str = ""):
|
|
"""``webhook_url`` rỗng nghĩa là chưa cấu hình — mọi lượt gửi về sau lặng lẽ bỏ
|
|
qua thay vì lỗi.
|
|
"""
|
|
self.webhook_url = (webhook_url or "").strip()
|
|
self.ca_bundle = (ca_bundle or "").strip()
|
|
|
|
@property
|
|
def configured(self) -> bool:
|
|
"""Đã cấu hình webhook hợp lệ chưa."""
|
|
return self.webhook_url.startswith("http")
|
|
|
|
def send(
|
|
self,
|
|
title: str,
|
|
text: str,
|
|
facts: Optional[Dict[str, str]] = None,
|
|
) -> Tuple[bool, str]:
|
|
"""Post a notification. Returns ``(ok, detail)``."""
|
|
if not self.configured:
|
|
return False, "Teams webhook URL is not configured."
|
|
|
|
# Workflows webhooks expect an Adaptive Card; classic connectors expect a
|
|
# MessageCard. Try both, then a plain-text fallback.
|
|
payloads = [
|
|
self._adaptive_card(title, text, facts),
|
|
self._message_card(title, text, facts),
|
|
{"text": f"**{title}**\n\n{text}"},
|
|
]
|
|
warn = self.url_warning()
|
|
last = ""
|
|
for payload in payloads:
|
|
try:
|
|
resp = self._post(self.webhook_url, payload)
|
|
except requests.RequestException as exc:
|
|
last = f"Teams connection error: {exc}"
|
|
continue
|
|
if resp.status_code < 300:
|
|
return True, "Notification sent to Teams."
|
|
last = self._explain(resp)
|
|
if warn:
|
|
last = f"{last} {warn}"
|
|
return False, last
|
|
|
|
_WEBHOOK_HOSTS = ("logic.azure.com", "webhook.office.com", "office.com", "powerplatform", "powerautomate")
|
|
|
|
def url_warning(self) -> str:
|
|
"""Return a hint if the configured URL doesn't look like a real webhook."""
|
|
url = self.webhook_url.lower()
|
|
if not any(h in url for h in self._WEBHOOK_HOSTS):
|
|
return ("⚠ This URL doesn't look like a Teams webhook — it should contain "
|
|
"'logic.azure.com' or 'webhook.office.com'. Copy the FULL HTTP URL from "
|
|
"Teams → Workflows → 'Post to a channel when a webhook request is received'.")
|
|
if "logic.azure.com" in url and "sig=" not in url:
|
|
return "⚠ The Workflows URL looks incomplete (missing '&sig=...'). Copy the entire URL."
|
|
return ""
|
|
|
|
def _post(self, url: str, payload: Dict):
|
|
"""POST while preserving the method across redirects.
|
|
|
|
``requests`` downgrades POST→GET on 301/302/303 redirects, and Teams
|
|
webhooks (``*.webhook.office.com``) often 302 to a regional endpoint —
|
|
the GET then fails with 405. We follow redirects manually as POST.
|
|
"""
|
|
current = url
|
|
resp = None
|
|
for _ in range(5):
|
|
verify = tls_trust.verify_for(current, self.ca_bundle)
|
|
try:
|
|
resp = requests.post(
|
|
current,
|
|
json=payload,
|
|
timeout=_TIMEOUT,
|
|
allow_redirects=False,
|
|
headers={"Content-Type": "application/json"},
|
|
verify=verify,
|
|
)
|
|
except requests.exceptions.SSLError as exc:
|
|
# Self-signed/internal-CA gateway: capture and pin its exact
|
|
# certificate instead of asking the user to hunt down a .pem
|
|
# file — see core.tls_trust.
|
|
if self.ca_bundle or not tls_trust.looks_like_cert_trust_error(exc):
|
|
raise
|
|
pinned = tls_trust.capture_and_trust(current)
|
|
if not pinned:
|
|
raise
|
|
resp = requests.post(
|
|
current, json=payload, timeout=_TIMEOUT, allow_redirects=False,
|
|
headers={"Content-Type": "application/json"}, verify=pinned,
|
|
)
|
|
if resp.status_code in (301, 302, 303, 307, 308):
|
|
location = (getattr(resp, "headers", {}) or {}).get("Location")
|
|
if location:
|
|
current = location
|
|
continue
|
|
return resp
|
|
return resp
|
|
|
|
@staticmethod
|
|
def _explain(resp) -> str:
|
|
"""Đổi phản hồi lỗi của Teams thành câu đọc được, kèm mã HTTP và 200 ký tự thân."""
|
|
code = resp.status_code
|
|
body = (getattr(resp, "text", "") or "")[:200]
|
|
if code == 405:
|
|
return ("Teams returned 405 (Method Not Allowed). The webhook URL is likely the "
|
|
"wrong type or expired. Recreate it via Teams → Workflows → "
|
|
"'Post to a channel when a webhook request is received' and paste the new URL.")
|
|
if code in (401, 403):
|
|
return f"Teams returned {code} (forbidden). The webhook may be revoked — recreate the URL."
|
|
if code == 404:
|
|
return "Teams returned 404. The webhook URL does not exist — check it or create a new one."
|
|
return f"Teams error {code}: {body}"
|
|
|
|
@staticmethod
|
|
def _message_card(title: str, text: str, facts: Optional[Dict[str, str]]) -> Dict:
|
|
"""Dựng payload khuôn MessageCard (webhook Connector cũ)."""
|
|
section: Dict = {"activityTitle": title, "text": text}
|
|
if facts:
|
|
section["facts"] = [{"name": k, "value": v} for k, v in facts.items()]
|
|
return {
|
|
"@type": "MessageCard",
|
|
"@context": "http://schema.org/extensions",
|
|
"themeColor": ACCENT,
|
|
"summary": title,
|
|
"sections": [section],
|
|
}
|
|
|
|
@staticmethod
|
|
def _adaptive_card(title: str, text: str, facts: Optional[Dict[str, str]]) -> Dict:
|
|
"""Dựng payload khuôn Adaptive Card (webhook Workflows mới)."""
|
|
body: List[Dict] = [
|
|
{"type": "TextBlock", "text": title, "weight": "Bolder", "size": "Medium"},
|
|
{"type": "TextBlock", "text": text, "wrap": True},
|
|
]
|
|
if facts:
|
|
body.append({
|
|
"type": "FactSet",
|
|
"facts": [{"title": k, "value": v} for k, v in facts.items()],
|
|
})
|
|
return {
|
|
"type": "message",
|
|
"attachments": [{
|
|
"contentType": "application/vnd.microsoft.card.adaptive",
|
|
"content": {
|
|
"type": "AdaptiveCard",
|
|
"version": "1.4",
|
|
"body": body,
|
|
},
|
|
}],
|
|
}
|