From e5356bdc3c38928df79dd527d0242ee902159976 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E6=A0=96=E7=9F=A5?= <2298888111@qq.com> Date: Sun, 25 Oct 2026 20:26:23 +0800 Subject: [PATCH] fix(HEL-849): unify agent composer select interactions Co-authored-by: multica-agent --- .../components/agent/AgentWorkspace.svelte | 84 ++- .../src/lib/components/omni/PillSelect.svelte | 610 +++++++++++------- calliope-web/static/themes.css | 16 + .../2026-10-25-hel849-agent-select.md | 13 + e2e/hel849.cjs | 539 ++++++++++++++++ e2e/run-hel849.py | 53 ++ 6 files changed, 1033 insertions(+), 282 deletions(-) create mode 100644 docs/changelogs/2026-10-25-hel849-agent-select.md create mode 100644 e2e/hel849.cjs create mode 100644 e2e/run-hel849.py diff --git a/calliope-web/src/lib/components/agent/AgentWorkspace.svelte b/calliope-web/src/lib/components/agent/AgentWorkspace.svelte index d29c7a4b..3bccee34 100644 --- a/calliope-web/src/lib/components/agent/AgentWorkspace.svelte +++ b/calliope-web/src/lib/components/agent/AgentWorkspace.svelte @@ -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="描述你的创作想法、目标与要求…" >
- 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))} + /> + 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))} + /> + 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))} + /> + - /** - * 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(null); - let menuEl = $state(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 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(null); + let menuEl = $state(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" }); + }); + }); -
- +
+
- {#if open} -
- {#each options as opt (opt.value)} - - {/each} -
+
+ {#each options as opt, index (opt.value)} + + {/each} +
{/if} diff --git a/calliope-web/static/themes.css b/calliope-web/static/themes.css index e2f074e0..c7e51569 100644 --- a/calliope-web/static/themes.css +++ b/calliope-web/static/themes.css @@ -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); diff --git a/docs/changelogs/2026-10-25-hel849-agent-select.md b/docs/changelogs/2026-10-25-hel849-agent-select.md new file mode 100644 index 00000000..5484297a --- /dev/null +++ b/docs/changelogs/2026-10-25-hel849-agent-select.md @@ -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 引用,本次没有声称对不可达页面完成浏览器验收。当前智能体成果区、任务输入菜单和原会话入口已完成实际回归。后端、模型配置/密钥、提示词、画布业务与依赖未修改;未部署、未合并。 diff --git a/e2e/hel849.cjs b/e2e/hel849.cjs new file mode 100644 index 00000000..6bbe10c0 --- /dev/null +++ b/e2e/hel849.cjs @@ -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; +}); diff --git a/e2e/run-hel849.py b/e2e/run-hel849.py new file mode 100644 index 00000000..0b911c17 --- /dev/null +++ b/e2e/run-hel849.py @@ -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)