Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cda754eab | ||
|
|
410eadea15 | ||
|
|
bc2a70ac5f | ||
|
|
c1d4feb4a8 | ||
|
|
0ffa8d00bb |
@@ -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():
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,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`。
|
||||
@@ -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(),
|
||||
}
|
||||
)
|
||||
)
|
||||
Reference in New Issue
Block a user