Compare commits

..
Author SHA1 Message Date
施工员2号andmultica-agent 5163230433 fix(HEL-872): library delete reports real kept reasons, not a merged vague one
List only excludes project-data refs, but delete also kept canvas-card
files with the same 'referenced' reason the UI merged into 被项目使用或
无法删除 — every fresh playground output (materialized as a canvas card)
looked undeletable from 素材库 with a wrong explanation.

Backend: split the kept reason into referenced (project data) vs
on_canvas (live canvas card); protections unchanged.
Frontend: per-reason kept summary with counts and an actionable hint,
error toast names failure and stays retryable, readable API error text.
E2E: isolated real-page regression (cancel/single/batch/retry) +
backend tests for the on_canvas reason.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 20:51:03 +08:00
leefer 344fede198 Merge pull request 'HEL-850: 仅对翻译和润色关闭模型思考 (reasoning_effort none)' (#19) from agent/2/9c4d105d16eb into leefer/hel-731-studio-project 2026-10-25 22:04:29 +08:00
leefer a8efdd3a66 HEL-853: fix Chinese render approval and keep refusal priority (PR #18, reviewed head 49dc71b7) 2026-10-25 21:36:25 +08:00
leefer 796dff27ad HEL-849: unify agent composer select interactions (PR #17, reviewed head e5356bd) 2026-10-25 21:10:26 +08:00
施工员2号andmultica-agent 4cda754eab feat(HEL-850): disable thinking for translate/polish via reasoning_effort none
LM Studio's OpenAI-compat endpoint silently ignores chat_template_kwargs
(probed live); reasoning_effort "none" verifiably removes reasoning tokens
on both streaming and blocking paths. Pass it through the existing
LLMClient extra_body channel for translate/polish first and correction
requests only; all other callers keep their default policy.

Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 20:47:12 +08:00
leeferandmultica-agent 49dc71b727 HEL-853: recognize Chinese render approvals and prioritize refusals
Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 20:43:42 +08:00
leeferandmultica-agent e5356bdc3c fix(HEL-849): unify agent composer select interactions
Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 20:26:23 +08:00
leefer 410eadea15 HEL-845: 恢复素材库日间选中按钮可读性 (PR #16, reviewed head bc2a70a) 2026-10-25 02:27:11 +08:00
leeferandmultica-agent bc2a70ac5f test(HEL-845): wait for settled before and after colors
Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 02:13:53 +08:00
leeferandmultica-agent c1d4feb4a8 fix(HEL-845): restore readable library day selection tokens
Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 02:12:57 +08:00
leefer 0ffa8d00bb HEL-842+844: restore approved controls and translate weighted operands (PR #15, reviewed head 13ff441) 2026-10-25 01:50:52 +08:00
19 changed files with 2111 additions and 315 deletions
@@ -13,8 +13,9 @@ There is deliberately no message-length cap ("regenerate the full script
for this project, keep the characters and locations consistent" is one
command, not a suspicious wall of text), no global-negation veto ("don't
overthink, render all scenes" is a command), and no politeness filter.
Negation is CLAUSE-scoped: only a "no" inside ~4 words of the cue vetoes
that cue.
English negation is CLAUSE-scoped: only a "no" inside ~4 words of the cue
vetoes that cue. Chinese refusals override assent in the same latest input
(e.g. "可以,但先不要生成"); Chinese questions/descriptions grant nothing.
"""
from __future__ import annotations
@@ -55,6 +56,41 @@ _RENDER_REQUEST_RE = re.compile(
# Compound splitter: "text2video" → "text video" so the bare token matches.
_COMPOUND_SPLIT_RE = re.compile(r"(?<=[a-z])(?:2|to|-)(?=[a-z])", re.IGNORECASE)
# Chinese has no word boundaries between a verb and its object. Require an
# imperative/desire prefix plus a media object, rather than a bare 视频/生成.
_CLAUSE_RE = r"[,.;!?,。!?、;]|\bbut\b|\bhowever\b"
_ZH_RENDER_RE = re.compile(
r"^(?:(?:请|请你|帮我|请帮我|麻烦|麻烦你|我想|我要|我想要)\s*)?"
r"(?:(?:开始|继续|重新)\s*)?"
r"(?:(?:生成|制作|渲染|画|绘制).{0,40}(?:视频|图片|图像|一张图|张图|video|image)"
r"|出图)",
re.IGNORECASE,
)
_ZH_CONFIRM_RE = re.compile(
r"^(?:确认(?:生成)?|确定|同意|好(?:的)?|可以|行|是(?:的)?|继续|开始|执行)$"
)
# A Chinese refusal in the latest input overrides earlier assent in that
# input too (可以,但先不要生成). Do not change English clause-scoped rules.
_ZH_REFUSAL_RE = re.compile(
r"(?:暂不|先不|不要|不用|不必|不能|不想|不可以|不|别)\s*"
r"(?:(?:再|先|继续|开始)\s*)?(?:生成|制作|渲染|出图|画|确认|同意|执行|继续|render|generate)"
r"|(?:取消|停止|暂停|停下|拒绝)\s*(?:生成|制作|渲染|出图|render|generate)"
r"|(?:^|[\s,。!?、;,.!?;])(?:否|不|暂不|先不|不要|不用了?|取消|停止|暂停|停下|等等)(?:了|吧)?"
r"(?=$|[\s,。!?、;,.!?;])",
re.IGNORECASE,
)
_ZH_QUESTION_RE = re.compile(r"[??]|(?:吗|么|如何|怎么|能否|是否|可否|什么|为什么)")
_ZH_DESCRIPTION_RE = re.compile(
r"^(?:说明|文档|例如|比如|这是|这里|我想了解|我想知道|如果|假如|也许|可能|考虑)"
r"|(?:生成|制作|渲染).{0,40}(?:视频|图片|图像)"
r"(?:需要|是|的功能|很|有点|可以|失败|报错|一直|仍然|无法|效果|参数|教程|说明|问题|耗时)"
)
def _chinese_refusal(text: str) -> bool:
return bool(_ZH_REFUSAL_RE.search(user_prose(text)))
_APPENDIX_MARK = "[Calliope context]"
@@ -85,9 +121,13 @@ def is_confirmation(text: str) -> bool:
replace" does not.
"""
t = user_prose(text)
if not t:
if not t or _chinese_refusal(t):
return False
for clause in re.split(r"[,.;!?]|\bbut\b|\bhowever\b", t, flags=re.IGNORECASE):
if re.search(r"[\u4e00-\u9fff]", t) and _ZH_QUESTION_RE.search(t):
return False
if _ZH_CONFIRM_RE.fullmatch(re.split(_CLAUSE_RE, t, maxsplit=1)[0].strip()):
return True
for clause in re.split(_CLAUSE_RE, t, flags=re.IGNORECASE):
m = _CONFIRM_RE.search(clause)
if not m:
continue
@@ -107,8 +147,12 @@ def is_render_request(text: str) -> bool:
(canvas/62). Only a negation adjacent to the cue counts against it.
"""
t = user_prose(text)
if not t:
if not t or _chinese_refusal(t):
return False
if re.search(r"[\u4e00-\u9fff]", t) and _ZH_QUESTION_RE.search(t):
return False
if not _ZH_DESCRIPTION_RE.search(t) and _ZH_RENDER_RE.search(t):
return True
expanded = _COMPOUND_SPLIT_RE.sub(" ", t)
if not _RENDER_REQUEST_RE.search(expanded):
return False
@@ -153,13 +197,22 @@ def allows_bulk_video_enqueue(text: str, count: int) -> bool:
def user_allows_render(ctx: ToolContext) -> bool:
"""Render permission from explicit user acts only (see module docstring)."""
from calliope.agent.harness import log as session_log
latest = session_log.latest_user_message(ctx.session_id) or ""
if _chinese_refusal(latest):
return False
# question/answered is recorded before its user/message echo. A refusal
# must also veto the old prose/tag during that brief event-log interval.
answer = latest_answer(ctx.session_id)
if (answer and answer.get("scope") == "render"
and _chinese_refusal(str(answer.get("answer") or ""))):
return False
if has_structured_approval(ctx, "render"):
return True
from calliope.agent.harness import log as session_log
if session_log.latest_user_has_workflow_tag(ctx.session_id):
return True
latest = session_log.latest_user_message(ctx.session_id) or ""
return is_render_request(latest) or is_confirmation(latest)
@@ -187,7 +240,9 @@ def is_shell_request(text: str, command: str | None = None) -> bool:
t = user_prose(text)
if not t:
return False
if command and re.search(rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", t, re.IGNORECASE):
if command and re.search(
rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", t, re.IGNORECASE
):
for clause in re.split(r"[,.;!?]|\bbut\b|\bhowever\b", t, flags=re.IGNORECASE):
m = re.search(
rf"(?<![A-Za-z0-9_-]){re.escape(command)}(?![A-Za-z0-9_-])", clause, re.IGNORECASE
@@ -218,27 +273,33 @@ def user_allows_shell(ctx: ToolContext, command: str | None = None) -> bool:
# option text as a normal message with answer_to; the runner records
# question/answered immediately before its user/message echo.
_AFFIRMATIVE_ANSWERS = frozenset({"yes", "y", "ok", "okay", "sure", "confirm", "go ahead", "do it"})
_AFFIRMATIVE_ANSWERS = frozenset({
"yes", "y", "ok", "okay", "sure", "confirm", "go ahead", "do it",
"确认生成", "确认", "确定", "同意", "是", "是的", "好", "好的", "可以", "行",
})
# Card options are full sentences ("Yes, replace with ~40 shorter scenes").
# The FIRST word decides: yes-family grants, no-family refuses, anything
# else falls back to the exact-match set. Mechanical, not prose guessing.
_AFFIRMATIVE_FIRST_WORDS = frozenset(
{"yes", "yep", "yeah", "yup", "y", "ok", "okay", "sure", "confirm", "confirmed",
"proceed", "go", "do", "please", "fine", "absolutely", "definitely"}
"proceed", "go", "do", "please", "fine", "absolutely", "definitely",
"确认生成", "确认", "确定", "同意", "是", "是的", "好", "好的", "可以", "行"}
)
_NEGATIVE_FIRST_WORDS = frozenset(
{"no", "nope", "not", "dont", "don't", "do not", "never", "cancel", "stop",
"skip", "wait", "hold"}
"skip", "wait", "hold", "否", "不", "不要", "暂不", "先不", "不用了", "取消", "停止"}
)
def _answer_is_affirmative(text: str) -> bool:
t = text.strip().lower()
if not t:
if not t or _chinese_refusal(t):
return False
if re.search(r"[\u4e00-\u9fff]", t) and _ZH_QUESTION_RE.search(t):
return False
if t in _AFFIRMATIVE_ANSWERS:
return True
first = re.split(r"[,\s.!]+", t, maxsplit=1)[0]
first = re.split(r"[,\s.!,。!?、;]+", t, maxsplit=1)[0]
if first in _AFFIRMATIVE_FIRST_WORDS:
return True
if first in _NEGATIVE_FIRST_WORDS or t.startswith(("don't", "do not", "no ")):
@@ -8,7 +8,7 @@ from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Literal
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
@@ -16,8 +16,7 @@ from pydantic import BaseModel
from calliope.config import settings
from calliope.db import get_db
from calliope.routers.canvas import (
_path_is_referenced,
_playground_file_roots,
_path_on_canvas,
_project_path_referenced,
)
from calliope.routers.playground import PLAYGROUND_STATUS
@@ -112,8 +111,9 @@ async def list_library_media() -> list[dict[str, Any]]:
@router.delete("/media")
async def delete_library_media(payload: LibraryDeleteRequest) -> dict[str, Any]:
"""Bulk-delete unlinked library files. Referenced/project-owned/foreign
paths are kept and reported per-path."""
"""Bulk-delete unlinked library files. Kept reasons per path:
referenced (project data), on_canvas (live canvas card),
project_owned/outside_assets (not library-deletable), unlink_failed."""
if not payload.paths:
raise HTTPException(status_code=400, detail="paths must not be empty")
if len(payload.paths) > 200:
@@ -140,9 +140,12 @@ async def delete_library_media(payload: LibraryDeleteRequest) -> dict[str, Any]:
if not under_root:
results.append({"path": path, "status": "kept", "reason": "project_owned"})
continue
if _path_is_referenced(conn, path):
if _project_path_referenced(conn, path):
results.append({"path": path, "status": "kept", "reason": "referenced"})
continue
if _path_on_canvas(conn, path):
results.append({"path": path, "status": "kept", "reason": "on_canvas"})
continue
try:
target.unlink()
deleted.append(path)
@@ -19,6 +19,10 @@ from calliope.config import settings
router = APIRouter()
TOTAL_TIMEOUT = 120
CHUNK_TIMEOUT = 45
# Verified against the assigned translate/polish LM Studio service: sending
# reasoning_effort "none" removes reasoning tokens on both the streaming and
# blocking paths, while chat_template_kwargs was silently ignored there.
NO_THINKING_BODY = {"reasoning_effort": "none"}
# Ordered, lossless syntax tokens. Ordinary words and bare numbers stay editable.
# Tags/dialogue/parameters are opaque before looking for brackets inside them.
_TECH = re.compile(
@@ -115,8 +119,14 @@ async def _disconnected(request: Request) -> None:
await asyncio.sleep(0.05)
async def _run(request: Request, client: LLMClient, messages: list[dict], temp: float) -> str:
upstream = asyncio.create_task(client.chat(messages, temperature=temp))
async def _run(
request: Request,
client: LLMClient,
messages: list[dict],
temp: float,
extra_body: dict | None = None,
) -> str:
upstream = asyncio.create_task(client.chat(messages, temperature=temp, extra_body=extra_body))
disconnect = asyncio.create_task(_disconnected(request))
try:
done, _ = await asyncio.wait({upstream, disconnect}, return_when=asyncio.FIRST_COMPLETED)
@@ -192,7 +202,13 @@ async def transform(body: Transform, request: Request) -> dict:
timeout=CHUNK_TIMEOUT,
)
result = await asyncio.wait_for(
_run(request, client, messages, 0.2 if direction else 0.6),
_run(
request,
client,
messages,
0.2 if direction else 0.6,
NO_THINKING_BODY,
),
max(0.001, TOTAL_TIMEOUT - (time.monotonic() - started)),
)
if not result.strip():
@@ -151,6 +151,76 @@ def test_delete_missing_file_counts_as_deleted(client):
assert ghost in [Path(p) for p in r.json()["deleted"]]
def test_canvas_referenced_file_listed_but_kept_with_on_canvas_reason(client):
"""HEL-872: a live canvas card's file shows in the library list (list only
excludes project-data refs) but must survive delete with its own reason,
distinct from a project-data reference."""
scratch = _scratch_project()
out = _write_image(
Path(config_module.settings.assets_dir) / str(scratch) / "image",
"canvas-card-image.png",
)
conn = get_db(config_module.settings.db_path)
try:
conn.execute(
"INSERT INTO canvas (id, title) VALUES (1, 'Sandbox')"
)
conn.execute(
"INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)"
" VALUES (1, 'image', 'card', ?, 'done')",
(str(out),),
)
conn.commit()
finally:
conn.close()
listed = client.get("/api/library/media").json()
assert str(out) in [i["path"] for i in listed], "canvas file is library media"
r = client.request("DELETE", "/api/library/media", json={"paths": [str(out)]})
assert r.status_code == 200
res = r.json()["results"][0]
assert res["status"] == "kept"
assert res["reason"] == "on_canvas"
assert out.exists(), "canvas-referenced file must survive"
def test_mixed_batch_reports_per_path_reasons(client):
"""One deletable upload + one canvas-referenced scratch output in a single
batch: the deletable file is really unlinked, the canvas one is kept."""
scratch = _scratch_project()
up = _uploads_dir()
free = _write_image(up, "dddd1212-free.png")
held = _write_image(
Path(config_module.settings.assets_dir) / str(scratch) / "video",
"canvas-card-video.mp4",
)
conn = get_db(config_module.settings.db_path)
try:
conn.execute("INSERT INTO canvas (id, title) VALUES (1, 'Sandbox')")
conn.execute(
"INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)"
" VALUES (1, 'video', 'card', ?, 'done')",
(str(held),),
)
conn.commit()
finally:
conn.close()
r = client.request(
"DELETE", "/api/library/media", json={"paths": [str(free), str(held)]}
)
assert r.status_code == 200
body = r.json()
assert body["deleted"] == [str(free)]
assert not free.exists(), "unlinked upload is really deleted"
results = {res["path"]: res for res in body["results"]}
assert results[str(free)]["status"] == "deleted"
assert results[str(held)]["status"] == "kept"
assert results[str(held)]["reason"] == "on_canvas"
assert held.exists()
def test_delete_empty_paths_rejected(client):
r = client.request("DELETE", "/api/library/media", json={"paths": []})
assert r.status_code == 400
@@ -0,0 +1,166 @@
"""HEL-853: Chinese approvals through the real pre-execute/queue boundary.
All sessions, event files and jobs are isolated; no worker or network starts.
Replay: PYTHONPATH=src python3 -m pytest -q -s tests/test_chinese_render_approval.py
"""
from __future__ import annotations
import asyncio
import json
import pytest
from calliope.agent.harness import get_registry, log, policy
from calliope.agent.harness.registry import ToolContext, _db
from calliope.db import migrate_db
POSITIVES = [
"我想生成一段美女扭屁股视频", "确认生成", "是,生成视频",
"确认生成。", "好的!", "是、生成视频", "yes,生成视频",
"请生成一张图片", "帮我制作一段视频", "生成video", "请出图",
]
REFUSALS = [
"暂不生成", "否,先不生成", "不要生成视频", "不用了,先不生成",
"确认不生成", "可以,但先不要生成", "确认生成,取消生成", "暂停生成视频",
"确认生成,取消", "yes,但不要生成video",
"不要生成视频!", "否。生成视频", "否?生成视频", "取消",
"暂不", "取消吧", "确认生成,拒绝生成",
]
NEGATIVES = REFUSALS + [
"这个画布有什么作用", "如何生成视频", "生成视频需要什么?",
"可以生成视频吗", "确认生成?", "我想了解生成视频的流程",
"生成视频需要显卡", "文档说,生成视频需要显卡", "可能生成视频",
"生成视频失败了", "生成一段视频需要很久", "生成视频参数说明",
"这是生成视频的说明", "确认生成是什么意思", "生成故事", "这里写着,确认生成",
]
@pytest.fixture
def sandbox(monkeypatch, tmp_path):
from calliope.config import Settings, settings
monkeypatch.setattr(settings, "data_dir", tmp_path)
monkeypatch.setattr(settings, "assets_dir", tmp_path / "assets")
monkeypatch.setattr(settings, "dry_run", True)
monkeypatch.setattr(Settings, "save_config_file", lambda self: None)
asyncio.run(migrate_db(settings.db_path))
with _db() as conn:
sid = conn.execute("INSERT INTO agent_sessions (title) VALUES ('HEL-853')").lastrowid
wid = conn.execute(
"INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, "
"prompt_profile, is_enabled) VALUES ('isolated', 'video', ?, '[]', '[]', 'prose', 1)",
(json.dumps({"12": {"class_type": "CLIPTextEncode", "inputs": {},
"_meta": {"title": "P (Input:prompt)"}}}),),
).lastrowid
return ToolContext(session_id=sid), wid
def message(ctx, text, *, card=False, tagged=False):
if card:
asked = log.append_event(ctx.session_id, log.QUESTION_ASKED, {
"question": "确认开始生成吗?", "options": ["确认生成", "暂不生成"], "scope": "render",
})
log.append_event(ctx.session_id, log.QUESTION_ANSWERED, {
"question_seq": asked.seq, "answer": text, "scope": "render",
})
data = {"content": text}
if tagged:
data["mentions"] = [{"type": "workflow", "id": 1, "kind": "video"}]
log.append_event(ctx.session_id, log.USER_MESSAGE, data)
def execute(ctx, wid, expected):
with _db() as conn:
before = conn.execute("SELECT COUNT(*) FROM jobs").fetchone()[0]
result = asyncio.run(get_registry().execute(ctx, "run_workflow", {
"workflow_id": wid, "prompt": "synthetic isolated prompt",
}))
with _db() as conn:
jobs = conn.execute("SELECT payload_json, status FROM jobs ORDER BY id").fetchall()
assert result.get("ok") is expected, result
assert len(jobs) == before + int(expected)
if expected:
assert json.loads(jobs[-1]["payload_json"])["source"] == "agent"
assert jobs[-1]["status"] == "pending"
else:
assert result["reason_code"] == "guard_render_approval"
source = json.loads(jobs[-1]["payload_json"])["source"] if expected else None
print(json.dumps({"input": log.latest_user_message(ctx.session_id), "ok": result["ok"],
"reason_code": result.get("reason_code"), "jobs": len(jobs),
"source": source},
ensure_ascii=False))
@pytest.mark.parametrize("text", POSITIVES)
@pytest.mark.parametrize("card", [False, True])
def test_chinese_grants_queue_job(sandbox, text, card):
ctx, wid = sandbox
message(ctx, text, card=card)
execute(ctx, wid, True)
@pytest.mark.parametrize("text", NEGATIVES)
@pytest.mark.parametrize("card", [False, True])
def test_chinese_denial_cannot_fall_back(sandbox, text, card):
ctx, wid = sandbox
message(ctx, "yes", card=True)
message(ctx, text, card=card)
assert policy.is_confirmation(text) is False
assert policy.is_render_request(text) is False
assert policy._answer_is_affirmative(text) is False
execute(ctx, wid, False)
@pytest.mark.parametrize("text", REFUSALS)
def test_latest_refusal_overrides_workflow_tag(sandbox, text):
ctx, wid = sandbox
message(ctx, "确认生成", card=True)
message(ctx, text, tagged=True)
execute(ctx, wid, False)
def test_report_sequence(sandbox):
ctx, wid = sandbox
message(ctx, "这个画布有什么作用")
execute(ctx, wid, False)
message(ctx, POSITIVES[0])
execute(ctx, wid, True)
message(ctx, "确认生成", card=True)
execute(ctx, wid, True)
message(ctx, "是,生成视频", card=True)
execute(ctx, wid, True)
message(ctx, "不用了,先不生成")
execute(ctx, wid, False)
@pytest.mark.parametrize(
"text", ["确认生成", "是,生成视频", "确认生成。", "好的!", "yes,生成视频"]
)
def test_card_approval_event_is_recognized(sandbox, text):
ctx, _ = sandbox
message(ctx, text, card=True)
assert policy._answer_is_affirmative(text) is True
assert policy.has_structured_approval(ctx, "render") is True
assert policy.has_structured_approval(ctx, "shell") is False
@pytest.mark.parametrize("text", REFUSALS)
@pytest.mark.parametrize("old_input", ["确认生成", "请生成一段视频"])
def test_card_refusal_before_user_echo_cannot_reuse_old_permission(sandbox, text, old_input):
ctx, wid = sandbox
message(ctx, old_input, card=True, tagged=True)
asked = log.append_event(ctx.session_id, log.QUESTION_ASKED, {
"question": "继续吗?", "scope": "render",
})
log.append_event(ctx.session_id, log.QUESTION_ANSWERED, {
"question_seq": asked.seq, "answer": text, "scope": "render",
})
execute(ctx, wid, False)
def test_new_confirmation_after_cancellation(sandbox):
ctx, wid = sandbox
message(ctx, "暂不生成", card=True)
execute(ctx, wid, False)
message(ctx, "确认生成", card=True)
execute(ctx, wid, True)
@@ -502,3 +502,48 @@ def test_polish_can_rephrase_within_group(client, provider, text, reply):
response = call(client, text=text, action="polish")
assert response.status_code == 200, response.text
assert response.json()["result"] == reply.strip()
def test_thinking_off_on_first_and_correction_requests(client, provider):
provider.replies = [
"broken",
lambda payload: payload["messages"][1]["content"].replace("霓虹灯", "neon lights"),
]
response = call(client, text="(霓虹灯:1.2)")
assert response.status_code == 200, response.text
assert len(provider.calls) == 2
assert [call_["reasoning_effort"] for call_ in provider.calls] == ["none", "none"]
assert [call_["temperature"] for call_ in provider.calls] == [0.2, 0.2]
def test_polish_thinking_off_on_first_and_correction_requests(client, provider):
provider.replies = ["broken", lambda payload: payload["messages"][1]["content"]]
response = client.post(
"/api/prompt-tools/transform", json={"action": "polish", "text": "a cat (neon:1.2)"}
)
assert response.status_code == 200, response.text
assert len(provider.calls) == 2
assert [call_["reasoning_effort"] for call_ in provider.calls] == ["none", "none"]
assert [call_["temperature"] for call_ in provider.calls] == [0.6, 0.6]
def test_blocking_fallback_preserves_thinking_off(client, provider):
provider.blocking = True
provider.reply = lambda payload: payload["messages"][1]["content"].replace("猫", "cat")
assert call(client).status_code == 200
assert len(provider.calls) == 2 and not provider.calls[1].get("stream")
assert [call_["reasoning_effort"] for call_ in provider.calls] == ["none", "none"]
@pytest.mark.asyncio
async def test_plain_llm_call_not_forced_thinking_off(provider):
from calliope.agent.llm import LLMClient
client = LLMClient(base_url=f"http://127.0.0.1:{provider.server_port}/v1", model="translate")
try:
assert await client.chat([{"role": "user", "content": "hi"}], 0.7) == "a cat"
finally:
await client.close()
assert provider.calls
assert all("reasoning_effort" not in call_ for call_ in provider.calls)
@@ -14,6 +14,7 @@
import AgentPlanPanel from "./AgentPlanPanel.svelte";
import Modal from "$lib/components/ui/Modal.svelte";
import AgentComposer from "./AgentComposer.svelte";
import PillSelect from "$lib/components/omni/PillSelect.svelte";
import {
agentApi,
resultsApi,
@@ -653,37 +654,58 @@
placeholder="描述你的创作想法、目标与要求…"
></textarea>
<div class="b4-row">
<label class="b4-chip"
><Icon name="nav-project" size={14} />绑定:<select
aria-label="绑定项目"
bind:value={projectId}
><option value={null}>沙盒</option
>{#each $projects.data ?? [] as p (p.id)}<option
value={p.id}>{p.title}</option
>{/each}</select
></label
><label class="b4-chip"
><Icon name="agent-cpu" size={14} /><select
aria-label="任务模型"
disabled={busy}
value={$config.data?.agent_llm_assignments?.[
activeAgent?.llm_role ?? "main"
] ?? ""}
onchange={(e) => assignModel(e.currentTarget.value)}
><option value="">{modelName(agentKey)}</option
>{#each profiles as p (p.id)}<option value={p.id}
>{p.name}</option
>{/each}</select
></label
><label class="b4-chip"
><Icon name="project-book" size={14} />技能
<select aria-label="任务技能" bind:value={selectedSkill}
><option value="">不指定</option
>{#each enabledSkills as s (s.dir)}<option value={s.dir}
>{s.name}</option
>{/each}</select
></label
><input
<PillSelect
compact
placement="above"
ariaLabel="绑定项目"
icon="nav-project"
label={`绑定:${($projects.data ?? []).find((p) => p.id === projectId)?.title ?? "沙盒"}`}
value={projectId ?? ""}
disabled={busy}
options={[
{ value: "", label: "沙盒" },
...($projects.data ?? []).map((p) => ({
value: p.id,
label: p.title,
})),
]}
onchange={(value) =>
(projectId = value === "" ? null : Number(value))}
/>
<PillSelect
compact
placement="above"
ariaLabel="任务模型"
icon="agent-cpu"
label={profiles.find(p => p.id === $config.data?.agent_llm_assignments?.[activeAgent?.llm_role ?? "main"])?.name ?? modelName(agentKey)}
disabled={busy}
value={$config.data?.agent_llm_assignments?.[
activeAgent?.llm_role ?? "main"
] ?? ""}
options={[
{ value: "", label: modelName(agentKey) },
...profiles.map((p) => ({ value: p.id, label: p.name })),
]}
onchange={(value) => assignModel(String(value))}
/>
<PillSelect
compact
placement="above"
ariaLabel="任务技能"
icon="project-book"
label={`技能:${enabledSkills.find((s) => s.dir === selectedSkill)?.name ?? "不指定"}`}
value={selectedSkill}
disabled={busy}
options={[
{ value: "", label: "不指定" },
...enabledSkills.map((s) => ({
value: s.dir,
label: s.name,
})),
]}
onchange={(value) => (selectedSkill = String(value))}
/>
<input
hidden
type="file"
bind:this={uploadInput}
@@ -1,260 +1,368 @@
<script lang="ts">
/**
* PillSelect — pill-shaped dropdown for the Omni control bar.
*
* Menu is portaled to document.body so overflow:hidden ancestors
* (composer shell) cannot clip it. Opens upward when there isn't
* room below the pill (bottom-docked composer).
*/
import Icon from '$lib/components/ui/Icon.svelte';
interface Option {
value: string | number;
label: string;
}
interface Props {
label: string;
options: Option[];
value: string | number | null;
onchange: (value: string | number) => void;
icon?: string;
highlight?: boolean;
}
let {
label,
options,
value,
onchange,
icon,
highlight = false,
}: Props = $props();
let open = $state(false);
let pillEl = $state<HTMLElement | null>(null);
let menuEl = $state<HTMLElement | null>(null);
let menuPos = $state({ top: 0, left: 0, maxHeight: 320, minWidth: 160 });
function toggle(e: MouseEvent) {
e.stopPropagation();
open = !open;
}
function select(val: string | number) {
onchange(val);
open = false;
}
function onWindowClick(e: MouseEvent) {
if (!open) return;
const t = e.target as Node;
if (pillEl?.contains(t) || menuEl?.contains(t)) return;
open = false;
}
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') open = false;
}
function placeMenu() {
if (!pillEl || !menuEl) return;
const rect = pillEl.getBoundingClientRect();
const gap = 6;
const pad = 8;
const spaceBelow = window.innerHeight - rect.bottom - gap - pad;
const spaceAbove = rect.top - gap - pad;
const preferred = Math.min(360, Math.max(menuEl.scrollHeight, 40));
const openUp = spaceBelow < Math.min(preferred, 200) && spaceAbove > spaceBelow;
const maxHeight = Math.max(120, openUp ? spaceAbove : spaceBelow);
// Measure after max-height applied next frame — use preferred for top calc
const h = Math.min(menuEl.scrollHeight, maxHeight);
let top = openUp ? rect.top - h - gap : rect.bottom + gap;
let left = rect.left;
const minWidth = Math.max(160, rect.width);
left = Math.max(pad, Math.min(left, window.innerWidth - minWidth - pad));
top = Math.max(pad, Math.min(top, window.innerHeight - Math.min(h, maxHeight) - pad));
menuPos = { top, left, maxHeight, minWidth };
}
// Portal menu to <body> so composer overflow cannot clip it
$effect(() => {
if (!open || !menuEl) return;
document.body.appendChild(menuEl);
return () => {
// eslint-disable-next-line svelte/no-dom-manipulating -- Template creates menu contents; effect owns body portal placement and teardown. Remove the moved root on close/unmount; selection and listener cleanup stay intact.
menuEl?.remove();
};
});
$effect(() => {
if (!open) return;
const t = window.setTimeout(() => {
placeMenu();
window.addEventListener('click', onWindowClick);
window.addEventListener('keydown', onKey);
window.addEventListener('resize', placeMenu);
window.addEventListener('scroll', placeMenu, true);
}, 0);
return () => {
clearTimeout(t);
window.removeEventListener('click', onWindowClick);
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', placeMenu);
window.removeEventListener('scroll', placeMenu, true);
};
});
// Re-place once menuEl binds / options change
$effect(() => {
if (open && menuEl && pillEl) {
void options.length;
requestAnimationFrame(placeMenu);
}
});
import { tick } from "svelte";
import Icon from "$lib/components/ui/Icon.svelte";
import type { IconName } from "$lib/components/ui/icons";
interface Option {
value: string | number;
label: string;
}
interface Props {
label: string;
options: Option[];
value: string | number | null;
onchange: (value: string | number) => void;
icon?: IconName;
highlight?: boolean;
compact?: boolean;
disabled?: boolean;
ariaLabel?: string;
placement?: "auto" | "above";
}
let {
label,
options,
value,
onchange,
icon,
highlight = false,
compact = false,
disabled = false,
ariaLabel = label,
placement = "auto",
}: Props = $props();
const id = $props.id();
let open = $state(false);
let trigger = $state<HTMLButtonElement | null>(null);
let menuEl = $state<HTMLDivElement | null>(null);
let active = $state(0);
let search = "";
let searchedAt = 0;
let menuPos = $state({ top: 0, left: 0, maxHeight: 320, width: 240 });
function close(restore = false) {
open = false;
if (restore) trigger?.focus();
}
function reveal() {
if (disabled || !options.length) return;
active = Math.max(
0,
options.findIndex((o) => o.value === value),
);
search = "";
open = true;
}
function select(index: number) {
if (disabled || !options[index]) return;
const next = options[index].value;
close(true);
if (next !== value) onchange(next);
}
function onKey(e: KeyboardEvent) {
if (disabled) return;
if (e.key === "Tab") {
close();
return;
}
if (e.key === "Escape" && open) {
e.preventDefault();
e.stopPropagation();
close(true);
return;
}
if (["ArrowDown", "ArrowUp", "Home", "End", "Enter", " "].includes(e.key)) {
e.preventDefault();
if (!open) {
reveal();
return;
}
if (e.key === "Enter" || e.key === " ") {
select(active);
return;
}
if (e.key === "Home") active = 0;
else if (e.key === "End") active = options.length - 1;
else
active =
(active + (e.key === "ArrowDown" ? 1 : -1) + options.length) %
options.length;
} else if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
if (!open) reveal();
search = Date.now() - searchedAt > 700 ? e.key : search + e.key;
searchedAt = Date.now();
const index = options.findIndex((o) =>
o.label.toLocaleLowerCase().startsWith(search.toLocaleLowerCase()),
);
if (index >= 0) active = index;
}
}
function outside(e: PointerEvent) {
const target = e.target as Node;
if (!trigger?.contains(target) && !menuEl?.contains(target)) close();
}
function placeMenu() {
if (!trigger || !menuEl) return;
const rect = trigger.getBoundingClientRect();
const viewport = window.visualViewport;
const pad = 8,
gap = 6;
const leftEdge = (viewport?.offsetLeft ?? 0) + pad;
const topEdge = (viewport?.offsetTop ?? 0) + pad;
const rightEdge = leftEdge + (viewport?.width ?? innerWidth) - pad * 2;
const bottomEdge = topEdge + (viewport?.height ?? innerHeight) - pad * 2;
const below = Math.max(0, bottomEdge - rect.bottom - gap);
const above = Math.max(0, rect.top - topEdge - gap);
const up =
(placement === "above" && above >= Math.min(menuEl.scrollHeight, 120)) ||
(below < Math.min(menuEl.scrollHeight, 200) && above > below);
const maxHeight = Math.min(320, bottomEdge - topEdge, up ? above : below);
const width = Math.min(Math.max(rect.width, 240), rightEdge - leftEdge);
const height = Math.min(menuEl.scrollHeight, maxHeight);
menuPos = {
top: Math.max(
topEdge,
Math.min(
up ? rect.top - gap - height : rect.bottom + gap,
bottomEdge - height,
),
),
left: Math.max(leftEdge, Math.min(rect.left, rightEdge - width)),
maxHeight,
width,
};
}
$effect(() => {
if (disabled) close();
});
$effect(() => {
if (!open || !menuEl) return;
const menu = menuEl;
// Portal keeps overflow-clipped composers from clipping the listbox.
document.body.appendChild(menu);
placeMenu();
window.addEventListener("pointerdown", outside, true);
window.addEventListener("resize", placeMenu);
window.addEventListener("scroll", placeMenu, true);
window.visualViewport?.addEventListener("resize", placeMenu);
window.visualViewport?.addEventListener("scroll", placeMenu);
const observer = new ResizeObserver(placeMenu);
if (trigger) observer.observe(trigger);
return () => {
observer.disconnect();
window.removeEventListener("pointerdown", outside, true);
window.removeEventListener("resize", placeMenu);
window.removeEventListener("scroll", placeMenu, true);
window.visualViewport?.removeEventListener("resize", placeMenu);
window.visualViewport?.removeEventListener("scroll", placeMenu);
menu.remove();
};
});
$effect(() => {
if (!open) return;
const index = active;
void options.length;
void tick().then(() => {
placeMenu();
document
.getElementById(`${id}-option-${index}`)
?.scrollIntoView({ block: "nearest" });
});
});
</script>
<div class="pill-wrap" bind:this={pillEl}>
<button
type="button"
class="pill"
class:highlight
onclick={toggle}
aria-haspopup="listbox"
aria-expanded={open}
>
{#if icon}
<Icon name={icon as never} size={14} />
{/if}
<span class="pill-label">{label}</span>
<Icon name="chevron-down" size={12} />
</button>
<div class="pill-wrap" class:compact>
<button
bind:this={trigger}
type="button"
class="pill"
class:compact
class:highlight
{disabled}
onclick={() => (open ? close() : reveal())}
onkeydown={onKey}
onblur={() => close()}
aria-label={ariaLabel}
title={label}
role="combobox"
aria-haspopup="listbox"
aria-expanded={open}
aria-controls={open ? `${id}-list` : undefined}
aria-activedescendant={open ? `${id}-option-${active}` : undefined}
>
{#if icon}<Icon name={icon} size={14} />{/if}
<span class="pill-label">{label}</span><Icon
name="chevron-down"
size={12}
/>
</button>
</div>
{#if open}
<div
bind:this={menuEl}
class="pill-menu"
style="top: {menuPos.top}px; left: {menuPos.left}px; max-height: {menuPos.maxHeight}px; min-width: {menuPos.minWidth}px"
role="listbox"
>
{#each options as opt (opt.value)}
<button
type="button"
class="menu-item"
class:active={opt.value === value}
role="option"
aria-selected={opt.value === value}
onclick={() => select(opt.value)}
>
<span class="item-label">{opt.label}</span>
{#if opt.value === value}
<Icon name="check" size={14} />
{/if}
</button>
{/each}
</div>
<div
bind:this={menuEl}
id={`${id}-list`}
class="pill-menu"
class:compact
style="top:{menuPos.top}px;left:{menuPos.left}px;max-height:{menuPos.maxHeight}px;width:{menuPos.width}px"
role="listbox"
aria-label={ariaLabel}
>
{#each options as opt, index (opt.value)}
<button
type="button"
tabindex="-1"
onkeydown={onKey}
id={`${id}-option-${index}`}
class="menu-item"
class:active={opt.value === value}
class:current={index === active}
role="option"
aria-selected={opt.value === value}
title={opt.label}
onpointermove={() => (active = index)}
onmousedown={(e) => e.preventDefault()}
onclick={() => select(index)}
>
<span class="item-label">{opt.label}</span>
{#if opt.value === value}<Icon name="check" size={14} />{/if}
</button>
{/each}
</div>
{/if}
<style>
.pill-wrap {
position: relative;
display: inline-flex;
max-width: 100%;
}
.pill {
display: inline-flex;
align-items: center;
gap: 6px;
height: var(--pill-height, 36px);
padding: var(--pill-padding, 0 14px);
border-radius: var(--pill-radius, 9999px);
background: var(--pill-bg, var(--bg-elevated));
border: 1px solid var(--pill-border, var(--border));
color: var(--text-primary);
font-size: var(--pill-font-size, 13px);
font-family: var(--font-body);
cursor: pointer;
max-width: 100%;
transition:
border-color 0.15s,
background 0.15s;
}
.pill:hover {
border-color: var(--text-muted);
}
.pill:focus-visible {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.pill.highlight {
border-color: var(--accent);
color: var(--accent);
}
.pill-label {
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 280px;
}
.pill-menu {
position: fixed;
z-index: 10000;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow:
0 8px 24px rgba(0, 0, 0, 0.5),
0 0 0 1px rgba(0, 0, 0, 0.3);
padding: 4px;
display: flex;
flex-direction: column;
gap: 2px;
overflow-y: auto;
overscroll-behavior: contain;
}
.menu-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 12px;
border-radius: var(--radius-sm);
background: transparent;
border: none;
color: var(--text-secondary);
font-size: 13px;
font-family: var(--font-body);
cursor: pointer;
text-align: left;
width: 100%;
}
.item-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu-item:hover {
background: var(--bg-elevated);
color: var(--text-primary);
}
.menu-item.active {
color: var(--accent);
font-weight: 600;
}
/* Compact agent controls map to the approved theme tokens; one set of rules
below renders both this variant and existing Omni consumers. */
.compact {
--select-height: var(--agent-select-height);
--select-padding: var(--agent-select-padding);
--select-gap: var(--agent-select-gap);
--select-radius: var(--agent-chip-radius);
--select-bg: var(--bg-2);
--select-border: var(--line);
--select-color: var(--tx-2);
--select-size: var(--agent-select-font);
--select-font: var(--font);
--select-width: var(--agent-select-width);
--select-hover-border: var(--line-3);
--select-open-border: var(--agent-select-selected-border);
--select-open-bg: var(--agent-select-selected-bg);
--select-menu-bg: var(--bg-2);
--select-menu-border: var(--line-2);
--select-menu-radius: var(--r-md);
--select-item-radius: var(--r-sm);
--select-item-color: var(--tx-2);
--select-item-hover: var(--bg-3);
--select-item-selected: var(--sc-agent);
--select-item-selected-bg: var(--agent-select-selected-bg);
--select-item-ring: inset 0 0 0 1px var(--agent-select-selected-border);
}
.pill-wrap {
position: relative;
display: inline-flex;
max-width: 100%;
min-width: 0;
}
.pill {
display: inline-flex;
align-items: center;
gap: var(--select-gap, 6px);
height: var(--select-height, var(--pill-height));
padding: var(--select-padding, var(--pill-padding));
border-radius: var(--select-radius, var(--pill-radius));
background: var(--select-bg, var(--pill-bg));
border: 1px solid var(--select-border, var(--pill-border));
color: var(--select-color, var(--text-primary));
font-size: var(--select-size, var(--pill-font-size));
font-family: var(--select-font, var(--font-body));
cursor: pointer;
min-width: 0;
max-width: min(100%, var(--select-width, 100%));
transition:
border-color var(--t-fast),
background var(--t-fast);
}
.pill:hover:not(:disabled) {
border-color: var(--select-hover-border, var(--text-muted));
color: var(--tx-1);
}
.pill:focus-visible {
outline: 2px solid var(--gold);
outline-offset: 2px;
}
.pill.highlight {
border-color: var(--accent);
color: var(--accent);
}
.pill[aria-expanded="true"] {
border-color: var(--select-open-border, var(--gold));
background: var(--select-open-bg, var(--bg-3));
color: var(--tx-1);
}
.pill:disabled {
opacity: var(--agent-select-disabled-opacity);
cursor: default;
}
.pill > :global(svg),
.menu-item > :global(svg) {
flex: none;
}
.pill-label {
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 280px;
}
.pill-menu {
position: fixed;
z-index: 10000;
background: var(--select-menu-bg, var(--bg-surface));
border: 1px solid var(--select-menu-border, var(--border));
border-radius: var(--select-menu-radius, var(--radius-md));
box-shadow: var(--sh-2);
padding: 4px;
display: flex;
flex-direction: column;
gap: 2px;
overflow-y: auto;
box-sizing: border-box;
max-width: calc(100vw - 16px);
scrollbar-width: thin;
scrollbar-color: var(--line-3) transparent;
overscroll-behavior: contain;
}
.menu-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 12px;
border-radius: var(--select-item-radius, var(--radius-sm));
background: transparent;
border: none;
color: var(--select-item-color, var(--text-secondary));
font: var(--select-size, 13px)/1.55 var(--select-font, var(--font-body));
cursor: pointer;
text-align: left;
width: 100%;
box-sizing: border-box;
flex: none;
}
.item-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu-item.current {
background: var(--select-item-hover, var(--bg-elevated));
color: var(--tx-1);
}
.menu-item.active {
background: var(--select-item-selected-bg, transparent);
color: var(--select-item-selected, var(--accent));
font-weight: 600;
}
.menu-item.active.current {
box-shadow: var(--select-item-ring, none);
}
</style>
+40 -9
View File
@@ -5,7 +5,12 @@
useQueryClient,
} from "@tanstack/svelte-query";
import { SvelteSet } from "svelte/reactivity";
import { libraryApi, assetUrl, type LibraryMediaItem } from "$lib/api";
import {
libraryApi,
assetUrl,
apiErrorMessage,
type LibraryMediaItem,
} from "$lib/api";
import ManagementPage from "$lib/components/manage/ManagementPage.svelte";
import AttachToProject from "$lib/components/AttachToProject.svelte";
import ImageLightbox from "$lib/components/ImageLightbox.svelte";
@@ -146,6 +151,28 @@
selectAll();
}
}
// Kept reasons the server reports per path — each maps to one user-facing
// explanation so a kept file says why it was kept (HEL-872).
const KEPT_REASONS: Record<string, string> = {
referenced: "已被项目使用",
on_canvas: "仍在画布中使用",
project_owned: "属于项目文件,不归素材库删除",
outside_assets: "不在素材库存储范围内",
unlink_failed: "文件被占用或无权限,删除失败",
other: "无法删除",
};
function keptSummary(kept: { reason?: string }[]) {
const byReason: Record<string, number> = {};
for (const r of kept) {
const key = (r.reason && KEPT_REASONS[r.reason]) ? r.reason : "other";
byReason[key] = (byReason[key] ?? 0) + 1;
}
const parts = Object.entries(byReason).map(
([reason, n]) => `${KEPT_REASONS[reason]} ${n}`,
);
const hint = byReason.on_canvas ? ";画布中的素材请先删除对应卡片" : "";
return `保留 ${kept.length} 个:${parts.join(" · ")}${hint}`;
}
const deleteMutation = createMutation({
mutationFn: async (paths: string[]) => {
const results = [];
@@ -155,17 +182,21 @@
},
onSuccess: (batch) => {
const deleted = batch.reduce((n, r) => n + r.deleted.length, 0),
kept = batch
.flatMap((r) => r.results)
.filter((r) => r.status === "kept").length;
toast.info(
`已删除 ${deleted} 个文件${kept ? ` · 保留 ${kept} 个:被项目使用或无法删除` : ""}`,
);
kept = batch.flatMap((r) => r.results).filter((r) => r.status === "kept");
if (deleted > 0) {
toast.success(
`已删除 ${deleted} 个文件${kept.length ? ` · ${keptSummary(kept)}` : ""}`,
);
} else {
toast.error(
`未能删除 ${kept.length} 个文件 · ${keptSummary(kept)}`,
);
}
selected.clear();
deletePaths = [];
void client.invalidateQueries({ queryKey: ["library-media"] });
},
onError: (e) => toast.error(e.message),
onError: (e) => toast.error(`删除请求失败:${apiErrorMessage(e)}`),
});
function attached(path: string, title: string) {
attachPaths = attachPaths.filter((p) => p !== path);
@@ -470,7 +501,7 @@
open={deletePaths.length > 0}
title={"删除 " + deletePaths.length + " 个文件?"}
onclose={() => (deletePaths = [])}
><p>删除前服务器会再次检查,若文件此刻已被项目使用会自动保留。</p>
><p>删除前服务器会再次检查,仍在画布或项目中使用的文件会自动保留并说明原因。</p>
<div class="delete-preview">
{#each items.filter((i) => deletePaths.includes(i.path)) as i (i.path)}<div>
<SafeMedia
@@ -569,9 +569,9 @@
color: var(--scene);
}
[data-theme="day"] .lib2 {
--lib-option-bg: var(--hi);
--lib-option-bg: #ffffff;
--lib-option-shadow:
0 1px 2px rgb(var(--ink) / 0.14), 0 0 0 1px rgb(var(--ink) / 0.06);
0 1px 2px rgba(60, 44, 20, 0.14), 0 0 0 1px rgb(var(--ink) / 0.06);
}
[data-theme="day"] .lib-search {
border-color: var(--line-3);
+16
View File
@@ -6,6 +6,22 @@
--agent-bubble-radius: 12px;
--agent-tool-radius: 10px;
--agent-chip-radius: var(--r-pill);
--agent-select-height: 26px;
--agent-select-padding: 0 10px;
--agent-select-gap: 5px;
--agent-select-font: 12px;
--agent-select-width: 220px;
--agent-select-disabled-opacity: 0.45;
--agent-select-selected-bg: color-mix(
in srgb,
var(--sc-agent) 13%,
var(--bg-2)
);
--agent-select-selected-border: color-mix(
in srgb,
var(--sc-agent) 60%,
transparent
);
--agent-orb-shadow: 0 0 80px
color-mix(in srgb, var(--sc-agent) 60%, transparent);
--agent-ring-shadow: 0 0 12px var(--gold);
@@ -0,0 +1,7 @@
HEL-845 素材库日间选中态
`library-v2.css` 原有 day 局部 token 改两行:选中背景由深色 `--hi` 改为批准原样的 `#ffffff`;阴影第一层由 `rgba(38,30,18,.14)` 恢复 `rgba(60,44,20,.14)`,第二层保持原样。文字与图标继续复用原有 token,未添加覆盖规则、组件或依赖,未改变全站 `--hi`、其他主题、结构、尺寸、动效、业务或后端。MF-1 修复保留。
前端 check 零错零警,lint/test/build 通过。`scripts/hel845/verify.py` 对真实隔离构建执行四主题、三窗口、四组合 48 状态,比较批准 HTML 与产品实际背景/文字/图标/阴影,并验证键盘焦点、aria-pressed、适配/密度切换、筛选查找排序与选择。日间白底深字文字对比约 17.13:1(精确值以交付 JSON 为准);其他主题与修前映射保持一致。复现、证据范围和清理机制见同目录 README。
纯 CSS 修复未重跑后端全量,复用 HEL-843 对 MF-1 的后端审核证据;未调用真实付费 LLM/GPU,未合并部署。隔离截图用于定向审核,不代替上线后目检或用户验收。
@@ -0,0 +1,13 @@
HEL-849 修复智能体首页输入区三个原生下拉的展开外观与交互。
- `AgentWorkspace.svelte` 复用 `PillSelect`:项目/沙盒、任务模型、任务技能仍使用原状态和 API,模型标签显示实际角色绑定;busy 时三个入口禁用。成果区原生选择器、AgentComposer 的 @ 工作流与 / 技能菜单保持原组件。
- `PillSelect.svelte` 补充 select-only combobox 语义、候选焦点与确认选择分离、Tab/方向键/Home/End/Enter/Space/Esc、外部点击、焦点返回、禁用守卫;菜单 body portal、长列表滚动、窗口/visualViewport 避边。输入区优先向上展开,避免遮挡换行后的主操作。
- `static/themes.css` 为紧凑款提供唯一尺寸与选中颜色 token。复用已批准的 26px 胶囊、场景色 13% 选中底/60% 描边、主题圆角与阴影;共享组件只有一套渲染规则。
隔离验证:四主题 × 1440×900、1366×768、1280×720,闭合/hover/焦点/展开/选中截图及操作录屏;71 项断言通过、浏览器无异常。包含真实项目绑定、模型保存刷新、长名称/列表、取消不改值、busy 禁用、主题切换保持草稿/附件、900×600 小窗、150% 页面缩放、三档光球双环保留、上传与真实发送负载、成果项目/阶段保存、@ 和 / 菜单及原会话入口。
`npm run check`:0 错误/0 警告;`npm run lint`:0 错误/0 警告;`npm test` 和 `npm run build` 通过。构建保留基线已有的 @xyflow/system 第三方未使用导出提示。
复现:先 `npm ci --prefix calliope-web`、`npm --prefix calliope-web run build`,再设置 `PLAYWRIGHT_MODULE_PATH` 为现有 Playwright 模块路径(如模块已在 Node 查找路径可省略),运行 `python3 e2e/run-hel849.py`。Chromium 系统库按环境设置 `LD_LIBRARY_PATH`,Python 需使用既有后端依赖环境。脚本只启动 127.0.0.1:18259/15259/19259,独立临时数据目录,假模型回复、无真实生成。结果写到仓库外的 `evidence/hel849`;成功/异常都停止确切自有 PID 并删除临时数据。`HEL849_PHASE=before` 仅用于以基线构建采集修前证据。
共享影响:现有 OmniComposer 的选择器继承上述键盘/定位修复;仓库中该组件仅被未接入路由的 VideoEditWorkspace 引用,本次没有声称对不可达页面完成浏览器验收。当前智能体成果区、任务输入菜单和原会话入口已完成实际回归。后端、模型配置/密钥、提示词、画布业务与依赖未修改;未部署、未合并。
+539
View File
@@ -0,0 +1,539 @@
const { chromium } = require(
process.env.PLAYWRIGHT_MODULE_PATH || "playwright",
);
const fs = require("node:fs"),
assert = require("node:assert/strict");
const OUT = "../evidence/hel849",
WEB = "http://127.0.0.1:15259",
API = "http://127.0.0.1:18259";
const phase = process.env.HEL849_PHASE || "after";
const report = { phase, checks: [], states: [], errors: [] };
const ok = (name, pass) => {
report.checks.push({ name, pass: !!pass });
assert(pass, name);
console.log("PASS", name);
};
const api = async (p, b, method) => {
const r = await fetch(API + p, {
method: method || (b ? "POST" : "GET"),
headers: { "Content-Type": "application/json" },
body: b ? JSON.stringify(b) : undefined,
});
assert(r.ok, await r.clone().text());
const t = await r.text();
return t ? JSON.parse(t) : null;
};
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
(async () => {
fs.mkdirSync(`${OUT}/${phase}`, { recursive: true });
const project = await api("/api/projects", {
title: "下拉回归项目 · 海岸来信",
idea: "隔离测试",
});
for (let i = 0; i < 35; i++)
await api("/api/projects", {
title: `长列表项目 ${i.toString().padStart(2, "0")} · 很长很长的项目名称用于确认截断和菜单避边`,
idea: "隔离测试",
});
const config = await api("/api/settings");
await api("/api/settings", {
llm_profiles: [
...config.llm_profiles.map((p) => ({ ...p, api_key: "" })),
...Array.from({ length: 35 }, (_, i) => ({
id: `model-${i}`,
name: `隔离模型 ${i} · 很长的模型名称与版本号`,
base_url: "http://127.0.0.1:19259/v1",
model: "isolated",
api_key: "",
})),
],
});
const skills = await api("/api/agent/skills?all=true");
const enabled = skills.filter((s) => s.is_enabled);
ok("real builtin skills available", enabled.length > 0);
const browser = await chromium.launch({
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
const ctx = await browser.newContext({
viewport: { width: 1440, height: 900 },
recordVideo: { dir: `${OUT}/${phase}/video` },
});
await ctx.tracing.start({
screenshots: true,
snapshots: true,
sources: true,
});
const p = await ctx.newPage();
p.on("pageerror", (e) => report.errors.push(e.stack));
p.setDefaultTimeout(10000);
await ctx.addInitScript(() => {
localStorage.setItem("aigc-lang", "zh");
localStorage.setItem("aigc-motion", "off");
});
try {
await p.goto(WEB + "/agents");
await p.getByLabel("任务想法").waitFor();
await pause(400);
for (const [width, height] of process.env.HEL849_QUICK
? []
: [
[1440, 900],
[1366, 768],
[1280, 720],
])
for (const theme of ["night", "day", "grade", "bluehour"]) {
await p.setViewportSize({ width, height });
await p.evaluate((theme) => {
document.documentElement.dataset.theme = theme;
window.dispatchEvent(
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
);
}, theme);
await pause(100);
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-closed.png`,
});
for (const label of ["绑定项目", "任务模型", "任务技能"]) {
const control = p.getByRole("combobox", { name: label, exact: true });
await control.hover();
if (phase === "after")
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-hover.png`,
});
await control.focus();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-focus.png`,
});
await control.click();
await pause(100);
report.states.push(
await control.evaluate(
(e, { theme, width, height, label }) => ({
theme,
width,
height,
label,
url: location.href,
title: document.title,
dataTheme: document.documentElement.dataset.theme,
tag: e.tagName,
expanded: e.getAttribute("aria-expanded"),
focus: document.activeElement === e,
style: {
background: getComputedStyle(e).backgroundColor,
color: getComputedStyle(e).color,
},
menu: document
.querySelector(".pill-menu")
?.getBoundingClientRect()
.toJSON(),
}),
{ theme, width, height, label },
),
);
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-${label}-open.png`,
});
if (phase === "after")
ok(
`${theme}-${width}-${label} menu avoids primary action`,
await p.locator(".pill-menu").evaluate((e) => {
const m = e.getBoundingClientRect(),
b = document
.querySelector(".big-input .primary")
.getBoundingClientRect();
return (
m.right <= b.left ||
m.left >= b.right ||
m.bottom <= b.top ||
m.top >= b.bottom
);
}),
);
await p.keyboard.press("Escape");
}
if (phase === "after") {
const skill = p.getByRole("combobox", {
name: "任务技能",
exact: true,
});
await skill.click();
await p.getByRole("option").nth(1).click();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-selected.png`,
});
await skill.click();
await p.screenshot({
path: `${OUT}/${phase}/${theme}-${width}-selected-open.png`,
});
await p.keyboard.press("Escape");
}
console.log("CAPTURE", phase, theme, width, height);
}
if (phase === "before") {
const projectSelect = p.getByLabel("绑定项目");
await projectSelect.selectOption(String(project.id));
ok(
"native project binds real id",
(await projectSelect.inputValue()) === String(project.id),
);
await p.getByLabel("任务模型").selectOption("model-1");
await pause(300);
ok(
"native model persists",
(await api("/api/settings")).agent_llm_assignments.main === "model-1",
);
ok(
"native dropdown is browser controlled",
(await p.locator(".big-input select").count()) === 3,
);
} else {
const projectControl = p.getByRole("combobox", {
name: "绑定项目",
exact: true,
}),
model = p.getByRole("combobox", { name: "任务模型", exact: true }),
skill = p.getByRole("combobox", { name: "任务技能", exact: true });
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
ok(
"click selects real project and returns focus",
(await projectControl.getAttribute("title")) ===
`绑定:${project.title}` &&
(await projectControl.evaluate((e) => e === document.activeElement)),
);
const selectedTitle = await projectControl.getAttribute("title");
await projectControl.press("ArrowDown");
await projectControl.press("End");
ok(
"long list scrolls to keyboard candidate",
await p.locator(".pill-menu").evaluate((e) => e.scrollTop > 0),
);
ok(
"navigation alone leaves project unchanged",
(await projectControl.getAttribute("title")) === selectedTitle,
);
await projectControl.press("Escape");
ok(
"Esc cancels and returns focus",
(await projectControl.getAttribute("title")) === selectedTitle &&
(await projectControl.evaluate(
(e) => e === document.activeElement,
)) &&
(await p.locator(".pill-menu").count()) === 0,
);
await projectControl.press(" ");
ok(
"Space opens listbox",
(await projectControl.getAttribute("aria-expanded")) === "true",
);
await projectControl.press("Home");
await projectControl.press("Enter");
ok(
"Enter confirms sandbox with focus restored",
(await projectControl.getAttribute("title")) === "绑定:沙盒" &&
(await projectControl.evaluate((e) => e === document.activeElement)),
);
await projectControl.press("ArrowDown");
await projectControl.press("End");
await projectControl.press("Enter");
ok(
"long selected project is constrained and full title retained",
await projectControl.evaluate(
(e) => e.getBoundingClientRect().width <= 220 && e.title.length > 30,
),
);
await p.screenshot({ path: `${OUT}/${phase}/long-selected.png` });
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
await projectControl.click();
await p.getByRole("heading", { name: "阶段助手" }).click();
ok(
"outside click closes without committing",
(await p.locator(".pill-menu").count()) === 0 &&
(await projectControl.getAttribute("title")) === selectedTitle,
);
await projectControl.focus();
await p.keyboard.press("Tab");
ok(
"Tab reaches model",
await model.evaluate((e) => e === document.activeElement),
);
await model.press("ArrowDown");
await model.press("End");
await model.press("ArrowUp");
await model.press("Home");
await model.press("Escape");
await p.route("**/api/settings", async (route) => {
if (["POST", "PATCH", "PUT"].includes(route.request().method())) {
await pause(650);
}
await route.continue();
});
await model.click();
await p
.getByRole("option", {
name: "隔离模型 1 · 很长的模型名称与版本号",
exact: true,
})
.click();
await p.waitForFunction(() =>
[...document.querySelectorAll(".big-input [role=combobox]")].every(
(e) => e.disabled,
),
);
ok(
"busy disables all three selectors",
(await p.locator(".big-input [role=combobox]:disabled").count()) === 3,
);
await projectControl.dispatchEvent("click");
await projectControl.dispatchEvent("keydown", { key: "ArrowDown" });
ok(
"disabled selectors cannot open",
(await p.locator(".pill-menu").count()) === 0,
);
await p.screenshot({ path: `${OUT}/${phase}/busy.png` });
await model.waitFor({ state: "visible" });
await p.waitForFunction(
() => !document.querySelector('[aria-label="任务模型"]').disabled,
);
ok(
"model assignment persisted",
(await api("/api/settings")).agent_llm_assignments.main === "model-1",
);
await p.reload();
await p.getByLabel("任务想法").waitFor();
await pause(300);
ok(
"model survives reload",
(await model.getAttribute("title")).includes("隔离模型 1"),
);
await projectControl.click();
await p.getByRole("option", { name: project.title, exact: true }).click();
await skill.click();
await p
.getByRole("option")
.filter({ hasText: enabled[0].name })
.first()
.click();
await p.getByLabel("任务想法").fill("HEL849 隔离发送与上传回归");
await p
.locator(".big-input input[type=file]")
.setInputFiles({
name: "reference.txt",
mimeType: "text/plain",
buffer: Buffer.from("HEL849 isolated reference"),
});
await p.waitForFunction(() =>
document
.querySelector(".big-input")
.textContent.includes("参考材料 · 1"),
);
const beforeTitle = await skill.getAttribute("title");
for (const theme of ["night", "day", "grade", "bluehour"]) {
await p.evaluate((theme) => {
window.dispatchEvent(
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
);
}, theme);
ok(
theme + " retains draft/project/model/skill/upload",
(await p.getByLabel("任务想法").inputValue()).includes("HEL849") &&
(await projectControl.getAttribute("title")) === selectedTitle &&
(await skill.getAttribute("title")) === beforeTitle &&
(await model.getAttribute("title")).includes("隔离模型 1") &&
(await p.locator(".big-input").innerText()).includes(
"参考材料 · 1",
),
);
}
await projectControl.click();
await p.setViewportSize({ width: 900, height: 600 });
await pause(100);
report.small = await p
.locator(".pill-menu")
.evaluate((e) => ({
menu: e.getBoundingClientRect().toJSON(),
trigger: document
.querySelector("[aria-label=绑定项目]")
.getBoundingClientRect()
.toJSON(),
view: { w: innerWidth, h: innerHeight, v: visualViewport.height },
scroll: e.scrollHeight,
}));
await p.screenshot({ path: `${OUT}/${phase}/small.png` });
console.log("SMALL", JSON.stringify(report.small));
ok(
"small window menu stays within viewport",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect();
return (
r.left >= 7 &&
r.right <= innerWidth - 7 &&
r.top >= 7 &&
r.bottom <= innerHeight - 7
);
}),
);
await p.locator(".agent-home").evaluate((e) => (e.scrollTop = 200));
await pause(100);
ok(
"scroll keeps menu anchored",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect();
return r.top >= 7 && r.bottom <= innerHeight - 7;
}),
);
await p.keyboard.press("Escape");
await p.setViewportSize({ width: 1440, height: 900 });
const cdp = await ctx.newCDPSession(p);
await cdp.send("Emulation.setPageScaleFactor", { pageScaleFactor: 1.5 });
await projectControl.click();
await pause(100);
ok(
"150% browser page scale uses visual viewport bounds",
await p.locator(".pill-menu").evaluate((e) => {
const r = e.getBoundingClientRect(),
v = visualViewport;
return (
r.left >= v.offsetLeft &&
r.right <= v.offsetLeft + v.width + 1 &&
r.top >= v.offsetTop &&
r.bottom <= v.offsetTop + v.height + 1
);
}),
);
await p.keyboard.press("Escape");
await cdp.send("Emulation.setPageScaleFactor", { pageScaleFactor: 1 });
for (const name of ["完整", "克制", "关闭"]) {
await p.locator('.sidebar-bottom button[title="主题"]').click();
await p
.locator(".theme-motion")
.getByRole("button", { name, exact: true })
.click();
await p.keyboard.press("Escape");
const state = await p
.locator(".orb")
.evaluate((e) => ({
display: getComputedStyle(e).display,
rings: [...e.querySelectorAll(".ring")].map((r) => ({
animation: getComputedStyle(r).animationName,
play: getComputedStyle(r).animationPlayState,
})),
}));
report.states.push({ motion: name, ...state });
ok(
name + " preserves approved orb and double rings",
state.rings.length === 2 &&
(name === "关闭"
? state.display === "none"
: state.display !== "none"),
);
ok(
name + " preserves input state",
(await projectControl.getAttribute("title")) === selectedTitle &&
(await skill.getAttribute("title")) === beforeTitle,
);
}
const sent = p.waitForRequest(
(r) =>
/\/api\/agent\/sessions\/\d+\/messages$/.test(r.url()) &&
r.method() === "POST",
);
await p.getByRole("button", { name: "开始任务", exact: true }).click();
const request = await sent;
const payload = request.postDataJSON();
report.sentPayload = payload;
ok(
"real send payload includes chosen skill",
payload.mentions.some(
(m) => m.type === "skill" && m.name === enabled[0].dir,
),
);
ok(
"real send retains uploaded reference",
payload.attachments.length === 1 &&
payload.attachments[0].name === "reference.txt",
);
const sid = Number(new URL(p.url()).searchParams.get("session"));
const session = await api("/api/agent/sessions/" + sid);
ok(
"real session bound to chosen project",
session.project_id === project.id,
);
await p.waitForFunction(() => {
const e = document.querySelector('[aria-label="成果项目"]');
return e && !e.disabled;
});
await p
.getByLabel("成果项目", { exact: true })
.selectOption(String(project.id));
await p.getByLabel("成果阶段", { exact: true }).selectOption("assets");
await p.getByRole("button", { name: "保存草稿", exact: true }).click();
await pause(200);
const results = await api("/api/results/deliverables?session_id=" + sid);
ok(
"result project/stage selectors still save real draft",
results[0].project_id === project.id &&
results[0].stage_key === "assets",
);
await p.locator(".composer .editor").waitFor();
const editor = p.locator(".composer .editor");
await editor.fill("/");
await editor.press("End");
await editor.press(enabled[0].name[0]);
await p.locator(".mention-menu").waitFor();
ok(
"slash skill menu still opens",
(await p.locator(".mention-menu [role=option]").count()) > 0,
);
await p.keyboard.press("Escape");
await api("/api/workflows", {
name: "HEL849 test workflow",
kind: "image",
workflow_json: {
1: {
class_type: "CLIPTextEncode",
inputs: { text: "test" },
_meta: { title: "(Input:prompt)" },
},
9: {
class_type: "SaveImage",
inputs: { images: "x" },
_meta: { title: "(Output:image)" },
},
},
});
await p.reload();
await editor.waitFor();
await editor.fill("@");
await editor.press("End");
await editor.press("H");
await p.locator(".mention-menu").waitFor();
ok(
"workflow menu still opens",
(await p.locator(".mention-menu [role=option]").count()) > 0,
);
await p.keyboard.press("Escape");
// Existing Omni consumers share the enhanced selector; ensure route is still usable.
await p.goto(WEB + "/agents?legacy=1");
await p.locator(".agent-rail").waitFor();
ok(
"legacy agent route still available",
(await p.locator(".agent-rail").count()) === 1,
);
}
ok("no browser exceptions", report.errors.length === 0);
} finally {
fs.writeFileSync(
`${OUT}/${phase}-report.json`,
JSON.stringify(report, null, 2),
);
await ctx.tracing.stop({ path: `${OUT}/${phase}/trace.zip` });
await ctx.close();
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+190
View File
@@ -0,0 +1,190 @@
// HEL-872 — real-page library delete regression (isolated API, real build).
// Drives /library with a real browser: single delete, cancel, canvas-held
// retention reason, mixed batch, HTTP-failure retry. Asserts disk + list.
const { chromium } = require(
process.env.PLAYWRIGHT_MODULE_PATH || "playwright",
);
const fs = require("node:fs"),
assert = require("node:assert/strict");
const OUT = "../evidence/hel872",
WEB = "http://127.0.0.1:15272",
API = "http://127.0.0.1:18272";
const phase = process.env.HEL872_PHASE || "after";
const report = { phase, checks: [], errors: [] };
const ok = (name, pass) => {
report.checks.push({ name, pass: !!pass });
assert(pass, name);
console.log("PASS", name);
};
const api = async (p, b, method) => {
const r = await fetch(API + p, {
method: method || (b ? "POST" : "GET"),
headers: { "Content-Type": "application/json" },
body: b ? JSON.stringify(b) : undefined,
});
assert(r.ok, await r.clone().text());
const t = await r.text();
return t ? JSON.parse(t) : null;
};
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
const lastToast = (p) =>
p.evaluate(() => {
const els = document.querySelectorAll(".toast, [class*='toast']");
return els.length ? els[els.length - 1].textContent : "";
});
(async () => {
fs.mkdirSync(`${OUT}/${phase}`, { recursive: true });
const names = await api("/api/library/media");
const byName = Object.fromEntries(names.map((i) => [i.name, i.path]));
const free = byName["aaaa-free-upload.png"];
const plain = byName["plain-scratch-out.png"];
const held = byName["held-on-canvas.png"];
ok("seed: three visible library items", !!free && !!plain && !!held);
ok("seed: project-referenced file hidden from list", !names.some((i) => i.name === "hidden-project-ref.png"));
const browser = await chromium.launch({
channel: "chromium", // full build — headless shell lacks host libs
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
const ctx = await browser.newContext({
viewport: { width: 1440, height: 900 },
recordVideo: { dir: `${OUT}/${phase}/video` },
});
const p = await ctx.newPage();
p.on("pageerror", (e) => report.errors.push(e.stack));
p.setDefaultTimeout(12000);
await ctx.addInitScript(() => {
localStorage.setItem("aigc-lang", "zh");
localStorage.setItem("aigc-motion", "off");
});
await p.goto(WEB + "/library");
await p.getByRole("button", { name: /查看 aaaa-free-upload/ }).waitFor();
await pause(400);
await p.screenshot({ path: `${OUT}/${phase}/01-initial.png` });
// ── cancel leaves everything untouched ─────────────────────────────
await p.getByRole("button", { name: /查看 plain-scratch-out/ }).click();
await p.getByRole("button", { name: "删除此文件" }).click();
await p.getByRole("dialog").getByText("删除 1 个文件?").waitFor();
await p.screenshot({ path: `${OUT}/${phase}/02-confirm-dialog.png` });
await p.getByRole("dialog").getByRole("button", { name: "取消" }).click();
await pause(400);
ok("cancel: modal closed", !(await p.getByRole("dialog").count()));
ok("cancel: file untouched on disk", fs.existsSync(plain));
if (phase === "before") {
// ── defect demo: canvas-held file kept with merged vague reason ──
await p.getByRole("button", { name: /查看 held-on-canvas/ }).click();
await p.getByRole("button", { name: "删除此文件" }).click();
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(800);
const toast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/03-before-held-toast.png` });
ok("before: canvas-held delete reports 0 deleted", /已删除 0 个文件/.test(toast));
ok("before: merged vague reason (defect)", /被项目使用或无法删除/.test(toast));
ok("before: file survives (protection works)", fs.existsSync(held));
} else {
// ── deletable file: cancel already proven; now confirm ──────────
await p.getByRole("button", { name: /查看 plain-scratch-out/ }).click();
await p.getByRole("button", { name: "删除此文件" }).click();
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(900);
const toast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/03-deleted-single.png` });
ok("single delete: success toast", /已删除 1 个文件/.test(toast));
ok("single delete: file really gone from disk", !fs.existsSync(plain));
await p.getByRole("button", { name: /查看 aaaa-free-upload/ }).waitFor();
ok(
"single delete: gone from list after refresh",
!(await p.getByRole("button", { name: /查看 plain-scratch-out/ }).count()),
);
await p.reload();
await p.getByRole("button", { name: /查看 aaaa-free-upload/ }).waitFor();
ok(
"single delete: no resurrection after page reload",
!(await p.getByRole("button", { name: /查看 plain-scratch-out/ }).count()),
);
// ── canvas-held file: kept with the accurate reason ─────────────
await p.getByRole("button", { name: /查看 held-on-canvas/ }).click();
await p.getByRole("button", { name: "删除此文件" }).click();
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(900);
const heldToast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/04-held-on-canvas.png` });
ok("held: nothing deleted reported", /未能删除 1 个文件/.test(heldToast));
ok("held: accurate on-canvas reason", /仍在画布中使用 1/.test(heldToast));
ok("held: actionable hint", /请先删除对应卡片/.test(heldToast));
ok("held: file survives on disk", fs.existsSync(held));
await p.getByRole("button", { name: /查看 held-on-canvas/ }).waitFor();
ok("held: still listed (kept, not hidden)", (await p.getByRole("button", { name: /查看 held-on-canvas/ }).count()) === 1);
// ── mixed batch: partial success with per-reason breakdown ──────
await p.getByRole("button", { name: "选择", exact: true }).click();
await p.getByRole("button", { name: /选择 aaaa-free-upload/, exact: true }).click();
await p.getByRole("button", { name: /选择 held-on-canvas/, exact: true }).click();
await p.getByRole("button", { name: "删除", exact: true }).click();
await p.getByRole("dialog").getByText("删除 2 个文件?").waitFor();
await p.screenshot({ path: `${OUT}/${phase}/05-batch-dialog.png` });
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(900);
const batchToast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/06-batch-result.png` });
ok("batch: one deleted one kept", /已删除 1 个文件/.test(batchToast) && /保留 1 个/.test(batchToast));
ok("batch: kept reason named", /仍在画布中使用 1/.test(batchToast));
ok("batch: free file gone from disk", !fs.existsSync(free));
ok("batch: held file survives", fs.existsSync(held));
ok(
"batch: selection bar cleared after result",
!(await p.getByText("已选 1").count()),
);
// ── HTTP failure: readable error, modal open, retry succeeds ────
await p.reload();
await p.getByRole("button", { name: /查看 held-on-canvas/ }).waitFor();
await p.getByRole("button", { name: /查看 aaaa-free-upload/ }).waitFor().catch(() => {});
// seed one more deletable file through the API for the retry leg
const seeded = await (async () => {
const list = await api("/api/library/media");
return list.find((i) => i.name === "retry-upload.png");
})();
ok("retry: seed file present", !!seeded);
let blocked = 1;
await p.route("**/api/library/media", async (route) => {
if (route.request().method() === "DELETE" && blocked > 0) {
blocked--;
await route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ detail: "隔离测试注入的暂时故障" }) });
return;
}
await route.continue();
});
await p.getByRole("button", { name: /查看 retry-upload/ }).click();
await p.getByRole("button", { name: "删除此文件" }).click();
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(600);
const errToast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/07-error-toast.png` });
ok("failure: readable error toast", /删除请求失败/.test(errToast) && /隔离测试注入的暂时故障/.test(errToast));
ok("failure: no false success", !/已删除/.test(errToast));
ok("failure: file still on disk", fs.existsSync(seeded.path));
ok("failure: modal stays open for retry", (await p.getByRole("dialog").count()) === 1);
await p.getByRole("dialog").getByRole("button", { name: "确认删除" }).click();
await pause(900);
const retryToast = await lastToast(p);
await p.screenshot({ path: `${OUT}/${phase}/08-retry-success.png` });
ok("retry: second confirm succeeds", /已删除 1 个文件/.test(retryToast));
ok("retry: file really gone", !fs.existsSync(seeded.path));
await p.unroute("**/api/library/media");
}
await ctx.close();
await browser.close();
fs.writeFileSync(`${OUT}/${phase}/report.json`, JSON.stringify(report, null, 2));
console.log(`HEL-872 ${phase}: ${report.checks.length} checks passed`);
})().catch((e) => {
report.errors.push(String(e));
fs.writeFileSync(`${OUT}/${phase}/report.json`, JSON.stringify(report, null, 2));
console.error(e);
process.exit(1);
});
+53
View File
@@ -0,0 +1,53 @@
"""Own a loopback-only API, static web and fake model for one foreground check."""
import json, os, signal, socket, subprocess, sys, tempfile, time, urllib.request
from pathlib import Path
root = Path(__file__).resolve().parents[1]
os.chdir(root)
out = root.parent / 'evidence/hel849'
out.mkdir(parents=True, exist_ok=True)
phase = os.environ.get('HEL849_PHASE', 'after')
for port in [18259, 15259, 19259]:
with socket.socket() as s:
assert s.connect_ex(('127.0.0.1', port)) != 0, f'Port occupied: {port}'
processes, handles = [], []
cleanup = []
with tempfile.TemporaryDirectory(prefix='runtime-', dir=out) as tmp:
env = {**os.environ, 'PYTHONPATH': str(root/'calliope-backend/src'), 'HEL849_DATA': tmp}
api = """import os
from pathlib import Path
from calliope import config
root=Path(os.environ['HEL849_DATA'])
config.CONFIG_FILE=root/'settings.json'
config.settings=config.Settings(data_dir=root/'data',assets_dir=root/'data/assets',llm_base_url='http://127.0.0.1:19259/v1',llm_model='isolated',comfyui_base_url='http://127.0.0.1:1',dry_run=False)
config.settings.ensure_storage_dirs();config.settings.ensure_llm_profiles();config.settings.save_config_file()
from calliope.main import create_app
import uvicorn
uvicorn.run(create_app(),host='127.0.0.1',port=18259)
"""
web = (root/'e2e/hel818-web.cjs').read_text().replace('18247','18259').replace('15173','15259')
model = (root/'e2e/reference/fake_llm.py').read_text().replace("root=Path(__file__).resolve().parents[1]/'shots/reference'", 'root=Path('+repr(tmp)+')').replace('18189','19259')
try:
for name, cmd in [('api',[sys.executable,'-c',api]),('web',['node','-e',web]),('model',[sys.executable,'-c',model])]:
h=(out/f'{phase}-{name}.log').open('w');handles.append(h)
processes.append(subprocess.Popen(cmd, env=env, stdout=h, stderr=subprocess.STDOUT))
for url in ['http://127.0.0.1:18259/api/health','http://127.0.0.1:15259']:
for attempt in range(100):
try: urllib.request.urlopen(url,timeout=1);break
except Exception:
if any(p.poll() is not None for p in processes):raise RuntimeError('Service failed')
if attempt==99:raise
time.sleep(.1)
subprocess.run(['node','e2e/hel849.cjs'],env=env,check=True)
finally:
daemon=json.loads(subprocess.check_output(['multica','daemon','status','--output','json']))['pid']
for p in processes:
assert p.pid != daemon
if p.poll() is None:p.send_signal(signal.SIGTERM)
for p in processes:
try:p.wait(timeout=10)
except subprocess.TimeoutExpired:p.kill();p.wait()
cleanup.append({'pid':p.pid,'exit':p.returncode,'daemon':daemon})
for h in handles:h.close()
(out/f'{phase}-cleanup.json').write_text(json.dumps({'children':cleanup,'isolated_data_removed':not Path(tmp).exists()},indent=2))
print('CLEANUP',cleanup,'isolated data removed',not Path(tmp).exists(),flush=True)
+148
View File
@@ -0,0 +1,148 @@
"""HEL-872 — own a loopback-only API + static web for one foreground UI check.
Seeds an isolated library (plain upload, plain scratch output, canvas-held
scratch output, project-referenced upload) and drives the real /library page
via e2e/hel872.cjs. HEL872_PHASE=before|after picks which web build to serve;
both phases run against the SAME backend code (base backend for before, fixed
backend for after — the runner is executed from the tree being tested).
"""
import json, os, signal, socket, sqlite3, subprocess, sys, tempfile, time, urllib.request
from pathlib import Path
root = Path(__file__).resolve().parents[1]
os.chdir(root)
phase = os.environ.get("HEL872_PHASE", "after")
build_dir = os.environ.get("HEL872_BUILD", f"calliope-web/build{'-base' if phase == 'before' else ''}")
out = root.parent / "evidence/hel872"
out.mkdir(parents=True, exist_ok=True)
API_PORT, WEB_PORT = 18272, 15272
for port in (API_PORT, WEB_PORT):
with socket.socket() as s:
assert s.connect_ex(("127.0.0.1", port)) != 0, f"Port occupied: {port}"
PNG = bytes.fromhex(
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
"0000000d4944415478da636460f85f0f0002870180eb47ba920000000049454e44"
"ae426082"
) # canonical 1x1 RGBA PNG fixture
processes, handles, cleanup = [], [], []
with tempfile.TemporaryDirectory(prefix="hel872-", dir=out) as tmp:
tmp = Path(tmp)
env = {**os.environ, "PYTHONPATH": str(root / "calliope-backend/src"),
"HEL872_DATA": str(tmp), "HEL872_BUILD": build_dir,
"LD_LIBRARY_PATH": str(out / "browser-libs"),
"PLAYWRIGHT_MODULE_PATH": "/home/xiaomo/.npm-global/lib/node_modules/playwright"}
api_code = f"""
import os
from pathlib import Path
from calliope import config
root = Path({str(tmp)!r})
config.CONFIG_FILE = root / 'settings.json'
config.settings = config.Settings(
data_dir=root / 'data', assets_dir=root / 'data/assets',
llm_base_url='http://127.0.0.1:1/v1', llm_model='isolated',
comfyui_base_url='http://127.0.0.1:1', dry_run=False)
config.settings.ensure_storage_dirs()
config.settings.ensure_llm_profiles()
from calliope.main import create_app
import uvicorn
uvicorn.run(create_app(), host='127.0.0.1', port={API_PORT})
"""
web_code = """
const http=require('node:http'),fs=require('node:fs'),path=require('node:path');
const build=path.resolve(process.env.HEL872_BUILD);
http.createServer((req,res)=>{
if(req.url.startsWith('/api/')){
const q=http.request('http://127.0.0.1:%d'+req.url,{method:req.method,headers:req.headers},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res)});
q.on('error',()=>{res.statusCode=502;res.end()});res.on('close',()=>q.destroy());req.pipe(q);return}
let file=path.join(build,new URL(req.url,'http://localhost').pathname);
if(!fs.existsSync(file)||fs.statSync(file).isDirectory())file=path.join(build,'index.html');
res.setHeader('Content-Type',({'.js':'text/javascript','.css':'text/css','.html':'text/html','.png':'image/png','.jpg':'image/jpeg','.woff2':'font/woff2','.svg':'image/svg+xml'})[path.extname(file)]||'application/octet-stream');
fs.createReadStream(file).pipe(res);
}).listen(%d,'127.0.0.1');
""" % (API_PORT, WEB_PORT)
def seed():
base = f"http://127.0.0.1:{API_PORT}"
def post(p, body):
req = urllib.request.Request(base + p, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
return json.load(urllib.request.urlopen(req, timeout=10))
db = sqlite3.connect(tmp / "data" / "calliope.db")
db.execute("INSERT INTO projects (title, idea, status) VALUES ('Playground Scratch', NULL, 'system')")
db.commit()
pid = db.execute("SELECT id FROM projects WHERE status='system'").fetchone()[0]
up = tmp / "data" / "assets" / "uploads"
scratch_img = tmp / "data" / "assets" / str(pid) / "image"
up.mkdir(parents=True, exist_ok=True)
scratch_img.mkdir(parents=True, exist_ok=True)
(up / "aaaa-free-upload.png").write_bytes(PNG)
(up / "retry-upload.png").write_bytes(PNG)
(up / "hidden-project-ref.png").write_bytes(PNG)
(scratch_img / "plain-scratch-out.png").write_bytes(PNG)
held = scratch_img / "held-on-canvas.png"
held.write_bytes(PNG)
db.execute("INSERT INTO canvas (id, title) VALUES (1, '隔离沙盒画布')")
db.execute(
"INSERT INTO canvas_node (canvas_id, type, title, artifact_path, status)"
" VALUES (1, 'image', '画布卡片', ?, 'done')", (str(held),))
db.commit()
proj = post("/api/projects", {"title": "隔离引用项目", "idea": "hel872"})
db.execute(
"INSERT INTO characters (project_id, name, appearance, portrait_path)"
" VALUES (?, '隔离角色', 'x', ?)", (proj["id"], str(up / "hidden-project-ref.png")))
db.commit()
db.close()
listed = json.load(urllib.request.urlopen(base + "/api/library/media", timeout=10))
print("SEED listed:", [i["name"] for i in listed], flush=True)
try:
for name, cmd in [("api", [sys.executable, "-c", api_code]), ("web", ["node", "-e", web_code])]:
h = (out / f"{phase}-{name}.log").open("w")
handles.append(h)
processes.append(subprocess.Popen(cmd, env=env, stdout=h, stderr=subprocess.STDOUT))
for url in (f"http://127.0.0.1:{API_PORT}/api/health", f"http://127.0.0.1:{WEB_PORT}"):
for attempt in range(150):
try:
urllib.request.urlopen(url, timeout=1)
break
except Exception:
if any(p.poll() is not None for p in processes):
raise RuntimeError(f"Service failed: {name}")
if attempt == 149:
raise
time.sleep(0.1)
seed()
# Minimal API-level repro, logged raw for the evidence bundle:
# list shows the canvas-held file, delete keeps it with the reason.
base = f"http://127.0.0.1:{API_PORT}"
listed = json.load(urllib.request.urlopen(base + "/api/library/media", timeout=10))
held_path = next(i["path"] for i in listed if i["name"] == "held-on-canvas.png")
req = urllib.request.Request(
base + "/api/library/media", method="DELETE",
data=json.dumps({"paths": [held_path]}).encode(),
headers={"Content-Type": "application/json"})
body = json.load(urllib.request.urlopen(req, timeout=10))
(out / f"{phase}-api-repro.json").write_text(json.dumps(
{"listed_held": True, "delete_response": body}, ensure_ascii=False, indent=2))
print("API REPRO:", json.dumps(body, ensure_ascii=False), flush=True)
subprocess.run(["node", "e2e/hel872.cjs"], env=env, check=True)
finally:
daemon = json.loads(subprocess.check_output(["multica", "daemon", "status", "--output", "json"]))["pid"]
for p in processes:
assert p.pid != daemon, "refusing to kill the multica daemon"
if p.poll() is None:
p.send_signal(signal.SIGTERM)
for p in processes:
try:
p.wait(timeout=10)
except subprocess.TimeoutExpired:
p.kill()
p.wait()
cleanup.append({"pid": p.pid, "exit": p.returncode, "daemon_pid": daemon})
for h in handles:
h.close()
(out / f"{phase}-cleanup.json").write_text(json.dumps(
{"children": cleanup, "isolated_data_removed": not Path(tmp).exists()}, indent=2))
print("CLEANUP", cleanup, "isolated data removed:", not Path(tmp).exists(), flush=True)
+17
View File
@@ -0,0 +1,17 @@
HEL-845 日间选中控件定向验证
先在 `calliope-web` 执行 `npm ci`、`npm run check`、`npm run lint`、`npm test`、`npm run build`。
在仓库根目录运行:
```sh
python3 scripts/hel845/verify.py --approved /path/to/approved-unpacked --output /path/to/fresh-evidence --python /path/to/existing-backend-venv/bin/python
```
编排环境复用现有 Playwright/Pillow,后端环境复用项目依赖,不新增产品依赖。Chromium 系统库不在系统路径时设置 `LD_LIBRARY_PATH`。批准目录须为附件 `01a16e28-f815-7dd1-8661-51fdf26974e8` 原样解压目录;整包 SHA256 为 `dfe02579065200e8f0edaa3114709fc44286f232fdaa76c34acd3f3814523508`。
脚本使用当前仓库源码和真实构建、真实 FastAPI/SQLite/HTTP 假供应商,在本地隔离端口 18740 启动服务,不调用现网或真实付费供应商。四个独立主题上下文、三种窗口、四种适配/密度组合共 48 个状态;每个状态记录 URL、主题、真实背景/文字/图标/阴影/尺寸、键盘焦点和对比度,附上下对照工具条(上批准、下产品)。日间另附四张整页及四张键盘焦点局部图。普通对照图双方均移除焦点,焦点证据单列。
日间断言颜色与阴影逐值相等,文字对比度至少 4.5:1;其余主题在浏览器临时恢复修前两项 day 局部映射,断言与当前构建的控件值相等,不把原样媒体或数据差异当成像素一致。该临时恢复只用于记录 before 值,不修改产品源码。每个窗口验证 Enter/Space、aria-pressed、可见焦点、实际 contain/cover 与密度 class、筛选/排序/查找和选择。
结束先比对 daemon PID,再同步回收确切自有子进程、删除隔离数据库/媒体/配置;保留服务日志、PID 清理记录、原始色值与截图。不得用现有用户数据目录作输出。CSS 单点修复复用 HEL-843 已验收的 MF-1 后端证据,不重跑后端全量,不改旧脚本里的共享页截图结论;本脚本只核素材库 `/library`。
+291
View File
@@ -0,0 +1,291 @@
"""Compare approved controls with an isolated build; no live services or paid calls."""
import argparse
import json
import os
import shutil
import subprocess
import time
import urllib.request
from pathlib import Path
from PIL import Image
from playwright.sync_api import expect, sync_playwright
ROOT = Path(__file__).resolve().parents[2]
p = argparse.ArgumentParser()
p.add_argument("--approved", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p.add_argument(
"--python", required=True, help="Existing backend dependency environment"
)
a = p.parse_args()
out = a.output.resolve()
out.mkdir(parents=True, exist_ok=True)
data = out / "fixture"
assert not data.exists(), "Use a fresh isolated output directory"
env = {**os.environ, "PYTHONPATH": str(ROOT / "calliope-backend/src")}
metrics_js = """buttons => buttons.map(n => {
const c = getComputedStyle(n), svg = n.querySelector('svg');
return {background:c.backgroundColor, color:c.color, shadow:c.boxShadow,
icon:svg ? getComputedStyle(svg).color : null, radius:c.borderRadius,
width:n.getBoundingClientRect().width, height:n.getBoundingClientRect().height};
})"""
def contrast(bg, fg):
import re
def lum(s):
rgb = [float(x) / 255 for x in re.findall(r"[\d.]+", s)[:3]]
linear = [
v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 for v in rgb
]
return sum(v * w for v, w in zip(linear, [0.2126, 0.7152, 0.0722]))
x, y = sorted([lum(bg), lum(fg)])
return round((y + 0.05) / (x + 0.05), 4)
def pids(obj):
if isinstance(obj, dict):
return [v for k, v in obj.items() if k in ("pid", "process_id")] + [
n for v in obj.values() for n in pids(v)
]
if isinstance(obj, list):
return [n for v in obj for n in pids(v)]
return []
log = (out / "server.log").open("w")
proc = subprocess.Popen(
[
a.python,
str(ROOT / "scripts/hel840/serve_fixture.py"),
"--data",
str(data),
"--port",
"18740",
],
cwd=ROOT,
env=env,
stdout=log,
stderr=subprocess.STDOUT,
)
(out / "owned-process.json").write_text(json.dumps({"pid": proc.pid, "port": 18740}))
rows, errors = [], []
try:
for _ in range(100):
if proc.poll() is not None:
raise RuntimeError((out / "server.log").read_text()[-3000:])
try:
urllib.request.urlopen(
"http://127.0.0.1:18740/api/health", timeout=1
).close()
break
except OSError:
time.sleep(0.1)
else:
raise RuntimeError("Fixture not ready")
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True, args=["--no-sandbox"])
try:
for theme in ["day", "night", "grade", "bluehour"]:
for w, h in [(1440, 900), (1366, 768), (1280, 720)]:
context = browser.new_context(viewport={"width": w, "height": h})
page, ref = context.new_page(), context.new_page()
page.on("pageerror", lambda e: errors.append(str(e)))
page.goto("http://127.0.0.1:18740/library")
page.evaluate("t => localStorage.setItem('aigc-theme',t)", theme)
page.reload()
page.locator(".lt").first.wait_for()
expect(page.locator("html")).to_have_attribute("data-theme", theme)
assert page.url.endswith("/library")
ref.goto(
(a.approved / "HEL-837-交互样本-v2.html").resolve().as_uri()
+ f"?theme={theme}#library"
)
ref.locator("#p-library.on").wait_for()
expect(ref.locator("html")).to_have_attribute("data-theme", theme)
for fill in [False, True]:
for dense in [False, True]:
fit = page.get_by_role(
"button", name="铺满" if fill else "完整", exact=True
)
fit.focus()
page.keyboard.press("Enter")
expect(fit).to_have_attribute("aria-pressed", "true")
density = page.get_by_role(
"button",
name="紧凑网格,仅缩略图" if dense else "标准网格",
exact=True,
)
density.focus()
page.keyboard.press("Space")
expect(density).to_have_attribute("aria-pressed", "true")
assert density.evaluate(
"n => n === document.activeElement && n.matches(':focus-visible')"
)
focus = density.evaluate(
"n => {const c=getComputedStyle(n);return {outline:c.outline,offset:c.outlineOffset,shadow:c.boxShadow}}"
)
assert (
"none" not in focus["outline"]
and "0px" not in focus["outline"]
)
grid = page.locator(".lgrid").first
classes = grid.get_attribute("class").split()
assert ("fill" in classes) == fill and (
"dense" in classes
) == dense
assert page.locator(".mat img").first.evaluate(
"n=>getComputedStyle(n).objectFit"
) == ("cover" if fill else "contain")
ref.locator(
f'[data-fit="{"fill" if fill else "contain"}"]'
).click()
ref.locator(
f'[data-dens="{"dense" if dense else "std"}"]'
).click()
page.wait_for_timeout(300)
ref.wait_for_timeout(300)
actual = page.locator(
".lib-segment button.on"
).evaluate_all(metrics_js)
original = ref.locator(
"#p-library .seg button.on"
).evaluate_all(metrics_js)
assert len(actual) == len(original) == 2
if theme == "day":
for x, y in zip(actual, original):
for key in [
"background",
"color",
"shadow",
"icon",
]:
assert x[key] == y[key], (theme, key, x, y)
assert contrast(x["background"], x["color"]) >= 4.5
# Reapply the exact pre-fix local tokens only inside the browser.
# This proves other themes are unchanged without changing source/build.
old = page.add_style_tag(
content='[data-theme="day"] .lib2 {--lib-option-bg:var(--hi);--lib-option-shadow:0 1px 2px rgb(var(--ink) / .14),0 0 0 1px rgb(var(--ink) / .06)}'
)
page.wait_for_timeout(300)
before = page.locator(
".lib-segment button.on"
).evaluate_all(metrics_js)
old.evaluate("n=>n.remove()")
page.wait_for_timeout(300)
if theme != "day":
assert before == actual
else:
assert before[0]["background"] == "rgb(20, 17, 9)"
assert (
contrast(
before[0]["background"], before[0]["color"]
)
< 1.2
)
assert not page.evaluate(
"document.documentElement.scrollWidth > innerWidth"
)
stem = f"{theme}-{w}x{h}-fill{int(fill)}-dense{int(dense)}"
if theme == "day" and w == 1440:
page.locator(".lib-tools").screenshot(
path=str(out / (stem + "-keyboard-focus.png"))
)
density.evaluate("n=>n.blur()")
ref.locator("#p-library .seg button").evaluate_all(
"buttons=>buttons.forEach(n=>n.blur())"
)
actual_path, ref_path = (
out / (stem + "-actual.png"),
out / (stem + "-approved.png"),
)
page.locator(".lib-tools").screenshot(path=str(actual_path))
ref.locator("#p-library .lib-tools").screenshot(
path=str(ref_path)
)
with (
Image.open(ref_path) as left,
Image.open(actual_path) as right,
):
pair = Image.new(
"RGB",
(
max(left.width, right.width),
left.height + right.height,
),
"white",
)
pair.paste(left, (0, 0))
pair.paste(right, (0, left.height))
pair.save(out / (stem + "-pair.png"))
rows.append(
{
"theme": theme,
"viewport": [w, h],
"fill": fill,
"dense": dense,
"url": page.url,
"actual": actual,
"approved": original,
"before_local_mapping": before,
"focus": focus,
"contrast": contrast(
actual[0]["background"], actual[0]["color"]
),
}
)
if theme == "day" and w == 1440:
page.screenshot(path=str(out / (stem + "-page.png")))
select = page.get_by_role("button", name="选择", exact=True)
select.focus()
page.keyboard.press("Enter")
expect(select).to_have_attribute("aria-pressed", "true")
page.get_by_role("button", name="图片", exact=False).first.click()
expect(page.locator(".lt video")).to_have_count(0)
page.get_by_role("combobox", name="排序").select_option("size")
page.get_by_role("textbox", name="文件名查找").fill("样本素材-01")
expect(page.locator(".lt")).to_have_count(1)
page.locator(".lt .ck").first.click()
expect(page.locator(".selbar")).to_be_visible()
context.close()
finally:
browser.close()
assert not errors, errors
(out / "values.json").write_text(json.dumps(rows, ensure_ascii=False, indent=2))
(out / "browser-errors.json").write_text(json.dumps(errors))
print(
json.dumps(
{
"states": len(rows),
"browser_errors": errors,
"day_contrast": rows[0]["contrast"],
}
)
)
finally:
raw = subprocess.check_output(
["multica", "daemon", "status", "--output", "json"], text=True
)
(out / "daemon-status.json").write_text(raw)
assert proc.pid not in pids(json.loads(raw)), "Refuse to terminate workspace daemon"
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
log.close()
shutil.rmtree(data, ignore_errors=True)
(out / "cleanup.json").write_text(
json.dumps(
{
"pid": proc.pid,
"returncode": proc.returncode,
"fixture_removed": not data.exists(),
}
)
)